instruction
stringlengths
0
30k
|boo|closures|
|closures|boo|
I've run into a strange syntax in [Boo Language Guide][1] : setter = { value | a = value } What does the | operator mean? [1]: http://boo.codehaus.org/Closures
C# console program can't send fax when run as a scheduled task
|c#|console|fax|
I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log. EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0, P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b, P7 1, P8 80, P9 system.io.filenotfoundexception, P10 NIL. I wrote a batch file to run the fax program and it fails with this message. Unhandled Exception: System.IO.FileNotFoundException: Operation failed. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer) Can anyone explain this behavior to me?
shouldn't this: {{ user.item }} be this? {{ item }} there is no user object in the context within that loop....?
MSDN [says][1] that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use [GetAddressBytes][2] method. You can convert IP address to numeric value using following code: var ipAddress = IPAddress.Parse("some.ip.address"); var ipBytes = ipAddress.GetAddressBytes(); var ip = (uint)ipBytes [3] << 24; ip += (uint)ipBytes [2] << 16; ip += (uint)ipBytes [1] <<8; ip += (uint)ipBytes [0]; [1]: http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx [2]: http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx
MSDN [says][1] that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use [GetAddressBytes][2] method. You can convert IP address to numeric value using following code: var ipAddress = IPAddress.Parse("some.ip.address"); var ipBytes = ipAddress.GetAddressBytes(); var ip = (uint)ipBytes [3] << 24; ip += (uint)ipBytes [2] << 16; ip += (uint)ipBytes [1] <<8; ip += (uint)ipBytes [0]; [1]: http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx [2]: http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx **EDIT:** As other commenters noticed above-mentioned code is for IPv4 addresses only. IPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted.
I think you would need to consider leap years. I didn't do the math, but I think during a leap year, with a hard code of 28 days for feb, a comparison of noon on 2/29 and noon on 3/1 would result in the same duplicate time stamp as before. Although it looks like you didn't implement it like that. They way you implemented it, I think you still have the problem but it's between dates on 12/31 of $leapyear and 1/1 of $leapyear+1. I think you might also have some collisions during time changes if your code has to handle time zones that handle them. The file doesn't really seem to be sorted in any useful way. I'm guessing that field $1 is some sort of status (the "OK" you're checking for). So it's sorted by record status, then by DAY, then MONTH, YEAR, HOURS, MINUTES, SECONDS. If it was year,month,day I think there could be some optimizations there. Still might be but my brain's going in a different direction right now. If there are a small number of duplicate keys in proportion to total number of lines, I think your best bet is to reduce the file your awk script works over to just duplicate keys (as [David said][1]). You could also preprocess the file so the only lines present are the /OK/ lines. I think I would do this with a pipeline where the first awk script only prints the lines with duplicate IDs and the second awk script is basically the one above but optimized to not look for /OK/ and with the knowledge that any key present is a duplicate key. If you know ahead of time that all or most lines will have repeated keys, it's probably not worth messing with. I'd bite the bullet and write it in C. Tons more lines of code, much faster than the awk script. [1]: http://stackoverflow.com/questions/6475/faster-way-to-find-duplicates-conditioned-by-time#6813
I'd go with your original idea. If you are concerned that the queue might get too large implement a buffer-zone for it (i.e. If is gets above 100 lines the stop reading the file and if it gets below 20 then start reading again. You'd need to do some testing to find the optimal barriers). Make it so that any of the threads can potentially be the "reader thread" as it has to lock the queue to pull an item out anyway it can also check to see if the "low buffer region" has been hit and start reading again. While it's doing this the other threads can read out the rest of the queue. Or if you prefer, have one reader thread assign the lines to three other *processor* threads (via their own queues) and implement a [work-stealing strategy][1]. I've never done this so I don't know how hard it is. [1]: http://portal.acm.org/citation.cfm?doid=324133.324234
The interesting thing here is how you can do it in the least amount of drops possible. Going to the 50th floor and dropping the first would be disastrous if the breaking floor is the 49th, resulting in us having to do 50 drops. We should drop the first marble at floor n, where n is the max amount of drops required. If the marble breaks at floor n, we may have to make n-1 drops after that. If the marble doesn't break we go up to floor 2n-1 and if it breaks here we have to drop the second marble n-2 times in the worst case. We continue like this up to the 100th floor and try to break it at 3n-2, 4n-3.... and n+(n-1)+(n-2)+...1 <=100 n=14
The interesting thing here is how you can do it in the least amount of drops possible. Going to the 50th floor and dropping the first would be disastrous if the breaking floor is the 49th, resulting in us having to do 50 drops. We should drop the first marble at floor n, where n is the max amount of drops required. If the marble breaks at floor n, we may have to make n-1 drops after that. If the marble doesn't break we go up to floor 2n-1 and if it breaks here we have to drop the second marble n-2 times in the worst case. We continue like this up to the 100th floor and try to break it at 3n-2, 4n-3.... and n+(n-1)+(n-2)+...1 <=100 **n=14 Is the maximum drops required**
Log4j has been around for a long time, and it works very well. I have no scientific study to back it, but based on what I've seen at a large number of clients, it is easily the logging framework that I see used more than any other. It has been around for a long time, and not been replaced by the Next Big Logging Framework, which says something. It is dead simple to set up, and easy to learn the basic appenders (outputs). There are a whole host appenders that are available, including: 1. ConsoleAppender 2. DailyRollingFileAppender 3. ExternallyRolledFileAppender 4. FileAppender 5. JDBCAppender 6. JMSAppender 7. NTEventLogAppender 8. RollingFileAppender 9. SMTPAppender 10. SocketAppender 11. SyslogAppender 12. TelnetAppender 13. WriterAppender Plus others. It isn't difficult to write your own appender either. Additionally there is a great deal of flexibility in each of the appenders that allow you to control specifically what is output in your log. One note, I had a series of classloader problems when I used apache commons logging in addition to log4j. It was only for one specific application, but I found it simpler to use log4j alone, rather than to have the flexibility offered when using an abstraction layer like commons logging. See this article for [more details][1]: Good luck! [1]: http://www.qos.ch/logging/thinkAgain.jsp
Yaws uses old config file
|yaws|
I'm developing a web app on Yaws 1.65 (installed through apt) running on Debian etch on a VPS with UML. Whenever I do /etc/init.d/yaws restart or a stop/start, it initializes according to an old version of the config file (/etc/yaws/yaws.conf). I know this because I changed the docroot from the default to another directory (call it A), then a few weeks later changed it to directory B, and the config file has stayed with B for the last several months. But then, after a restart, it switches back to A. If it switched back to the package default, that would be understandable, but it switches to an old customized version instead. The funny thing is that if I leave it stopped for several minutes, when I start it again, everything switches back to normal (using directory B). But while it's stopped, if I run ps, I don't see any yaws-related processes (yaws, heart, etc). This problem has survived several reboots, so it's got to be an old cached copy of the config somewhere, but I have yet to find anything like that. Any idea what could be going on?
I'm developing a web app on Yaws 1.65 (installed through apt) running on Debian etch on a VPS with UML. Whenever I do /etc/init.d/yaws restart or a stop/start, it initializes according to an old version of the config file (/etc/yaws/yaws.conf). I know this because I changed the docroot from the default to another directory (call it A), then a few weeks later changed it to directory B, and the config file has stayed with B for the last several months. But then, after a restart, it switches back to A. If it switched back to the package default, that would be understandable, but it switches to an old customized version instead. The funny thing is that if I leave it stopped for several minutes, when I start it again, everything switches back to normal (using directory B). But while it's stopped, if I run ps, I don't see any yaws-related processes (yaws, heart, etc). This problem has survived several reboots, so it's got to be an old cached copy of the config somewhere, but I have yet to find anything like that. Any idea what could be going on? Update: @Gorgapor - I stopped yaws, renamed the config file and tried to start it again. It failed to start. However, I was able to restart a couple of times and this time it didn't switch back to the old version.
Generally a unit test is intended to exercise the public interface of a class or unit, private methods therefore are implementation detail that you would not expect to test explicitly.
If you have several options that follow this layout, why not create a user control? The user control will contain the CheckBox, a NumericUpDown, a ComboBox and a label for the "after loading". You can override OnFontChanged to adjust the location of the controls based on the rendering of the text with the given font. Add an EventHandler to the Label to check/uncheck the CheckBox. As for having the focus rectangle surround all of the controls, you should be able to give the user control focus when one of its inner controls is clicked.
My solution to this, that I hope can be bettered, is to use Oracle to explicitly convert the TIMESTAMP into a string: cursor.execute("SELECT TO_CHAR(WhenAdded, 'YYYY-MM-DD HH:MI:SSAM') FROM Log") This works, but isn't portable. I'd like to use the same Python script against a SQL Server database, so an Oracle-specific solution (such as TO_CHAR) won't work.
Use sessions to ensure that any Ajax posts are done in an authenticated context. Think of your Ajax code as just another client to your server, it becomes easier to tackle authentication issues that way.
What is your static memory manager actually doing? Unless it is doing something unsafe (P/Invoke, unsafe code), the behaviour you are seeing is a bug in your program, and not due to the behaviour of the CLR. Secondly, what do you mean by 'pointer', with respect to links between structures? Do you literally mean an unsafe KdTree* pointer? Don't do that. Instead, use an index into the array. Since I expect that all nodes for a single tree are stored in the same array, you won't need a separate reference to the array. Just a single index will do. Finally, if you really really must use KdTree* pointers, then your static memory manager should allocate a large block using e.g. Marshal.AllocHGlobal or another unmanaged memory source; it should both treat this large block as a KdTree array (i.e. index a KdTree* C-style) **and** it should suballocate nodes from this array, by bumping a "free" pointer. If you ever have to resize this array, then you'll need to update all the pointers, of course. The basic lesson here is that unsafe pointers and managed memory do **not** mix outside of 'fixed' blocks, which of course have stack frame affinity (i.e. when the function returns, the pinned behaviour goes away). There is a way to pin arbitrary objects, like your array, using GCHandle.Alloc(yourArray, GCHandleType.Pinned), but you almost certainly don't want to go down that route. You will get more sensible answers if you describe in more detail what you are doing.
Any request that the AJAX calls in your pages can make can also be made by someone outside of the application. If done right, you will not be able to tell if they were made as part of an AJAX call from your webapp or by hand/other means. There are two scenarios I can think of which you might be talking about when you say you want to make sure that only your AJAX calls can post data: either you don't want a malicious user to be able to post data that interferes with another user's data or you actually want to restrict the posts to being in the "flow" of a multi-request operation. If you are concerned with the first case (someone posting malicious data to/as another user) the solution is the same whether you are using AJAX or not -- you just have to authenticate the user through whatever means is necessary -- usually via session cookie. If you are concerned with the second case, then you are going to have to do something like issue a unique token at each step of the process, and store the expected token on the server side. Then when a request is made, check that there is a corresponding entry on the server side for the action that is being taken and that the expected tokens match and that that token has not been used yet. If there is no, you reject the request, if there is, then you mark that token as used and process the request. If what you are concerned about is something other than one of these two scenarios then the answer will depend on more specifics than you have provided.
@buyutec Instead of list.RemoveAll(item => ShouldIRemoveThis(item)); you can use: list.RemoveAll(ShouldIRemoveThis); The lambda has the same signature as the method, so they are equivalent so you can just pass the method directly.
In IIS, check the settings on the application pool that SSRS is running in. On the properties pane->Performance tab you can set the amount of time the worker process needs to be idle for before it shuts down. You can also disable this entirely.
Your example just compiles to a compiler-named private inner class (with field firedCount and a compiler-named method). Each call to PotentialMemoryLeaker creates a new instance of the closure class to which where foo keeps a reference by way of a delegate to the single method. If you don't reference the whole object that owns PotentialMemoryLeaker, then that will all be garbage collected. Otherwise, you can either set _foo_ to null or empty foo's event handler list by writing this: foreach (var handler in AnEvent.GetInvocationList()) AnEvent -= handler; Of course, you'd need access to the **MyObject** class's private members.
* Apache Axis can generate proxy code from WSDL <http://ws.apache.org/axis/java/user-guide.html#UsingWSDLWithAxis> * NetBeans with the RESTful Web Services plug-in can generate code for you. Instructions for an example client for the eBay shopping web service are at <http://ebay.custhelp.com/cgi-bin/ebay.cfg/php/enduser/std_adp.php?p_faqid=1230>.
If you want to specify both a limit for number of items to remove and a condition to select the items to remove, you can use this approach: int limit = 30; // Suppose you want to remove 30 items at most list.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0);
The database is often running as a service under an account with no network access. If this is the case, then you wouldn't be able to restore directly over the network. Either the backup needs to be copied to the local machine or the database service needs to run as a user with the proper network access.
It refers to the [lambda calculus](http://en.wikipedia.org/wiki/Lambda_calculus) which is a formal system that just has lambda expressions, which represents a function that takes a function for its sole argument and returns a function. All functions in the lambda calculus are of that type. Lisp used the lambda concept to name its anonymous function literals. This lambda represents a function that takes two arguments, x and y, and returns their product: (lambda (x y) (* x y)) It can be applied in-line like this (evaluates to *50*): ((lambda (x y) (* x y)) 5 10)
You can think of it as an anonymous function - here's some more info: [Wikipedia - Anonymous Function][1] [1]: http://en.wikipedia.org/wiki/Anonymous_function
> Note that a responsible web developer > does not use fonts that are only > available on Windows (and especially > ones that are only available on > Vista), nor do they use a technology > that isn't supported by at least the > majority of browsers. There's nothing wrong or incorrect about using Windows/Vista-specific fonts provided you gracefully degrade to a widely-available font. For example: font-face: Calibri, Tahoma, Helvetica, Sans-Serif; In fact that's the whole point!
My experience is with Java, not C#, so apologies if these solutions don't apply. The immediate solution I can think up off the top of my head would be to have an executor that runs 3 threads (using [`Executors`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html)`.newFixedThreadPool`, say). For each line/record read from the input file, fire off a job at the executor (using [`ExecutorService`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html)`.submit`). The executor will queue requests for you, and allocate between the 3 threads. Probably better solutions exist, but hopefully that will do the job. :-) ETA: Sounds a lot like Wolfbyte's second solution. :-)
My experience is with Java, not C#, so apologies if these solutions don't apply. The immediate solution I can think up off the top of my head would be to have an executor that runs 3 threads (using [`Executors`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/Executors.html)`.newFixedThreadPool`, say). For each line/record read from the input file, fire off a job at the executor (using [`ExecutorService`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html)`.submit`). The executor will queue requests for you, and allocate between the 3 threads. Probably better solutions exist, but hopefully that will do the job. :-) ETA: Sounds a lot like Wolfbyte's second solution. :-) ETA2: [`System.Threading.ThreadPool`](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx) sounds like a very similar idea in .NET. I've never used it, but it may be worth your while!
If you use javascript to hide the buttons, you open a security hole in the application. A malicious user could either disable javascript or apply some of their own to get around your security. I suggest using PHP to chose to either render the buttons or not. I do this in .NET quite often. You should be able to check the user's access on the server-side whenever they try to use a restricted button as well.
showing a message box from a bash script in linux
|linux|bash|scripting|ubuntu|gtk|
I'm writing a few little bash scripts under Ubuntu linux. I want to be able to run them from the GUI without needing a terminal window to enter any input or view any output. So far the only input required is a password for sudo - and gksudo handles that fine. But I haven't found an easy way to show a message box yet. Is there some kind of 'gkmessage' command available? I'd prefer something present in a default Ubuntu install, but I don't mind installing a new package if necessary.
You can't do it without any static variables, however if you are willing to tolerate one, you can use [Boost.Thread](http://www.boost.org/doc/html/thread.html) for this purpose. Read the "one-time initialisation" section for more info. Then in your singleton accessor function, use `boost::call_once` to construct the object, and return it.
Development of shaders in XNA (which obviously uses DirectX) requires knowledge of [HLSL][1] or shader assembly. I'd recommend getting familiar with the former before diving into the latter. Before writing any shaders, it's a good idea to get solid understanding of the shader pipeline, and attempt to get your mind around what is possible when using programmable shaders. When you're familiar with the life of a pixel (from source data all the way through to the screen) then understanding examples of shaders becomes a lot easier. Next make an attempt to write your own HLSL which does what the [Fixed T&L][2] pipeline used to do, just to get you hands dirty. This is the equivalent of a "hello world" program in vertex/pixel shader world. When you're able to do that and you understand what you've written you're ready to go onto the more fun stuff. As a next step you might want to simulate basic [sepcular lighting][3] in one of your shaders from a single light source. You can then adapt this down the track to use multiple lights. Play with colours, and movement of lights. This will help get familiar with the use of shader constants as well. When you have a couple of basic shaders together, you should attempt to make it so that your game/engine uses multiple/different shaders on different objects. Start adding some other bits like basic [bump][4] or [normal maps][5]. When you get to this stage, the world is your oyster. You can start diving into some funky effectcs, and even consider using the GPU for [more][6] than it was originally intended. For those who are a little more advanced, there are a couple of good books that are available for free online which have some great information from Nvidia [here][7] and [here][8]. Don't forget that there's an excellent series of books called ShaderX which covers some awesome shader stuff. There's [1][9], [2][10], [3][11], [4][12], [5][13] and [6][14] already in print, and [7][15] is coming soon. Good luck. If you get some shaders going, I'd love to see them :) [1]: http://msdn.microsoft.com/en-us/library/bb509561(VS.85).aspx [2]: http://www.computerhope.com/jargon/t/tandl.htm [3]: http://www.gamasutra.com/features/20030418/engel_pfv.htm [4]: http://www.paulsprojects.net/tutorials/simplebump/simplebump.html [5]: http://www.bencloward.com/tutorials_normal_maps1.shtml [6]: http://www.gpgpu.org/ [7]: http://developer.nvidia.com/object/gpu_gems_home.html [8]: http://developer.nvidia.com/object/gpu_gems_2_home.html [9]: http://www.amazon.com/gp/product/1556220413?ie=UTF8&tag=ojsra-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1556220413 [10]: http://www.amazon.com/gp/product/1556229887?ie=UTF8&tag=ojsra-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1556229887 [11]: http://www.amazon.com/gp/product/1584503572?ie=UTF8&tag=ojsra-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1584503572 [12]: http://www.amazon.com/gp/product/1584504250?ie=UTF8&tag=ojsra-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1584504250 [13]: http://www.amazon.com/gp/product/1584504994?ie=UTF8&tag=ojsra-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1584504994 [14]: http://www.amazon.com/gp/product/1584505443?ie=UTF8&tag=ojsra-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=1584505443 [15]: http://www.shaderx7.com/
You've got a few issues here that don't relate well to each other. At the basic database level you can track changes by having a separate table that gets an entry added to it via triggers on INSERT/UPDATE/DELETE statements. Thats the general way of tracking changes to a database table. The other thing you want is to know which *user* made the change. Generally your triggers wouldn't know this. I'm assuming that if you want to know which user changed a piece of data then its possible that multiple users could change the same data. There is no right way to do this, you'll probably want to have a separate table that your application code will insert a record into whenever a user updates some data in the other table, including user, timestamp and id of the changed record. Make sure to use a transaction so you don't end up with cases where update gets done without the insert, or if you do the opposite order you don't end up with insert without the update.
A trace log in a separate table (with an ID column, possibly with timestamps)? Are you going to want to undo the changes as well - perhaps pre-create the undo statement (a DELETE for every INSERT, an (un-) UPDATE for every normal UPDATE) and save that in the trace?
The problem is your action does two things, violating the Single Responsibility Principle. If your Create action redirects to the List action when it's done creating the item, then this problem disappears.
In general, if your application is structured into layers, have the data access tier call a stored procedure on your database server to write a log of the database changes. In languages that support such a thing [aspect-oriented programming][1] can be a good technique to use for this kind of application. Auditing database table changes is the kind of operation that you'll typically want to log for all operations, so AOP can work very nicely. Bear in mind that logging database changes will create lots of data and will slow the system down. It may be sensible to use a message-queue solution and a separate database to perform the audit log, depending on the size of the application. It's also perfectly feasible to use stored procedures to handle this, although there may be a bit of work involved passing user credentials through to the database itself. [1]: http://en.wikipedia.org/wiki/Aspect-oriented_programming
While a fast forward cursor does have some optimizations in Sql Server 2005, it is *not* true that they are anywhere close to a set based query in terms of performance. There are very few situations where cursor logic cannot be replaced by a set-based query. Cursors will always be inherently slower, due in part to the fact that you have to keep interrupting the execution in order to fill your local variables. Here are few references, which would only be the tip of the iceberg if you research this issue: [http://www.code-magazine.com/Article.aspx?quickid=060113][1] [http://sqlblog.com/blogs/adam_machanic/archive/2007/10/13/cursors-run-just-fine.aspx][2] [1]: http://www.code-magazine.com/Article.aspx?quickid=060113 [2]: http://sqlblog.com/blogs/adam_machanic/archive/2007/10/13/cursors-run-just-fine.aspx
I don't know much about development at that level, but... it seems like it would be a good idea to separate into multiple solutions. You could have a final "pre-ship" step that consolidates them all into a single .dll if you/your customers really insist. Compare, e.g., to the .NET Framework where we have lots of different assemblies (System, System.Drawing, System.Windows.Forms, System.Xml...). Presumably all of these could be in different solutions, referencing each other's build results (as opposed to all in a single solution, referencing each other as projects).
> Note that a responsible web developer > does not use fonts that are only > available on Windows (and especially > ones that are only available on > Vista), nor do they use a technology > that isn't supported by at least the > majority of browsers. There's nothing wrong or incorrect about using Windows/Vista-specific fonts provided you gracefully degrade to a widely-available font. For example: font-family: Calibri, Tahoma, Helvetica, Sans-Serif; In fact that's the whole point!
The PRE tag can be a valid solution, depending on your needs. However, if you are trying to use the 2 space rule in sentences throughout your site, you'll soon find that the other characters the PRE tag preserves are the line feed/carriage returns (or lack of) will muck up any styling you try to do. In general, I tend to ignore the "2 spaces after a sentence" rule, or if you're a stickler for it, I'd stick with the &amp;nbsp;, but you'll occasionally run into the issue Nicolas stated.
A lambda is a type of function, defined inline. Along with a lambda you alsu usually have some kind of variable type that can hold a reference to a function, lambda or otherwise. For instance, here's a C# piece of code that doesn't use a lambda: public Int32 Add(Int32 a, Int32 b) { return a + b; } public Int32 Sub(Int32 a, Int32 b) { return a - b; } public delegate Int32 Op(Int32 a, Int32 b); public void Calculator(Int32 a, Int32 b, Op op) { Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b)); } public void Test() { Calculator(10, 23, Add); Calculator(10, 23, Sub); } This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation. In C# 2.0 we got anonymous methods, which shortens the above code to: public delegate Int32 Op(Int32 a, Int32 b); public void Calculator(Int32 a, Int32 b, Op op) { Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b)); } public void Test() { Calculator(10, 23, delegate(Int32 a, Int32 b) { return a + b; }); Calculator(10, 23, delegate(Int32 a, Int32 b) { return a - b; }); } And then in C# 3.0 we got lambdas which makes the code even shorter: public delegate Int32 Op(Int32 a, Int32 b); public void Calculator(Int32 a, Int32 b, Op op) { Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b)); } public void Test() { Calculator(10, 23, (a, b) => a + b); Calculator(10, 23, (a, b) => a - b); }
With both queries, it looks like you are trying to insert into #temp. #temp is located on one of the databases (for arguments sake, databaseA). So when you try to insert into #temp from databaseB, it reports that it does not exist. Try changing it from *Into **#temp** From* to *Into **databaseA.dbo.#temp** From* in both statements. Also, make sure that the connection strings have permissions on the other DB, otherwise this will not work.
With both queries, it looks like you are trying to insert into #temp. #temp is located on one of the databases (for arguments sake, databaseA). So when you try to insert into #temp from databaseB, it reports that it does not exist. Try changing it from *Into **#temp** From* to *Into **databaseA.dbo.#temp** From* in both statements. Also, make sure that the connection strings have permissions on the other DB, otherwise this will not work. Update: relating to the temp table going out of scope - if you have one connection string that has permissions on both databases, then you could use this for both queries (while keeping the connection alive). While querying the table in the other DB, be sure to use [DBName].[Owner].[TableName] format when referring to the table.
As of PHP 5.1.0 you can use [*date_default_timezone_set()*][1] function to set the default timezone used by all date/time functions in a script. For MySql (quoted from [MySQL Server Time Zone Support][2] page) > Before MySQL 4.1.3, the server operates only in the system time zone set at startup. Beginning with MySQL 4.1.3, the server maintains several time zone settings, some of which can be modified at runtime. Of interest to you is per-connection setting of the time zones, which you would use at the beginning of your scripts SET timezone = 'Europe/London'; As for detecting the client timezone setting, you could use a bit of JavaScript to get and save that information to a cookie, and use it on subsequent page reads, to calculate the proper timezone. //Returns the offset (time difference) between Greenwich Mean Time (GMT) //and local time of Date object, in minutes. var offset = new Date().getTimezoneOffset(); document.cookie = 'timezoneOffset=' + escape(offset); Or you could offer users the chioce to set their time zones themselves. [1]: http://www.php.net/manual/en/function.date-default-timezone-set.php [2]: http://dev.mysql.com/doc/refman/4.1/en/time-zone-support.html
Has anybody used "props"? You type "prop" and then press [TAB] twice, it generates useful code for your properties and can speed your typing. I know this works in VS 2005 (I use it) but I don´t know in previous versions.
In the tomcat/conf/server.xml there are several connectors configured. each connector has an optional "address" attribute where you can specify a bind address for that connector. <Connector port="8080" protocol="HTTP/1.1" address="127.0.0.1" connectionTimeout="20000" redirectPort="8443" />
This is a good question, one that I will be subscribing too :) I am still relatively new to web dev, and I too am looking at a lot of code that is largely untested. For me, I keep the UI **as light as possible** (normally only a few lines of code) and test the crap out of everything else. At least I can then have some confidence that everything that makes it to the UI is as correct as it can be. Is it perfect? Perhaps not, but at least it as still quite highly automated and the core code (where most of the "magic" happens) still has pretty good coverage..
If this were me, I would define 2 namespaces: Protocol and Protocol.Driver Dividing the namespace like this separates your "library code" vs your "executable / test code." I also create my namespaces to match the directory structure; it will give logic to your programs structure and codefiles. (maybe you already do this...)
I save all my dates as a bigint due to having had issues with the dateTime type before. I save the result of the time() PHP function into it, now they count as being in the same timezone :)
We've been using it for a project here at work that needed to run on Linux but reuse some .NET libraries that we built in Managed C++. I've been very surprised at how well it has worked out. Our main executable is being written in C# and we can just reference our Managed C++ binaries with no issue. The only difference in the C# code between Windows and Linux is RS232 serial port code. The only big issue I can think of happened about a month ago. The Linux build had a memory leak that wasn't seen on the Windows build. After doing some manual debugging (the basic profilers for Mono on Linux didn't help much), we were able to narrow the issue down to a specific chunk of code. We ended up patching a workaround, but I still need to find some time to go back and figure out what the root cause of the leak was.
Check that you set correct working directory for your task
Is the scheduled task running on the same computer you're developing on, or is it on a dedicated olp server? It's quite common for paths to change when you change environments, so is the path to the document you're trying to send the same?
I can't explain it - but I have a few ideas. Most of the times, when a program works fine testing it, and doesn't when scheduling it - security is the case. In the context of which user is your program scheduled? Maybe that user isn't granted enough access. Is the resource your programm is trying to access a network drive, that the user running the scheduled task simply haven't got?
The 'standard' way to do this with rails is to run a "pack" of Mongrel instances (ie: 4 copies of the rails application) and then use apache or nginx or some other piece of software to sit in front of them and act as a load balancer. This is probably how it's done with other ruby frameworks such as merb etc, but I haven't used those personally. The OS will take care of running each mongrel on it's own CPU. If you install [mod_rails aka phusion passenger](http://www.modrails.com/) it will start and stop multiple copies of the rails process for you as well, so it will end up spreading the load across multiple CPUs/cores in a similar way.
As other's have mentioned we use CCNET here, which we don't usually work on a nightly build, but instead go with a Continuous Integration strategy (every check-in). I would advise doing the same, whether it be by yourself or within a team, because you can very easily set up unit testing to run on every checkin as well, FXCop testing, and a slew of other products. If it's just you in a one man team, and you don't have too many projects on the go, I would also advise checking out [Team City][1] as an option, because it has a free version, and the reporting and setup is reportedly much simpler (it does look nice to me). That said, we started with CCNET, and have grown several products too large to look at Team City on the free version and are very happy with what we have. Features that help with CCNET include: - XML based configuration - you can usually copy and paste most of what you need. - More or less you'll be able to plug your treesurgeon script in as your build script, and point CCNET at that as an executable task to run the compilation. - Lots of documentation and very easy to set up nunit, ncover, fxcop, etc. - Taskbar app that will let you know the status of your projects at any time, and it can also fire off an email or keep an RSS feed with the same information. But I'd definitely go with running a CI build on every check-in - for the most part will run the unit tests before checking in, but let the CCNET server handle run any applications/assemblies that would have dependencies on the assembly we're checking in, and they get re-built, and re-tested on every checkin. Given it's free and takes very little time to set up - I'd highly recommend just going for it. [1]: http://www.jetbrains.com/teamcity/
I would store the referring URL using the [ViewState][1]. Storing this outside the scope of the page (i.e. in the Session state or cookie) may be overkill. The example below validates that the page was called internally (i.e. not requested directly) and bounces back to the referring page after the user submits their response. public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.UrlReferrer == null) { //Handle the case where the page is requested directly throw new Exception("This page has been called without a referring page"); } if (!IsPostBack) { ReturnUrl = Request.UrlReferrer.PathAndQuery; } } public string ReturnUrl { get { return ViewState["returnUrl"].ToString(); } set { ViewState["returnUrl"] = value; } } protected void btn_Click(object sender, EventArgs e) { //Do what you need to do to save the page //... //Go back to calling page Response.Redirect(ReturnUrl, true); } } [1]: http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx
PostgreSQL's [UPDATE][1] statement has the RETURNING clause that will return a result set like a SELECT statement: UPDATE mytable SET views = 5 WHERE id = 16 RETURNING id, views, othercolumn; I'm pretty sure this is not standard though. I don't know if any other databases implement it. [1]: http://www.postgresql.org/docs/8.3/static/sql-update.html
PostgreSQL's [UPDATE][1] statement has the RETURNING clause that will return a result set like a SELECT statement: UPDATE mytable SET views = 5 WHERE id = 16 RETURNING id, views, othercolumn; I'm pretty sure this is not standard though. I don't know if any other databases implement it. Edit: I just noticed that your question has the "MySQL" tag. Maybe you should mention it in the question itself. It's a good generic database question though - I would like to see how to do it in other databases. [1]: http://www.postgresql.org/docs/8.3/static/sql-update.html
You do it the exact same way. Put a string in as the first statement in the module.
NT authentication login
|authentication|ntlm|
I have a site I am working on, on this site users can login to get more private information. My client has another site elseware that uses nt authentication for accessing it. What they want to do is have a button on the site I am working on under the private area that will send them to the ntauthenticated site, but not require them to log on to that site instead passing the username and password that they used to log into my site to the other site for them. Is it possible to do this? and how would I accomplish it? Is there a better way to do this?
It would help if you listed the RDBMS you are using SQL Server has the OUTPUT statement Example USE AdventureWorks; GO DECLARE @MyTestVar table ( OldScrapReasonID int NOT NULL, NewScrapReasonID int NOT NULL, WorkOrderID int NOT NULL, ProductID int NOT NULL, ProductName nvarchar(50)NOT NULL); UPDATE Production.WorkOrder SET ScrapReasonID = 4 OUTPUT DELETED.ScrapReasonID, INSERTED.ScrapReasonID, INSERTED.WorkOrderID, INSERTED.ProductID, p.Name INTO @MyTestVar FROM Production.WorkOrder AS wo INNER JOIN Production.Product AS p ON wo.ProductID = p.ProductID AND wo.ScrapReasonID= 16 AND p.ProductID = 733; SELECT OldScrapReasonID, NewScrapReasonID, WorkOrderID, ProductID, ProductName FROM @MyTestVar; GO
I like the second one purely because any avoidance of magic strings/numbers in code is a good thing. IMO if you need to reference a number or string literal in code more than once, it should be a constant. In most cases even if it's only used once it should be in a constant
@Mendelt Siebenga: You can only call GetType on the value property if the variable is not set to null; otherwise, you'll get an exception. What you want to do is use the "GetValueOrDefault" property and call GetType on that, since you are guaranteed it will not be null. Example: Dim i As Nullable(Of Integer) = Nothing Dim t As Type = i.GetValueOrDefault().GetType()
[ActiveRecord][1] seems to be the state of the art at the moment. I can't recommend any good PHP frameworks for that though. I tried [Propel][2] which, while nice, is not easy to set up (especially on a host that you can't install anything on). Ultimately, I rolled my own ORM/ActiveRecord framework, which is not too much work and very instructive. I'm sure other people can recommend good PHP frameworks. [1]:http://en.wikipedia.org/wiki/Active_record_pattern [2]: http://propel.phpdb.org/
Good Starting Places for SQL Server Alerts/Notifications?
|sql-server|ssis|etl|notifications|alert|
Just recently started having issues with a SQL Server Agent Job that contains a SSIS package to extract production data and summarize it into a separate reporting database. I *think* that some of the Alerts/Notifications settings I tried playing with caused the problem as the job had been running to completion unattended for the previous two weeks. So... Where's a good place to start reading up on SQL Agent Alerts and Notifications? I want to enable some sort of alert/notification so that I'm always informed: 1. That the job completes successfully (as a check to ensure that it's always executed), or 2. That the job ran into some sort of error, which should include enough info (such as error number) that I can diagnose the cause of the error As always, any help will be greatly appreciated!
ARMV4i (Windows Mobile 6) Native Code disassembler
|windows-mobile|arm|disassembly|
Does anyone know of a disassembler for ARMV4i compiled executables and dlls? I've got a plugin DLL I'm writing and it has a very rare data abort (<5% of the time) that I have narrowed down to a specific function (via dumpbin and the memory address output by the data abort) however it's a fairly large function and I would like to narrow it down a little. I know it's happening in a memset() call, but that particular function has about 35 of them, so I was hoping that by looking at the disassembly I could figure out where about the problem actually is.
I don't entirely understand your question. Are you saying that files you check out on one machine seems to be unaccessible on another of your machines? I'd say that would be entirely by design, as now you have a file that has local modifications done on one machine, which may or may not be available on your other machines. When you say *checked out by somebody else*, what does that mean exactly? How are you verifying this, what are you looking at? Or do you mean something else? In that case, please elaborate.
Are you sure you have no ImageMagick on server? I guest you use PHP (question is tagged with PHP). Hosting company which I use has no ImageMagick extension turned on according to phpinfo(). But when I asked them about they said *here is the list of ImageMagick programs available from PHP code*. So simply -- there are no IM interface in PHP, but I can call IM programs directly from PHP. I hope you have the same option. And I **strongly** agree -- storing images in database is not good idea.
My basic rule in Django is: if you could conceivably need the functionality from somewhere other than the view itself, it doesn't belong in the view function. I'd also recommend downloading some of the plethora of apps on [Django Pluggables][1] and seeing how they do it. [1]: http://djangoplugables.com/
It is a function that has no name. For e.g. in c# you can use numberCollection.GetMatchingItems<int>(number => number > 5); to return the numbers that are greater than 5. number => number > 5 is the lambda part here. It represents a function which takes a parameter (number) and returns a boolean value (number > 5). GetMatchingItems method uses this lambda on all the items in the collection and returns the matching items.
This question was not about optimizing the algorithm - but thanks anyway ;-) At the time I wrote it, I considered the labeled continue as a readable solution. I asked SO a [question][1] about the convention (having the label in all caps or not) for labels in Java. Basically every answer told me "do not use them - there is always a better way! refactor!". So I posted this question to ask for a more readable (and therefore better?) solution. Until now, I am not completely convinced by the alternatives presented so far. Please don't get me wrong. Labels are evil most of the time. But in my case, the conditional tests are pretty simple and the algorithm is taken from a mathematical paper and therefore very likely to not change in the near future. So I prefer having all the relevant parts visible at once instead of having to scroll to another method named something like checkMatrixAtRow(x). Especially at more complex mathematical algorithms, I find it pretty hard to find "good" function-names - but I guess that is yet another question [1]: http://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501
I like the explanation of Lambdas in this article: [The Evolution Of LINQ And Its Impact On The Design Of C#][1]. It made a lot of sense to me as it shows a real world for Lambdas and builds it out as a practical example. Their quick explanation: Lambdas are a way to treat code (functions) as data. [1]: http://msdn.microsoft.com/en-us/magazine/cc163400.aspx
I've done this in the past. Either do it manually, (build a nice gui that helps the user do it quickly) or have it automated and check against a recent address database (you have to buy that) and manually handle errors. Manual handling will take about 10 seconds each, meaning you can do 3600/10 = 360 per hour, so 4000 should take you approximately 11-12 hours. This will give you a high rate of accuracy. For automation, you _need_ a recent US address database, and tweak your rules against that. I suggest not going fancy on the regex (hard to maintain long-term, so many exceptions). Go for 90% match against the database, do the rest manually. Do get a copy of Postal Addressing Standards (USPS) at [http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf][1] and notice its 130+ pages long. Regexes to implement that would be nuts. [1]: http://pe.usps.gov/cpim/ftp/pubs/Pub28/pub28.pdf For international addresses, all bets are off. US-based workers would not be able to validate. Alternatively, use a data service. I have, however, no recommendations. Furthermore: when you do send out the stuff in the mail (that's what it's for, right?) make sure you put "address correction requested" on the envelope (in the right place) and _update_ the database. (We made a simple gui for the front desk person to do that; the person who actually sorts through the mail) Finally, when you have scrubbed data, look for duplicates.
One method I've seen quite often is to have audit tables. Then you can show just what's changed, what's changed and what it changed from, or whatever you heart desires :) Then you could write up a trigger to do the actual logging. Not too painful if done properly... No matter how you do it, though, it kind of depends on how your users connect to the database. Are they using a single application user via a security context within the app, are they connecting using their own accounts on the domain, or does the app just have everyone connecting with a generic sql-account? If you aren't able to get the user info from the database connection, it's a little more of a pain. And then you might look at doing the logging within the app, so if you have a process called "CreateOrder" or whatever, you can log to the Order_Audit table or whatever. Doing it all within the app opens yourself up a little more to changes made from outside of the app, but if you have multiple apps all using the same data and you just wanted to see what changes were made by yours, maybe that's what you wanted... <*shrug*> Good luck to you, though! --Kevin
Retrieving an Oracle timestamp using Python's Win32 ODBC module
|python|oracle-database|
Given an Oracle table created using the following: CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); Using the Python ODBC module from its Win32 extensions (from the win32all package), I tried the following: import dbi, odbc connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log") results = cursor.fetchall() When I run this, I get the following: Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?
Given an Oracle table created using the following: CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); Using the Python ODBC module from its [Win32 extensions][1] (from the win32all package), I tried the following: import dbi, odbc connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD") cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log") results = cursor.fetchall() When I run this, I get the following: Traceback (most recent call last): ... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps? [1]: http://www.python.org/download/windows/
@Domenic: indeed, it would be a good thing... However, a whole team's been at it for some time now, and until they succeed we are stuck with a single .dll and something quite monolithic :-(
Is SOAP now a legacy technology?
|soap|rpc|
Ok so I found the [xmessage][1] command, which is sort of good enough. If anyone knows of something better - ie. uses GTK widgets and so on, please post :) [1]: http://www.linuxmanpages.com/man1/xmessage.1x.php
Here's a little Tcl script that will do what you want. The Wish interpreter should be installed by default on Ubuntu. #!/usr/bin/wish pack [label .msg -text [lindex $argv 0]] pack [entry .ent] bind .ent <KeyPress-Return> { puts [.ent get]; destroy . } focus .ent Call it like this: myanswer=`gui-prompt "type your answer and press enter"`
This will eliminate bottlenecks of having a single thread do the reading: open file for each thread n=0,1,2,3: seek to file offset 1/n*filesize scan to next complete line process all lines in your part of the file
While this question has already been answered, I think there are some other points to mention: - If you want lazy-instantiation of the singleton while using a pointer to a dynamically allocated instance, you'll have to make sure you clean it up at the right point. - You could use Matt's solution, but you'd need to use a proper mutex/critical section for locking, and by checking "pObj == NULL" both before and after the lock. Of course, **pObj** would also have to be *static* ;) . A mutex would be unnecessarily heavy in this case, you'd be better going with a critical section. But as already stated, you can't guarantee threadsafe lazy-initialisation without using at least one synchronisation primitive.