input
stringlengths
51
42.3k
output
stringlengths
18
55k
MS Source Server: significance of srcsrv.ini variable <p>The MS source server technology uses an initialization file named srcsrv.ini. One of the values identifies the source server location(s), e.g.,</p> <pre><code>MYSERVER=\\machine\foobar </code></pre> <p>The docs leave much unanswered about this value. To start with, I haven't been able to find the significance of the value name, i.e., what's on the left side--and I don't see it used anywhere else. Hewardt &amp; Pravat in <a href="http://www.advancedwindowsdebugging.com/" rel="nofollow">Advanced Windows Debugging</a> say "The left side ... represents the project name", but that doesn't seem to jibe with MS's "MYSERVER" example.</p> <p>What <i>is</i> the significance of the left side? Where else is it used? Does the value reference a server or a project, and is there one per server, or one per project?</p>
<p>For anyone looking into this in the future, I received the following information from MS:</p> <blockquote> <p>The name on the left side is the logical name of a version control server. The name is also used in the source-indexed symbol files (pdb). For example, a symbol file may contain this string value:<br><br>&nbsp;&nbsp;MYSERVER=mymachine1.sys-mygroup.corp.microsoft.com:2003<br><br>and the source files are referenced like this in pdb:<br><br>&nbsp;&nbsp;*MYSERVER*/base/myfolder/mycode.c<br><br>When SrcSrv starts, it looks at Srcsrv.ini for values; these values override the information contained in the .pdb file:<br><br>&nbsp;&nbsp;"MYSERVER=mymachine.sys-mygroup.corp.microsoft.com:1666" overrides <br> &nbsp;&nbsp;"MYSERVER=mymachine1.sys-mygroup.corp.microsoft.com:2003"<br><br>This enables users to configure a debugger to use an alternative source control server at debug time. The info is documented at <a href="http://msdn.microsoft.com/en-us/library/ms680641.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms680641.aspx</a>.</p> </blockquote> <p>So, it is a logical name for a source server, and its value can be changed at debug time to reference a different server than the one originally used when the PDBs were created.</p>
Microsoft MIDL does not report an error if a typedef uses an unknown type, is it a bug? <p>I would like to know whether I am missing something:</p> <pre><code>//this is test.idl typedef foo foo_t; // end of test.idl </code></pre> <p>When I compile test.idl with the following command:</p> <pre><code>midl /W4 test.idl </code></pre> <p>I get this output</p> <pre><code>Microsoft (R) 32b/64b MIDL Compiler Version 6.00.0366 Copyright (c) Microsoft Corporation 1991-2002. All rights reserved. Processing .\test.idl test.idl </code></pre> <p>and I get a wrong test.h (at the bottom of this message) which has only</p> <pre><code>typedef foo_t; </code></pre> <p>where the unknown foo type was silently discarded.</p> <p>I would have expected an error message stating "foo is an unknown type", am I wrong?</p> <p>Do I need to pass any particular arguments to the MIDL command?</p> <p>I got the same result with MIDL compiler version 7.00.0500</p> <pre><code>/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 6.00.0366 */ /* at Thu Nov 13 11:47:40 2008 */ /* Compiler settings for test.idl: Oicf, W4, Zp8, env=Win32 (32b run) protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec (novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ //@@MIDL_FILE_HEADING( ) #pragma warning( disable: 4049 ) /* more than 64k source lines */ /* verify that the &lt;rpcndr.h&gt; version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 475 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of &lt;rpcndr.h&gt; #endif // __RPCNDR_H_VERSION__ #ifndef __test_h__ #define __test_h__ #if defined(_MSC_VER) &amp;&amp; (_MSC_VER &gt;= 1020) #pragma once #endif /* Forward Declarations */ #ifdef __cplusplus extern "C"{ #endif void * __RPC_USER MIDL_user_allocate(size_t); void __RPC_USER MIDL_user_free( void * ); /* interface __MIDL_itf_test_0000 */ /* [local] */ typedef foo_t; extern RPC_IF_HANDLE __MIDL_itf_test_0000_v0_0_c_ifspec; extern RPC_IF_HANDLE __MIDL_itf_test_0000_v0_0_s_ifspec; /* Additional Prototypes for ALL interfaces */ /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif </code></pre>
<p>I submitted the following bug to Microsoft:</p> <p><a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=382571" rel="nofollow">MIDL does not report an error if a typedef uses an unknown type</a></p>
SQL - How to make a conditional INSERT <p>Using <strong>only MySQL</strong>, I'm seeing if it's possible run an insert statement ONLY if the table is new. I successfully created a user variable to see if the table exists. The problem is that you can't use "WHERE" along with an insert statement. Any ideas on how to get this working?</p> <pre><code>// See if the "country" table exists -- saving the result to a variable SELECT @table_exists := COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'country'; // Create the table if it doesn't exist CREATE TABLE IF NOT EXISTS country ( id INT unsigned auto_increment primary key, name VARCHAR(64) ); // Insert data into the table if @table_exists &gt; 0 INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands') WHERE 0 &lt; @table_exists; </code></pre>
<pre><code>IF @TableExists &gt; 0 THEN BEGIN INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands'); END </code></pre>
Can I make a website full screen without flash or silverlight? <p>I'm working on something that needs a webpage to go full screen. The screen must become completely white. </p> <p>Is there anyway that I can do this without flash or silverlight? Thanks in advance</p> <p>edit: Im not trying to force anybody into fullscreen, this will be mainly used by a couple of people. Even so I'll give proper feedback on how to get in and out of fullscreen .</p>
<p>You cant do full screen, because of security reasons the title bar is still there and so on in different browsers.</p> <p>But a way could be to make the window larger than the screen, lets say 100 pixels wider and 100 pixels higher and position the window at -50, -50. I havent tried that but if there is no restrains against window size being bigger than screen size it could be a solution.</p>
C++ reading from a file blocks any further writing. Why? <p>I am implementing a very simple file database. I have 2 basic operations: </p> <pre><code>void Insert(const std::string &amp; i_record) { //create or append to the file m_fileStream.open(m_fileName.c_str(), std::ios::out | std::ios::app); if (m_fileStream.is_open()) { m_fileStream &lt;&lt; i_record &lt;&lt; "\n"; } m_fileStream.flush(); m_fileStream.close(); } /* * Returns a list with all the items in the file. */ std::vector&lt;std::string&gt; SelectAll() { std::vector&lt;std::string&gt; results; m_fileStream.open(m_fileName.c_str(), std::ios::in); std::string line; if (m_fileStream.is_open()) { while (!m_fileStream.eof()) { getline (m_fileStream, line); results.push_back(line); } } m_fileStream.close(); return results; } </code></pre> <p>the class has m_fileStream and m_fileName as private members. </p> <p>OK - here's the problem: </p> <p>If I do something like: </p> <pre><code>db-&gt;Insert("a"); db-&gt;SelectAll(); db-&gt;Insert("b"); </code></pre> <p>The end result is that the file will contain <em>only</em> "a"; WHY? </p> <p>NOTE: it seems that getline() will set the fail bit. but why?</p>
<p>Change </p> <pre><code> while (!m_fileStream.eof()) { getline (m_fileStream, line); results.push_back(line); } </code></pre> <p>to </p> <pre><code> while (getline (m_fileStream, line)) { results.push_back(line); } </code></pre> <p>Otherwise you will get one additional empty line at the end. <code>eof()</code> will return true only once you tried to read past the end of the file, and <em>not</em> if only the next read would be past the end of the file.</p> <p>It sets the <code>failbit</code> because <code>getline</code> tries to extract characters from the stream. If there are no characters left (and no <code>'\n'</code> has been seen yet), <code>stream.get(c)</code> to a character will set the <code>failbit</code>. Then <code>getline</code> will set the <code>eofbit</code> and then <code>.eof()</code> will return true, and your loop exits.</p> <p>If you don't want <code>failbit</code> set, then change your condition from <code>!stream.eof()</code> to <code>stream.peek() != EOF</code> (and make sure there is a trailing newline in your file).</p> <p>This now is also the solution to your problem: <code>.close()</code> doesn't <code>.clear()</code> your stream, so the <code>failbit</code> still is set if you reopen your file. call <code>stream.clear()</code> after reading your stuff in, and then it works.</p>
Silverlight DataBinding Error - Works in WPF Though! <p>Start a new Silverlight application... and in the code behind (in the "Loaded" event), put this code:</p> <pre><code>// This will *NOT* cause an error. this.LayoutRoot.DataContext = new string[5]; </code></pre> <p>But...</p> <pre><code>// This *WILL* cause an error! this.LayoutRoot.DataContext = this; </code></pre> <p>The error that is raised is "Value does not fall within the expected range." BTW, this code works 100% in regular WPF (Windows development), and there should be no reason why it won't work in WPF/E :)</p> <p>Any thoughts?</p>
<p>You can't currently use visual elements as a data source for data binding in Silverlight 2. I think this is slated to be added for Silverlight v.Next.</p>
How to correctly unregister an event handler <p>In a code review, I stumbled over this (simplified) code fragment to unregister an event handler:</p> <pre><code> Fire -= new MyDelegate(OnFire); </code></pre> <p>I thought that this does not unregister the event handler because it creates a new delegate which had never been registered before. But searching MSDN I found several code samples which use this idiom.</p> <p>So I started an experiment:</p> <pre><code>internal class Program { public delegate void MyDelegate(string msg); public static event MyDelegate Fire; private static void Main(string[] args) { Fire += new MyDelegate(OnFire); Fire += new MyDelegate(OnFire); Fire("Hello 1"); Fire -= new MyDelegate(OnFire); Fire("Hello 2"); Fire -= new MyDelegate(OnFire); Fire("Hello 3"); } private static void OnFire(string msg) { Console.WriteLine("OnFire: {0}", msg); } } </code></pre> <p>To my surprise, the following happened:</p> <ol> <li><code>Fire("Hello 1");</code> produced two messages, as expected.</li> <li><code>Fire("Hello 2");</code> produced one message!<br /> This convinced me that unregistering <code>new</code> delegates works!</li> <li><code>Fire("Hello 3");</code> threw a <code>NullReferenceException</code>.<br /> Debugging the code showed that <code>Fire</code> is <code>null</code> after unregistering the event.</li> </ol> <p>I know that for event handlers and delegate, the compiler generates a lot of code behind the scene. But I still don't understand why my reasoning is wrong.</p> <p>What am I missing?</p> <p>Additional question: from the fact that <code>Fire</code> is <code>null</code> when there are no events registered, I conclude that everywhere an event is fired, a check against <code>null</code> is required.</p>
<p>The C# compiler's default implementation of adding an event handler calls <code>Delegate.Combine</code>, while removing an event handler calls <code>Delegate.Remove</code>:</p> <pre><code>Fire = (MyDelegate) Delegate.Remove(Fire, new MyDelegate(Program.OnFire)); </code></pre> <p>The Framework's implementation of <code>Delegate.Remove</code> doesn't look at the <code>MyDelegate</code> object itself, but at the method the delegate refers to (<code>Program.OnFire</code>). Thus, it's perfectly safe to create a new <code>MyDelegate</code> object when unsubscribing an existing event handler. Because of this, the C# compiler allows you to use a shorthand syntax (that generates exactly the same code behind the scenes) when adding/removing event handlers: you can omit the <code>new MyDelegate</code> part:</p> <pre><code>Fire += OnFire; Fire -= OnFire; </code></pre> <p>When the last delegate is removed from the event handler, <code>Delegate.Remove</code> returns null. As you have found out, it's essential to check the event against null before raising it:</p> <pre><code>MyDelegate handler = Fire; if (handler != null) handler("Hello 3"); </code></pre> <p>It's assigned to a temporary local variable to defend against a possible race condition with unsubscribing event handlers on other threads. (See <a href="http://code.logos.com/blog/2008/11/events_and_threads_part_4.html">my blog post</a> for details on the thread safety of assigning the event handler to a local variable.) Another way to defend against this problem is to create an empty delegate that is always subscribed; while this uses a little more memory, the event handler can never be null (and the code can be simpler):</p> <pre><code>public static event MyDelegate Fire = delegate { }; </code></pre>
How best can I isolate my application from an unreliable database? <p>I have a Java SOAP data service which sits on top of a Sybase database which, for reasons out of my control, has unreliable performance. The database is part of a vendor package which has been modified by an internal team and most of the issues are caused by slow response times at certain times of the day. </p> <p>The SOAP service provides data to a calculation grid and when I request data, I need the response time to be both fast and <em>consistent</em>. The service provides basic CRUD functionality, but the ratio of reads to writes is approximately 100:1. </p> <p>What is the best strategy to isolate myself from the database's unreliable performance and ensure that the SOAP service is fast and reliable?</p>
<p>I have seen this issue a few times, normally with a vendor database. </p> <p>If this is on Windows, you could create a Windows service as an intermediary between the SOAP service and the database. Then put a message queue (either MSMQ or a JMS implementation such as MQ Series) between the SOAP service and Windows service for asynchronous communications. In this way the database performance issues will no longer affect the SOAP service. This solution does, however, come at the cost of increased complexity.</p> <p>Note that a .NET web service can be called by, and respond asynchronously to, its clients. I'm not sure if that's possible with a Java SOAP service. </p> <p>If this is on some flavour of Unix, I assume it has similar functionality to a Windows service - maybe a daemon.</p>
Spring Integration as embedded alternative to standalone ESB <p>Does anybody has an experience with <a href="http://springframework.org/spring-integration" rel="nofollow">Spring Integration</a> project as embedded ESB?</p> <p>I'm highly interesting in such use cases as:</p> <ul> <li>Reading files from directory on schedule basis</li> <li>Getting data from JDBC data source</li> <li>Modularity and possibility to start/stop/redeploy module on the fly (e.g. one module can scan directory on schedule basis, another call query from jdbc data source etc.)</li> <li>repeat/retry policy</li> </ul> <p><strong>UPDATE:</strong></p> <p>I found answers on all my questions except "Getting data from JDBC data source". Is it technically possible?</p>
<p>Remember, "ESB" is just a marketing term designed to sell more expensive software, it's not a magic bullet. You need to consider the specific jobs you need your software to do, and pick accordingly. If Spring Integration seems to fit the bill, I wouldn't be too concerned if it doesn't look much like an uber-expensive server installation.</p>
Print Report without ReportViewer in ASP.NET <p>I am using Business Intelligent reporting servicess to reporting some data from My MS SQL Database. In ASP.NET I create new Reporting Viewer that take data from BI and display the report then I can Print it.</p> <p>My Question is How can I print the report without report viewer?</p> <p>thanks in advance :)</p>
<p>I tend to deliver reports optimized for printing as .pdf responses. This assumes the client has a .pdf reader installed. Since you scenario sounds like a business focused one, this might be reasonable.</p> <p>If the report server is directly accessible, you can access the report via the report's url (something like this...):</p> <pre><code>"http://myserver/reportserver?/MyReports/MyPrintFriendlyReport&amp;rs:Command=Render&amp;rc:LinkTarget=main&amp;rs:Format=PDF" </code></pre> <p>I don't usually get to do this. To overcome secure access/firewall issues, I create a page to call the reporting services web service. The render method returns a byte array based on the parameters you provide ("pdf" if you specify). Then you modify the content-type headers and Response.BinaryWrite the result. </p> <p>You should be able to google for sample code for this (I have none accessible right now).</p>
What constitutes a good memory profile? <p>In designing any desktop applications, are there any general rules on how much memory should the application uses?</p> <p>For heavy-weight applications, those can be easily understood or at least profiled such as Firefox or Google Chrome. But for smaller utilities or line-of-business application, how much is an acceptable amount of memory usage?</p> <p>I asked because I've recently come across a trade-off between memory usage and performance and wonder if there is any general consensus regarding it?</p> <p><strong>EDIT:</strong> Platform is Windows XP for users with machine just capable of running rich internet applications.</p> <p>My specific trade-off problem is about caching a lot of images in memory. If possible, I'd love to have my app cache as much as the user's memory will allow. I have done it so that the application will cache upto a certain maximum limit <em>considering memory pressure at the moment.</em>.</p> <p>But what would be a good number? How do you come up with one? That's the point I'm asking.</p>
<p>There is no absolute answer for this. It depends on too many variables.</p> <p>Here are some trade-offs for consideration:</p> <ul> <li>What device/platform are you developing for?</li> <li>Do you expect your user to use this software as the main purpose for their computer (example maybe you are developing some kind of server software)</li> <li>Who is your target audience, home users? power users?</li> <li>Are you making realistic expectations for the amount of RAM a user will have?</li> <li>Are you taking into consideration that the user will be using a lot of other software on that computer as well?</li> </ul> <p>Sometimes it's possible to have your cake and eat it too. For example if you were reading a file and writing it back out, you could read it chunk by chunk instead of reading the whole file into memory and then writing it out. In this case you have better memory usage, and no speed decrease.</p> <p>I would generally recommend to use more RAM to get better speed if you must. But only if the RAM requirements are realistic for your target audience. For example if you expect a home user that has 1GB of RAM to use your program, then don't use 600MB of RAM yourself.</p> <p>Consider using more RAM in this instance to get better speed, and to optimize some other part of your code to use less RAM. </p> <p><strong>Edit:</strong></p> <p>About your specific situation of caching images. I think it would be best for you to allow the user to set the amount of caching they would like to perform as an option. That way people with a lot of RAM can put it higher for better performance, and the people with little RAM can set it low. </p>
Algorithm to determine how positive or negative a statement/text is <p>I need an algorithm to determine if a sentence, paragraph or article is negative or positive in tone... or better yet, how negative or positive.</p> <p>For instance:</p> <blockquote> <blockquote> <p>Jason is the worst SO user I have ever witnessed (-10)</p> <p>Jason is an SO user (0)</p> <p>Jason is the best SO user I have ever seen (+10)</p> <p>Jason is the best at sucking with SO (-10)</p> <p>While, okay at SO, Jason is the worst at doing bad (+10)</p> </blockquote> </blockquote> <p>Not easy, huh? :)</p> <p>I don't expect somebody to explain this algorithm to me, but I assume there is already much work on something like this in academia somewhere. If you can point me to some articles or research, I would love it.</p> <p>Thanks.</p>
<p>There is a sub-field of natural language processing called <a href="http://en.wikipedia.org/wiki/Sentiment_analysis">sentiment analysis</a> that deals specifically with this problem domain. There is a fair amount of commercial work done in the area because consumer products are so heavily reviewed in online user forums (ugc or user-generated-content). There is also a prototype platform for text analytics called <a href="http://gate.ac.uk/">GATE</a> from the university of sheffield, and a python project called <a href="http://sourceforge.net/projects/nltk/">nltk</a>. Both are considered flexible, but not very high performance. One or the other might be good for working out your own ideas.</p>
Function persistence in Common Lisp <p>Is there any persistence solution for Common Lisp, such as Elephant, that allows function persistence? Currently my app stores an identifier on the db and later searches in a function table which it is, but this method does not allow dynamically created functions to be stored.</p>
<p>It's not a database persistence mechanism, but most Common Lisps have a way of <a href="http://www.franz.com/support/documentation/8.1/doc/operators/excl/fasl-write.htm" rel="nofollow">writing FASLs</a> for all kinds of objects, including functions. For example:</p> <pre><code>cl-user(1): (compile (defun hello () (format t "~&amp;Hello~%"))) hello nil nil cl-user(2): (excl:fasl-write (symbol-function 'hello) "/tmp/hello.fasl") t cl-user(3): (excl:fasl-read "/tmp/hello.fasl") (#&lt;Function hello @ #x1000a964d2&gt;) </code></pre> <p>You can write to a stream (here I used a file for convenience), so you can trivially capture those bytes and stuff them into a database if you wished.</p>
Positive lookahead for exclamation mark <p>I'm trying to build a Java regular expression to match "<code>.jar!</code>"</p> <p>The catch is that I don't want the matcher to consume the exclamation mark. I tried using <code>Pattern.compile("\\.jar(?=!)")</code> but that failed. As did escaping the exclamation mark.</p> <p>Can anyone get this to work or is this a JDK bug?</p> <p><strong>UPDATE</strong>: I feel like an idiot, <code>Pattern.compile("\\.jar(?=!)")</code> does work. I was using Matcher.matches() instead of Matcher.find().</p>
<p>Using your regex works for me (using Sun JDK 1.6.0_02 for Linux):</p> <pre><code>import java.util.regex.*; public class Regex { private static final String text = ".jar!"; private static final String regex = "\\.jar(?=!)"; public static void main(String[] args) { Pattern pat = Pattern.compile(regex, Pattern.DOTALL); Matcher matcher = pat.matcher(text); if (matcher.find()) { System.out.println("Match: " + matcher.group()); } else { System.out.println("No match."); } } } </code></pre> <p>prints:</p> <pre><code>Match: .jar </code></pre> <p>(without the !)</p>
How semantic is your XHTML/CSS markup? <p>I think I'm pretty good at using semantic markup on my pages but I still have a handful of classes like this:</p> <pre><code>/**** Aligns ****/ .right_align { text-align: right; } .left_align { text-align: left; } .center_align { text-align: center; } </code></pre> <p>Which, technically, is a no-no. But when you just want to position some text in a table, how crazy am I supposed to get with the semantic markup?</p>
<p>Why do you want to align the text?</p> <p>The answer to the question is the name of the id or class you need to have for your selector. Do you want to align it right because it's a price?</p> <pre><code>table .price { text-align: right } </code></pre> <p>Just ask yourself <em>why</em> do you want to apply a particular style, and all will become clear.</p> <p>I probably overdid it, but my last work project was pretty close 100% semantic- anything I needed which was not semantic (say, a filler div which I could not do without for a layout requirement), I added dynamically using jQuery.</p>
Vb6: Need some help with a loop <p>So I have a loop that's supposed to do three things, go through a text file line by line, the text file contains pathnames and filenames(C:\Folder\file1.txt) If the line contains a certain string, it then copies a file to that location, renames it to what it is named in the text file, and then replaces a string within the copied file(still with me?). If not it goes on to the next line. I thought this would be fairly straight forward but I doesn't seem to be working, I'm currently unable to even compile as I'm getting errors saying the loop's syntax is wrong. Any help would be appreciated, here's the entire function's code:</p> <pre><code>Private Sub Command2_Click() Dim LineData As String Dim FileHandle As Integer FileHandle = FreeFile Open "C:\textfile.txt" For Input As #FileHandle Do While Not EOF(FileHandle) Line Input #FileHandle, LineData If InStr(LineData, ".log") Then FileCopy "C:\thefile.log",LineData Open LineData For Input As #3 #3 = Replace$(#3, "abc", "xyz") Else End If Loop Close #FileHandle Close #3 MsgBox "Copy, Replace, Complete!" End Sub </code></pre> <p>Thanks in Advance!</p>
<p>I don't believe</p> <pre><code>#3 = Replace$(#3, "abc", "xyz") </code></pre> <p>is valid. You will need to read the contents of that file in, preferable line by line (or some sensible chunk at a time), do your replacement, then write it back out to a new file. As you are copying the file anyway I would suggest reading it from the source location, and writing the new version to the location that the file would have been copied to anyway.</p> <p>for example...</p> <pre><code>Private Sub Command2_Click() Dim LineData As String Dim FileHandle As Integer Dim sourceHandle as Integer Dim destHandle as Integer dim temp as string FileHandle = FreeFile Open "C:\textfile.txt" For Input As #FileHandle Do While Not EOF(FileHandle) Line Input #FileHandle, LineData If InStr(LineData, ".log") Then sourceHandle=FreeFile Open "C:\thefile.log" For Input as #sourceHandle destHandle=FreeFile Open LineData For Output as #destHandle Do while Not EOF(sourceHandle) Line Input #sourceHandle,temp temp=replace$(temp,"abc","xyz") Print #destHandle,temp Loop Close #destHandle Close #sourceHandle End If Loop Close #FileHandle MsgBox "Copy, Replace, Complete!" End Sub </code></pre> <p>Sorry if there are any errors, this isn't tested as I don't have a VB IDE installed on this computer.</p>
Using application settings across assemblies <p>I'm writing an application that includes a plugin system in a different assembly.</p> <p>The problem is that the plugin system needs to get application settings from the main app (like the directory to look for plugins).</p> <p>How is this done, or am I going about this the wrong way?</p> <p>Edit: I was encouraged to add some details about how the plugin system works. I haven't completely worked that out and I've only just begun implementing it, but I basically went by <a href="http://divil.co.uk/net/articles/plugins/plugins.asp" rel="nofollow">this article</a>.</p>
<p>Let the main application get the plugin directory from the application settings and push it into the plugin system.</p>
"Unknown column 'user_id' error in django view <p>I'm having an error where I am not sure what caused it.</p> <p>Here is the error:</p> <pre><code>Exception Type: OperationalError Exception Value: (1054, "Unknown column 'user_id' in 'field list'") </code></pre> <p>Does anyone know why I am getting this error? I can't figure it out. Everything seems to be fine. </p> <p>My view code is below:</p> <pre><code>if "login" in request.session: t = request.POST.get('title', '') d = request.POST.get('description', '') fid = request.session["login"] fuser = User.objects.get(id=fid) i = Idea(user=fuser, title=t, description=d, num_votes=1) i.save() return HttpResponse("true", mimetype="text/plain") else: return HttpResponse("false", mimetype="text/plain") </code></pre> <p>I appreciate any help! Thanks!</p> <p>Edit: Also a side question. Do I use objects.get(id= or objects.get(pk= ? If I use a primary key, do I need to declare an id field or an index in the model?</p> <p>Edit: Here are the relevant models:</p> <pre><code>class User (models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200) password = models.CharField(max_length=200) class Idea (models.Model): user = models.ForeignKey(User) title = models.CharField(max_length=200) description = models.CharField(max_length=255) num_votes = models.IntegerField() </code></pre>
<ol> <li><p>The <code>user_id</code> field is the FK reference from <code>Idea</code> to <code>User</code>. It looks like you've changed your model, and not updated your database, then you'll have this kind of problem.</p> <p>Drop the old table, rerun syncdb.</p></li> <li><p>Your model tables get an <code>id</code> field by default. You can call it <code>id</code> in your queries. You can also use the synonym of <code>pk</code>.</p> <p>If you define your own primary key field you, you don't get the automatic <code>id</code> field. But you can still use <code>pk</code> to refer to the Primary Key.</p></li> </ol>
Why Isn't My C Code Being Compiled To An EXE <p>I'm just starting out writing trying to write a simple program in C and I am using Visual Studios to do so. I heard that it does compile C as well as C++. And I know that it does because it says it compiles. The only problem is that when I go to the output directory, there isn't a .exe file in the directory! It has the following:</p> <ul> <li>BuildLog.html</li> <li>mt.dep</li> <li>test1.obj</li> <li>vc90.idb</li> <li>vc90.pdb</li> </ul> <p>But that is all! No EXE. I've looked through all the options and made sure that it is set to compile to an exe and i checked the output file. That is $(OutDir)\$(ProjectName).exe. But alas, no exe appears. Any ideas?</p> <p>Also when i try to hit f5 and run with debut i get an error that says</p> <blockquote> <p>This application has failed to start because MSVCR90.DLL was not found. Re-installing the application may fix this problem</p> </blockquote>
<p>By default when you're creating a new C++ project within a new solution, you're getting folder structure like this:</p> <p>C:\Projects\YourSolution C:\Projects\YourSolution\YourCppProject</p> <p>YourSolution contains YourSolution.sln and YourCppProject contains YourCppProject.vcproj.</p> <p>When you build the solution, all intermediate files from YourCppProject are getting stored under YourCppProject\Debug or YourCppProject\Release, but resulting YourCppProject.exe goes under YourSolution\Debug or YourSolution\Release.</p> <p>Your $(OutDir) is configured by General -> Output Directory. Check project configuration for YourCppProject and see that it uses $(SolutionDir) for the output.</p>
How to deploy an RubyGem-based Server <p>We have built a custom socket server in ruby and packaged it as a gem. Since this is an internal project we can not simply publish it to RubyForge or GitHub. I tried to setup our own gem server but gem would not authenticate over https. Our other deployment is all for standard rails applications that use capistrano and svn for deployment.</p> <p>Our current setup which is to use a rails-like deployment with capistrano. which does the following:</p> <ul> <li>Check out the code from svn</li> <li>Build the gem</li> <li>Install the gem</li> <li>Restart the server</li> </ul> <p>This just seems awkward, and makes the gem packaging seem like extra work -- but outside of the deployment issue it fits really nicely as a gem.</p> <p>Is there a cleaner approach?</p>
<p>You can install gems from the local filesystem.</p> <pre><code>gem install /path/to/some.gem </code></pre> <p>Shouldn't be too hard for you to script scp with that, or use an NFS mount, etc.</p>
Can I use CSS in directory listing of Firefox? <p>For example if I put "C:\docs" in address bar of Firefox, it shows all files in the directory. Is it possible to customize this page with CSS?</p> <p>Apache 2.2 allows us to do it using IndexStyleSheet directive, so I wondered if Firefox can do it.</p>
<p>Firefox has a file userContent.css for each profile (found in the profile's settings folder). That file defines the standard CSS, why may then be overwritten by a website. So they also apply to directory listings.</p> <p>You should have a look at the actual HTML code Firefox is creating for the directory listing to see how to do the CSS definitions right. You will find extensive documentation about userContent.css on the web.</p> <p><a href="http://www.mozilla.org/unix/customizing.html#userContent" rel="nofollow">http://www.mozilla.org/unix/customizing.html#userContent</a></p>
Dynamically include .js files from Zend_Controller_Action? <p>I came across the case where depending on the execution path I may need to invoke an inclusion of .js file from controller. Is there a nice way of doing it? (besides setting some view variable with actual .js include code)?</p>
<p>See the view helper headScript(). I'm just writing this off the top of my head but I think it works like this:</p> <p>From within a view file: <code>$this-&gt;headScript()-&gt;appendFile('filename.js');</code></p> <p>From within a controller: <code>$this-&gt;view-&gt;headScript()-&gt;appendFile('filename.js');</code></p> <p>And then somewhere in your layout you need to echo out your headScript object:</p> <p><code>&lt;?=$this-&gt;headScript();?&gt;</code></p>
If I'm posting a question about Oracle SQL query performance, what should I include in my question? <p>If I am posting a question about a query against an Oracle database, what should I include in my question so that people have a chance to answer me? How should I get this information?</p> <p>Simply providing the poorly performing query may not be enough.</p>
<ul> <li>The schema definition of the tables involved.</li> <li>The indexes defined on those tables.</li> <li>The query you are executing.</li> <li>The resulting query execution plan</li> </ul>
jQuery two sliders controlling each other <p>This is in reference to the <a href="http://stackoverflow.com/questions/282944/jquery-one-slider-controls-another">question</a> previously asked The problem here is, each slider controls the other. It results in feedback. How do I possibly stop it?</p> <pre><code>$(function() { $("#slider").slider({ slide: moveSlider2 }); $("#slider1").slider({ slide: moveSlider1 }); function moveSlider2( e, ui ) { $('#slider1').slider( 'moveTo', Math.round(ui.value) ); } function moveSlider1( e, ui ) { $('#slider').slider( 'moveTo', Math.round(ui.value) ); } }); </code></pre>
<p>This is sort of a hack, but works:</p> <pre><code>$(function () { var slider = $("#slider"); var slider1 = $("#slider1"); var sliderHandle = $("#slider").find('.ui-slider-handle'); var slider1Handle = $("#slider1").find('.ui-slider-handle'); slider.slider({ slide: moveSlider1 }); slider1.slider({ slide: moveSlider }); function moveSlider( e, ui ) { sliderHandle.css('left', slider1Handle.css('left')); } function moveSlider1( e, ui ) { slider1Handle.css('left', sliderHandle.css('left')); } }); </code></pre> <p>Basically, you avoid the feedback by manipulating the css directly, not firing the slide event.</p>
In C#, how do I save a webpage to file without destroying whatever the encoding is? <p>Here's what I got so far (that doesn't work). At this point I thought my target was Ansi encoded, but I really don't want to have to know at this point. My browser seems to be able to determine what encoding to use, How can I?</p> <pre><code>static void GetUrl(Uri uri, string localFileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); // Save the stream to file Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.Default); Stream fileStream = File.OpenWrite(localFileName); using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default)) { sw.Write(reader.ReadToEnd()); sw.Flush(); sw.Close(); } } </code></pre> <p><hr /></p> <p><strong>After answers</strong> (currently only tested on a UTF-8 site):</p> <pre><code>static void GetUrl(Uri uri, string localFileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); try { // Hope GetEncoding() knows how to parse the CharacterSet Encoding encoding = Encoding.GetEncoding(response.CharacterSet); StreamReader reader = new StreamReader(response.GetResponseStream(), encoding); using (StreamWriter sw = new StreamWriter(localFileName, false, encoding)) { sw.Write(reader.ReadToEnd()); sw.Flush(); sw.Close(); } } finally { response.Close(); } } </code></pre>
<p>There are three ways how web-browsers try to detect character encoding.</p> <p>Look for (if it's HTML):</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"&gt; </code></pre> <p>or (for XHTML)</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; </code></pre> <p>or sometimes it's even specified in http header</p> <pre><code>Content-Type: text/html; charset=ISO-8859-1 </code></pre>
Free space in a CMD shell <p>Is there a way to get the amount of free diskspace of a disk or a folder in a CMD without having to install some thirdparty applications?</p> <p>I have a CMD that copies a big file to a given directory and could of course use the errorlevel return from the copy command, but then I have to wait for the time it takes to copy the file (eg...to that then the disk is full and the copy operation fails).</p> <p>I would like to know before I start the copy if it is any idea at all. Tried the DU.EXE utility from Sysinternals, but that show occupied space only.</p>
<p>If you run "<code>dir c:\</code>", the last line will give you the free disk space.</p> <p><strong>Edit:</strong> Better solution: "<code>fsutil volume diskfree c:</code>"</p>
How to use Castle Windsor with ASP.Net web forms? <p>I am trying to wire up dependency injection with Windsor to standard asp.net web forms. I think I have achieved this using a HttpModule and a CustomAttribute (code shown below), although the solution seems a little clunky and was wondering if there is a better supported solution out of the box with Windsor?</p> <p>There are several files all shown together here</p> <pre><code> // index.aspx.cs public partial class IndexPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Logger.Write("page loading"); } [Inject] public ILogger Logger { get; set; } } // WindsorHttpModule.cs public class WindsorHttpModule : IHttpModule { private HttpApplication _application; private IoCProvider _iocProvider; public void Init(HttpApplication context) { _application = context; _iocProvider = context as IoCProvider; if(_iocProvider == null) { throw new InvalidOperationException("Application must implement IoCProvider"); } _application.PreRequestHandlerExecute += InitiateWindsor; } private void InitiateWindsor(object sender, System.EventArgs e) { Page currentPage = _application.Context.CurrentHandler as Page; if(currentPage != null) { InjectPropertiesOn(currentPage); currentPage.InitComplete += delegate { InjectUserControls(currentPage); }; } } private void InjectUserControls(Control parent) { if(parent.Controls != null) { foreach (Control control in parent.Controls) { if(control is UserControl) { InjectPropertiesOn(control); } InjectUserControls(control); } } } private void InjectPropertiesOn(object currentPage) { PropertyInfo[] properties = currentPage.GetType().GetProperties(); foreach(PropertyInfo property in properties) { object[] attributes = property.GetCustomAttributes(typeof (InjectAttribute), false); if(attributes != null &amp;&amp; attributes.Length &gt; 0) { object valueToInject = _iocProvider.Container.Resolve(property.PropertyType); property.SetValue(currentPage, valueToInject, null); } } } } // Global.asax.cs public class Global : System.Web.HttpApplication, IoCProvider { private IWindsorContainer _container; public override void Init() { base.Init(); InitializeIoC(); } private void InitializeIoC() { _container = new WindsorContainer(); _container.AddComponent&lt;ILogger, Logger&gt;(); } public IWindsorContainer Container { get { return _container; } } } public interface IoCProvider { IWindsorContainer Container { get; } } </code></pre>
<p>I think you're basically on the right track - If you have not already I would suggest taking a look at Rhino Igloo, an WebForms MVC framework, <a href="http://ayende.com/Blog/archive/2007/09/03/Rhino-Igloo-ndash-MVC-Framework-for-Web-Forms.aspx">Here's a good blog post on this</a> and the source is <a href="https://rhino-tools.svn.sourceforge.net/svnroot/rhino-tools/trunk/rhino-igloo">here</a> - Ayende (the Author of Rhino Igloo) tackles the issue of using Windsor with webforms quite well in this project/library.</p> <p>I would cache the reflection info if you're going to inject the entire nested set of controls, that could end up being a bit of a performance hog I suspect.</p> <p>Last of all spring.net approaches this in a more configuration-oriented way, but it might be worth taking a look at their implementation - here's a good <a href="http://blogger.forgottenskies.com/?p=70">reference blog post</a> on this.</p>
What is the difference between CIL and MSIL (IL)? <p>Are these two terms interchangeable?</p>
<p>CIL is the term used in the <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">CLI Standard</a>. MSIL is (I suppose) CIL created by MS tools. Effectively they are synonymous.</p> <p><a href="http://blogs.msdn.com/brada/archive/2005/09/20/CILorMSIL.aspx">Brad Abrams says this.</a></p>
Is there a fast way to transfer all the variables of one identical object into another in C#? <p>This is probably a simple question. Suppose I have a object called Users and it contains a lot of protected variables. </p> <p>Inside that Users class I have a method that creates a temporary Users object, does something with it, and if successful, transfers all the variables from the temp Users object into the one I have. </p> <p>Is there some fast way to transfer all the variables from one Users object into another Users object without doing this using C#?</p> <pre><code>this.FirstName = temp.FirstName; this.LastName = temp.LastName; ........75 variables later...... this.FavoriteColor = temp.FavoriteColor </code></pre>
<p>A better approach is to implement the IClonable interface. But you'll find it doesn't save you a lot of work.</p>
How can I automate (script) creating a war file in eclipse? <p>It's 5 button clicks to get eclipse to create a deployable war file for my eclipse project, I figure there's probably some eclipse command line option to do the same thing, so I can just write it into a script, but I'm not seeing it.</p>
<p>Use the <a href="http://ant.apache.org/manual/Tasks/war.html" rel="nofollow">Ant <code>war</code> task</a>, set up a relevant build file and you can just hit the "external tools" button to execute it. </p>
How to expand 'select' option width after the user wants to select an option <p>Maybe this is an easy question, maybe not. I have a select box where I hardcode with width. Say 120px.</p> <pre><code>&lt;select style="width: 120px"&gt; &lt;option&gt;ABC&lt;/option&gt; &lt;option&gt;REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I want to be able to show the second option so that the user can see the full length of the text.</p> <p>Like everything else. This works fine in Firefox, but doesn't work with Internet Explorer6.</p>
<p>I fixed my problem with the following code:</p> <pre><code>&lt;div style="width: 180px; overflow: hidden;"&gt; &lt;select style="width: auto;" name="abc" id="10"&gt; &lt;option value="-1"&gt;Any&lt;/option&gt; &lt;option value="123"&gt;123&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>Hope it helps!</p> <p>Cheers, Cychan</p> <p><hr /></p>
dllimport failed to locate dll even though it is in the PATH <p>I use [Dllimport("DllName.dll")] where I'm sure a path to my dll exists in the process PATH environment variable, and still I get "DllName.dll could not be found"</p>
<p>"DllName.dll could not be found" could also mean that DllImport has not found one of DllName.dll dependencies.</p> <p>Grab <a href="http://www.dependencywalker.com/">Dependecy Walker</a> to check which dependecy you are missing.</p>
Best way to move a data row to another shard? <p>The question says it all. </p> <p>Example: I'm planning to shard a database table. The table contains customer orders which are flagged as "active", "done" and "deleted". I also have three shards, one for each flag.</p> <p>As far as I understand a row has to be moved to the right shard, when the flag is changed. </p> <p>Am I right? What's the best way to do this? Can triggers be used?</p> <p>I thought about not moving the row immediately, but only at the end of the day/week/month, but then it is not determined, in which shard a rows with a specific flag resides and searches have to be done always over all shards.</p> <p>EDIT: Some clarification:</p> <p>In general I have to choose on a criterum to decide, in which shard a row resides. In this case I want it to be the flag described above, because it's the most natural way to shard this kind of data. (In my opinion) There is only a limited number of active orders which is accessed very often. There is a large number of finished orders, which are seldom accessed and there's a very huge number of data rows which are almost never accessed.</p> <p>If I want to now where a specific data row resides I dont have to search all shards. If the user wants to load an active order, I know already in which database I have to look.</p> <p>Now the flag, which is my sharding criterium, changes and I want to know the best way to deal with this case. If I'd just keep the record in its original database, eventually all data would accumulate in a single table.</p>
<p>Sharding usually refer to separating them in different databases on different servers. Oracle can do what you want using a feature called partitioned tables.</p> <p>If you're using triggers (after/before_update/insert), it would be an immediate move, other methods would result in having different types of data in the first shard (active), until it is cleaned-up.</p> <p>I would also suggest doing this by date (like a monthly job that moves anything that's inactive and older than a month to another "Archive" Database).</p> <p>I'd like to ask you to reconsider doing this if you're doing it to increase performance (Unless you have terabytes of data in this table). Please tell us why you want to shard and we'll all think about ways to solve your problem.</p>
Dragging an image in WPF <p>I'm trying to create a WPF application where I can drag an image around.</p> <p>Currently I have an image placed in the center of the window, and I'm thinking of using the three mouseevents MouseDown, MouseMove and MouseUp to calculate the new position when dragging the image.</p> <p>Are there any other good ideas on how to do this? I'm totally new to WPF so my mindset is still in the Windows Forms world.</p> <p>As far as I can see I need to use a in order to have absolute positioning available.</p>
<p>ok, here's an attached property "behaviour" that you can use to make any element draggable provided it's on a canvas:</p> <pre><code>public class DraggableExtender : DependencyObject { // This is the dependency property we're exposing - we'll // access this as DraggableExtender.CanDrag="true"/"false" public static readonly DependencyProperty CanDragProperty = DependencyProperty.RegisterAttached("CanDrag", typeof(bool), typeof(DraggableExtender), new UIPropertyMetadata(false, OnChangeCanDragProperty)); // The expected static setter public static void SetCanDrag(UIElement element, bool o) { element.SetValue(CanDragProperty, o); } // the expected static getter public static bool GetCanDrag(UIElement element) { return (bool) element.GetValue(CanDragProperty); } // This is triggered when the CanDrag property is set. We'll // simply check the element is a UI element and that it is // within a canvas. If it is, we'll hook into the mouse events private static void OnChangeCanDragProperty(DependencyObject d, DependencyPropertyChangedEventArgs e) { UIElement element = d as UIElement; if (element == null) return; if (e.NewValue != e.OldValue) { if ((bool)e.NewValue) { element.PreviewMouseDown += element_PreviewMouseDown; element.PreviewMouseUp += element_PreviewMouseUp; element.PreviewMouseMove += element_PreviewMouseMove; } else { element.PreviewMouseDown -= element_PreviewMouseDown; element.PreviewMouseUp -= element_PreviewMouseUp; element.PreviewMouseMove -= element_PreviewMouseMove; } } } // Determine if we're presently dragging private static bool _isDragging = false; // The offset from the top, left of the item being dragged // and the original mouse down private static Point _offset; // This is triggered when the mouse button is pressed // on the element being hooked static void element_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { // Ensure it's a framework element as we'll need to // get access to the visual tree FrameworkElement element = sender as FrameworkElement; if (element == null) return; // start dragging and get the offset of the mouse // relative to the element _isDragging = true; _offset = e.GetPosition(element); } // This is triggered when the mouse is moved over the element private static void element_PreviewMouseMove(object sender, MouseEventArgs e) { // If we're not dragging, don't bother - also validate the element if (!_isDragging) return; FrameworkElement element = sender as FrameworkElement; if (element == null) return; Canvas canvas = element.Parent as Canvas; if( canvas == null ) return; // Get the position of the mouse relative to the canvas Point mousePoint = e.GetPosition(canvas); // Offset the mouse position by the original offset position mousePoint.Offset(-_offset.X, -_offset.Y); // Move the element on the canvas element.SetValue(Canvas.LeftProperty, mousePoint.X); element.SetValue(Canvas.TopProperty, mousePoint.Y); } // this is triggered when the mouse is released private static void element_PreviewMouseUp(object sender, MouseButtonEventArgs e) { _isDragging = false; } } </code></pre> <p>You can then use this in your XAML by importing the namespace your class is contained in (something like this:)</p> <pre><code>&lt;Window x:Class="WPFFunWithDragging.Window1" xmlns:local="clr-namespace:WPFFunWithDragging" .. &gt; </code></pre> <p>And then you can just set DraggableExtender.CanDrag="true" on elements to drag around:</p> <pre><code>&lt;Canvas&gt; &lt;Image Source="Garden.jpg" Width="50" Canvas.Left="10" Canvas.Top="10" local:DraggableExtender.CanDrag="true"/&gt; &lt;/Canvas&gt; </code></pre> <p>Hope this is of some use :)</p>
How do I retrieve an HTML element's actual width and height? <p>Suppose that I have a <code>&lt;div&gt;</code> that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <code>&lt;div&gt;</code> element. </p> <p>What should I use? Please include information on browser compatibility.</p>
<p>You should use the <code>.offsetWidth</code> and <code>.offsetHeight</code> properties. Note they belong to the element, not <code>.style</code>.</p> <p><code>var width = document.getElementById('foo').offsetWidth;</code></p>
How do you call a constructor for global objects, for arrays of objects, and for objects inside classes/structs? <p>How would you call the constructor of the following class in these three situations: Global objects, arrays of objects, and objects contained in another class/struct?</p> <p>The class with the constructor (used in all three examples):</p> <pre><code>class Foo { public: Foo(int a) { b = a; } private: int b; }; </code></pre> <p>And here are my attempts at calling this constructor:</p> <h2>Global objects</h2> <pre><code>Foo global_foo(3); // works, but I can't control when the constructor is called. int main() { // ... } </code></pre> <h2>Arrays of objects</h2> <pre><code>int main() { // Array on stack Foo array_of_foos[30](3); // doesn't work // Array on heap Foo *pointer_to_another_array = new Foo(3) [30]; // doesn't work } </code></pre> <p>There I'm attempting to call the constructor for all elements of the arrays, but I'd also like to know how to call it on individual elements.</p> <h2>Objects contained in classes/structs</h2> <pre><code>class Bar { Foo foo(3); // doesn't work }; int main() { Bar bar; } </code></pre>
<h3>Global objects</h3> <p>Yours is the only way. On the other hand, try to avoid this. It’s better to use functions (or even other objects) as factories instead. That way, you can control the time of creation.</p> <h3>Arrays of objects</h3> <p>There’s no way to do this directly. Non-POD objects will always be default-constructed. <code>std::fill</code> is often a great help. You might also want to look into allocators and <code>std::uninitialized_fill</code>.</p> <h3>Objects contained in classes/structs</h3> <p>Use initialization lists in your constructor:</p> <pre><code>class Bar { Foo foo; Bar() : foo(3) { } }; </code></pre> <p>Static members must actually be defined outside the class:</p> <pre><code>class Bar { static Foo foo; }; Foo Bar::foo(3); </code></pre>
How do I get the mouse button pressed from a command event in XUL? <p>It seems that the XUL <em>command</em> and <em>click</em> events are somewhat different.</p> <p>Although my function does get called when using the <em>command</em> event, the event object does not contain the <em>button</em> property.</p> <p>My question is: <strong>how do I detect what mouse button that was pressed without using the <em>click</em> event?</strong></p> <p>The simplest code that can demonstrate my problem:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;?xml-stylesheet href="chrome://global/skin/" type="text/css"?&gt; &lt;window id="yourwindow" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"&gt; &lt;script language="JavaScript"&gt; var showMeTheButton=function(e) { alert(e.button); } &lt;/script&gt; &lt;button onclick="showMeTheButton(event)" label="Click me with onclick"&gt;&lt;/button&gt; &lt;button oncommand="showMeTheButton(event)" label="Click me with oncommand"&gt;&lt;/button&gt; &lt;/window&gt; </code></pre>
<p>The main thing to keep in mind is that <code>oncommand</code> is fired for any action that results in an activation of the button which can include pressing the space bar when the button has the focus, using a keyboard shortcut attached to the button, or clicking the button with the mouse. The event handler is not really supposed to care how it was called, only that it was. (I imagine this was a conscious decision to keep a consistent user interface.)</p> <p>The only actions that result in the button property being added to the Event object are <code>onclick</code>, <code>ondblclick</code>, <code>onmousedown</code>, and <code>onmouseup</code>. You'll note that even if you disable your <code>onclick</code> button, the event still fires whereas with <code>oncommand</code> it won't.</p> <p>To get the same functionality as <code>oncommand</code>, you'd need to handle both <code>onclick</code> and <code>onkeydown</code> events yourself while making sure the button is still enabled. You also might be able to create a custom button using XBL which have custom events like <code>onleftclick</code> or <code>onmiddleclick</code> that then fall back to <code>oncommand</code> if they are not set--but I've not tried it.</p>
NHibernate, Codesmith and project physical architecture <p>Recently I tried CodeSmith templates for NHibernate. As many of you might watched, there is a video explaining how to create a Petshop.Data using these templates. My question is what is the correct architecture in this approach? Should we have a BLL (or Services) layer to interact with this Petshop.Data or directly call ManagerFactory in our presentation layer? Also should our presentation layer be unaware of Business Objects in our Petshop.Data and shoud we have Business Entities in BLL again?</p>
<p>Please feel free to address these issues in our <a href="http://community.codesmithtools.com/Template_Frameworks/f/67.aspx" rel="nofollow">community site</a> and on our <a href="http://code.google.com/p/codesmith/issues/list?can=2&amp;q=Framework-NHibernate" rel="nofollow">template bug tracker</a>. We take all feedback seriously and look over it daily.</p> <p>Thanks -Blake Niemyjski</p>
How do I find userid by login (Python under *NIX) <p>I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find <code>uid</code> if I have <code>login</code>?</p> <p>I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?</p>
<p>You might want to have a look at the <a href="http://docs.python.org/library/pwd.html">pwd</a> module in the python stdlib, for example:</p> <pre><code>import pwd pw = pwd.getpwnam("nobody") uid = pw.pw_uid </code></pre> <p>it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually</p>
What are some techniques for code generation? <p>I'm generating C++ code, and it seems like it's going to get very messy, even my simple generating classes already have tons of special cases. Here is the code as it stands now: <a href="http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp" rel="nofollow">http://github.com/alex/alex-s-language/tree/local%2Fcpp-generation/alexs_lang/cpp</a> .</p>
<p>I wrote <a href="http://nedbatchelder.com/code/cog/index.html">Cog</a> partly to generate C++ code from an XML data schema. It lets you use Python code embedded in C++ source files to generate C++ source.</p>
Algorithm to match preferred partners into groups of three <p>What's a good algorithm to solve this problem?</p> <p>I have three groups of people - group A, group B, and group C. There are the same number of people in each group. They each have a list of people in the other groups that they're willing to work with. I want to group all these people together in groups of 3 (one from A, one from B, and one from C) such that everyone in a group wants to work with the other people in their group. </p> <p>How can I find these groups in a fast way? If there's no way to make everyone happy, then the algorithm should first make as many groups have three people who want to work with each other, and then make as many people in the other groups happy.</p> <p>One final point: people agree on who they want to work with (if person x wants to work with person y, then y also wants to work with x). If you could also give a big-O of the running time of your algorithm, that'd be great!</p>
<p>This is like the stable marriage problem, but with 3 parties instead of two.</p> <p>Have a look at efficient solutions for former problem (bi-partite graph matching) and adapt them to your needs.</p> <p><a href="http://en.wikipedia.org/wiki/Stable_marriage_problem">http://en.wikipedia.org/wiki/Stable_marriage_problem</a></p> <p>One adaptation could be to first build working pairs from groups A and B only. Then these pairs have to be paired with a worker from group C each. Let the pairs only prefer workers which both members of the pair agree on (given their lists). Note that this will only give a local optimum.</p> <p>An optimal solution to k-partite matching is NP-hard to find:</p> <p><a href="http://www.math.tau.ac.il/~safra/PapersAndTalks/k-DM.ps">http://www.math.tau.ac.il/~safra/PapersAndTalks/k-DM.ps</a></p> <p>See this paper for a non-optimal solution to the k-partite matching problem:</p> <p><a href="http://books.google.com/books?id=wqs31L1MF4IC&amp;pg=PA309&amp;lpg=PA309&amp;dq=k-partite+matching&amp;source=bl&amp;ots=kgBuvi7ym_&amp;sig=j3Y-nyo51y8qp0-HwToyUlkao4A&amp;hl=de&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result">http://books.google.com/books?id=wqs31L1MF4IC&amp;pg=PA309&amp;lpg=PA309&amp;dq=k-partite+matching&amp;source=bl&amp;ots=kgBuvi7ym_&amp;sig=j3Y-nyo51y8qp0-HwToyUlkao4A&amp;hl=de&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result</a></p> <p>I'm sure you can find others on Google yourself now that you know the terms to search for. I don't know if there is an efficient algorithm giving the optimal solution for k=3.</p>
How to improve performance of an Abstract Factory when all the time appears to be spent in memory allocation <p>The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory). It's too slow. Profiling says all the time is spent in <code>operator new</code>.</p> <p>Notes: The application already uses a custom memory allocator that does pooling. The compiler is VC++ 6.0 and the code uses the old RogueWave collections rather than the STL.</p> <p>The only idea I have right now is to introduce Object Pooling. I'd maintain large collections of pre-allocated objects for each type and re-use them. But this will be a lot of work in this old code, and I'm not yet sure there's enough re-use that it would even help. I was hoping someone smarter than me has an idea.</p>
<p>The only way is to reduce the number of memory allocations. Have you used a profiler that will tell you exactly what is doing the allocation? Are you possibly doing some string manipulation?<br /> If all the time is spent allocating the objects the factory is creating, you may need to go to a pool. </p>
How does ASP.NET MVC communicate w/ an AJAX enabled webpage? <p>How does the data go from the MVC to the browser and back again? Does it use Microsoft's own technology like ASMX or WCF or something completely different? </p> <p>This sounds like MVC is using a ASMX Web Service they are using but I can't seem to find any documentation which gives the real answer. </p>
<p>The data from the MVC app &lt;-> browser is just plain ole HTTP request/response data. To see what this raw data is, install <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow" title="FireBug:Firefox addon">Firebug</a> or <a href="https://addons.mozilla.org/en-US/firefox/addon/1843" rel="nofollow" title="FireBug:Firefox addon">Fiddler</a> on your PC and use that to show you the raw in and out data. It's all pretty simple.</p> <p>WebForms use this same request/response model. the browser passes some info to the webserver (ie. the Request ... like .. i want to see <a href="http://www.mysite.com/foo" rel="nofollow">http://www.mysite.com/foo</a>) and the web server replies with some html, json, xml, binary data (for images), etc... this is the Response.</p> <p>All browsers talk to all websites using this <em>Request/Response</em> model.</p> <p>Now .. the difference with MVC and WebForms is HOW the webserver handles the request and how it generates the response. So they both follow the same concept, just handle it differently. For example, MVC uses controllers to determine what to show the user, while WebForms have a 'pages' which determine what data (for that page) to show.</p> <p>So - in essence - you program your site to say:</p> <ul> <li>If a user goes <em>here</em>, then <em>show</em> them <em>this data</em>.</li> </ul>
How do you show animated gifs with .NET Compact Framework <p>I would like to display an animated gif on a .NET Compact <code>Form</code>. Currently I use a <code>PictureBox</code> control and toggle between <code>.Visible = true</code> and <code>.Visible = false</code>.</p> <p>After <code>.Visible = true</code> the gif is shown however it's not animated. How can I get the .NET Compact Framework to animate it?</p> <p>I already tried <a href="http://stackoverflow.com/questions/165735/how-do-you-show-animated-gifs-on-a-windows-form-c">this</a> but it doesn't work.</p>
<p>By default the .Net Compact framework does not support displaying GIF based animations on a Windows Form. It is possbile to code up a custom animator that will essentially do the same. Here's a link to a sample class for displaying a GIF on the compact framework.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa446483.aspx">http://msdn.microsoft.com/en-us/library/aa446483.aspx</a></p>
ASP.NET MVC - User Input and Service/Repository - Where to do Validation? <p>This might be too opinionated a question, but looking for help!</p> <p>I have been trying to refine my ASP.NET MVC program structure. I just started using it at preview 5 and it is my first foray into business application development -- so everyting is new!</p> <p>At the controller level, I have a service object responsible for talking to the repository and taking care of all business logic. At the action level, I have an object that holds all view data -- user input and generated output -- that I'll call view object (is there a general term for this?). Unlike most examples I see, this object is not a database object, but an object specific to the view.</p> <p>So now I want to add user validation. The problem is, I'm not sure where to put it. It makes the most sense to me to do it in the Service layer. The Service layer is responsible for all the business logic and validation is business logic. On the other hand, most validation frameworks that I see are for validating an object, which makes me think the view object should be validation aware. Finally, there are some validation methods that would require a database connection (checking if a user input field has a corresponding database record for example), and the view object has no concept of a database, only the Service.</p> <p>So some options I see are:</p> <ul> <li>Do validation in the Service.Method on the parameters passed to the method.</li> <li>Do validation in the view object before calling Service.Method.</li> <li>Do validation in the view object but make the Service.Method require a view object reference so it is initiating the validation on the object.</li> </ul> <p>I'm sure there are more. I'm curious of how other people handle user input validation in the MVC sense. I've previously used the Enterprise Validation Block and liked being able to use stock validators for everything, but I'm not sure how to make it fit into a seperate view object and service layer. It would be easy if they (view object / service) were the same object, which is maybe what people do? Like I said, its all new to me and I'm looking for best practice / patterns.</p>
<p>I typically do basic validation (required fields, email format, etc.) in the controller action when the form is submitted. I then let the business layer handle validation that requires business knowledge. I usually double check the basic stuff in the business layer as well, so if I expose that logic through web services or use it in another application later, I still have validation where it is most important (IMO).</p>
Pycurl WRITEDATA WRITEFUNCTION collision/crash <p>How do I turnoff WRITEFUNCTION and WRITEDATA?</p> <p>Using pycurl I have a class call curlUtil. In it I have pageAsString (self, URL) which returns a string. </p> <p>To do this I setopt WRITEFUNCTION. Now in downloadFile (self, URL, fn, overwrite=0) I do an open and self.c.Setopt (pycurl.WRITEFUNCTION, 0) which cause problems. Int is not a valid argument. </p> <p>I then assumed WRITEDATA would overwrite the value or there would be a NOWRITEFUNCTION commend. NOWRITEFUNCTION didn't exist so I just used WRITEDATA and Python crashed. </p> <p>I wrote a quick func called reboot() which closes curl, opens it again, and calls reset to put it in the default state. I call it in both pageAsString and downloadFile and there is no problem at all. But, I don't want to reinitialize curl. There might be some special options I set. </p> <p>How do I turnoff WRITEFUNCTION and WRITEDATA?</p>
<p>using the writefunction, instead of turning it off would save you a lot off trouble. you might want to rewrite your pageAsString by utilizing WRITEFUNCTION..</p> <p>as an example: </p> <pre><code>from cStringIO import StringIO c = pycurl.Curl() buffer = StringIO() c.setopt(pycurl.WRITEFUNCTION, buffer.write) c.setopt(pycurl.URL, "http://example.com") c.perform() ... buffer.getvalue() # will return the data fetched. </code></pre>
Using Stomp and Apache ActiveMQ as reliable syslog <p>One of my programs requires a reliable way to log across unreliable network (ie internet). The sender or receiver may go offline any time and can come back later. But any message sent by client should not be missed. Obviously syslog does not fit the bill. I am exploring the use of messaging servers like Apache ActiveMQ instead of syslog. Message senders are in perl, ruby and c. So I have Stomp as the message transport. </p> <p>Does this serve my purpose? Is there any pitfall I am missing here?</p> <p>raj</p>
<p>That all sounds fine to me</p>
Embedding XULRunner application on Java <p><strong>My goal is to get Limewire(JAVA) and Songbird(XULRunner) to run together.</strong></p> <p>I was thinking the best way is to run the XUL application(songbird) inside a JAVA swing panel. Is there another way?</p> <p>Would it be better or possible to have the GUI entirely in XUL, and then access my JAVA objects somehow?</p> <p>How would I go about doing this?</p> <p>Thanks</p>
<p>Take a look at <a href="http://jrex.mozdev.org/" rel="nofollow">JRex</a>, as it might let you peek into a couple of ideas.</p> <p>Other than that, I'd also research about <a href="http://zelea.com/project/textbender/o/rhinohide/description.xht" rel="nofollow">Rhinohide</a> as well.</p>
Requesting memory for your application <p>I am having a similar issue to <a href="http://stackoverflow.com/questions/28387/sql-server-2k5-memory-consumption">this person</a>. The primary difference being the application is NOT meant for a developer environment, and therefore I need to know how to optimize the space used by Sql Server (possibly per machine based on specs).</p> <p>I was intrigued by <a href="http://stackoverflow.com/users/10795/ricardo-c">Ricardo C's</a> answer, particularly the following:</p> <blockquote> <p>Extracted fromt he SQL Server documentation:</p> <p>Maximum server memory (in MB)</p> <p>Specifies the maximum amount of memory SQL Server can allocate when it starts and while it runs. This configuration option can be set to a specific value if you know there are multiple applications running at the same time as SQL Server and you want to guarantee that these applications have sufficient memory to run. If these other applications, such as Web or e-mail servers, request memory only as needed, then do not set the option, because SQL Server will release memory to them as needed. <strong>However, applications often use whatever memory is available when they start and do not request more if needed</strong>. If an application that behaves in this manner runs on the same computer at the same time as SQL Server, set the option to a value that guarantees that the memory required by the application is not allocated by SQL Server.</p> </blockquote> <p>My question is: how does an application request memory from the OS when it needs it? Is this something built into compilation or something managed by the developer? The two primary apps running on this machine are Sql Server and the (fairly heavyweight) C# application I'm developing, and I'm almost certain we didn't specifically do anything in the realm of asking the OS for memory. Is there a correct/necessary way to do this?</p>
<p>Some applications allocate a lot of memory at startup, and then run their own memory management system on it. This can be good for applications that have particular allocation patterns, and that feel they can do a better job than the more generic memory manager provided by the runtime system.</p> <p>Many games do this, since they often have a very good idea of how their memory usage pattern is going to look, and often are heavily optimized. The default/system allocator is general-purpose and not always fast enough. <a href="http://doom.wikia.com/wiki/Zone_memory" rel="nofollow">Doom did this</a>, and is fairly well-known for it and of course its code is available and widely discussed.</p> <p>In "managed" languages like C# I think this is very rare, and nothing you need to worry about.</p>
c# Pre-processor directive scope <p>I'm looking to use: </p> <pre><code>#define </code></pre> <p>and</p> <pre><code>#if </code></pre> <p>to allow me to simulate potentially absent hardware during unit tests. What are the rules for using the <code>#define</code> statements? </p> <p>i.e. what is its default scope? can I change the scope of the directive?</p>
<p>As Chris said, the scope of #define is just the file. (It's worth noting that this isn't the same as "the class" - if you have a partial type, it may consist of two files, one of which has symbol defined and one of which doesn't!</p> <p>You can also define a symbol project-wide, but that's done with <a href="http://msdn.microsoft.com/en-us/library/c7f8bfy4.aspx">project properties</a> or a <a href="http://msdn.microsoft.com/en-us/library/0feaad6z.aspx">compiler switch</a> rather than being specified in source code.</p>
C++ mark as deprecated <p>I have a method in an interface that I want to deprecate with portable C++. When I Googled for this all I got was a Microsoft specific solution; <a href="http://msdn.microsoft.com/en-us/library/c8xdzzhh(VS.80).aspx">#pragma deprecated</a> and <a href="http://msdn.microsoft.com/en-us/library/044swk7y(VS.80).aspx">__declspec(deprecated)</a>.</p> <p>A second prize solution would be to ifdef a MSVC and a GCC solution.<br> Thanks</p>
<p>This should do the trick:</p> <pre><code>#ifdef __GNUC__ #define DEPRECATED(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define DEPRECATED(func) __declspec(deprecated) func #else #pragma message("WARNING: You need to implement DEPRECATED for this compiler") #define DEPRECATED(func) func #endif ... //don't use me any more DEPRECATED(void OldFunc(int a, float b)); //use me instead void NewFunc(int a, double b); </code></pre> <p>However, you will encounter problems if a function return type has a commas in its name e.g. <code>std::pair&lt;int, int&gt;</code> as this will be interpreted by the preprocesor as passing 2 arguments to the DEPRECATED macro. In that case you would have to typedef the return type.</p> <p>Edit: simpler (but possibly less widely compatible) version <a href="http://stackoverflow.com/a/21265197/2651243">here</a>.</p>
How to pass an unpersisted modified object from view back to controller without a form? <p><em>Short:</em> how does modelbinding pass objects from view to controller?</p> <p><em>Long:</em><br /> First, based on the parameters given by the user through a search form, some objects are retrieved from the database. These objects are given meta data that are visible(but not defining) to the customer (e.g: naming and pricing of the objects differ from region to region).<br /> Later on in the site, the user can click links that should show details of these objects. Because these meta data are important for displaying, but not defining, I need to get the previously altered object back in the controller. When I use the default asp.net mvc modelbinding, the .ToString() method is used. This off course doesn't return a relevant string for recreating the complete object.<br /> I would have figured the ISerializable interface would be involved, but this is not so. How should I go about to get the desired effect? I can't imagine I'm the first one to be faced with this question, so I guess I'm missing something somewhere...</p>
<p>The default model binding takes form parameters by name and matches them up with the properties of the type specified in the argument list. For example, your model has properties "Price" and "Name", then the form would need to contain inputs with ids/names "Price" and "Name" (I suspect it does a case insensitive match). The binder uses reflection to convert the form values associated with these keys into the appropriate type and assigns it to the properties of a newly created object of the type specified by the parameter (again derived by reflection).</p> <p>You can actually look at (and download) the source for this at <a href="http://www.codeplex.com/aspnet" rel="nofollow">http://www.codeplex.com/aspnet</a>, although you'll have to drill down into the MVC source from there. I'd give a link to the DefaultModelBinder source, but the way they are constructed, I believe the link changes as revisions are introduced.</p> <p>So, to answer your question, you need to have parameters (could be hidden) on your form that correspond to the properties of the object that you want to recreate. When you POST the form (in the view) to the controller, the binder should reconstitute an object of the specified type using the form parameters. If you need to do translation from the values in the form parameter to the object properties, you'll probably need to implement your own custom model binder.</p> <p>[EDIT] In response to your second post:</p> <p>Let's say that we want to have a link back to an action that uses a customized object. We can store the customized object in TempData (or the Session if we need it to last more through more than one postback) with a particular key. We can then construct the action link and provide the key of the object as value to the ActionLink in an anonymous class. This will pass back the key as a Request parameter. In our action we can use the key from this parameter to retrieve the object from TempData.</p> <pre><code>&lt;%= Html.ActionLink( ViewData["CustomObject1", "Select", new { TempDataKey = ViewData["CustomObject1_Key"] } ) %&gt; &amp;nbsp; public ActionResult Select() { Entity custObj = null; string objKey = Request.Params["TempDataKey"]; if (!string.IsNullOrEmpty(objKey)) { custObj = (Entity)TempData[objKey]; } ... continue processing } </code></pre>
How can I achieve uploading same files as a batch using jQuery? <p>When uploading some image/audio/video files in the same batch I want the file selected in the one field should not get accepted in the other buttons. How can I achieve this?</p>
<p>I think you are asking how to make it so no two files in a list of file upload boxes are the same, so you don't accidentally upload the same file twice.</p> <p>This could be easily done using the input.onchange event. When you add a new file input box, assign its onchange event to a function like this one:</p> <pre><code>function fileChanged() { $(createFileInput()).insertAfter(this).wrap('&lt;p&gt;' + '&lt;/p&gt;').change(fileChanged); if(!isFileUnique(this)) { $(this).remove(); alert('You already chose to upload this file.\nPlease choose a different file.'); return false; } return true; } </code></pre> <p>Use some helper functions:</p> <pre><code>function isFileUnique(input) { if(input.value == '') return true; var fileInputs = $(input).parents('form').find('input:file'); var sameInputs = $.grep(fileInputs, function(item, index) { if(item == input) return false; if(item.value == input.value) return true; return false; }); return sameInputs.length == 0; } function createFileInput() { var input = document.createElement('input'); input.type = 'file'; return input; } </code></pre> <p>Things are a little complicated because you can't do a mere "this.value = '';" So we just delete "this" and create a new input field. We need to create a new one anyway (so the user can upload an extra file), so it the issue is counteracted.</p> <p>(Return values for fileChanged aren't needed, because I don't think file inputs will allow Javascript to ignore the change command.)</p>
Get SQL Server database folder of selected instance by using vbscript <p>Assume that you have a running SQL Server Express instance named (local)\SQLEXPRESS. Its database folder is c:\program files\Microsoft SQL Server\MSSQL.1\MSSQL\Data. </p> <p>How can VBScript be used to retrieve that folder? </p> <p>Maybe by using SMO? And if so, how? &lt;- Forget that. SMO uses .NET. Only possible in PowerShell.</p> <p><hr /></p> <p><strong>Update:</strong> The reason for this is, that I am developing an MSI setup that uses a custom action (call to a .NET based assembly) for attaching mdf Files to an existing SQL server instance. for this, the .mdf files get transferred from the installation medium to the hard drive. So the setup needs to know where to place the files.</p> <p>Since I would like to support the standards, I need to place the files into the common data folder.</p> <p><hr /></p> <p><strong>Update:</strong> When selecting a SQL server instance in InstallShield, the Property IS _ SQLSERVER _ SERVER is set with the instance name.</p> <p>I found out, that I can query the registry under HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL to get the SQL name for the instance name (e.g. SQLEXPRESS -> MSSQL.1).</p> <p>With this information, I can query HKLM\Software\Microsoft\Microsoft SQL Server\MSSQL.1\Setup to retrieve the SQLDataRoot key. When I append a \Data to the value found here, I have the folder, I was looking for. </p> <p>However, is there a better way?</p>
<p>The <a href="http://technet.microsoft.com/en-us/library/ms144134.aspx" rel="nofollow">PrimaryFilePath Property</a> of <a href="http://technet.microsoft.com/en-us/library/ms133993.aspx" rel="nofollow">SQL-DMO</a> looks interesting. </p> <p>The MSDN states that SQL-DMO is deprecated as of SQL Server 2008, but for now it should still be working.</p> <p>If you don't want to use SQL-DMO anymore, I guess there might be something usable in the <code>root\Microsoft\SqlServer</code> namespace of WMI. But Microsoft has either hidden it very well or my search skills have left me, at the moment I cant find anything in this regard.</p> <p><em>(EDIT: Removed something that did not answer the question.)</em></p> <p>The default data path is also stored in the registry:</p> <pre> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\DefaultData </pre> <p>I'm not sure where instances write their data, but it must be somewhere in the logical vicinity.</p>
How to call a Delphi DLL from VB6 <p>Given the following Delphil DLL declaration</p> <pre><code>function csd_HandleData(aBuf: PChar; aLen: integer): integer; stdcall; </code></pre> <p>what would be the VB6 declaration to use it?</p> <p>I've tried a variety of declarations, e.g.</p> <pre><code>Declare Function csd_HandleData Lib "chsdet.dll" (ByVal aBuf As String, ByVal aLen As Integer) Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Long, ByVal aLen As Integer) Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Byte, ByVal aLen As Integer) </code></pre> <p>with the relevant code to suit the parameters, but nothing seems to work, i.e. the Delphi debugger says I have a too-largish value in aLen and a null string in aBuf.</p> <p>I am working toward using a TypeLib to drive the connection, but was prototyping with Declares.</p>
<p>try</p> <pre><code>Declare Function csd_HandleData Lib "chsdet.dll" (ByVal aBuf As String, ByVal aLen As Integer) As Integer </code></pre> <p>Seems you forgot the return value.</p>
css layers ordering and arranging <p>I am trying to have one one layer, and center images within. I.E., if I have 3 images and want 3 links beneath them, is there a way to do this without using a separate div tag for each link and image? To automatically make the links be centered under the images, and the images to be spaced evenly within a layer? </p> <p>I was also wondering how I would make the div show behind standard html if that is possible. I.E. if I have some text and a div over the text, the div will default show over the text, when I would like it to be behind. Is this only possible by using another layer?</p>
<p>Yes, you'll have to put a container element, such as a div, around each image and its caption to keep them together.</p> <pre><code>&lt;div class="pictureBox"&gt; &lt;div&gt; &lt;img /&gt; caption caption &lt;/div&gt; &lt;div&gt; &lt;img /&gt; more caption &lt;/div&gt; &lt;/div&gt; -------- .pictureBox div { text-align: center; /* whatever width/height/positioning you want */ } </code></pre> <p>for the second part of the question, regarding putting it behind the other text, take a look at <a href="http://www.w3schools.com/css/pr_pos_z-index.asp" rel="nofollow">CSS z-index</a>, though I think that only applies to absolutely positioned elements.</p>
What is a partial class? <p>What is and how can it be used in C#.<br/> Can you use the same concept in Python/Perl?</p>
<p>A <a href="http://msdn.microsoft.com/en-us/library/wa80x488.aspx">partial type</a> (it doesn't have to be a class; structs and interfaces can be partial too) is basically a single type which has its code spread across multiple files.</p> <p>The main use for this is to allow a code generator (e.g. a Visual Studio designer) to "own" one file, while hand-written code is put in another.</p> <p>I've no idea whether Python/Perl have the same capabilities, I'm afraid.</p>
what does this preg_replace_callback do in PHP? and how do I stop it leaking memory? <p>I've got a section of code on a b2evo PHP site that does the following: </p> <pre><code>$content = preg_replace_callback( '/[\x80-\xff]/', create_function( '$j', 'return "&amp;#".ord($j[0]).";";' ), $content); </code></pre> <p>What does this section of code do? My guess is that it strips out ascii characters between 128 and 256, but I can't be sure. </p> <p>Also, as it stands, every time this bit of code is called from within a page, PHP allocates and then does not free upto 2K of memory. If the function is called 1000+ times on a page (this can happen), then the page uses an extra 2MB of memory. </p> <p>This is causing problems with my web application. Why am I losing memory, and how do I rewrite this so I don't get a memory leak?</p>
<p>It's <code>create_function</code> that's leaking your memory - just use a normal function instead and you'll be fine.</p> <p>The function itself is replacing the characters with numeric HTML entities (<code>&amp;#xxx;</code>)</p>
Logging every data change with Entity Framework <p>There is a need from a customer to log every data change to a logging table with the actual user who made the modification. The application is using one SQL user to access the database, but we need to log the "real" user id.</p> <p>We can do this in t-sql by writing triggers for every table insert and update, and using context_info to store the user id. We passed the user id to a stored procedure, stored the user id in the contextinfo, and the trigger could use this info to write log rows to the log table.</p> <p>I can not find the place or way where or how can I do something similar using EF. So the main goal is: if I make a change in the data via EF, I would like to log the exact data change to a table in a semi-automatic way (so I don't want to check for every field for change before saving the object). We are using EntitySQL.</p> <p>Unfortunately we have to stick on SQL 2000 so the data change capture introduced in SQL2008 is not an option (but maybe that's also not the right way for us).</p> <p>Any ideas, links or starting points?</p> <p><strong>[Edit]</strong> Some notes: by using ObjectContext.SavingChanges eventhandler, I can get the point where I can inject the SQL statement to initialize the contextinfo. However I cannot mix the EF and the standard SQL. So I can get the EntityConnection but I cannot execute a T-SQL statement using it. Or I can get the connection string of the EntityConnection and create an SqlConnection based on it, but it will be a different connection, so the contextinfo will not affect the save made by the EF.</p> <p>I tried the following in the SavingChanges handler:</p> <pre><code>testEntities te = (testEntities)sender; DbConnection dc = te.Connection; DbCommand dcc = dc.CreateCommand(); dcc.CommandType = CommandType.StoredProcedure; DbParameter dp = new EntityParameter(); dp.ParameterName = "userid"; dp.Value = textBox1.Text; dcc.CommandText = "userinit"; dcc.Parameters.Add(dp); dcc.ExecuteNonQuery(); </code></pre> <p>Error: The value of EntityCommand.CommandText is not valid for a StoredProcedure command. The same with SqlParameter instead of EntityParameter: SqlParameter cannot be used.</p> <pre><code>StringBuilder cStr = new StringBuilder("declare @tx char(50); set @tx='"); cStr.Append(textBox1.Text); cStr.Append("'; declare @m binary(128); set @m = cast(@tx as binary(128)); set context_info @m;"); testEntities te = (testEntities)sender; DbConnection dc = te.Connection; DbCommand dcc = dc.CreateCommand(); dcc.CommandType = CommandType.Text; dcc.CommandText = cStr.ToString(); dcc.ExecuteNonQuery(); </code></pre> <p>Error: The query syntax is not valid.</p> <p>So here I am, stuck to create a bridge between Entity Framework and ADO.NET. If I can get it working, I will post a proof of concept.</p>
<p>How about handling Context.<a href="http://msdn.microsoft.com/en-us/library/cc716714.aspx">SavingChanges</a>?</p>
Help with XML-RPC server <p>I'm now trying to create a xml-rpc server with the CodeIgniter Framework. </p> <pre><code>&lt;?php $this-&gt;load-&gt;library('xmlrpc'); $this-&gt;load-&gt;library('xmlrpcs'); $config['functions']['weblogUpdates.ping'] = array('function' =&gt; 'weblogUpdates.ping'); $config['functions']['ping'] = array('function' =&gt; 'weblogUpdates.ping'); $config['functions']['weblogUpdates'] = array('function' =&gt; 'weblogUpdates.ping'); $config['object'] = $this; $this-&gt;xmlrpcs-&gt;serve(); ?&gt; </code></pre> <p>But the problem I have is when Wordpress is trying to ping my file. I can't figure out what I should have as function in the $config['functions'][HERE];</p> <p>Anyone have a solution to this?</p>
<p>Have you looked at <a href="http://codeigniter.com/user_guide/libraries/xmlrpc.html" rel="nofollow">the codeigniter user guide</a>?</p>
.net remoting stops every 100 seconds <p>We have very strange problem, one of our applications is continually querying server by using .net remoting, and every 100 seconds the application stops querying for a short duration and then resumes the operation. The problem is on a client and not on the server because applications actually queries several servers in the same time and stops receiving data from all of them in the same time.</p>
<p>100 Seconds is a give away number as it's the default timeout for a webrequest in .Net.</p> <p>I've seen in the past that the PSI (Project Server Interface within Microsoft Project) didn't override the timeout and so the default of 100 seconds was applied and would terminate anything talking to it for longer than that time.</p> <p>Do you have access to all of the code and are you sure you have set timeouts where applicable so that any defaults are not being applied unbeknownst to you?</p>
Why do people use tarballs? <p>As a primarily Windows developer, perhaps I'm missing something cultural in the Linux community, but it has always confused me when downloading something that the files are first put into a .tar archive, then zipped. Why the two step process? Doesn't zipping achieve the file grouping? Is there some other benefit that I'm not aware of?</p>
<p>bzip and gzip work on single files, not groups of files. Plain old zip (and pkzip) operate on groups of files and have the concept of the archive built-in.</p> <p>The *nix philosophy is one of small tools that do specific jobs very well and can be chained together. That's why there's two tools here that have specific tasks, and they're designed to fit well together. It also means you can use tar to group files and then you have a choice of compression tool (bzip, gzip, etc).</p>
System.Random keeps on returning the same value <p>I am using a System.Random object which is instantiated with a fixed seed all thoughout the application. I am calling the NextDouble method and after some time passed I am getting 0.0 as result.</p> <p>Is there any remedy to this, has anyone else encountered this ?</p> <p>EDIT: I have one seed for the whole run which is set to 1000 for convience sake. The random.NextDouble is called several hundred thousand times. It is an optimizer application and could run for couple hours, but this actually happens after 10-0 mins of execution. I have recently added little bit more random calls to the app.</p>
<p>The random number generator in .NET is not thread safe. Other developers have noticed the same behaviour, and one solution is as follows (from <a href="http://blogs.msdn.com/brada/archive/2003/08/14/50226.aspx">http://blogs.msdn.com/brada/archive/2003/08/14/50226.aspx</a>):</p> <pre><code>class ThreadSafeRandom { private static Random random = new Random(); public static int Next() { lock (random) { return random.Next(); } } }</code></pre>
What harm can DBO do to a server? <p>Aside from executing XP_CmdShell, which I have disabled in my SQL 2005 installation, what could a malicious user who gains DBO rights to my database do:</p> <ul> <li>To my database,</li> <li>To my server?</li> </ul> <p>I'm assessing the worst-case security risk of someone obtaining DBO to justify running a "least-privileged" user account in an application. Some allege that since we're not working with "confidential data" that the impact of someone gaining DBO is minimal.</p>
<p>he can run any XP_ sproc so it can mess up the registry and mess up your whole server for one thing. drop/change tables, etc... </p>
How can I abort a running JDBC transaction? <p>Is there a way to prematurely abort a transaction? Say, I have sent a command to the database which runs five minutes and after four, I want to abort it.</p> <p>Does JDBC define a way to send a "stop whatever you are doing on this connection" signal to the DB?</p>
<p>As mentioned by james, <a href="https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#cancel()">Statement.cancel()</a> will cancel the execution of a running Statement (select, update, etc). The JDBC docs specifically say that Statement.cancel() is safe to run from another thread and even suggests the usage of calling it in a timeout thread.</p> <p>After canceling the statement, you're still stuck with the job of rolling back the transaction. That is <em>not</em> documented as being safe to run from another thread. The <a href="https://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html#rollback()">Connection.rollback()</a> should happen in the main thread doing all the other JDBC calls. You can handle that after the canceled Statement.execute...() call completes with a JDBCException (due to the cancel).</p>
Does Visual Studio 2008 have integration with SourceSafe? <p>I'm using Visual Studio 2008 Professional Edition. In previous versions, there has been integration with VSS, through which one could "open from SourceSafe" and then, in the solution view, have the ability to interact with the source control by clicking on individual files. I seem to have some integration under 2008, namely there is a "Source Control" menu item under the File menu, but all I can do there is "Launch Microsoft Visual SourceSafe." How do I get the integration that I had in 2005?</p>
<p>You have to install the VSS client software, and if you want the auto check out, etc. the project has to be bound to the source control repository. </p> <p>Also try looking in the Tools -> Options -> Source control menu item.</p>
Stateful PHP Web Service Using SOAP <p>I'm trying to implement a stateful web service in PHP using the SOAP extension. (Yes I know that web services are supposed to be stateless; all I really care to persist is some form of a session ID so I don't need to authenticate with every call to the service). PHP.net's API documentation is somewhat lacking on this, and there isn't much else written on it.</p> <p>I found one page that discusses it (<a href="http://bytes.com/forum/thread160816.html" rel="nofollow">http://bytes.com/forum/thread160816.html</a>) and implemented the code as a test. I built a small .NET application that consumes the web service and calls each function and displays the result. From what I've read, the PHP SOAP extension will persist class variables between calls as long as the functionality is encapsulated in a class using the setClass() function and the setPersistence() function is passed SOAP_PERSISTENCE_SESSION.</p> <p>Here is my code:</p> <pre><code>&lt;?php class User { var $name = "Initial value"; function setName($name) { $this-&gt;name = $name; // Tried this too. // $this-&gt;name = "Set to string constant" ; } function getName() { // This always returns "Initial value" return $this-&gt;name; } } // Tried placing session_start() in several places // before $server-&gt;handle()... // One guy says this doesn't need to be called. // I assume it depends on if session autostart is on. session_start(); $server = new SoapServer(null, array('uri' =&gt; 'http://localhost/')); $server-&gt;setClass('User'); $server-&gt;setPersistence(SOAP_PERSISTENCE_SESSION); $server-&gt;handle(); ?&gt; </code></pre> <p>The problem I run into is that $name is not persisted between calls -- I always get the initialized value and not the value I assign to setName(). As I stated, I'm trying to persist a session ID after authenticating against a database -- if anyone has a better way to do this I'm open to suggestions; however, I would still like to solve the general case. Anyone have any ideas?</p>
<p>I actually solved my own problem.</p> <p>I was working under the assumptions that: 1) .NET handles cookies automatically; and 2) my problem was with the PHP. Neither was the case. My PHP code was fine but I needed to add one more element to my .NET code to handle the session cookie.</p> <p>After instantiating the web service object, I needed to assign an instance of the CookieContainer class to the web service object. My final client side code is below:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WsTest { public partial class PhpWsForm : Form { private localhost.MyWebService ws; public PhpWsForm() { InitializeComponent(); ws = new WsTest.localhost.MyWebService(); // The line below is the part that I forgot! ws.CookieContainer = new System.Net.CookieContainer(); } private void butSetVal_Click(object sender, EventArgs e) { ws.setName(txtSetVal.Text); } private void butGetVal_Click(object sender, EventArgs e) { txtGetVal.Text = ws.getName(); } } } </code></pre> <p>Thanks anyway!</p>
How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS? <p>How can I create a table that has its first row and first column both locked, as in Excel, when you activate 'freeze panes'? I need the table to both scroll horizontally and vertically (a lot of solutions for this exist, but only allow vertical scrolling).</p> <p>So, when you scroll down in the table, the first row will stay put, since it will have the column headings. This may end up being in a <code>thead</code>, or it may not, whatever makes the solution easier.</p> <p>When you scroll right, the first column stays put, since it holds the labels for the rows.</p> <p>I'm pretty certain this is impossible with CSS alone, but can anyone point me toward a JavaScript solution? It needs to work in all major browsers.</p>
<p>Oh well, I looked up for scrollable table with fixed column to understand the need of this specific requirement and your question was one of it with no close answers.. </p> <p>I answered this question <a href="http://stackoverflow.com/questions/10838700/large-dynamically-sized-html-table-with-a-fixed-scroll-row-and-fixed-scroll-colu/10922732#10922732">Large dynamically sized html table with a fixed scroll row and fixed scroll column</a> which inspired to showcase my work as a plugin <a href="https://github.com/meetselva/fixed-table-rows-cols">https://github.com/meetselva/fixed-table-rows-cols</a></p> <p>The plugin basically converts a well formatted HTML table to a scrollable table with fixed table header and columns.</p> <p>The usage is as below,</p> <pre><code>$('#myTable').fxdHdrCol({ fixedCols : 3, /* 3 fixed columns */ width : "100%", /* set the width of the container (fixed or percentage)*/ height : 500 /* set the height of the container */ }); </code></pre> <p>You can check the <a href="http://meetselva.github.io/fixed-table-rows-cols/">demo and documentation here</a></p>
C# Create a hidden transaction <p>I am using C# and DSL Tools for VS2005. </p> <p>I need to create Transactions to change some data but i want them to be hidden from the user, that means, to not show in the UNDO list in VS2005.</p> <p>I tried by disabling the UndoManager</p> <pre><code>store.UndoManager.UndoState = UndoState.Disabled; </code></pre> <p>But by disabling it all existing previous actions in the undo list are cleared.</p> <p>Transactions have a property called "isHidden" but it's readonly i don't know how i can set the to hidden. I also tried to create a new UndoManager but it's also a readonly property...</p> <p>How can i create a transaction that does not appear in the undo list?</p> <p>I'd be glad to write some more details in order to clarify any doubts, Thank you very much, Luís Filipe</p> <p>[added]</p> <p>i paint every shape's background based on a property value. E.g, green if true, red if false. I need to open a transaction to paint the shape's background but for me it behaves as a calculated (read-only) property.</p>
<p><code>store.UndoManager.UndoState = UndoState.Disabled</code>; </p> <p>is almost right for what u want,</p> <p><code>store.UndoManager.UndoState = UndoState.DisabledNoFlush;</code> </p> <p>this will not clear the rest of the undo list :) cyas at lunch Luis.</p>
What are the best practices to log an error? <p>Many times I saw logging of errors like these:</p> <pre><code>System.out.println("Method aMethod with parameters a:"+a+" b: "+b); print("Error in line 88"); </code></pre> <p>so.. What are the best practices to log an error?</p> <p><strong>EDIT:</strong></p> <p>This is java but could be C/C++, basic, etc.</p>
<p>Logging directly to the console is horrendous and frankly, the mark of an inexperienced developer. The only reason to do this sort of thing is 1) he or she is unaware of other approaches, and/or 2) the developer has not thought one bit about what will happen when his/her code is deployed to a production site, and how the application will be maintained at that point. Dealing with an application that is logging 1GB/day or more of completely unneeded debug logging is maddening.</p> <p>The generally accepted best practice is to use a Logging framework that has concepts of: </p> <ol> <li>Different log objects - Different classes/modules/etc can log to different loggers, so you can choose to apply different log configurations to different portions of the application.</li> <li>Different log levels - so you can tweak the logging configuration to only log errors in production, to log all sorts of debug and trace info in a development environment, etc.</li> <li>Different log outputs - the framework should allow you to configure <em>where</em> the log output is sent to without requiring any changes in the codebase. Some examples of different places you might want to send log output to are files, files that roll over based on date/size, databases, email, remoting sinks, etc.</li> <li>The log framework should never <em>never</em> <strong>never</strong> throw any Exceptions or errors from the logging code. Your application should not fail to load or fail to start because the log framework cannot create it's log file or obtain a lock on the file (unless this is a critical requirement, maybe for legal reasons, for your app).</li> </ol> <p>The eventual log framework you will use will of course depend on your platform. Some common options:</p> <ul> <li>Java: <ul> <li><a href="http://commons.apache.org/logging/">Apache Commons Logging</a> </li> <li><a href="http://logging.apache.org/log4j/">log4j</a></li> <li><a href="http://logback.qos.ch/">logback</a></li> <li>Built-in <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/logging/package-summary.html">java.util.logging</a></li> </ul></li> <li>.NET: <ul> <li><a href="http://logging.apache.org/log4net/index.html">log4net</a></li> </ul></li> <li>C++: <ul> <li><a href="http://logging.apache.org/log4cxx/index.html">log4cxx</a></li> </ul></li> </ul>
Regex match question <p>In javascript, I've got a block of HTML like this:</p> <pre><code>&lt;h2&gt;{title}&lt;/h2&gt; &lt;p&gt;&lt;a href="{url}"&gt;{content}&lt;/a&gt;&lt;/p&gt; </code></pre> <p>And I'm trying use regex "match" to spit out an array of all the {item}'s. So my output should look like:</p> <pre><code>['title', 'url', 'content'] </code></pre> <p>I've gotten as far as:</p> <pre><code>var pattern = new RegExp("\{[a-zA-Z]+\}+"); var match = pattern.exec("{Sample} bob {text}"); </code></pre> <p>But it's only returning the first tag. </p> <p>This is just beyond my regex skills. Can anyone help?</p> <p>Cheers!</p>
<p>You need to create a pattern with the global flag:</p> <pre><code>var pattern = new RegExp("\{[a-zA-Z]+\}", "g"); </code></pre> <p>or:</p> <pre><code>var pattern = /\{[a-zA-Z]+\}/g; </code></pre> <p>Then you can call the match() method on your string to get a list of matches:</p> <pre><code>var matches = "{Sample} bob {text}".match(pattern); </code></pre>
Which is more efficient in Python: standard imports or contextual imports? <p>I apologize in advance if this question seems remedial.</p> <p>Which would be considered more efficient in Python:</p> <p><strong>Standard import</strong></p> <pre><code>import logging try: ...some code... exception Exception, e: logging.error(e) </code></pre> <p>...or...</p> <p><strong>Contextual import</strong></p> <pre><code>try: ...some code... exception Exception, e: import logging logging.error(e) </code></pre>
<p>Contextual imports are technically more efficient, but I think they can create other problems.</p> <p>Later, if you want to add a similar except clause, you now have two places to maintain the same block of code. You also now have the problem of testing the exception, to make sure that the first import doesn't cause any unforeseen issues in your code.</p>
How to Check if File is ASCII or Binary in C++ <p>So using the system command file we can use file to determine if a file is ASCII Text or "data". I wanted to know if there is a way to check in code which one it was? I want to basically throw a corrupt error if the file is 'data'. I am using ifstream for reading the files. Thanks for any help!</p> <p><strong>Duplicate of <a href="http://stackoverflow.com/questions/277521/how-to-identify-the-file-content-is-in-ascii-or-binary#277538">this question</a>.</strong></p>
<p>You can iterate over the bytes of the file and use <code>std::isprint</code> from <code>&lt;cchar&gt;</code> to test whether the character is printable. If there are nonprintable characters in the file, chances are it's a binary file. Notice that this only works for legacy encodings (e.g. ASCII mentioned by you), not for Unicode-encoded files.</p>
How do I remove a specific number of files using python (version 2.5)? <p>I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance. </p>
<p>It sounds like what you really want is a temp file: <a href="http://docs.python.org/library/tempfile.html" rel="nofollow">http://docs.python.org/library/tempfile.html</a></p>
Win32 console processes in VISTA - 10% CPU, but VERY SLOW <p>I have a Win32 console application which is doing some computations, compiled in Compaq Visual Fortran (which probably doesn't matter). </p> <p>I need to run a lot of them simultaneously.</p> <p>In XP, they take around 90-100% CPU together, work very fast. In Vista, no matter how many of them I run, they take no more than 10% of CPU (together), and work very slow respectively.</p> <p>There is quite a bit of console output going on, but now VERY much. I can minimize all the windows, it does not help. CPU is basically doing nothing...</p> <p>Any ideas?</p> <p><strong>Update:</strong></p> <p>No, these are different machines, but they run relatively the same hardware. 2. Threads are not used, this is a VERY OLD (20 yrs) plain app for DOS, compiled in win32. It is supposed to compute iterations until they meet, consume all it has. My impression - VISTA just does NOT GIVE IT MORE CPU</p>
<p>Have you tried redirecting the console output to a file? If your applications are being held up writing to the console (this happens sometimes unfortunately) then redirecting the output should help, as it's much quicker to write to a simple file than write to the console.</p> <p>You do this like so</p> <pre><code>c:\temp&gt; dir &gt; output.log </code></pre> <p>If you really don't care about the output at all, you can throw it away, by redirecting to <code>nul</code>. eg:</p> <pre><code>c:\temp&gt; dir &gt; nul </code></pre>
using date range in Lucene.net <p>I understand how Lucene.net can work for text indexing. Will I be able to efficiently search for documents based on a given date range? Or will Lucene.net just use text matching to match the dates?</p>
<p>Lucene.Net will just use text matching, so you'd need to format the dates correctly before adding to the index:</p> <pre><code> public static string Serialize(DateTime dateTime) { return dateTime.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture); } public static DateTime Deserialize(string str) { return DateTime.ParseExact(str, "yyyyMMddHHmmss", CultureInfo.InvariantCulture); } </code></pre> <p>You can then, for example, perform a range based query to filter by date (e.g. 2006* to 2007* to include all dates in 2006 and 2007).</p>
Mount/Unmount USB drives with VBSCript <p>I am looking for a way to mount\unmount a USB flash drive using VBScript. This is the closest I was able to get.</p> <pre><code>Sub EjectDrive(strDrive) On Error Resume Next CONST SSF_DRIVES = 17 Set objShell = CreateObject("Shell.Application") Set objDrive = objShell.Namespace(SSF_DRIVES).ParseName(strDrive) objDrive.InvokeVerb "E&amp;ject" End Sub </code></pre>
<p>This will work on Windows Server 2003, but not NT/2000/XP/Vista unfortunately.</p> <pre><code>strComputer = "." Set objWMIService = GetObject("winmgmts:" _ &amp; "{impersonationLevel=impersonate}!\\" &amp; strComputer &amp; "\root\cimv2") Set colItems = objWMIService.ExecQuery _ ("Select * From Win32_Volume Where Name = 'E:\\'") For Each objItem in colItems objItem.Dismount(True, True) Next </code></pre> <p>From <a href="http://www.microsoft.com/technet/scriptcenter/scripts/storage/disks/drives/stdvvb07.mspx?mfr=true" rel="nofollow">Dismount a Volume</a>.</p>
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other? <p>We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this:</p> <p>Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux?</p> <p>Primarily languages will be Java, C/C++, Python, and PHP.</p> <p>Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing <a href="http://bouncybouncy.net/ramblings/posts/more%5Fon%5Fjson%5Fvs%5Fthrift%5Fand%5Fprotocol%5Fbuffers/">compressed JSON performing similar / better than Thrift / Protocol Buffers</a>, so I'm throwing JSON into this question as well.</p>
<p>Latest comparison available here at the <a href="https://github.com/eishay/jvm-serializers/wiki/">thrift-protobuf-compare</a> project wiki. It includes many other serialization libraries.</p>
Disappearing Foreign Keys in phpMyAdmin <p>I am creating a new table inside mysql and I am trying to add a foreign key constraint to one of the fields.</p> <pre> CREATE TABLE `onlineorder` ( `receiptid` varchar(10) NOT NULL default '', `delivereddate` date default NULL, `cid` int(10) NOT NULL, `card#` int(10) default NULL, `expire` date default NULL, PRIMARY KEY (`receiptid`), FOREIGN KEY (receiptid) REFERENCES purchase ) ENGINE=MyISAM DEFAULT CHARSET=latin1; </pre> <p>However, after it creates it, I go into phpMyAdmin and export the table. and it seems like the foreign key constraint has disappeared.</p> <pre> CREATE TABLE `onlineorder` ( `receiptid` varchar(10) NOT NULL default '', `delivereddate` date default NULL, `cid` int(10) NOT NULL, `card#` int(10) default NULL, `expire` date default NULL, PRIMARY KEY (`receiptid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; </pre> <p>Does phpMyAdmin get rid of foreign keys or am I doing something wrong here?</p>
<p>You need to use the InnoDB engine to have foreign keys.</p> <p>Ref: <a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html">http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html</a></p>
Adding handlers to Dynamically Created Context Menu <p>I need to populate a context menu from a database at run time. I do not know the number of items that will be in the list, so I would like to handle the click event in a single place. How do I declare the handler so I can tell which menu item actually triggered the click.</p> <pre><code>Public Function GetBookmarkContextMenu(ByVal aBookmark As Bookmark) As System.Windows.Controls.ContextMenu Dim myContextMenu As New Controls.ContextMenu myContextMenu.Name = "BookmarkMenu" For Each aMailingList As MasterService.FalconBookmarkMailingListType In GlobalUserSettings.MailingLists Dim mySubMenuItem As New Controls.MenuItem mySubMenuItem.Name = "MailingListName" &amp; aMailingList.ID.ToString mySubMenuItem.Header = aMailingList.Title AddHandler (myMenuItem.Click), AddressOf ForwardToList_Click mySubMenuItem.IsEnabled = True myMenuItem.Items.Add(mySubMenuItem) Next myContextMenu.Items.Add(myMenuItem) return myContextMenu End Function Public Sub ForwardToList_Click() 'How do I know which of the dynamically created items was clicked? End Sub </code></pre>
<pre><code>Dim mnuitm As New ToolStripMenuItem mnuitm.Name = name_cbk.Items(i) mnuitm.Text = name_cbk.Items(i) AddHandler (mnuitm.Click), AddressOf item_Click menulist.Items.Add(mnuitm) </code></pre>
Changing a Property into a Method - any side effects? <p>I have a class that has some properties. And I want something that calculates a Score out of these properties. Since this is a trivial task (some additions and divisions, but nothing spectacular).</p> <p>So naturally, the question is: "When to use a Property with some code in the getter, and when to use a function?", and <a href="http://stackoverflow.com/questions/67063/">that question was already answered</a>.</p> <p>Now, I wonder about one thing though: If - against all expectations - I ever needed to make this Getter so complicated that it should be a function (for example, because I need to put data in or because it can throw an exception or whatever), is it easy to change a Property into a Method?</p> <p>Of course, it seems really trivial, just changing</p> <pre><code>public double Score { get { return Math.Round(A + B / C * D,3); } } </code></pre> <p>to</p> <pre><code>public double Score(){ return Math.Round(A + B / C * D,3); } </code></pre> <p>But I wonder: Are there any side effects? Is anything going to break when changing stuff around like this? I can only ever see this as a possible problem when Reflection is involved, but what in situations where I have 2 Assemblies - one that defines the class and one that uses the class - and only change the one that contains the class without recompiling the consumer assembly. Is that a possible source of "weird bugs that are nearly impossible to track" or is it completely safe to change Properties to Methods?</p>
<p>Pull up reflector, you'll see that your properties already are methods :)</p>
Huge Transaction Log - Is This Normal? <p>I have a 5GB database and a 20GB transaction log (SQL Server 2005). Not sure why it is so large or what happened to make it that large, it used to be around 1/2 the size of the DB. DB grows about 1GB/month. </p> <p>Are there any guidelines to how how big your transaction log should be relative to your database file size? </p> <p>EDIT: I'm not saying my transaction log is huge (I know some DBAs would laugh at my weenie-sized DB), just in relation to the DB file I think it is huge.</p>
<p>Er... excuse the bleeding obvious, but do you have scheduled backups with "BACKUP LOG"</p> <p>If the recovery model is FULL then this needs to happen.</p> <p>There are other, rare options that I'll include (not exhaustive):</p> <ul> <li>Large table index rebuild/maintenance. However, backup log will clear this.</li> <li>An open transaction preventing backup log removing entries (hence it grows)</li> <li>A connection with <a href="http://msdn.microsoft.com/en-us/library/ms190230(SQL.90).aspx">SET IMPLICIT_TRANSACTIONS ON</a> (see previous point)</li> </ul>
What's the Windows equivalent of a UNIX shell script? <p>I want to have an executable file that will call some other programs. The way I would do this in Linux is with a simple bash script that looks like this:</p> <pre><code>#!/bin/bash echo "running some-program" /home/murat/some-program arg1 arg2 </code></pre> <p>What's the best way to do this kind of thing under Windows?</p>
<p>Take a look at <a href="http://www.microsoft.com/downloads/details.aspx?familyid=C6EF4735-C7DE-46A2-997A-EA58FDFCBA63&amp;displaylang=en">PowerShell</a>, which is the closest you will get to a true scripting language like you have in Unix. Other than that, for simple things such as simply runnning an application, take a look at Windows command script/MS-DOS batch files.</p>
How do you get the current time of day? <p>How do you get the current time (not date AND time)?</p> <p>Example: 5:42:12 PM</p>
<p><code>DateTime.Now.TimeOfDay</code> gives it to you as a <code>TimeSpan</code> (from midnight).</p> <p><code>DateTime.Now.ToString("h:mm:ss tt")</code> gives it to you as a <em>string</em>.</p> <p>DateTime reference: <a href="https://msdn.microsoft.com/en-us/library/system.datetime">https://msdn.microsoft.com/en-us/library/system.datetime</a></p>
Partial Keyword Searching (MS SQL 2005) <p>Current, I've got a stored procedure that has a main goal of doing a full text search through a database table of films and tv shows. In order to get it to do partial-keyword searching, I added some code in SQL to split up the search query by spaces, and output a statement like the following:</p> <p>' "batman*" ~ "be*" '</p> <p>The original string, "batman be", for instance, could be generated from a textbox on the page as the user is typing and on each javascript keyup event, I send whatever is in that textbox to the stored proc for results to get results as I type (like autocomplete). In this case, the user may have been looking for "Batman Begins", or "The Batman: Batgirl Begins" (a TV show episode) and they both should show up as a result.</p> <p>Below is a sample of my query. @partialKeywordString is, in the example above, ' "batman*" ~ "be*" '.</p> <pre><code>SELECT f.title FROM Films f INNER JOIN CONTAINSTABLE(Films, Title, @partialKeywordString) f_key ON f.filmid = f_key.[key] ORDER BY f_key.Rank DESC </code></pre> <p>The problem I have with the query is that the ranking doesn't seem to be exactly what I'd expect. If I were to just search for "batman", one would believe that all movie titles, beginning with, or only containing the word "batman" would appear first. But they don't. A sample result of what happens when one searches for just "batman" is below:</p> <p>"Batman: The animated series - Episode 114" "Adventures of Batman and Robin - Episode 218" "Batman and Robin - Episode 101" "The Batman - Episode 101" "Batman and Robin - Episode 204"</p> <p>Much further down the list is the movie I was searching for--"Batman Begins" or even just "Batman".</p> <p>I'm looking for advice on how to tweak this query--I'm definitely not a SQL expert, and I feel like I just man-handled the above code to get it to work. I have a feeling there's a more elegant or powerful solution, and I just haven't found it yet.</p> <p>Thank you in advance</p>
<p>After some more researching, I'm going to try and use Lucene.Net for my movie-title search engine, and not rely on Full-Text Searching in SQL Server 2005. Early testing shows that the results have been better and more relevant with Lucene. A search for "batman" returns the following partial result-set:</p> <ul> <li>Batman </li> <li>Batman Begins</li> <li>Batman Returns</li> <li>Batman and Robin: Batman Takes Over</li> <li>Batman Beyond: A Touch of Curaré</li> <li>Batman Beyond: Babel</li> <li>The Batman: Season 02</li> <li>The Batman: Topsy Turvy</li> <li>Batman and Robin: Tunnel of Terror</li> <li>Batman Beyond [Animated TV Series]</li> <li>The New Adventures of Batman: Curses! Oiled Again!</li> <li>The New Adventures of Batman: This Looks Like a Job for Bat-Mite!</li> </ul>
How to generate sound effects in Java? <p>I'm looking for Java code that can be used to generate sound at runtime - NOT playback of existing sound files.</p> <p>For example, what's the best code for generating a sawtooth waveform at 440 Hz for a duration of 2 milliseconds? <b>Source code appreciated!</b></p> <p>I remember my Commodore 128 had a simple Sound command that took as parameters voice, frequency, waveform, and duration to define a sound. That worked great in a lot of simple cases (quick and dirty games, experiments with sound, etc).</p> <p>I am looking specifically for sound-effect like sounds, not music or MIDI (which the <a href="http://www.jfugue.org">JFugue</a> library covers quite well).</p>
<p>The <a href="http://java.sun.com/javase/technologies/desktop/media/jmf/index.jsp" rel="nofollow">Java media framework</a> does both. You can play back recorded sounds or use the MIDI interface to synthesize your own sounds and music. It also provides a mixer API.</p> <p>Of course, if you know the details of the waveform you want to play, you can "sample" the function at regular intervals and pass the resulting samples to the playback API, as if it were a pre-recorded sound file.</p> <p>The JMF isn't actively maintained by Sun, but there are functioning distributions for various platforms.</p> <p>My first computer was the Commodore 64, and I remember Tears for Fears' "Everybody Wants to Rule the World" on pumping out of its SID chip. I can't tell if <a href="http://dreamfabric.com/c64/jsidplay/impl.php" rel="nofollow">this pure Java SID emulator</a> is open source or not, but it might give you some pointers on implementing higher-level Attack-Decay-Sustain-Release and waveform functionality.</p>
AS/400 ODBC Drivers <p>We have been using the Client Access ODBC drivers when accessing AS/400 data from our .net applications and SQL DTS/SSIS packages. Are there third party drivers that provide better performance or functionality?</p>
<p>Our company is using the same Client Access drivers. As far as we know there are no other ones available. One issue we ran into last year was that there were no 64-bit drivers available so our servers that have applications connecting to the AS/400 must be 32-bit.</p>
How to place text in the clipboard so that it pastes as a table in Word? <p>Using VBA in MS Office, how do I add text to the Windows clipboard so that it will paste into Word as a table?</p>
<p>The Windows clipboard supports multiple formats. When you want to place things in the clipboard, you make one or more calls to RegisterClipboardFormat() telling it the formats of the objects you will be placing on the clipboard, followed by calls to SetClipboardData() which actually places the data into the clipboard.</p> <p>If you want to be able to paste a Table into Word, then HTML is the easiest format to work with. Just copy an HTML table onto the clipboard, and it will paste correctly into Word, provided that you first register the clipboard data as an HTML object.</p> <p>I'd give you some code, but it's easiest to just reference an example on MSDN:</p> <p><a href="http://support.microsoft.com/kb/274326">How to add HTML code to the clipboard using Visual Basic</a></p> <p>This page even shows an example of copying an HTML table onto the clipboard.</p>
Best way to use a DB table as a message/job queue <p>I have a databases table with ~50K rows in it, each row represents a job that need to be done. I have a program that extracts a job from the DB, does the job and puts the result back in the db. (this system is running right now)</p> <p>Now I want to allow more than one processing task to do jobs but be sure that no task is done twice (as a performance concern not that this will cause other problems). Because the access is by way of a sproce, my current though is to replace said sproce with something that looks something like this</p> <pre><code>update tbl set owner=connection_id() where avalable and owner is null limit 1; select stuff from tbl where owner = connection_id(); </code></pre> <p>BTW; worker's tasks might drop there connection between getting a job and submitting the results. Also, I don't expect the DB to even come close to being the bottle neck unless I mess that part up (~5 jobs per minute)</p> <p>Are there any issues with this? Is there a better way to do this?</p> <p>Note: the <a href="http://tripatlas.com/Database_as_an_IPC">"Database as an IPC anti-pattern"</a> is only slightly apropos here because 1) I'm not doing IPC (there is no process generating the rows, they all already exist right now) and 2) the primary gripe described for that anti-pattern is that it results in unneeded load on the DB as processes wait for messages (in my case, if there are no messages, everything can shutdown as everything is done)</p>
<p>Here's what I've used successfully in the past:</p> <p>MsgQueue table schema</p> <pre><code>MsgId identity -- NOT NULL MsgTypeCode varchar(20) -- NOT NULL SourceCode varchar(20) -- process inserting the message -- NULLable State char(1) -- 'N'ew if queued, 'A'(ctive) if processing, 'C'ompleted, default 'N' -- NOT NULL CreateTime datetime -- default GETDATE() -- NOT NULL Msg varchar(255) -- NULLable </code></pre> <p>Your message types are what you'd expect - messages that conform to a contract between the process(es) inserting and the process(es) reading, structured with XML or your other choice of representation (JSON would be handy in some cases, for instance). </p> <p>Then 0-to-n processes can be inserting, and 0-to-n processes can be reading and processing the messages, Each reading process typically handles a single message type. Multiple instances of a process type can be running for load-balancing. </p> <p>The reader pulls one message and changes the state to "A"ctive while it works on it. When it's done it changes the state to "C"omplete. It can delete the message or not depending on whether you want to keep the audit trail. Messages of State = 'N' are pulled in MsgType/Timestamp order, so there's an index on MsgType + State + CreateTime.</p> <p>Variations:<br> State for "E"rror.<br> Column for Reader process code.<br> Timestamps for state transitions. </p> <p>This has provided a nice, scalable, visible, simple mechanism for doing a number of things like you are describing. If you have a basic understanding of databases, it's pretty foolproof and extensible.</p> <hr> <p>Code from comments:</p> <pre><code>CREATE PROCEDURE GetMessage @MsgType VARCHAR(8) ) AS DECLARE @MsgId INT BEGIN TRAN SELECT TOP 1 @MsgId = MsgId FROM MsgQueue WHERE MessageType = @pMessageType AND State = 'N' ORDER BY CreateTime IF @MsgId IS NOT NULL BEGIN UPDATE MsgQueue SET State = 'A' WHERE MsgId = @MsgId SELECT MsgId, Msg FROM MsgQueue WHERE MsgId = @MsgId END ELSE BEGIN SELECT MsgId = NULL, Msg = NULL END COMMIT TRAN </code></pre>
CodeDOM & .Net Modules <p>How do I programmatically embed a .Net module to the assembly generated by CodeDOM?</p>
<p>on VB</p> <pre><code>dim param as CompilerParameteres param.EmbeddedResources.Add("dynamiclinklibrary") </code></pre>
How to Consume JSON Web Services from a Windows Client <p>Is it possible to consume a JSON enabled WCF Web Service from a standard Proxy Client (i.e. not JavaScript)? </p> <p>Basically I want to minimize the payload size between 2 web services. </p>
<p>Yes, it is, if the service interface definition on the client side is setup correctly (i.e. the RequestFormat/ResponseFormat properties of the WebGet/WebInvoke attribute on the operation contracts are set to Json. Also remember you'll need to use the WebHttp or WebScriptEnabled behaviors on your client.</p> <p>Notice that JSon won't necessarily be most efficient given the current implementation in WCF; there are definite trade offs you'll be making. There's a good overview of it on <a href="http://oakleafblog.blogspot.com/2007/12/json-vs-xml-datacontract-serialization.html" rel="nofollow">this article</a>.</p>
Installing a ASP.NET application <p>Ok, this has got to be a super simple problem. I just can't seem to find the answer anywhere. First - I'm not a web developer of any kind, I'm an old school c programmer - so don't flame me for what's probably something quite trivial :)</p> <p>I need to write a small proof-of-concept web app using ASP.NET. My first attempt here is to create a "Hello World!" app. So I opened up Visual Studio, and made a new web application. I have my Default.aspx file that calls a C# function that is inside the helloworld.dll created automatically by Visual Studio.</p> <p>I installed IIS on my local machine and created a virtual directory in the wwwroot subdirectory. I put the Default.aspx and helloworld.dll in that directory. Now when I browse to that page I see the following.</p> <pre><code>Server Error in '/test' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not load type 'HelloWorld._Default'. Source Error: Line 1: &lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HelloWorld._Default" %&gt; Line 2: Line 3: &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; Source File: /test/default.aspx Line: 1 </code></pre> <p>Obviously, IIS doesn't know where to look for the .dll or anything like that. I just don't know how to register the .dll with IIS (or whoever manages that stuff in .net) so that it can find the functions it need.</p> <p>Can someone let me know how to "install" an ASP.NET application on IIS?</p>
<p>Your best bet is to use 'Publish website' from the Visual Studio Solution Explorer.</p> <p><a href="http://stackoverflow.com/users/2424/chris-lively">Chris Lively</a> adds: </p> <blockquote> <p>Just a minor add: Publish Website can be found by Right Clicking on the project name. The command will be named "Publish..."</p> </blockquote>
Getting .png pixel data in Silverlight <p>We have a Silverlight application that needs to load a number of .png files. We can load the images OK, but Silverlight doesn't support reading the pixel data from the Image class.</p> <p>Can anyone suggest a simple solution for getting at this data? Our current best bet would be a third party .png loading library, but we are having trouble finding a suitable one.</p>
<p>There is no built in classes for doing pixel based imagine manipulation/generation i n Silverlight. You need to implement your own PNG Encoder/Decoder that works on an byte array containing the image information. Joe Stegman has implemented one such encoder you should check out. He got lots of great information about "editable images" in Silverlight over at <a href="http://blogs.msdn.com/jstegman/" rel="nofollow">http://blogs.msdn.com/jstegman/</a>. He does things like applying filters to images, generating mandlebrots and more.</p> <p>This blog discuss a JPEG Silverilght Encoder (FJCore) you can use to resize and recompress photos client size: <a href="http://fluxcapacity.net/2008/07/14/fjcore-to-the-rescue/" rel="nofollow">http://fluxcapacity.net/2008/07/14/fjcore-to-the-rescue/</a></p> <p>Another tool is "Fluxify" which lets you resize and upload photos using Silverilght 2. Can be found over at <a href="http://fluxtools.net/" rel="nofollow">http://fluxtools.net/</a></p> <p>So yes, client side image processing can definitely be done in Silverilght 2. Happy hacking!</p>
list of email addresses that can be used to test a javascript validation script <p>Does anyone have a list of email addresses that I can use to test my JS address validation script? I'm looking for as complete of a list as is reasonable to test the most common edge cases, if not all cases.</p>
<p>Examples valid according to RFC2822</p> <ul> <li>me@example.com</li> <li>a.nonymous@example.com</li> <li>name+tag@example.com</li> <li>name\@tag@example.com – this is a valid email address containing two @ symbols.</li> <li>spaces\ are\ allowed@example.com</li> <li>"spaces may be quoted"@example.com</li> <li>!#$%&amp;'<em>+-/=.?^</em>`{|}~@[1.0.0.127]</li> <li>!#$%&amp;'<em>+-/=.?^</em>`{|}~@[IPv6:0123:4567:89AB:CDEF:0123:4567:89AB:CDEF]</li> <li>me(this is a comment)@example.com – comments are discouraged but not prohibited by RFC2822.</li> </ul> <p>Examples invalid according to RFC2822s</p> <ul> <li>me@</li> <li>@example.com</li> <li>me.@example.com</li> <li>.me@example.com</li> <li>me@example..com</li> <li>me.example@com</li> <li>me\@example.com</li> </ul> <p>From : <a href="http://en.wikibooks.org/wiki/JavaScript/Best_Practices">http://en.wikibooks.org/wiki/JavaScript/Best_Practices</a></p>
Tabs, Text-Mate, Editing HTML (Rails) <p>Is there any way to force Text-Mate to use a two-space tab instead of a full tab when editing HTML (Rails) documents?</p>
<p>Yes. There's a pop-up menu near the bottom middle of the window that probably reads <code>Tabs: 4</code> or something like that. Click on it and hange it to <code>2</code> and <code>Soft Tabs</code>.</p> <p>You should have an <code>rhtml</code> or <code>erb</code> document (or whatever file type you want to change) open for editing when doing this. The changes will stick for all documents of that type.</p>
Use GET or POST for a search form <p>I have a couple search forms, 1 with ~50 fields and the other with ~100. Typically, as the HTML spec says, I do searches using the GET method as no data is changed. I haven't run into this problem yet, but I'm wondering if I will run out of URL space soon?</p> <p>The limit of <a href="http://support.microsoft.com/kb/208427">Internet Explorer</a> is 2083 characters. Other browsers, have a <a href="http://www.boutell.com/newfaq/misc/urllength.html">much higher limit</a>. I'm running Apache, so the limit there is around 4000 characters, which IIS is 16384 characters.</p> <p>At 100 fields, say average field name length of 10 characters, that's already 5000 characters...amazing on the 100 field form, I haven't had any errors yet. (25% of the fields are multiple selects, so the field length is much longer.)</p> <p>So, I'm wondering what my options are. (Shortening the forms is not an option.) Here my ideas:</p> <ul> <li>Use POST. I don't like this as much because at the moment users can bookmark their searches and perform them again later--a really dang nice feature.</li> <li>Have JavaScript loop through the form to determine which fields are different than default, populate another form and submit that one. The user would of course bookmark the shortened version.</li> </ul> <p>Any other ideas?</p> <p>Also, does anyone know if the length is the encoded length or just plain text?</p> <p>I'm developing in PHP, but it probably doesn't make a difference.</p> <p><strong>Edit:</strong> I am unable to remove any fields; I am unable to shorten the form. This is what the client has asked for and they often do use a range of fields, in the different categories. I know that it's hard to think of a form that looks nice with this many fields, but the users don't have a problem understanding how it works.</p>
<p>Are your users actually going to be using all 50-100 fields to do their searches? If they're only using a few, why not POST the search to an "in between" page which header()-redirects them to the results page with only the user-changed fields in the URL? The results page would then use the default values for the fields that don't exist in the URL.</p>
asp.net gridview sort without data rebind <p>I am trying to make a gridview sortable which uses a stored procedure as a datasource, I would not want it to rerun the query each time to achieve this. How would I get it to work my current code is:</p> <pre><code>protected override void OnPreRender(EventArgs e) { if (!IsPostBack) { SqlCommand cmd2 = new SqlCommand("SR_Student_Course_List", new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RDCV2ConnectionString"].ConnectionString)); try { cmd2.CommandType = CommandType.StoredProcedure; cmd2.CommandTimeout = 120; cmd2.Parameters.Add("student_id", SqlDbType.Char, 11).Value = student; cmd2.Connection.Open(); grdCourses.DataSource = cmd2.ExecuteReader(); grdCourses.DataSourceID = string.Empty; grdCourses.DataBind(); } finally { cmd2.Connection.Close(); cmd2.Connection.Dispose(); cmd2.Dispose(); }}} </code></pre> <p>This code just binds the data when it isn't a postback, the gridview has viewstate enabled. On pressing the column headers a postback happens but no sorting occurs. If anyone has a simple fix for this please let me know or even better an ajax sort which would avoid the postback would be even better. The dataset is relatively small however takes a long time to query which is why I would not like to requery on each sort.</p>
<p>If you are not paging the results, and just doing a read, then something like the jquery tablesorter plugin would be a quick and easy fix. I have used this on tables of up to 1400 rows and works great, although ~> few hundred probably better on slow putas.</p> <p>If the gridview is editable, then aspnet event/input validation might spit a dummy if you don't go through the proper registration of client scripts etc.</p>
How should I interact with the geometry of a UIView, disregarding any transforms applied? <p>I have a view that I would like the user to rotate around its center, by tapping and holding somewhere and just move their finger round and round.</p> <p>I have all the geometry worked out; What I do is store the initial touch angle relative to the center as offsetAngle, then my touchesMoved method looks like this:</p> <pre><code>- (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event { self.transform = CGAffineTransformMakeRotation(0); CGPoint location = [[touches anyObject] locationInView: self]; CGPoint actualCenter = [self convertPoint: self.center fromView: self.superview]; CGPoint relativeTouch = [MathHelper translatePoint:location relativeTo: actualCenter]; CGPoint zero = CGPointMake(0, 0); float angle = [MathHelper getAngleForPoint:zero andPoint:relativeTouch]; self.transform = CGAffineTransformMakeRotation(offsetAngle-angle); } </code></pre> <p>The ugly bit is the first line, where I have to restore the rotation in order to get the correct event positions in the view. If I don't that, then the locations jump all over the place as there's no continuity, since the view is rotating...</p> <p>Another issue is when you want to manipulate a view's frame (eg. moving it down), when the view has a transform applied:</p> <pre><code>- (IBAction)toggleSettingsView { BOOL state = [settingsSwitch isOn]; float height = optionsView.bounds.size.height; CGRect polygonFrame = polygonView.frame; [UIView beginAnimations:@"advancedAnimations" context:nil]; [UIView setAnimationDuration:0.3]; if (state) { optionsView.alpha = 1.0; polygonFrame.origin.y += height; } else { optionsView.alpha = 0.0; polygonFrame.origin.y -= height; } polygonView.frame = polygonFrame; [UIView commitAnimations]; } </code></pre> <p>This distorts the view heavily.</p> <p>I must mention that both the CGTransform and the CALayer transform have the same effect.</p> <p>This smells like I'm doing something wrong, but I don't know what I should be doing.</p>
<p>I would use the coordinate system of the superview, since it is unaffected by the rotation:</p> <pre><code>- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint location = [[touches anyObject] locationInView:self.superview]; CGPoint relativeTouch = [MathHelper translatePoint:location relativeTo:self.center]; CGPoint zero = CGPointMake(0, 0); float angle = [MathHelper getAngleForPoint:zero andPoint:relativeTouch]; self.transform = CGAffineTransformMakeRotation(offsetAngle-angle); }</code></pre>
Creating a selector from a method name with parameters <p>I have a code sample that gets a <code>SEL</code> from the current object, </p> <pre><code>SEL callback = @selector(mymethod:parameter2); </code></pre> <p>And I have a method like </p> <pre><code> -(void)mymethod:(id)v1 parameter2;(NSString*)v2 { } </code></pre> <p>Now I need to move <code>mymethod</code> to another object, say <code>myDelegate</code>.</p> <p>I have tried:</p> <pre><code>SEL callback = @selector(myDelegate, mymethod:parameter2); </code></pre> <p>but it won't compile. </p>
<p>SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:</p> <pre><code>-(void)methodWithNoArguments; SEL noArgumentSelector = @selector(methodWithNoArguments); -(void)methodWithOneArgument:(id)argument; SEL oneArgumentSelector = @selector(methodWithOneArgument:); // notice the colon here -(void)methodWIthTwoArguments:(id)argumentOne and:(id)argumentTwo; SEL twoArgumentSelector = @selector(methodWithTwoArguments:and:); // notice the argument names are omitted </code></pre> <p>Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:</p> <pre><code>-(void)someMethod:(NSTimer*)timer; </code></pre> <p>So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:</p> <pre><code>@implementation MyObject -(void)myTimerCallback:(NSTimer*)timer { // do some computations if( timerShouldEnd ) { [timer invalidate]; } } @end // ... int main(int argc, const char **argv) { // do setup stuff MyObject* obj = [[MyObject alloc] init]; SEL mySelector = @selector(myTimerCallback:); [NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES]; // do some tear-down return 0; } </code></pre> <p>In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds. </p>
How can I clean up dead connections using Oracle? <p>Right now I have a few new applications being developed against an Oracle Database, and sometimes they crash or fail to end correctly, etc... anyways the problem is they sometimes seem to leave their connections open, and I need to cleanup after them. My question is if there is a way from the database-side of things to determine dead connections and clean them up?</p>
<p>Here's a page referring to connection timeout parameters you can set in <a href="http://download.oracle.com/docs/cd/B28359_01/java.111/e10788/optimize.htm#sthref181" rel="nofollow">Oracle 11g</a>. I think the 'Abandon Connection Timeout' is what you're looking for. </p>