input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
Regular expression to match URLs in Java <p>I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java <code>String</code> flavor and pasted it into Java code, it does not work. The following class prints <code>false</code>: </p>
<pre><code>public class RegexFoo {
public static void main(String[] args) {
String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";
String text = "http://google.com";
System.out.println(IsMatch(text,regex));
}
private static boolean IsMatch(String s, String pattern) {
try {
Pattern patt = Pattern.compile(pattern);
Matcher matcher = patt.matcher(s);
return matcher.matches();
} catch (RuntimeException e) {
return false;
}
}
}
</code></pre>
<p>Does anyone know what I am doing wrong?</p>
|
<p>Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.</p>
<pre><code>String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
</code></pre>
<p>This works too:</p>
<pre><code>String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
</code></pre>
<p>Note:</p>
<pre><code>String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>
String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
</code></pre>
|
Database Design Issues with relationships <p>I'm working on an upgrade for an existing database that was designed without any of the code to implement the design being considered. Now I've hit a brick wall in terms of implementing the database design in code. I'm certain whether its a problem with the design of the database or if I'm simply not seeing the correct solution on how to what needs to be done. </p>
<p>The basic logic stipulates the following:</p>
<ol>
<li>Users access the online trainings by way of Seats. Users can have multiple Seats.</li>
<li>Seats are purchased by companies and have a many-to-many relationship with Products.</li>
<li>A Product has a many-to-many relationship with Modules.</li>
<li>A Module has a many-to-many relationship with Lessons.</li>
<li>Lessons are the end users access for their training.</li>
<li>To muddy the waters, for one reason or another some Users have multiple Seats that contain the same Products. </li>
<li>Certification takes place on a per Product basis, not on a per Seat basis.</li>
<li>Users have a many-to-many relationship with lessons that stores their current status or score for the lesson.</li>
<li>Users certify for a Product when they complete all of the Lessons in all of the Modules for the Product.</li>
<li>It is also significant to know when all Lessons for a particular Module are completed by a User.</li>
<li>Some Seats will be for ReCertification meaning that Users that previously certified for a Product can sign up and take a recertification exam.</li>
<li>Due to Rule 11, Users can and will have multiple Certification records.</li>
<li>Edit: When a User completes a Lesson (scores better than 80%) then the User has (according to the current business logic) completed the Lesson for all Products and all Seats that contain the Lesson.
</ol>
<p>The trouble that I keep running into with the current design and the business logic as I've more or less described it is that I can't find a way to effectively tie whether a user has certified for a particular product and seat vs when they have not. I keep hitting snags trying to establish which Products under which Seats have been certified for the User and which haven't. Part of the problem is because if they are currently registered for multiple of the same Product under different Seats, then I have to count the Product only once.</p>
<p>Below is a copy of the portion of the schema that's involved. Any suggestions on how to improve the design or draw the association in code would be appreciated. In case it matters, this site is built on the LAMPP stack.</p>
<p>You can view the relevant portion of the database schema here: <a href="http://lpsoftware.com/problem_db_structure.png" rel="nofollow">http://lpsoftware.com/problem_db_structure.png</a></p>
|
<p>What you're looking for is <a href="http://www.dbazine.com/ofinterest/oi-articles/celko1" rel="nofollow">relational division</a>
Not implemented directly in SQL, but it can be done. Search google for other examples.</p>
|
Printing to a pdf printer programatically <p>I am trying to print an existing file to PDF programmatically in Visual Basic 2008.</p>
<p>Our current relevant assets are:
Visual Studio 2008 Professional
Adobe Acrobat Professional 8.0</p>
<p>I thought about getting a sdk like ITextSharp, but it seem like overkill for what I am trying to do especially since we have the full version of Adobe. </p>
<p>Is there a relatively simple bit of code to print to a PDF printer (and of course assign it to print to a specific location) or will it require a the use of another library to print to pdf?</p>
<hr>
<p>I want to print a previosly created document to a pdf file. In this case it a .snp file that I want to make into a .pdf file, but I think the logic would be the same for any file type.</p>
<hr>
<p>I just tried the above shell execute, and it will not perform the way I want it to. as it prompts me as to where I want to print and still does not print where I want it to (multiple locations), which is crucial as we create a lot of the same named PDF files (with different data within the PDF and placed in corresponding client folders) </p>
<hr>
<p>The current process is:</p>
<ul>
<li>Go to \\report server\client1 </li>
<li>create pdf files of all the snp documents in the folder by hand </li>
<li>copy the pdf to \\website reports\client1</li>
<li>then repeat for all 100+ clients takes roughly two hours to complete and verify</li>
</ul>
<p>I know this can be done better but I have only been here three months and there were other pressing concerns that were a lot more immediate. I also was not expecting something that looks this trivial to be that hard to code.</p>
|
<p>This is how I do it in VBScript. Might not be very useful for you but might get you started. You need to have a PDF maker (adobe acrobat) as a printer named "Adobe PDF".</p>
<pre><code>'PDF_WILDCARD = "*.pdf"
'PrnName = "Adobe PDF"
Sub PrintToPDF(ReportName As String, TempPath As String, _
OutputName As String, OutputDir As String, _
Optional RPTOrientation As Integer = 1)
Dim rpt As Report
Dim NewFileName As String, TempFileName As String
'--- Printer Set Up ---
DoCmd.OpenReport ReportName, View:=acViewPreview, WindowMode:=acHidden
Set rpt = Reports(ReportName)
Set rpt.Printer = Application.Printers(PrnName)
'Set up orientation
If RPTOrientation = 1 Then
rpt.Printer.Orientation = acPRORPortrait
Else
rpt.Printer.Orientation = acPRORLandscape
End If
'--- Print ---
'Print (open) and close the actual report without saving changes
DoCmd.OpenReport ReportName, View:=acViewNormal, WindowMode:=acHidden
' Wait until file is fully created
Call waitForFile(TempPath, ReportName & PDF_EXT)
'DoCmd.Close acReport, ReportName, acSaveNo
DoCmd.Close acReport, ReportName
TempFileName = TempPath & ReportName & PDF_EXT 'default pdf file name
NewFileName = OutputDir & OutputName & PDF_EXT 'new file name
'Trap errors caused by COM interface
On Error GoTo Err_File
FileCopy TempFileName, NewFileName
'Delete all PDFs in the TempPath
'(which is why you should assign it to a pdf directory)
On Error GoTo Err_File
Kill TempPath & PDF_WILDCARD
Exit_pdfTest:
Set rpt = Nothing
Exit Sub
Err_File: ' Error-handling routine while copying file
Select Case Err.Number ' Evaluate error number.
Case 53, 70 ' "Permission denied" and "File Not Found" msgs
' Wait 3 seconds.
Debug.Print "Error " & Err.Number & ": " & Err.Description & vbCr & "Please wait a few seconds and click OK", vbInformation, "Copy File Command"
Call sleep(2, False)
Resume
Case Else
MsgBox Err.Number & ": " & Err.Description
Resume Exit_pdfTest
End Select
Resume
End Sub
Sub waitForFile(ByVal pathName As String, ByVal tempfile As String)
With Application.FileSearch
.NewSearch
.LookIn = pathName
.SearchSubFolders = True
.filename = tempfile
.MatchTextExactly = True
'.FileType = msoFileTypeAllFiles
End With
Do While True
With Application.FileSearch
If .Execute() > 0 Then
Exit Do
End If
End With
Loop
End Sub
Public Sub sleep(seconds As Single, EventEnable As Boolean)
On Error GoTo errSleep
Dim oldTimer As Single
oldTimer = Timer
Do While (Timer - oldTimer) < seconds
If EventEnable Then DoEvents
Loop
errSleep:
Err.Clear
End Sub
</code></pre>
|
Is there a maximum number of characters that can be written using a StreamWriter? <p>Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that <code>WriteLine()</code> can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code:</p>
<pre><code>StreamWriter sw = new StreamWriter(pathToFile);
foreach (GridViewRow record in gv_Records.Rows)
{
string recordInfo = "recordInformation";
sw.WriteLine(recordInfo);
}
</code></pre>
|
<p>Are you calling StreamWriter.Close() or Flush()?</p>
|
AJAX and the Browser Back Button <p>I run a browser based game at www.darknovagames.com. Recently, I've been working on reformatting the site with CSS, trying to get all of its pages to verify according to the HTML standard.</p>
<p>I've been toying with this idea of having the navigation menu on the left AJAX the pages in (rather than taking the user to a separate page each time, requiring a reload of the title and nav bar, which almost never change) and I know that if I do so, I will probably break the Forward/Back buttons in the browser. My question I guess is, should I go ahead and AJAX the site, thus requiring the user to use the sites navigation to play the game, or should I leave the site as it currently stands, and use standard hyperlinks and things for navigation?</p>
<p>The reason I ask I guess is that I built a forums system into the site, and a lot of times I would want to link say to a particular topic within the forums.</p>
<p>I'm also open to suggestions. Is there a standard (preferably without traditional frames) way to make only the body area of the site reload, while still changing the URL so that users can bookmark and forward/back, etc? That could potentially solve my problem as well. I'm just asking for the best solution here, not an answer to a specific question. ^_^</p>
<p>Thanks</p>
|
<p>Use ajax for portions of the page that needs to update, not the entire thing. For that you should use templates.</p>
<p>When you want to still preserve the back button for your various state changes on the page, combine them with # achors to alter the url (without forcing the browser to issue another GET).</p>
<p>For example, gmail's looks like this:</p>
<p>mail.google.com/#inbox/message-1234</p>
<p>everything past the # was a page state change that happened via ajax. If I press Back, I'll go to the inbox again (again, without another browser GET)</p>
|
ASP.NET project size <p>Are there any known issues around how many "pages" are in an ASP.NET project?</p>
<p>Does the size of the DLL created by the project matter at all?</p>
<p>My existing project is about 150 pages and the DLL is only around 3MB but it has increased from about 50 pages and 0.5 MB recently</p>
|
<p><a href="http://www.hanselman.com/blog/WhatsTheUpperLimitOnTheNumberOfProjectsWithinVS2005.aspx" rel="nofollow">Scott Hanselman</a> got on the subject two years ago.</p>
<p>The absolute limit is your system memory. The bigger the project the more memory it will use.</p>
<p>Surely you can stay in a [50-200] projects in a solution.</p>
<p>If you find your Visual Studio taking more than memory than expected start thinking about breaking your projects up. </p>
<p>In my opinion the best thing to do is to make the project size a design requirement.</p>
<p><strong>EDIT</strong> : I'm not really answering to your question. To make it clear. The more elements (Pages, projects, image, references, etc.) you have in your VS2003, VS2005 or VS2008 solution the more Visual Studio will take on memory.</p>
|
Generic GDI+ Error <p>I have a Form being launched from another form on a different thread. Most of the time it works perfectly, but I get the below error from time to time. Can anyone help?</p>
<pre><code>at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at System.Drawing.Icon.ToBitmap()
at System.Windows.Forms.ThreadExceptionDialog..ctor(Exception t)
at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
at System.Windows.Forms.Control.WndProcException(Exception e)
at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
</code></pre>
|
<p>The user has to be able to see multiple open accounts simultaneously, right? So you need multiple instances of a form?</p>
<p>Unless I'm misreading something, I don't think you need threads for this scenario, and I think you are just introducing yourself to a world of hurt (like these exceptions) as a result.</p>
<p>Assuming your account form is called AccountForm, I'd do this instead:</p>
<pre><code>Dim acctForm As New AccountForm()
acctForm.Show()
</code></pre>
<p>(Of course you'll have your own logic for that ... ) I might even put it in the <code>ShowForm</code> method so that I could just update my caller thusly:</p>
<pre><code>ShowForm()
</code></pre>
<p>And be done. Now all of this assumes that you've encapsulated the AccountForm nicely so that each instance has its own data, and they don't share anything between instances.</p>
<p>Using threads for this is not only overkill, but likely to introduce bugs like the exception at the top. And my experience in debugging multi-threaded WinForms apps has shown that these bugs are often very difficult to replicate, and extremely tricky to find and fix. Oftentimes, the best fix is to not multithread unless you absolutely, positively <strong>have</strong> to.</p>
|
HTML/Javascript app that runs on the filesystem, security issue <p>I'm putting together a little tool that some business people can run on their local filesystems, since we don't want to setup a host for it.</p>
<p>Basically, its just HTML + Javascript (using jQuery) to pull some reports using REST from a 3rd party.</p>
<p>The problem is, FF3 and IE don't allow the ajax call, I get:</p>
<pre><code>Access to restricted URI denied" code: "1012
</code></pre>
<p>Obviously its an XSS issue...how do I work around it? The data returned is in XML format.</p>
<p>I was trying to do it this way:</p>
<pre><code>$.get(productUrl, function (data){
alert (data);
});
</code></pre>
<p><strong>EDIT</strong>: To be clear...I'm not setting up an internal host for this(Way to much red tape), and we CANNOT host this externally due to the data being retrieved.</p>
<p><strong>EDIT #2</strong>: A little testing shows that I can use an IFRAME to make the request. Does anyone know if there any downsides to using a hidden IFRAME?</p>
|
<p>In a similar situation, my solution was to use Mark Of The Web, which is a special HTML comment that IE recognizes. It places the page in a different security zone.</p>
<p>Reference: <a href="http://msdn.microsoft.com/en-us/library/ms537628(VS.85).aspx" rel="nofollow">MSDN</a></p>
|
Best Source Control Solution for Oracle/ASP.NET Environment? <p>I am trying to plan a way for 5 developers to use Visual Studio 2005/2008 to collaboratively develop an ASP.NET web app on a development web server against an Oracle 8i(soon to be 10g) Database.</p>
<p>The developers are either on the local network or coming in over a vpn (not a very fast connection), </p>
<p>I evaluated the latest Visual SourceSafe, but ran into the following gotchas: </p>
<p>1) We can't use decentralized development because we can't replicate a development oracle database to all developers computers. Also, the vpn is too slow to let their local app instances connect to the database server.</p>
<p>2) Since VSS source code not on the file system, the only way to debug it is to build the app and run debugger, which only one developer can do at a time on a centralized development server. This is unacceptable. We tried using shadow folders so that every time a file is checked in it gets published to the app instance on the development server, but this failed for remote developers on the vpn. </p>
<p>3) Since the developers do a lot of web code, it is important for productivity reasons that when they SAVE a file, they should be able to immediately see the change working on the development server. </p>
<p>4) No easy way to implement a controlled process for pushing files to the production server. </p>
<p>Any suggestions on a source control solution that would work under these contraints? </p>
<p>Thanks in advance for any suggestions!</p>
<p><strong>Update:</strong> I guess since development is forced to be on the server, we need to go with a "Lock and Check In" model. So which source control solution would work best for "Lock and Check In' scenarios?</p>
<p><strong>Update:</strong> Does Visual SVN support developing centrally against a development server? As in, the dev can immediately see his update on the development server after saving in VS? </p>
|
<p>I have used <a href="http://subversion.tigris.org/" rel="nofollow">Subversion</a> and <a href="http://tortoisesvn.tigris.org/" rel="nofollow">TortoiseSVN</a> and was very pleased.</p>
|
Should QA test from a strictly black-box perspective? <p>Assuming that unit tests are handled by development, is there any reason for QA to have knowledge of the details of how a product works? By which I mean, do they need to know what's going on in the background and should they test segments of a product without using the normal UI? For example, would it make sense for a tester to go into a database and manually change values to see what will happen?<BR><BR>
EDIT:
<br>
Let's assume that we're working with an application to be used by non-developers, we're not working on something with an API attached.</p>
|
<p>It depends on the approach and the kind of software you are writing. There are different kinds of QA. If the software should be fault-tolerant, QA should simulate faults. Also, knowing how a product works can help QA think of potentially problematic cases and test them more thoroughly.</p>
<p>On the other hand, knowing how a product works might prevent the QA from testing completely from the user's point of view. So maybe first the basic tests should be designed without knowing the internals, and then more in-depth tests based on potential problems.</p>
|
Ping Failure Without IPv6 <p>Our user interface is communicating with another application on a different machine, often connecting using domain names. </p>
<p>On our network, when IPv6 is installed, DNS name resolution works great, all machines can be pinged and contacted fine.</p>
<p>When IPv6 is uninstalled, pinging the same DNS names returns an IP address on some distant subnet (24.28.193.9; local subnet is 192.168.1.1); our application is then unable to communicate. When IPv6 is reinstalled, the DNS resolution corrects itself. </p>
<p>Even without IPv6 when ping is not working, I can still browse other machines using Windows Explorer by entering <code>\\\\MACHINE_NAME\\</code>. I'm not sure why the name resolution seems to work here. We are working in the Windows XP SP2 environment.</p>
<p>The IPs of the machines can be pinged successfully. It is only the DNS names that do not resolve properly. </p>
<p>I looked for the address of our DNS server. All of our computers are pointing at the network gateway, which is a wireless router. The router has the same DNS server address listed when IPv6 is installed as it does when it isn't installed.</p>
<p>The strangest thing is that I just discovered that it does not matter what DNS name I ping. All pings to DNS names return the same address: "24.28.193.9".</p>
<p>I tried flushing the DNS Resolver Cache and registering DNS on the target machine and the source machine. All to no avail. The only DNS name that I can ping is the name of the current machine.</p>
<p>Any thoughts as to why our software can't communicate without IPv6 installed?</p>
<hr>
<p><strong>UPDATE:</strong> </p>
<p>OK, I've done a little more research now.</p>
<p>I looked for the address of our DNS server. All of our computers are pointing at the network gateway, which is a wireless router. The router has the same DNS server address listed when IPv6 is installed as it does when it isn't installed.</p>
<p>The strangest thing is that I just discovered that it does not matter what DNS name I ping. All pings to DNS names return the same address: "24.28.193.9".</p>
<p>I tried flushing the DNS Resolver Cache and registering DNS on the target machine and the source machine. All to no avail. The only DNS name that I can ping is the name of the current machine.</p>
<p>Any other suggestions? Thanks so much for your help.</p>
|
<p>You've got multiple things going on here</p>
<ol>
<li>DNS Name resolution</li>
<li>Windows Name resolution</li>
<li>IP-IP ICMP communication</li>
</ol>
<p>You've written your question as if there's a problem with #3, but everything you describe points to the problem actually being with #1. If you take resolution out of the question, can you ping the correct IPs with our without IPv6 installed?</p>
<p>It sounds like maybe you have an IPv6 name server installed that has correct information and the IPv4 name server is incorrect? Are you receiving name servers via DHCP or hard coding? What are the IPs of the name servers you are using when IPv6 is installed and when it isn't?</p>
|
Sql 2005 Express edition slow connections <p>I'm running SqlServer 2005 express edition on my laptop for development purposes. It seems that when I open a connection to the database, the setup time is REALLY slow. It can take up to 10 seconds to get a connection. I usually have multiple connections open at the same time (Profiler, Development environment, Query Analyser, etc.) I have a hunch that the slow times are related to the fact that I have multiple connections open. </p>
<p>Is there a governor in Express edition that throttles connection times when multiple connections are made to an instance?</p>
<p>Update:
My workstation is not on active directory, and SQL is running mixed mode security. I will try the login with sql authentication. I am not using user instances.</p>
<p>Update2:
I setup a trace to try and figure out what is going on. When the connection to the database is opened the follow command is executed:</p>
<pre><code>master.dbo.sp_MShasdbaccess
</code></pre>
<p>This command takes 6 seconds to execute.</p>
|
<p>I figured it out. The problem was I had multiple databases with AutoClose set to true. I shut it off in all my databases and the problem went away.</p>
<p>see <a href="http://www.sqlservercentral.com/articles/Administering/autoclosefordatabases/891/" rel="nofollow">this article</a> for more info.</p>
|
Why is it that UTF-8 encoding is used when interacting with a UNIX/Linux environment? <p>I know it is customary, but why? Are there real technical reasons why any other way would be a really bad idea or is it just based on the history of encoding and backwards compatibility? In addition, what are the dangers of not using <code>UTF-8</code>, but some other encoding (most notably, <code>UTF-16</code>)? </p>
<p>Edit : By interacting, I mostly mean the <code>shell</code> and <code>libc</code>. </p>
|
<p>Partly because the file systems expect NUL ('\0') bytes to terminate file names, so UTF-16 would not work well. You'd have to modify a lot of code to make that change.</p>
|
Programmatically launching standalone Adobe flashplayer on Linux/X11 <p>The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.</p>
<p>My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke. </p>
<p>If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.</p>
<p><b>UPDATE</b> (the solution I used... thanks to ypnos' answer):</p>
<pre><code>./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F
</code></pre>
|
<p>You can use a dedicated application which sends the keystroke to the window manager, which should then pass it to flash, if the window starts as being the active window on the screen. This is quite error prone, though, due to delays between starting flash and when the window will show up.</p>
<p>For example, your script could do something like this:
flashplayer *.swf
sleep 3 && xsendkey Control+F</p>
<p>The application xsendkey can be found here: <a href="http://people.csail.mit.edu/adonovan/hacks/xsendkey.html" rel="nofollow">http://people.csail.mit.edu/adonovan/hacks/xsendkey.html</a>
Without given a specific window, it will send it to the root window, which is handled by your window manager. You could also try to figure out the Window id first, using xprop or something related to it.</p>
<p>Another option is a Window manager, which is able to remember your settings and automatically apply them. Fluxbos for example provides this feature. You could set fluxbox to make the Window decor-less and stretch it over the whole screen, if flashplayer supports being resized. This is also not-so-nice, as it would probably affect all the flashplayer windows you open ever.</p>
|
To Nest or Not to Nest? <p><strong>Premise:</strong>
Usually during preparation of a new Ruby on Rails App, I draw out models and relations regarding user navigations. Usually I hit a place where I need to ask myself, whether or not I should go beyond the usual "rule of thumb" of nesting no more 1 level deep. Sometimes I feel the need to nest, rather than creating another namespace route and duplicating work.
<br/>Here's an example:<br/></p>
<p><strong>Models:</strong> User, Company, Location <br/>
User has and belongs to many Companies (many to many) <br/>
User has and belongs to many Locations (many to many) <br/>
Company has and belongs to many Locations (many to many) <br/></p>
<p><strong>Routes:</strong><br/>
<strong><em>1 level nesting</em></strong> <br/>
users/:user_id/companies/ - list all companies related to a user<br/>
users/:user_id/locations/ - list all locations related to a user<br/>
<strong><em>more than 1 level nesting</em></strong><br/>
users/:user_id/companies/:company_id/locations/ - list all company-locations of a user</p>
<p><strong>So, my question is whether or not it is appropriate to nest more than 1 level deep in RoR? Yes or no? And why?</strong></p>
|
<p>I tend to follow Jamis Buck's <a href="http://weblog.jamisbuck.org/2007/2/5/nesting-resources" rel="nofollow">advice</a> and never nest more than one level deep.</p>
<p>Edit:
If you are going to nest more than 1 level I would check out the new <a href="http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-shallow-routes" rel="nofollow">shallow routes</a> feature in Edge</p>
|
How can I see my applications threads while debugging in Visual Studio? <p>I would like to see the threads currently active in my application while debugging it.</p>
<p>How can I do this using Visual Studio?</p>
|
<p>Yes, go to Debug->Windows->Threads</p>
|
How to create and resolve relative paths? <p>My app open file in subdirectory of directory where it is executed, subdirectory is called <code>sample</code> and it contains files:</p>
<ul>
<li><code>example.raf</code> (example extension, non significant)</li>
<li><code>background.gif</code></li>
</ul>
<p><code>example.raf</code> contains relative path to <code>background.gif</code> (in this case only file name cause the files is in same directory as raf) and opening of RAF causes application to read and display <code>background.gif</code>.</p>
<p>When I use <code>OpenFileDialog</code> to load RAF file everything is alright, image loads correctly. I know that open file dialog changes in some way current working directory but i was unable to recreate this without calling open file dialog</p>
<p>Unfortunately in case when i call <strong>raf reading</strong> method directly from code, without supplying path to file form <code>OpenFileDialog</code> like this</p>
<pre><code>LoadRAF("sample\\example.raf");
</code></pre>
<p>in this case i got problem, app try to load image from <strong>ExecutablePath</strong> and not from subdirectory which contains <strong>RAF</strong> file and <strong>image</strong>. Ofcourse it is normal behavior but in this case it is highkly unwanted. It is required to handle both relative and absolute type of paths in my app, so what should i do to solve this, how to <strong>change ExecutablePath</strong> or what other thing i can do to make this work at least as in case of <code>OpenFileDialog</code>?</p>
|
<p>Next code from my project ZipSolution (http://zipsolution.codeplex.com/)
shows how to resolve and create relative pathes in .net</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ZipSolution
{
internal static class RelativePathDiscovery
{
/// <summary>
/// Produces relative path when possible to go from baseLocation to targetLocation
/// </summary>
/// <param name="baseLocation">The root folder</param>
/// <param name="targetLocation">The target folder</param>
/// <returns>The relative path relative to baseLocation</returns>
/// <exception cref="ArgumentNullException">base or target locations are null or empty</exception>
public static string ProduceRelativePath(string baseLocation, string targetLocation)
{
if (string.IsNullOrEmpty(baseLocation))
{
throw new ArgumentNullException("baseLocation");
}
if (string.IsNullOrEmpty(targetLocation))
{
throw new ArgumentNullException("targetLocation");
}
if (!Path.IsPathRooted(baseLocation))
{
return baseLocation;
}
if (!Path.IsPathRooted(targetLocation))
{
return targetLocation;
}
if (string.Compare(Path.GetPathRoot(baseLocation), Path.GetPathRoot(targetLocation), true) != 0)
{
return targetLocation;
}
if (string.Compare(baseLocation, targetLocation, true) == 0)
{
return ".";
}
string resultPath = ".";
if (!targetLocation.EndsWith(@"\"))
{
targetLocation = targetLocation + @"\";
}
if (baseLocation.EndsWith(@"\"))
{
baseLocation = baseLocation.Substring(0, baseLocation.Length - 1);
}
while (!targetLocation.StartsWith(baseLocation + @"\", StringComparison.OrdinalIgnoreCase))
{
resultPath = resultPath + @"\..";
baseLocation = Path.GetDirectoryName(baseLocation);
if (baseLocation.EndsWith(@"\"))
{
baseLocation = baseLocation.Substring(0, baseLocation.Length - 1);
}
}
resultPath = resultPath + targetLocation.Substring(baseLocation.Length);
// preprocess .\ case
return resultPath.Substring(2, resultPath.Length - 3);
}
/// <summary>
/// Resolves the relative pathes
/// </summary>
/// <param name="relativePath">Relative path</param>
/// <param name="basePath">base path for discovering</param>
/// <returns>Resolved path</returns>
public static string ResolveRelativePath(string relativePath, string basePath)
{
if (string.IsNullOrEmpty(basePath))
{
throw new ArgumentNullException("basePath");
}
if (string.IsNullOrEmpty(relativePath))
{
throw new ArgumentNullException("relativePath");
}
var result = basePath;
if (Path.IsPathRooted(relativePath))
{
return relativePath;
}
if (relativePath.EndsWith(@"\"))
{
relativePath = relativePath.Substring(0, relativePath.Length - 1);
}
if (relativePath == ".")
{
return basePath;
}
if (relativePath.StartsWith(@".\"))
{
relativePath = relativePath.Substring(2);
}
relativePath = relativePath.Replace(@"\.\", @"\");
if (!relativePath.EndsWith(@"\"))
{
relativePath = relativePath + @"\";
}
while (!string.IsNullOrEmpty(relativePath))
{
int lengthOfOperation = relativePath.IndexOf(@"\") + 1;
var operation = relativePath.Substring(0, lengthOfOperation - 1);
relativePath = relativePath.Remove(0, lengthOfOperation);
if (operation == @"..")
{
result = Path.GetDirectoryName(result);
}
else
{
result = Path.Combine(result, operation);
}
}
return result;
}
}
}
</code></pre>
|
CLOS like object model for PHP <p>I have returned to php development from <a href="http://www.iinteractive.com/moose/" rel="nofollow">Moose</a> and I really miss CLOS like object model for php. Is there some kind of syntaxtic sugar which would allow me to write <strong>less code</strong> in php when dealing with objects?</p>
<p>Just to stress this requirement a bit more. I don't want to write one thing in several places. I can live with part of code being generated automatically, but in the code that I have to see to develop I don't want to see redundant information which is just clutter (think: LISP macro if you really need more analogy). So this part can be also called DSL if that makes more sense.</p>
<p>I would love to have at least <strong>roles</strong> (mixins), and some kind of <strong>introspection</strong> without re-inventing the weel. Code generators and auto-loaders might be one way to solve at least part of this problem.</p>
<p>p.s. For JavaScript there is <a href="http://code.google.com/p/joose-js/" rel="nofollow">Joose</a>, so similar API would be very useful.</p>
|
<p>There are no mixins in php yet but there is an RFC for traits which will work roughly the same. <a href="http://wiki.php.net/rfc/traits" rel="nofollow">http://wiki.php.net/rfc/traits</a></p>
<p>Using overloading for __call can allow you to dispatch methods to other classes and have it look like a mixin.</p>
|
If I grab a paramenter out of the query string, is it URL decoded? <p>In .NET if I do something like:</p>
<pre><code>string temp = Request.QueryString["myKey"];
</code></pre>
<p>is the value in temp already URL decoded?</p>
|
<p>Yes, it is.</p>
|
Referencing build artifacts from an svn:external build in .Net project <p>This is a continuation question from a previous question <a href="http://stackoverflow.com/questions/142237/integrating-external-sources-in-a-build.">I have asked</a></p>
<p>I now have a /externals directory in the root of my project tree. Inside this I have a reference to another project. I'm able to script the build of all my externals in the main project NAnt script. The result of these builds are as follows:</p>
<p>/externals/external-project1/build/buildartifacts/{dlls|html|js}</p>
<p>/externals/external-project2/build/buildartifacts/{dlls|html|js}</p>
<p>This is all well and good, but now I'm curious as to how my main project should reference these build artifacts. For example, let's say that external project builds a DLL that some of my codebase depends on. Should I simply reference the DLL in the build artifacts directory or should I implement another NAnt task that copies these to a /thirdparty/libs/ folder?</p>
<p>This means that my build is now dependent on the ability to build this external project (which could either be internal, or thirdparty). Is it a good idea to check in the latest set of build artifacts to ensure that the main build won't break because of dependent builds breaking?</p>
<p>Hope that's clear enough. Just writing this down has a least clarified the problem for me :-).</p>
<p>--Edit--</p>
<p>Thanks guys. I think I'm going to implement the "checkout a revision", but since the builds are so quick I'm not going to check in any build artifiacts. Also going to have to figure out how to deal with the dependencies of the external project (eg: prototype, swfobject, etc).</p>
|
<p>I'd say build them once and check the build artifacts in /public/ext/some_dependency/ref (obviously, the naming of that folder is up to you :-)) and reference them from there.</p>
<p>My main reason is that you seldom need to build external dependencies every time you do a build of your product. In general external dependencies should be changing rarely. Plus, you want strict control over when you pick external dependency changes, to avoid introducing instability during the coding phase.</p>
<p>As a extension to this, I would add a separate CI task that would build the external dependencies only and check them in the aforementioned folder upon some external condition - a commit in the dependency source folder or something else.</p>
|
Installing .NET 3.5 on a server with .NET 2.0 applications <p>I would like to upgrade my web projects on an IIS 5 server from .NET 2.0 to .NET 3.5. These web applications live on a server with other web applications that will not be upgraded to .NET 3.5. The server administrator is reluctant to install .NET 3.5 because he is afraid it will break the applications on that machine that are running 2.0 and 1.1.</p>
<p>As far as I know this WON'T be a problem since .NET 3.5 is an addition to 2.0 more than it is a new Framework. I would like the communities help gathering evidence to show him that their concerns are moot and it won't hurt the other applications.</p>
<p>Thanks in advance.</p>
|
<p>If you have .NET 2 SP1 you shouldn't have a problem.</p>
<p>To be exact .NET 3 & 3.5 are built on top of .NET 2.0 SP 1, we had a problem deploying 3.5 onto a server which only had .NET 2 (not SP1) and it caused the apps on there to break. The reason is your core framework assemblies in .NET 2 are upgraded and have new version numbers which the app wasn't compiled against.</p>
|
SubSonic SubSonic.SqlQuery & Dates <p>Does SubSonic.SqlQuery have a between/and for date ranges? If not, what would be the best way to get a range.</p>
|
<p>Try something like this:</p>
<pre><code>SqlQuery query = new SqlQuery().From("Table")
.WhereExpression("Column")
.IsBetweenAnd("1/1/2008", "12/31/2008");
DataSet dataSet = query.ExecuteDataSet(); // Or whatever output you need
</code></pre>
|
In Ruby on Rails, how do I format a date with the "th" suffix, as in, "Sun Oct 5th"? <p>I want to display dates in the format: short day of week, short month, day of month without leading zero but including "th", "st", "nd", or "rd" suffix.</p>
<p>For example, the day this question was asked would display "Thu Oct 2nd".</p>
<p>I'm using Ruby 1.8.7, and <a href="http://ruby-doc.org/core/Time.html#method-i-strftime">Time.strftime</a> just doesn't seem to do this. I'd prefer a standard library if one exists.</p>
|
<p>Use the ordinalize method from 'active_support'.</p>
<pre><code>>> time = Time.new
=> Fri Oct 03 01:24:48 +0100 2008
>> time.strftime("%a %b #{time.day.ordinalize}")
=> "Fri Oct 3rd"
</code></pre>
<p>Note, if you are using IRB with Ruby 2.0, you must first run:</p>
<pre><code>require 'active_support/core_ext/integer/inflections'
</code></pre>
|
How to add a Tooltip to a "td" with jquery? <p>I need to add a tooltip/alt to a "td" element inside of my tables with jquery.</p>
<p>Can someone help me out?</p>
<p>I tried:</p>
<pre><code>var tTip ="Hello world";
$(this).attr("onmouseover", tip(tTip));
</code></pre>
<p>where I have verified that I am using the "td" as "this".</p>
<p>**Edit:**I am able to capture the "td" element through using the "alert" command and it worked. So for some reason the "tip" function doesn't work. Anyone know why this would be?</p>
|
<pre><code>$(this).mouseover(function() {
tip(tTip);
});
</code></pre>
<p>a better way might be to put <code>title</code> attributes in your HTML. That way, if someone has javascript turned off, they'll still get a tool tip (albeit not as pretty/flexible as you can do with jQuery).</p>
<pre><code><table id="myTable">
<tbody>
<tr>
<td title="Tip 1">Cell 1</td>
<td title="Tip 2">Cell 2</td>
</tr>
</tbody>
</table>
</code></pre>
<p>and then use this code:</p>
<pre><code>$('#myTable td[title]')
.hover(function() {
showTooltip($(this));
}, function() {
hideTooltip();
})
;
function showTooltip($el) {
// insert code here to position your tooltip element (which i'll call $tip)
$tip.html($el.attr('title'));
}
function hideTooltip() {
$tip.hide();
}
</code></pre>
|
Why is my Perl regex using so much memory? <p>I'm running a regular expression against a large scalar. Though this match isn't capturing anything, my process grows by 30M after this match:</p>
<pre><code># A
if (${$c} =~ m/\G<<\s*/cgs)
{
#B
...
}
</code></pre>
<p><code>$c</code> is a reference to a pretty big scalar (around 21M), but I've verified that <code>pos(${$c})</code> is in the right place and the expression matches at the first character, with <code>pos(${$c})</code> being updated to the correct place after the match. But as I mentioned, the process has grown by about 30M between #A and #B, even though I'm not capturing anything with this match. Where is my memory going?</p>
<p>Edit: Yes, use of <code>$&</code> was to blame. We are using Perl 5.8.8, and my script was using <a href="http://search.cpan.org/dist/Getopt-Declare" rel="nofollow">Getopt::Declare</a>, which uses the built-in <a href="http://search.cpan.org/dist/Text::Balanced" rel="nofollow">Text::Balanced</a>. The 1.95 version of this module was using <code>$&</code>. The 2.0.0 version that ships with Perl 5.10 has removed the reference to <code>$&</code> and alleviates the problem.</p>
|
<p>Just a quick sanity check, are you mentioning $&, $` or $' (sometimes called $MATCH, $PREMATCH and $POSTMATCH) anywhere in your code? If so, Perl will copy your entire string for <em>every</em> regular expression match, just in case you want to inspect those variables.</p>
<p>"In your code" in this case means indirectly, including using modules that reference these variables, or writing <code>use English</code> rather than <code>use English qw( -no_match_vars )</code>.</p>
<p>If you're not sure, you can use the <a href="http://search.cpan.org/perldoc?Devel::SawAmpersand" rel="nofollow">Devel::SawAmpersand</a> module to determine if they have been used, and <a href="http://search.cpan.org/perldoc?Devel::FindAmpersand" rel="nofollow">Devel::FindAmpersand</a> to figure out <em>where</em> they are used.</p>
<p>There may be other reasons for the increase in memory (which version of Perl are you using?), but the match variables will definitely blow your memory if they're used, and hence are a likely culprit.</p>
<p>Cheerio,</p>
<p><em>Paul</em></p>
|
Can J# code run on JVM <p>If I create a J# Application is there any way I can execute it on JVM as well</p>
|
<p>No, J# programs are designed to run on the .NET platform. See the <a href="http://msdn.microsoft.com/en-nz/vjsharp/bb188604.aspx" rel="nofollow">J# FAQ</a>.</p>
|
How to debug RESTful services? <p>I'm looking for an easy way to debug RESTful services. For example, most webapps can be debugged using your average web browser. Unfortunately that same browser won't allow me to test HTTP PUT, DELETE, and to a certain degree even HTTP POST.</p>
<p>I am not looking to automate tests. I'd like to run new services through a quick sanity check, ideally without having to writing my own client.</p>
|
<p>Use an existing 'REST client' tool that makes it easy to inspect the requests and responses, like <a href="https://github.com/wiztools/rest-client">RESTClient</a>.</p>
|
What's the nicest way to do observer/observable in objective-c (iphone version) <p>I'm used to coding Java Swing UIs, and in those if you have some properties that change, and you want your UI to update, you would implement the observer/observable pattern. In Java you do this normally by having your class maintain a list of listeners that it notifies of different events.</p>
<p>I've played with Objective-C on the Mac, and that has KVC and binding which seems to work very nicely, and requires less code. The iPhone SDK doesn't seem to have this functionality though, so my question is:
If I have a class that holds data that changes, what's the best way for me to register a UI component with that class so that it can be notified of changes in the data that it needs to display?</p>
|
<p>There are two built-in ways of doing observation in Cocoa: Key-Value Observing and notifications. In neither system do you need to maintain or notify a collection of observers yourself; the framework will handle that for you.</p>
<p>Key-Value Observing (KVO) lets you observe a property of an object â including even a property that represents a collection â and be notified of changes to that property. You just need to send the object <code>-addObserver:forKeyPath:options:context:</code> passing the object you want to receive updates, the key path of the property (relative to the receiver) for which you want to receive updates, and the types of updates you want to receive. (There are similar methods you can use if you want to observe a property representing a collection.)</p>
<p>Notifications are older and heavier-weight. You register with an <code>NSNotificationCenter</code> â usually the default center â an object and selector pair to be passed a notification when an event occurs. The notification object itself can contain arbitrary data via its <code>userInfo</code> property, and you can choose to observe all notifications of a specific name rather than those that apply to a particular object.</p>
<p>Which should you use in any particular case? In general, if you care about changes to a specific property of a specific object, use Key-Value Observing. That's what it's designed for and it's intentionally lightweight. (Among other uses, it is the foundation on which Cocoa Bindings are built.) If you care about a change in state that isn't represented by a property, then notifications are more appropriate.</p>
<p>For example, to stay in sync when the user changes the name of a model object, I'd use KVO. To know when an entire object graph was saved, I'd use notifications.</p>
|
What is the best way for me to implement record locking? <p>I have a question about locking. This doesn't have to be only about record locking, but anyway.</p>
<p>Let's say I'm writing a web accessible CMS. I am struggling with some ideas.</p>
<p>I could, on the moment when a user opens an article for editing, flag the article as being 'in use'. so far so good.</p>
<p>but when do I remove the flag? when the user saves the article? but what if the user doesn't feel like typing anymore and decides to close his browser and go to bed?</p>
<p>a time-out mechanism comes to mind, but how long does it take to write an article? 10 minutes too short, 30 minutes too long..</p>
<p>Maybe I am over-complicating this. I'd like to hear your thoughts on this subject.</p>
|
<p>My vote is for <a href="http://www.15seconds.com/issue/030604.htm" rel="nofollow">optimistic locking</a> wherever possible. </p>
<p>In one place, where I have implemented actual locks, I had an admin page to remove locks. There was also a service running on the server to unlock any locks which did not have a corresponding active session..</p>
|
Site-Mining tools <p>Many of the questions asked here are relevant to research I'm doing. These questions and answers are widely dispersed and not always easy to find, doing manual browsing, and sometimes an insightful answer or comment occurs in unrelated topics as well.</p>
<p>I want to automate finding these relevant Q's & A's, based on sets of keywords, then use the information as pointers towards further in-depth research.</p>
<p>What tools, preferably open-source, are available that I can use for this type of site-mining? I am not a web guru & for me to try to develop them will take a long time and also impact on time I could have spent on my R&D.</p>
|
<p>Another option would be using <a href="http://pipes.yahoo.com/pipes/" rel="nofollow">Yahoo! Pipes</a>. (<a href="http://www.jumpcut.com/fullscreen?id=F4396574585311DC87A2000423CF0184&type=clip" rel="nofollow">demo</a>)</p>
<p>You can build such system visually online using a combination of feed urls, filters, etc... Learning time is minimal compared to programming. [edited: tense]</p>
|
How can I get data from a stored procedure into a temp table? <p>Am working on sybase ASE 15. Looking for something like this</p>
<pre><code>Select * into #tmp exec my_stp;
</code></pre>
<p>my_stp returns 10 data rows with two columns in each row.</p>
|
<p>In ASE 15 I believe you can use functions, but they're not going to help with multirow datasets.</p>
<p>If your stored proc is returning data with a "select col1,col2 from somewhere" then there's no way of grabbing that data, it just flows back to the client.</p>
<p>What you can do is insert the data directly into the temp table. This can be a little tricky as if you create the temp table within the sproc it is deleted once the sproc finishes running and you don't get to see the contents. The trick for this is to create the temp table outside of the sproc, but to reference it from the sproc. The hard bit here is that every time you recreate the sproc you must create the temp table, or you'll get "table not found" errors.</p>
<pre><code>
--You must use this whole script to recreate the sproc
create table #mine
(col1 varchar(3),
col2 varchar(3))
go
create procedure my_stp
as
insert into #mine values("aaa","aaa")
insert into #mine values("bbb","bbb")
insert into #mine values("ccc","ccc")
insert into #mine values("ccc","ccc")
go
drop table #mine
go
</code></pre>
<p>The to run the code:</p>
<pre><code>
create table #mine
(col1 varchar(3),
col2 varchar(3))
go
exec my_stp
go
select * from #mine
drop table #mine
go
</code></pre>
|
How can I scale the content of an iframe? <p>How can I scale the content of an iframe (in my example it is an HTML page, and is not a popup) in a page of my web site?</p>
<p>For example, I want to display the content that appears in the iframe at 80% of the original size.</p>
|
<p><a href="http://stackoverflow.com/questions/166160/how-can-i-scale-the-content-of-iframe/2224816#2224816">Kip's solution</a> should work on Opera and Safari if you change the CSS to:</p>
<pre><code><style>
#wrap { width: 600px; height: 390px; padding: 0; overflow: hidden; }
#frame { width: 800px; height: 520px; border: 1px solid black; }
#frame {
-ms-zoom: 0.75;
-moz-transform: scale(0.75);
-moz-transform-origin: 0 0;
-o-transform: scale(0.75);
-o-transform-origin: 0 0;
-webkit-transform: scale(0.75);
-webkit-transform-origin: 0 0;
}
</style>
</code></pre>
<p>You might also want to specify overflow: hidden on #frame to prevent scrollbars.</p>
|
How to convert a DB2 date-time string into an Excel Date <p>I'll regularly get an extract from a DB/2 database with dates and timestaps formatted like this:</p>
<pre><code>2002-01-15-00.00.00.000000
2008-01-05-12.36.05.190000
9999-12-31-24.00.00.000000
</code></pre>
<p>Is there an easier way to convert this into the Excel date format than decomposing with substrings?</p>
<pre><code>DB2date = DateValue(Left(a, 4) + "/" + Mid(a, 6, 2) + "/" + Mid(a, 9, 2))
</code></pre>
<p>thanks for your help!</p>
|
<p>It's not clear if you talk about formula functions or VBA functions.</p>
<h2>Formula functions</h2>
<p>Don't use the DateValue function, which expects a string; use the Date function, which expects numeric Year, Month, Day:</p>
<pre><code>=DATE(INT(LEFT(A1,4)),INT(MID(A1,6,2)),INT(MID(A1,9,2)))
</code></pre>
<p>assuming that the date-as-string is in A1.</p>
<h2>VBA functions</h2>
<p>Similar calculation as above, just use the <strong>DateSerial</strong> function instead:</p>
<pre><code>dt= DateSerial(Int(Left$(dt$, 4), Int(Mid$(dt$, 6, 2)), Int(Mid$(dt$, 9, 2)))
</code></pre>
|
Restore Eclipse subversion project connection <p>I have a project in subversion, which I'm developing using Eclipse. I did the original checkout from the svn repository from inside Eclipse. All was well for some weeks then for some unknown reason, Eclipse (specifically: subclipse in Ganymede) no longer recognizes my project as being under svn control. The team context-menu only shows the basic "apply patch" / "share this project" menu options. From the shell, I can still update the project using the svn command line tools, so I know that the svn credentials still work. Other projects under subversion in the same copy of Eclipse still work.</p>
<p>I realise that I can delete the local copy and check it out again, but I'd rather understand what has gone wrong - fix the problem, rather than mask the symptoms. Where does Eclipse store its knowledge of which projects are under version control? I looked at the <code>.project</code> file and the <code>.settings</code> directory, but couldn't see any obvious mention of svn nature or anything similar, even in the projects that are still working properly.</p>
|
<p>If you are using sublipse as your SVN provider I recommend doing the following</p>
<p>Team -> Share project is usually enough to connect the metadata.</p>
<p>(that is, assuming that the .svn files are still there which they seem to be if you can work on the command line).</p>
<p>Hope this helps as to why this would happen I have no idea</p>
|
Oracle instant client with OraOLE DB provider? <p>Is it possible to use oracle instant client for application that use oraoledb driver for connecting to oracle 9i DB.</p>
|
<p>I don't believe so. The <a href="http://www.oracle.com/technology/tech/oci/instantclient/ic-faq.html#A3661" rel="nofollow">Instant Client FAQ</a> states</p>
<blockquote>
<p>What can Instant Client be used for?
Instant Client can be used to run your OCI, OCCI, Pro*C, JDBC, and ODBC applications without installing a full Oracle Client. In addition, Instant Client supports SQL*Plus. As of Instant Client 10.2, it is also possible to develop applications for OCI and OCCI using the Instant Client SDK download.</p>
</blockquote>
<p>OLE DB is conspicuously absent from that list. Now, potentially, you could use the Microsoft OLE DB to ODBC provider along with the Instant Client and ODBC, but adding additional layers to software is never very fun.</p>
|
Parameterized Sql queries <p>This is a nut I'm cracking these days</p>
<p>Application I'm working on has some advanced processing towards SQL. One of the operations selects various metadata on the objects in the current context from different tables, based on the item names in the collection. For this, a range of "select...from...where...in()" is executed, and to prevent malicious SQL code, Sql parameters are used for constructing the contents of the "in()" clause.</p>
<p>However, when the item collection for constructing the "in()" clause is larger than 2100 items, this fails due to the Sql Server limitation of max 2100 Sql parameters per query.</p>
<p>One approach I'm trying out now is creating a #temp table for storing all item names and then joining the table in the original query, instead of using "where in()". This has me scratching my head on how to populate the table with the item names stored in an Array in the .NET code. Surely, there has to be some bulk way to insert everything rather than issuing a separate "insert into" for each item?</p>
<p>Other than that, I'm very much interested in alternative approaches for solving this issue.</p>
<p>Thanks a lot</p>
|
<p>One potential workaround is to use the ability to query XML and simply send all the data for your 'in' as an xml column and then join on that. </p>
<p>The same approach could be used to populate your temp table, but then again, why not just use it directly.</p>
<p>Here's a short sample that should illustrate:</p>
<pre><code>declare @wanted xml
set @wanted = '<ids><id>1</id><id>2</id></ids>'
select *
from (select 1 Id union all select 3) SourceTable
where Id in(select Id.value('.', 'int') from @wanted.nodes('/ids/id') as Foo(Id))
</code></pre>
<p>Simply build the xml in your application and pass it as parameter.</p>
|
Write a password protected Zip file in Java <p>I need to zip and password-protect a file. Is there a good (free) library for this?</p>
<p>This needs to be opened by a third party, so the password protection needs to work with standard tools.</p>
|
<p>You can try <a href="http://www.lingala.net/zip4j/">Zip4j</a>, a pure java library to handle zip file. It supports encryption/ decryption of PKWare and AES encryption methods.</p>
<p>Key features:</p>
<ul>
<li>Create, Add, Extract, Update, Remove files from a Zip file</li>
<li>Read/Write password protected Zip files</li>
<li>Supports AES 128/256 Encryption</li>
<li>Supports Standard Zip Encryption</li>
<li>Supports Zip64 format</li>
<li>Supports Store (No Compression) and Deflate compression method</li>
<li>Create or extract files from Split Zip files (Ex: z01, z02,...zip)</li>
<li>Supports Unicode file names</li>
<li>Progress Monitor</li>
</ul>
<p>License:</p>
<ul>
<li>Zip4j is released under <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.</li>
</ul>
|
Writing a generic class to handle built-in types <p>Not too practical maybe, but still interesting.</p>
<p>Having some abstract question on matrix multiplication I have quickly implemented a matrix for ints, then tested my assumptions.</p>
<p>And here I noticed that just int matrix is not good, if I occasionally want to use it with decimal or double. Of course, I <em>could</em> try just to cast all to double, but that's not convenient way.</p>
<p>Continue with assumption we could have a bunch of objects we are able to add and multiply - why don't use them in my matrix?</p>
<p>So, just after considering it would be a Matrix class now I faced that generic T could not be used, I need it to support some interface which could add and multiply.</p>
<p>And the problem is I could override operators in my class, but I could not introduce an interface which would support operators. And I have an operators in built-in types, but still no interface over them.</p>
<p>What would you do in such a case considering you do not want to duplicate worker class body? Wrappers and implicit casting didn't help me much, I'm interested in a beautiful solution.</p>
<p>Thanks.</p>
|
<p>For this you need generic maths. Luckily <a href="http://www.yoda.arachsys.com/csharp/genericoperators.html" rel="nofollow">I have done this</a>. Usage would be similar to this "complex" (i.e. x+iy) <a href="http://csharpindepth.com/ViewNote.aspx?NoteID=50" rel="nofollow">example</a>.
The Operator class is now part of <a href="http://www.yoda.arachsys.com/csharp/miscutil/" rel="nofollow">MiscUtil</a>.</p>
|
What deployment directories do you use for Rails applications (deploying to a debian box)? <p>I wonder what's the best deployment directory for Rails apps? Some developers use directories such as <code>/u/apps/#{appname}</code>. Are there <strong>any</strong> advantages when using <code>/u/apps/#{appname}</code> instead of <code>/var/www/#{appname}</code> or other OS default directories?</p>
<p>Obviously I want to pick the directory with the best security properties and the least friction for setting up the server environment.</p>
<p>How do you deploy your Rails apps? Why are you using a specific directory? Do you think it really matters anyway?</p>
|
<p>As other people have said, it really doesn't matter where you keep your applications - the thing that does matter is that you're consistent about it, so that whichever server you're on, its just a case of going to the usual location.</p>
<p>I think the only reason people use /u/apps/#{appname} is that it's Capistrano's default setting - certainly it seems odd to me doing things that way.</p>
|
Does NetworkStream.DataAvailable see buffered data? <p>Does NetworkStream.DataAvialable know whether the sender's send buffer is empty? Or does it simply indicate whether the receiver's read buffer has data? My assumption is the latter...</p>
<p>Specifically, for some socket work involving an ongoing conversation, I currently use a length-prefix so the the receiver knows exactly how much data is in the current batch; however, I've been sent a .patch suggesting I use NetworkStream.DataAvailable instead. My concern is that this will just tell me what the reciever has got - not what the sender originally sent - but I'm not a sockets expert.</p>
<p>Am I wrong? Or is length-prefix the way to go?</p>
<p>(note I can't simply Read() until the stream is closed, since multiple batches are sent on the same connection, and it is vital that I treat each batch as separate; if I read too much in one batch (even if it gets buffered and discarded) then the conversation will break).</p>
|
<p>One side of a connection is not going to know whether the other side's send buffer is empty.</p>
<p><code>DataAvailable</code> only indicates whether there is incoming data to be read. You could use that prior to <code>Read()</code>, but it alone doesn't give you the information you want. It doesn't tell you the beginning and ending of each batch.</p>
<p>I've coded back-and-forth conversation before, and I used length-prefixes in the data. What I did was write helper functions that read an exact number of bytes (chunks at a time) and no more.</p>
<p>The only alternative to length-of-batch values in the stream is some way of examining the incoming data and recognizing the beginnings and endings of batches.</p>
|
What to put in the IF block and what to put in the ELSE block? <p>This is a minor style question, but every bit of readability you add to your code counts.</p>
<p>So if you've got:</p>
<pre><code>if (condition) then
{
// do stuff
}
else
{
// do other stuff
}
</code></pre>
<p>How do you decide if it's better like that, or like this:</p>
<pre><code> if (!condition) then
{
// do other stuff
{
else
{
// do stuff
}
</code></pre>
<p>My heuristics are:</p>
<ol>
<li>Keep the condition positive (less
mental calculation when reading it)</li>
<li>Put the most common path into the
first block</li>
</ol>
|
<p>I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive.</p>
<pre><code>if (condition)
return;
DoSomething();
</code></pre>
<p>I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.</p>
|
java date format incompatible with xquery xs:date format, how to fix? <p>In java, when using SimpleDateFormat with the pattern:</p>
<pre><code>yyyy-MM-dd'T'HH:mm:ss.SSSZ
</code></pre>
<p>the date is outputted as:</p>
<pre><code>"2002-02-01T18:18:42.703-0700"
</code></pre>
<p>In xquery, when using the xs:dateTime function, it gives the error:</p>
<pre><code>"Invalid lexical value [err:FORG0001]"
</code></pre>
<p>with the above date. In order for xquery to parse properly, the date needs to look like:</p>
<pre><code>"2002-02-01T18:18:42.703-07:00" - node the ':' 3rd position from end of string
</code></pre>
<p>which is based on the ISO 8601, whereas Java date is based on the RFC 822 standard.</p>
<p>I would like to be able to easily specify the timezone in Java so that it will output the way that xquery wants.</p>
<p>Thanks!</p>
|
<p>OK, the linked to forum post DID help, thank you. I did however find a simpler solution, which I include below:</p>
<p>1) Use Apache commons.lang java library<br>
2) Use the following java code: </p>
<pre class="lang-java prettyprint-override"><code>//NOTE: ZZ on end is not compatible with jdk, but allows for formatting
//dates like so (note the : 3rd from last spot, which is iso8601 standard):
//date=2008-10-03T10:29:40.046-04:00
private static final String DATE_FORMAT_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSSZZ";
DateFormatUtils.format(new Date(), DATE_FORMAT_8601)
</code></pre>
|
How to repeat a string a variable number of times in C++? <p>I want to insert 'n' spaces (or any string) at the beginning of a string in C++. Is there any direct way to do this using either std::strings or char* strings?</p>
<p>E.g. in Python you could simply do</p>
<pre><code>>>> "." * 5 + "lolcat"
'.....lolcat'
</code></pre>
|
<pre><code>std::string foo = std::string(5, '.') + "lolcat";
</code></pre>
<p>Check out <a href="http://www.cppreference.com/wiki/string/string_constructors">std::string's constructors</a>.</p>
|
Should I have a dedicated primary key field? <p>I'm designing a small SQL database to be used by a web application.</p>
<p>Let's say a particular table has a Name field for which no two rows will be allowed to have the same value. However, users will be able to change the Name field at any time.</p>
<p>The primary key from this table will be used as a foreign key in other tables. So if the Name field was used as the primary key, any changes would need to be propagated to those other tables. On the other hand, the uniqueness requirement would be handled automatically.</p>
<p>My instinct would be to add an integer field to act as the primary key, which could be automatically populated by the database. Is there any point in having this field or would it be a waste of time? </p>
|
<p>I would use a generated PK myself, just for the reasons you mentioned. Also, indexing and comparing by integer is faster than comparing by strings. You can put a unique index on the name field too without making it a primary key.</p>
|
Removing a subset of a dict from within a list <p>This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this:</p>
<pre><code>a = {1:'', 2:'', 3:'', 4:''}
exclusion = [3, 4, 5]
# have to build up a new list or the iteration breaks
toRemove = []
for var in a.iterkeys():
if var in exclusion:
toRemove.append(var)
for var in toRemove:
del a[var]
</code></pre>
<p>This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict.</p>
<p>This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.</p>
|
<p>Consider <a href="http://docs.python.org/library/stdtypes.html#dict.pop" rel="nofollow">dict.pop</a>:</p>
<pre><code>for key in exclusion:
a.pop(key, None)
</code></pre>
<p>The <code>None</code> keeps pop from raising an exception when <code>key</code> isn't a key.</p>
|
RSpec Stories and Specs: When to use what? <p>So I want to start using RSpec stories, but I am not sure where writing controller, model and view specs fit in. </p>
<p>For example, you have the story "Logging in" with "User provides wrong password" scenario, don't you end up testing the same stuff than controller/model specs (response.should render..., user.should be_nil, etc.)</p>
<p>So my question is: for those who are used to doing bdd (or story dd) with RoR, do you still write model/controller specs? If so, how is the workflow you follow ("first story, then narrow to specific specs")?</p>
|
<p>If you are starting with stories now (as opposed to having a lot of legacy stories) you may want to look at <a href="http://github.com/aslakhellesoy/cucumber/wikis/migration-from-rspec-stories">Cucumber</a> which is the long term replacement for the RSpec story runner.</p>
<p>The easiest way of splitting between specs and stories is to use stories for full-stack testing of business requirements and specs for isolated low-level specifications of the components (views, helpers, controllers and models). 'Full stack' can a range from controller/model/database through client simulation with Webrat to in-browser testing with Watir or Selenium.</p>
<p>The ultimate 'outside in' BDD way of doing things is to start with stories based on customer requirements and then add in specs for the components you find you need when implementing the stories. Ideally you will fully cover the individual components with specs and have stories for the most important workflows of your users so you can check at the highest level that your app is delivering the functionality you have been asked for.</p>
|
Class data responsibilities <p>I have a 'Purchase Order' class. It contains information about a single purchase order. I have a DAO class for database methods.</p>
<p>Where should the responsibility reside for the methods that will load and update the purchase order?</p>
<p>Should the PurchaseOrder class have '.update', 'insert', 'delete', and '.load' methods that use the DAO class directly, or should the PurchaseOrder class be ignorant of the DAO methods and have a POController class that manages these interactions?</p>
<p>The user will only be working on a single PurchaseOrder at a time.</p>
<p>Thanks!</p>
|
<p>The Purchase Order should be ignorant of the details of its persistence. This is the point of having some sort of data access layer, it handles the management of the object and the object itself can concentrate on just being a purchase order.</p>
<p>This also makes the system easier to test, as you can create mock Purchase orders and test the logic of how the system handles them without getting entangled in persistence issues.</p>
|
Eclipse for IntelliJ Idea Users <p>I have a coworker who is looking to switch from InteilliJ Idea to Eclipse, and is concerned about not knowing the Eclipse set of commands. </p>
<p>I was wondering - would anyone have a link to keyboard mappings that can set Eclipse commands to at least sort of match Idea? </p>
<p>Have you made this switch? Any "gotchas", tips, or info we should be aware of? </p>
<p>Thanks!</p>
|
<p>Get the plugin from <a href="http://www.jroller.com/santhosh/entry/intellij_idea_key_scheme_for">here</a>. It seems easier to install than the one in Bartosz' answer, plus no 404s...</p>
<p>For the lazy: <a href="http://jroller.com/santhosh/resource/IdeaKeyScheme_1.0.0.jar">direct link to plugin</a></p>
<p>Drop the plugin jar in eclipse/plugins folder and restart eclipse. Now in preferences dialog under General > Keys you can find "Intellij Idea" key scheme.</p>
|
Does anyone know some cool PL/SQL plugin for IntelliJ Idea? <p>I've evaluated some plugins from official IntelliJ repository, but none of them seems to provide more then basic syntax highlighting. Even highlighting is limited. For example, Database Navigator doesn't highlight IF. It would be great to have proper highlighting. And if it would have auto-complete feature and provide file structure view I would be completely happy.
I use SQL Query Plugin when I need to post some little stuff to database or to query something from it. I use PL/SQL Developer when I need to make more complex things, or when I need to modify PL/SQL. But most of the time I need to navigate through mix of Java, JavaScript and PL/SQL code. Unfortunately, SQL Query Plugin doesn't help with that as well as PL/SQL Developer.</p>
|
<p>Have you tried <a href="http://java.sstiller.de/sql/index.html" rel="nofollow" title="KiwiSoft - SQL Query Plugin">SQL Query Plugin</a>? It comes with a great host of features, including multiple query windows, direct editing of tables, and of course, proper highlighting for PL/SQL syntax and a browser of the internal database structure.</p>
<p>It also integrates well with the main editor: you can right-click on any selected Java string containing SQL and "Send to SQLPlugin" to strip out all of the quotes and non-SQL syntax.</p>
|
Is there a way to prevent the VB6 compiler from shuffling the contents of files? <p>For reasons unknown, the VB6 compiler often likes to reorder the contents of .vbp files and the control descriptor block at the top of .frm files (The code that describes the properties of controls on the form. Code that you don't see in the IDE but you do see in a text editor and <em>when doing diffs against the previous revision in version control</em>.). This is monumentally annoying and very distracting when comparing revisions of a file.</p>
<p>Is there a way to prevent this?</p>
|
<p>I don't think there's much you can do about this. I've noticed the same problem: the IDE likes to rearrange things for seemingly no apparent reason. Some things I've noticed:</p>
<ul>
<li><p>When you use the SSTab control, VB
likes to rearrange properties for
tabs, especially the TabEnabled
property.</p></li>
<li><p>For project files, it randomly
rearranges the order in which files
appear and I think I remember seeing
cases where similar file types are
not always grouped together and end
up mixed in with the project
properties. You don't have
much control over this, unless you run all your VBP's through some type of sanitizer that groups like files together (forms in one group, modules in another group, etc.) and sorts them alphabetically or something, so that they remain consistent. One possible way to handle this could be to write an IDE add-on that automatically does this everytime you save changes to a project file, or come up with some batch process that will just recurse over your source directories and clean up all the VBP's in one go.</p></li>
<li><p>The IDE seems to randomly change the
case of things; this seems to happen
frequently to project references.
Sometimes they are output in lower
case, and other times they are
output in upper case. You can get
around this by choosing "Ignore
Case" when you diff files in
SourceSafe.</p></li>
<li><p>Control coordinates, such
Top, Left, Height, and Width, can differ between
two revisions of the same form. This is due
to different developers using
different screen resolutions and/or
different screen DPI settings while working on the same form.
If you aren't doing this already, I
highly recommend that you get
everyone to develop using the same
resolution and same DPI setting.
The differing values are caused by rounding errors that
occur when logical screen
coordinates at different resolutions/DPI settings
are converted to twips, the default
coordinate space that VB uses for
laying out forms. Additionally, while I'm on the topic, make
sure everyone has their display set to 96dpi,
because if you develop VB forms at
120dpi, there is a really really good
chance they won't display correctly
on a display set to 96dpi.</p></li>
<li><p>There are probably other things I
can't remember right now...</p></li>
</ul>
<p>As for the order of controls being changed in form files, this is normal, and you usually don't want to try rearrange the order of controls by hand if it happens to change from one revision of the form to the next. The order that the controls appear in a form file determines their Z-order on the form. If the order of the controls changes in the .frm file, this will change their relative Z-order on the form, which could lead to unintended results in how your forms are displayed.</p>
|
Any problems with SVN merge on a multi column ( tab delimited ) text file? <p>I have a multi-column text file ( tab delimited ) that I use for localized text in my project. </p>
<p>I picked this format since it can easily be edited by anyone in most text editors (and excel too). </p>
<p>My makefile processes it into a bunch of defines and binary data for including directly into my app. </p>
<p>Do you know if SVN merge only does line by line merging or can it so sub-line merging too?</p>
<p>For example:</p>
<p>Original File ( untranslated ) contains:</p>
<pre><code>DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES *YES* *YES*
STRING_NO NO *NO* *NO*
</code></pre>
<p>Then the french tranlator updates it:</p>
<pre><code>DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES *YES* OUI
STRING_NO NO *NO* NON
</code></pre>
<p>Then the german tranlator updates it:</p>
<pre><code>DEFINE ENGLISH GERMAN FRENCH
STRING_YES YES JA *YES*
STRING_NO NO NEIN *NO*
</code></pre>
<p>Then they both merge the results back int SVN, so will they overwrite each others changes or can it handle mulitple changes on a line?</p>
|
<p>It is line by line.</p>
<ol>
<li>The person who tries to commit later will get 'out of date' error, and when they try to update it, they will get a conflict in changed lines.</li>
<li>Same with the merge. The one who merges later will have to sort out conflicts manually.</li>
</ol>
|
Possible Memory leak in Number of Loaded classes in Java Application <p>I recently began profiling an osgi java application that I am writing using VisualVM. One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate. The Heap size and the PermGen size remains constant, however. The number of classes never falls, even after it stops sending data. Is this a memory leak? I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.</p>
<p>For the screenshot of my profiling application go <a href="http://sites.google.com/site/javaperformacescreenshot/Home/profile.png">here</a></p>
|
<blockquote>
<p>Are you dynamically creating new classes on the fly somehow?</p>
</blockquote>
<p>Thanks for your help. I figured out what the problem is. In one of my classes, I was using Jaxb to create an XML string. In doing this, JAXB ueses reflection to create a new class.</p>
<pre><code>JAXBContext context = JAXBContext.newInstance(this.getClass());
</code></pre>
<p>So although the JAXBContext wasn't saying around in the heap, the classes had been loaded.</p>
<p>I have run my program again, and I see a normal plateau as I would expect.</p>
|
Hiding a function <p>I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can invalidate the state.<p>
So I must have the ability, a member function, to set internal variables from the unit test programs. But I want to <b>strongly discourage</b> normal users from calling this function. (Yes, a determined user can muck with anything... but I don't want to <i>advertise</i> that there is a way to do something <i>wrong</i>.)<p>
It would be nice to be able to tell Intellisense to not show the function, for instance.<p>
The best solution I have at the moment is to just name the function something like: DangerousSet().<p>
What other options do I have?<P>
<b>Follow-Up</b><p>
I found David B's answer most useful to my situation. Thanks!<br>
Mufasa's suggestion to use reflection was great, but harder to implement (for me).<br>
Chris' suggestion of using a decorator was good, but didn't pan out.<br>
BFree's suggestion on XML is also good, and was already in use, but doesn't really solve the problem.<p>
Finally, BillTheLizard's suggestion that the problem is in the source documents is not something I can control. International experts publish highly technical books and journal articles for use by their community. The fact that they don't address my particular needs is a fact of life. There simply are no alternative documents.</p>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="nofollow">InternalsVisibleToAttribute</a> to mark internal members as visible to your test assembly. It seems to shine when used in this context, though its not quite "friend".</p>
<ol>
<li><p>Mark your <code>DangerousSet</code> function <code>internal</code> instead of <code>public</code>.</p></li>
<li><p>In Properties\AssemblyInfo.cs of the project containing <code>DangerousSet</code>:</p>
<p><code>[assembly:InternalsVisibleTo("YourTestAssembly")]</code></p></li>
</ol>
<p>If you have two test assemblies for whatever reason, the syntax is:</p>
<pre><code>[assembly:InternalsVisibleTo("TestAssembly1"),
InternalsVisibleTo("TestAssembly2")]
</code></pre>
|
How can I embed one file into another with Ant? <p>I am developing a small web app project (ColdFusion) and I am trying to keep my project split into multiple files during development, but deploy just one file on completion.</p>
<p>I have references to external files, for instance:</p>
<pre><code><script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<link type="text/css" rel="stylesheet" href="project.css" />
</code></pre>
<p>And when I build my project, I want to have the files included and embedded within the single finished product file.</p>
<pre><code><script type="text/javascript">eval(function(p,a,c,k,e,r) [...]</script>
<style type="text/css">div{font:normal;} [...]</style>
</code></pre>
<p>Anyway, it doesn't look like there is a basic way for Ant to do this. Anyone know?</p>
|
<p>Does this do what you want?</p>
<pre><code><property
name="filename"
value="jquery-1.2.6.pack.js"
/>
<loadfile
property="contents"
srcfile="${filename}"
/>
<replace dir=".">
<include name="index.cfm"/>
<replacetoken><![CDATA[<script type="text/javascript" src="${filename}"></script>]]></replacetoken>
<replacevalue><![CDATA[<script type="text/javascript">${contents}</script>]]></replacevalue>
</replace>
</code></pre>
|
JPA and inheritance <p>I have a some JPA entities that inherit from one another and uses discriminator to determine what class to be created (untested as of yet).</p>
<pre><code>@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="500")
public class DmsSwitch extends Switch implements Serializable {}
@MappedSuperclass
public abstract class Switch implements ISwitch {}
@Entity(name="switch_accounts")
public class SwitchAccounts implements Serializable {
@ManyToOne()
@JoinColumn(name="switch_id")
DmsSwitch _switch;
}
</code></pre>
<p>So in the SwitchAccounts class I would like to use the base class Switch because I don't know which object will be created until runtime. How can I achieve this?</p>
|
<p>As the previous commentors I agree that the class model should be different. I think something like the following would suffice:</p>
<pre><code>@Entity(name="switches")
@DiscriminatorColumn(name="type")
@DiscriminatorValue(value="400")
public class Switch implements ISwitch {
// Implementation details
}
@Entity(name="switches")
@DiscriminatorValue(value="500")
public class DmsSwitch extends Switch implements Serializable {
// implementation
}
@Entity(name="switches")
@DiscriminatorValue(value="600")
public class SomeOtherSwitch extends Switch implements Serializable {
// implementation
}
</code></pre>
<p>You could possibly prevent instantiation of a Switch directly by making the constructor protected. I believe Hibernate accepts that. </p>
|
How can I do bi-directional communication with a custom USB device? <p>I'm planning to build a USB device that has buttons that some software needs to respond to, and indicators that the software needs to control. I'm new to USB, so I'm looking for any pointers that will get me started.</p>
|
<p>When I did some USB development a while ago, I found the information at <a href="http://www.lvr.com/usb.htm" rel="nofollow">USB Central</a> extremely valuable.</p>
<p>For low bandwidth requirements, you can use something like the <a href="http://www.ftdichip.com/Products/FT232R.htm" rel="nofollow">FT232R</a> which is a single-chip USB serial implementation. The FTDI drivers are readily available and make the device appear as a regular serial port to the host computer. This is orders of magnitude easier than rolling your own USB implementation (for either end!).</p>
|
Other than for LINQ queries, how do you use anonymous types in C#? <p>I've been trying to get up to speed on some of the newer features in C# and one of them that I haven't had occasion to use is anonymous types.</p>
<p>I understand the usage as it pertains to LINQ queries and I looked at <a href="http://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c">this SO post</a> which asked a similar question. Most of the examples I've seen on the net are related to LINQ queries, which is cool. I saw some somewhat contrived examples too but not really anything where I saw a lot of value. </p>
<p>Do you have a novel use for anonymous types where you think it really provides you some utility?</p>
|
<p>With a bit of reflection, you can turn an anonymous type into a Dictionary<string, object>; Roy Osherove blogs his technique for this here: <a href="http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx" rel="nofollow">http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx</a></p>
<p>Jacob Carpenter uses anonymous types as a way to initialize immutable objects with syntax similar to object initialization: <a href="http://jacobcarpenter.wordpress.com/2007/11/19/named-parameters-part-2/" rel="nofollow">http://jacobcarpenter.wordpress.com/2007/11/19/named-parameters-part-2/</a></p>
<p>Anonymous types can be used as a way to give easier-to-read aliases to the properties of objects in a collection being iterated over with a <code>foreach</code> statement. (Though, to be honest, this is really nothing more than the standard use of anonymous types with <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" rel="nofollow">LINQ to Objects</a>.) For example:</p>
<pre><code>Dictionary<int, string> employees = new Dictionary<int, string>
{
{ 1, "Bob" },
{ 2, "Alice" },
{ 3, "Fred" },
};
// standard iteration
foreach (var pair in employees)
Console.WriteLine("ID: {0}, Name: {1}", pair.Key, pair.Value);
// alias Key/Value as ID/Name
foreach (var emp in employees.Select(p => new { ID = p.Key, Name = p.Value }))
Console.WriteLine("ID: {0}, Name: {1}", emp.ID, emp.Name);
</code></pre>
<p>While there's not much improvement in this short sample, if the <code>foreach</code> loop were longer, referring to <code>ID</code> and <code>Name</code> might improve readability.</p>
|
Do .net applications run on Linux? <p>Do .net applications run on linux? </p>
<p>Are there any free/paid interop libraries available ?</p>
|
<p><a href="http://www.mono-project.com/" rel="nofollow">Mono</a> is a .NET-compatible platform, including compiler and runtime. The <a href="http://www.mono-project.com/Moma" rel="nofollow">Mono Migration Analyzer</a> helps figure out compatibility issues.</p>
|
Is it possible to connect PHP to SQL Server Compact Edition? <p>Is it possible to connect PHP to a SQL Server Compact Edition database? What would be the best driver?</p>
<hr>
<p>I need it for a desktop application where SQL Server Express is too heavy.</p>
|
<p>Short Answer : <strong>No.</strong></p>
<p>Long Answer : To my knowledge, unlike PostgreSQL / MySQL / MS-SQL, there is no native driver to connect PHP to SQL Server Compact Edition.</p>
<p>If you want to connect to it, your best bet is to use PHP ODBC connections to talk to a ODBC Driver connected to the SQL Compact server. But its pretty much a hack, and you'd be crazy to use this kind of thing for anything remotely important. </p>
<p>If you are worried about SQL Server Express being too heavy, use MySQL with MyISAM tables. It's pretty fast and lightweight. <a href="http://emergent.urbanpug.com/?p=61" rel="nofollow">Emergent has a good checklist of things to configure / disable</a> to make MySQL even faster and use less resources.</p>
<p><br />
Relevant links :</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2775563&SiteID=1" rel="nofollow">MSDN Post asking the same question </a></p>
<p><a href="http://erikej.blogspot.com/2008/04/import-sql-compact-data-to-excel.html" rel="nofollow">Erik EJ's blog - SQL Compact with OLE DB</a></p>
|
How do I show an embedded excel file in a WebPage? <p>I want to allow an Excel report to be viewed embedded in a WebPage... is there a way?</p>
<ul>
<li><p>I don't want to use an ActiveX, or OWC (Office Web Components), I just want to open an existing file from the internet explorer application.</p></li>
<li><p>I don't want users to download and then open it.</p></li>
</ul>
<p>Using an iframe wouldn't be a problem, but my preliminary tests weren't successful</p>
<p>Any ideas? Is it at all possible?</p>
|
<p>This has to do with the local person's browser set up and not really anything you can do on your end. If they click a link with the .xls(x) extension, the browser determines if it wants to open it itself or in a new window.</p>
<p>Here is a microsoft page on how to change these settings: <a href="http://support.microsoft.com/kb/162059">http://support.microsoft.com/kb/162059</a></p>
|
How do you add a link that will add an event to your iPhone calendar from safari? <p>This seems like it should be simple but after a couple hours of googling I have not figured it out. I know I can add iCal links using ICS files, but this does not work on the iPhone.</p>
<p>BTW, when I say iPhone I would like it to work on the touch also. Anyone have any luck with this?</p>
|
<p>You can get iPhone to download the .ics file (using Safari on a mobile web page) by using the webcal protocol:</p>
<p>webcal://website.mobi/mymeeting.ics</p>
|
Where are some good resources for learning the new features of Perl 5.10? <p>I didn't realize until recently that Perl 5.10 had significant new features and I was wondering if anyone could give me some good resources for learning about those. I searched for them on Google and all I found was some slides and a quick overview. Some of the features (to me at least) would be nice if they had more explanation.</p>
<p>Any links would be appreciated.</p>
<p>-fREW</p>
|
<p>The <a href="http://search.cpan.org/dist/perl-5.10.0/pod/perl5100delta.pod">perldelta</a> manpage has all the nitty-gritty details. There's a brief (but informative) slide presentation, <a href="http://www.slideshare.net/rjbs/perl-510-for-people-who-arent-totally-insane/">Perl 5.10 for people who aren't totally insane</a>. And a good <a href="http://www.perlmonks.org/?node_id=654042">PerlMonks discussion</a> on the issue. </p>
|
Display a tooltip over a button using Windows Forms <p>How can I display a tooltip over a button using <a href="http://en.wikipedia.org/wiki/Windows_Forms">Windows Forms</a>?</p>
|
<p>The ToolTip is actually a WinForms control that handles displaying tool tips for multiple elements on a single form.</p>
<p>Say your button is called MyButton.</p>
<ol>
<li>Add a ToolTip control (under Common
Controls in the Windows Forms
toolbox) to your form. </li>
<li>Give it a
name - say MyToolTip </li>
<li>Set the "Tooltip on MyToolTip" property of MyButton (under Misc in
the button property grid) to the text that should appear when you hover over it.</li>
</ol>
<p>The tooltip will automatically appear when the cursor hovers over the button, but if you need to display it programatically, call</p>
<pre><code>MyToolTip.Show("Tooltip text goes here", MyButton)
</code></pre>
<p>in your code to show the tooltip, and MyToolTip.Hide(MyButton) to make it disappear again.</p>
|
Best Practices for Performing Sequential Operations <p>What is the best way to perform a couple of tasks together and if one task fails then the next tasks should not be completed? I know if it were the database operations then I should have used Transactions but I am talking about different types of operations like the following: </p>
<p>All tasks must pass: </p>
<p>SendEmail
ArchiveReportsInDatabase
CreateAFile</p>
<p>In the above scenario all the tasks must pass or else the whole batch operation must be rollback. </p>
|
<p>Rollbacks are tough - AFAIK, there's really only 2 ways to go about it. Either a <a href="http://en.wikipedia.org/wiki/Two-phase-commit_protocol" rel="nofollow">2 phase commit protocol</a>, or <a href="http://en.wikipedia.org/wiki/Compensating_transaction" rel="nofollow">compensating transactions</a>. You really have to find a way to structure your tasks in one of these fashions.</p>
<p>Usually, the better idea is to take advantage of other folks' hard work and use technologies that already have 2PC or compensation built in. That's one reason that RDBMS are so popular.</p>
<p>So, the specifics are task dependent...but the pattern is fairly easy:</p>
<pre><code>class Compensator {
Action Action { get; set; }
Action Compensate { get; set; }
}
Queue<Compensator> actions = new Queue<Compensator>(new Compensator[] {
new Compensator(SendEmail, UndoSendEmail),
new Compensator(ArchiveReportsInDatabase, UndoArchiveReportsInDatabase),
new Compensator(CreateAFile, UndoCreateAFile)
});
Queue<Compensator> doneActions = new Queue<Compensator>();
while (var c = actions.Dequeue() != null) {
try {
c.Action();
doneActions.Add(c);
} catch {
try {
doneActions.Each(d => d.Compensate());
} catch (EXception ex) {
throw new OhCrapException("Couldn't rollback", doneActions, ex);
}
throw;
}
}
</code></pre>
<p>Of course, for your specific tasks - you may be in luck. </p>
<ul>
<li>Obviously, the RDBMS work can already be wrapped in a transaction. </li>
<li>If you're on Vista or Server 2008, then you get <a href="http://en.wikipedia.org/wiki/Transactional_NTFS" rel="nofollow">Transactional NTFS</a> to cover your CreateFile scenario.</li>
<li>Email is a bit trickier - I don't know of any 2PC or Compensators around it (I'd only be slightly surprised if someone pointed out that Exchange has one, though) so I'd probably use <a href="http://en.wikipedia.org/wiki/Microsoft_Message_Queuing" rel="nofollow">MSMQ</a> to write a notification and let a subscriber pick it up and eventually email it. At that point, your transaction really covers just sending the message to the queue, but that's probably good enough.</li>
</ul>
<p>All of these can participate in a <a href="http://msdn.microsoft.com/en-us/library/ms973865.aspx" rel="nofollow">System.Transactions</a> Transaction, so you should be in pretty good shape.</p>
|
Can you get a Windows (AD) username in PHP? <p>I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?</p>
|
<p>Check the <code>AUTH_USER</code> request variable. This will be empty if your web app allows anonymous access, but if your server's using basic or Windows integrated authentication, it will contain the username of the authenticated user.</p>
<p>In an Active Directory domain, if your clients are running Internet Explorer and your web server/filesystem permissions are configured properly, IE will silently submit their domain credentials to your server and <code>AUTH_USER</code> will be <code>MYDOMAIN\user.name</code> without the users having to explicitly log in to your web app.</p>
|
Questions when moving from MbUnit to MsTest <p>Our team is looking to switch from using mbunit to mstest, but there appears to be some disconnect between the two.</p>
<p>Does anyone know how to simulate the CombinatorialTest and Factory attributes from mbunit when using mstest?</p>
<p>I think that is our only stumbling block before doing the switch.</p>
|
<p>As far as I'm aware, you basically need to write a test method that generates all of the combinations (or calls the factory and iterates through the items) that calls your original test (now no longer a test method) a bunch of times.</p>
<p>Unfortunately, these do not show up as individual tests in results - they show up as just one test- so you have to pretty explicit in your error output. This means that as with this approach, as soon as one fails it stops the rest (you can get around this by keeping a big list of results, but that's yet more overhead)</p>
<p>I'd think twice before going to mstest right now unless you have to - the lack of a test runner on a clean machine is killer, and it's neither extensible nor frequently updated. </p>
|
Pseudocode Programming Process vs. Test Driven Development <p>For those who haven't read Code Complete 2, the Pseudocode Programming Process is basically a way to design a routine by describing it in plain English first, then gradually revise it to more detailed pseudocode, and finally to code. The main benefit of this is to help you stay at the right level of abstraction by building systems top-down rather than bottom-up, thereby evolving a clean API in distinct layers. I find that TDD is less effective at this, because it focuses too much on doing the bare minimum to get a test to pass and encourages little up-front design. I also find that having to maintain a suite of unit tests for unstable code (code that's constantly being refactored) is quite difficult, because it's typically the case that you have a dozen unit tests for a routine that's only needed once or twice. When you do refactor - change a method signature, for example - most of the work you do is in updating the tests rather than the prod code. I prefer adding unit tests after a component's code has stabilized a bit.</p>
<p>My question is - of those who've tried both approaches, which do you prefer?</p>
|
<p>My team mixes both approaches and it's an awesome way to develop (at least for us). We need unit tests because we have a large and complex software system. But the Pseudocode Programming Process is hands-down the best approach to software design I've come across. To make them work together:</p>
<ul>
<li>We start by writing our classes,
and fill in with fully commented
method stubs, with inputs and
outputs.</li>
<li>We use pair coding and peer review as a dialogue to refine and validate the design, still only with the method stubs.</li>
<li>At this point we've now both designed our system and have some testable code. So we go ahead and write our unit tests.</li>
<li>We go back in and start filling in the methods with comments for the logic that needs to be written.</li>
<li>We write code; the tests pass.</li>
</ul>
<p>The beauty of it is that by the time we actually write code, most of the work of implementation is already done, because so much of what we think of as implementation is actually code design. Also the early process replaces the need for UML - class and method stubs are just as descriptive, plus it'll actually be used. And we always stay at the appropriate level of abstraction.</p>
<p>Obviously the process is never really quite as linear as I've described - some quirk of implementation may mean that we need to revisit the high-level design. But in general, by the time we write unit tests the design is really quite stable (at the method level), so no need for lots of test rewriting.</p>
|
Python - How do I write a decorator that restores the cwd? <p>How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called.</p>
|
<p>The answer for a decorator has been given; it works at the function definition stage as requested.</p>
<p>With Python 2.5+, you also have an option to do that at the function <em>call</em> stage using a context manager:</p>
<pre><code>from __future__ import with_statement # needed for 2.5 ⤠Python < 2.6
import contextlib, os
@contextlib.contextmanager
def remember_cwd():
curdir= os.getcwd()
try: yield
finally: os.chdir(curdir)
</code></pre>
<p>which can be used if needed at the function call time as:</p>
<pre><code>print "getcwd before:", os.getcwd()
with remember_cwd():
walk_around_the_filesystem()
print "getcwd after:", os.getcwd()
</code></pre>
<p>It's a nice option to have.</p>
<p>EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.</p>
|
Is there a way to change something in Tool->Options via a macro? <p>I'd like to be able to toggle easily between two values for "maximum number of parallel project builds" in Visual Studio 2008 (in Tools->Options->Projects and Solutions->Build and Run). (When I'm planning on doing concurrent work I'd like to reduce it from 4 to 3.) I'm not too well versed in writing macros for the IDE. When I try recording a macro, and perform all the actions (open the dialog, change the setting, click OK), the only thing that gets recorded is this:</p>
<pre><code>DTE.ExecuteCommand ("Tools.Options")
</code></pre>
<p>Is my goal unattainable?</p>
|
<p>It appears to be impossible, according to the MSDN page for <em><a href="http://msdn.microsoft.com/en-us/library/ms165642.aspx" rel="nofollow">Determining Names of Property Items in Tools Options Pages </a></em></p>
<p>If it <em>was</em> possible, it would have been something like this:</p>
<pre><code>Dim p = DTE.Properties("ProjectsAndSolutions","BuildAndRun")
p.Item("MaxNumParallelBuilds")
</code></pre>
|
What's the right way to display emoticons? <p>In your own application that is.</p>
<p>[edit]</p>
<p><strong>Alright, so I agree completely -- more than you know -- without equivocation that graphical emoticons are an abomination.
But! That doesn't help me when the project owners tell me that we must support graphical emoticons.</strong></p>
<p>[/edit]</p>
<p>The problem more complex than it would initially seem, especially when you take into account editing, word wrapping, variable width fonts, and color emoticons.</p>
<p><strong>So my question is really to people who have done this, have you come up with a satisfactory way of rendering emoticons that isn't just one massive hack?</strong></p>
<p>To start the discussion:</p>
<p>In two implementations I've tried the following approaches.</p>
<p>In a 3D application where lines of text where rendered to "textures"; I replaced emoticon strings with images, matching the type of the text renders, so the emoticon becomes just another element of the text.</p>
<p>Essentially the text rendering engine had to be modified at the deepest levels. This produces good results, but is very time consuming, and very hard to get right (Or at least for me anyway ;P)</p>
<p>In the second approach (With a different language and platform) I decided to try a higher-level "fake" by replacing emoticon strings with a single character and drawing emotions over the replaced character. This of course has lots of limitations, but has the benefit of being fairly fast to implement, and it's possible to reach a reasonably stable state without an excess of effort.</p>
|
<ol>
<li>Create a new font. <em>This is left as an exercise for the reader</em></li>
<li>Transcode your
strings into the character set of
your new font. </li>
<li>Draw:</li>
<li>Make repeated calls operating environment function to calculate Text Metrics - to locate the position of your emoticons.
<li>Draw the emoticons before the text (if you're using the font to enhance whatever background image is - say a face, with the font glyphs drawing the black on the face) or after the text (in which case the glyph for each emoticon is moot, and only the size of the glyphs is important).
</ol>
|
Set server or workstation GC <p>How can I configure an application, or even an entire machine, to use either the server or workstation flavor of the CLR's garbage collection? </p>
|
<p>Have a look <a href="http://blogs.msdn.com/maoni/archive/2004/09/25/234273.aspx" rel="nofollow">here</a>. </p>
<p>I recommend giving the entire series of blog posts a good read - very informative.</p>
|
what is the best way to do keep alive socket checking in .NET? <p>I am looking for a way to do a keep alive check in .NET. The scenario is for both UDP and TCP.</p>
<p>Currently in TCP what I do is that one side connects and when there is no data to send it sends a keep alive every X seconds.</p>
<p>I want the other side to check for data, and if non was received in X seconds, to raise an event or so.</p>
<p>One way i tried to do was do a blocking receive and set the socket's RecieveTimeout to X seconds. But the problem was whenever the Timeout happened, the socket's Receive would throw an SocketExeception and the socket on this side would close, is this the correct behaviour ? why does the socket close/die after the timeout instead of just going on ?</p>
<p>A check if there is data and sleep isn't acceptable (since I might be lagging on receiving data while sleeping).</p>
<p>So what is the best way to go about this, and why is the method i described on the other side failing ?</p>
|
<p>If you literally mean "KeepAlive", try the following.</p>
<pre><code> public static void SetTcpKeepAlive(Socket socket, uint keepaliveTime, uint keepaliveInterval)
{
/* the native structure
struct tcp_keepalive {
ULONG onoff;
ULONG keepalivetime;
ULONG keepaliveinterval;
};
*/
// marshal the equivalent of the native structure into a byte array
uint dummy = 0;
byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
BitConverter.GetBytes((uint)(keepaliveTime)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)keepaliveTime).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
BitConverter.GetBytes((uint)keepaliveInterval).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
// write SIO_VALS to Socket IOControl
socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
</code></pre>
|
Initializing C# auto-properties <p>I'm used to writing classes like this:</p>
<pre><code>public class foo {
private string mBar = "bar";
public string Bar {
get { return mBar; }
set { mBar = value; }
}
//... other methods, no constructor ...
}
</code></pre>
<p>Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?</p>
<pre><code>public class foo2theRevengeOfFoo {
//private string mBar = "bar";
public string Bar { get; set; }
//... other methods, no constructor ...
//behavior has changed.
}
</code></pre>
<p>You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.</p>
<p>Something like this would make more sense to me:</p>
<pre><code>public string Bar { get; set; } = "bar";
</code></pre>
|
<p>Update - the answer below was written before C# 6 came along. In C# 6 you can write:</p>
<pre><code>public class Foo
{
public string Bar { get; set; } = "bar";
}
</code></pre>
<p>You can <em>also</em> write read-only automatically-implemented properties, which are only writable in the constructor (but can also be given a default initial value:</p>
<pre><code>public class Foo
{
public string Bar { get; }
public Foo(string bar)
{
Bar = bar;
}
}
</code></pre>
<hr>
<p>It's unfortunate that there's no way of doing this right now. You have to set the value in the constructor. (Using constructor chaining can help to avoid duplication.)</p>
<p>Automatically implemented properties are handy right now, but could certainly be nicer. I don't find myself wanting this sort of initialization as often as a read-only automatically implemented property which could only be set in the constructor and would be backed by a read-only field.</p>
<p>This hasn't happened up until and including C# 5, but is being planned for C# 6 - both in terms of allowing initialization at the point of declaration, <em>and</em> allowing for read-only automatically implemented properties to be initialized in a constructor body.</p>
|
Merging Rails databases <p>I have two databases with the same structure. The tables have an integer as a primary key as used in Rails.</p>
<p>If I have a patients table, I will have one patient using primary key 123 in one database and another patient using the same primary key in the other database.</p>
<p>What would you suggest for merging the data from both databases?</p>
|
<p>Set both your databases up with entries in config/database.yml, then generate a new migration.</p>
<p>Use ActiveRecord::Base.establish_connection to switch between the two databases in the migration like this:</p>
<pre><code>def self.up
ActiveRecord::Base.establish_connection :development
patients = Patient.find(:all)
ActiveRecord::Base.establish_connection :production
patients.each { |patient| Patient.create patient.attributes.except("id") }
end
</code></pre>
<p>YMMV depending on the number of records and the associations between models.</p>
|
Simple way to programmatically get all stored procedures <p>Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it our using SQL Server Management Studio, without having to install the GUI.</p>
<p>I've seen some references to do thing via the PowerShell but in the end a C# console app is what I really want.</p>
<p><strong><em>To clarify....</em></strong></p>
<p>I'd like to script out the stored procedures. The list via the <code>Select * from sys.procedures</code> is helpful, but in the end I need to script out each of these.</p>
|
<p>You can use SMO for that. First of all, add references to these assemblies to your project:</p>
<ul>
<li>Microsoft.SqlServer.ConnectionInfo</li>
<li>Microsoft.SqlServer.Smo</li>
<li>Microsoft.SqlServer.SmoEnum</li>
</ul>
<p>They are located in the GAC (browse to C:\WINDOWS\assembly folder). </p>
<p>Use the following code as an example of scripting stored procedures:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.SqlServer.Management.Smo;
class Program
{
static void Main(string[] args)
{
Server server = new Server(@".\SQLEXPRESS");
Database db = server.Databases["Northwind"];
List<SqlSmoObject> list = new List<SqlSmoObject>();
DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.StoredProcedure);
foreach (DataRow row in dataTable.Rows)
{
string sSchema = (string)row["Schema"];
if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA")
continue;
StoredProcedure sp = (StoredProcedure)server.GetSmoObject(
new Urn((string)row["Urn"]));
if (!sp.IsSystemObject)
list.Add(sp);
}
Scripter scripter = new Scripter();
scripter.Server = server;
scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = @"C:\StoredProcedures.sql";
scripter.Script(list.ToArray());
}
}
</code></pre>
<p>See also: <a href="http://blogs.msdn.com/mwories/archive/2005/05/07/basic-scripting.aspx">SQL Server: SMO Scripting Basics</a>.</p>
|
Open source cad drawing (dwg) library in C# <p>Anyone knows of an open source DWG (autocad drawing) library in C#?</p>
|
<p>The major hurdle with the DWG format is that the binary format changes every 3 years - and it is due to change again in March 2009. It is encrypted and the specifications for it are not made public. It is a massively complicated library with many dark alleys unknown to even AutoDesk (they acquired it years ago).</p>
<p>Not open source but the <a href="http://www.opendesign.com/">Open Design Alliance</a> ... (from their Web site)...</p>
<blockquote>
<p>is a non-profit membership-based
consortium of software companies,
developers and users committed to
promoting the open exchange of CAD
data now and in the future. In
addition to setting standards for CAD
data formats, the ODA also focuses on
the practical matter of developing
software libraries of exceptional
quality that enable ODA members to
develop applications capable of
reading and writing the popular DWG
and DGN CAD file formats.</p>
</blockquote>
<p>Cost depends on what you are using the libraries for but the base-level cost for a developer is U$100/year with a U$250 joining fee. Compare that to <a href="http://usa.autodesk.com/adsk/servlet/index?siteID=123112&id=770257">AutoDesk's RealDWG</a> at $2500/year and $5000 for the 1st year then it's a bargain. The RealDWG licence is per product, by the way. The ODA licenses are a bit more reasonable and also allow you to make more than 1 product on the same license. you can pay for the source code but it costs a bomb - less than developing it yourself though</p>
<p>If you only have 1 product then perhaps RealDWG will suit you but it's Windows only - bonus, it has a .NET API which the ODA are still working on. The ODA products are compiled for a number of operating systems, including Windows (32-bit), SGI, Solaris, Windows (64-bit), Macintosh, HP, Windows CE, Linux, IBM AIX.</p>
<p>I any case that's a massive wheel to reinvent so it's definitely worth paying for one that already turns.</p>
<p>Some 3rd-party libraries exist out there with limited specific API functionality to try searching for those if your needs are very specific.</p>
<p>It is also worth noting that AutoDesk has been in more-or-less continuous litigation with the ODA for years now. If you decide to compete with them then that's another complexity you have to look forward to.</p>
<p>I am also developing a product that talks to DWG files. I'm going the commercial route because the time, expense and hassle involved is utterly uneconomical for me.</p>
|
Generic Java Framework to Manage Bidirectional Associations and Inverse Updates <p>I've been looking for a generic way to deal with bidirectional associations and a way to handle the inverse updates in manual written Java code.</p>
<p>For those who don't know what I'm talking about, here is an example. Below it are my current results of (unsatisfying) solutions.</p>
<pre><code>public class A {
public B getB();
public void setB(B b);
}
public class B {
public List<A> getAs();
}
</code></pre>
<p>Now, when updating any end of the association, in order to maintain consistency, the other end must be updated as well. Either manually each time </p>
<pre><code>a.setB(b);
b.getA().add(a);
</code></pre>
<p>or by putting matching code in the setter / getter and use a custom List implementation.</p>
<p>I've found an outdated, unmaintained project whose dependencies are no longer available (<a href="https://e-nspire-gemini.dev.java.net/" rel="nofollow">https://e-nspire-gemini.dev.java.net/</a>). It deals with the problem by using annotations that are used to inject the necessary code automatically.</p>
<p>Does anyone know of another framework that deals with this in a generic, unobtrusive way ala gemini?</p>
<p>ciao,
Elmar</p>
|
<p>google collections (from google's internal code) -- <a href="http://code.google.com/p/google-collections/">http://code.google.com/p/google-collections/</a> is Java Generics compatible(not only compatible, uses generics very well)</p>
<p>Class BiMap -- <a href="http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html">http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/package-summary.html</a>
allows for Bidirectional associations.</p>
<p>Some of these classes are expected to make their way into JDK 7.</p>
|
Aren't Information Expert / Tell Don't Ask at odds with Single Responsibility Principle? <p>It is probably just me, which is why I'm asking the question. Information Expert, Tell Don't Ask, and SRP are often mentioned together as best practices. But I think they are at odds. Here is what I'm talking about:</p>
<p>Code that favors SRP but violates Tell Don't Ask, Info Expert:</p>
<pre><code>Customer bob = ...;
// TransferObjectFactory has to use Customer's accessors to do its work,
// violates Tell Don't Ask
CustomerDTO dto = TransferObjectFactory.createFrom(bob);
</code></pre>
<p>Code that favors Tell Don't Ask / Info Expert but violates SRP:</p>
<pre><code>Customer bob = ...;
// Now Customer is doing more than just representing the domain concept of Customer,
// violates SRP
CustomerDTO dto = bob.toDTO();
</code></pre>
<p>If they are indeed at odds, that's a vindication of my OCD. Otherwise, please fill me in on how these practices can co-exist peacefully. Thank you.</p>
<p>Edit: someone wants a definition of the terms - </p>
<p>Information Expert: objects that have the data needed for the operation should host the operation</p>
<p>Tell Don't Ask: don't ask objects for data in order to do work; tell the objects to do the work</p>
<p>Single Responsibility Principle: each object should have a narrowly defined responsibility</p>
|
<p>I don't think that they are so much at odds as they are emphasizing different things that will cause you pain. One is about structuring code to make it clear where particular responsibilities are and reducing coupling, the other is about reducing the reasons to modify a class.</p>
<p>We all have to make decisions each and every day about how to structure code and what dependencies we are willing to introduce into designs. </p>
<p>We have built up a lot of useful guidelines, maxims and patterns that can help us to make the decisions. </p>
<p>Each of these is useful to detect different kinds of problems that could be present in our designs. For any specific problem that you may be looking at there will be a sweet spot somewhere. </p>
<p>The different guidelines do contradict each other. Just applying every piece of guidance you have heard or read will not make your design better. </p>
<p>For the specific problem you are looking at today you need to decide what the most important factors that are likely to cause you pain are. </p>
|
Does the iPhone timeout if a function takes too long to execute? <p>I have a function in which I get en external resource from the web using cocoa's Url object. And it works fine on the simulator, but occasionally fails on the device itself (it's a google query so the resource obviously does exist). Which leads me to believe that there is some internal timeout barrier on the hardware, but haven't read that such a barrier exists or not.</p>
<p>Anyone else encountered similar issues? Or knows if the timeout is documented or can be changed?</p>
|
<p>The iPhone OS will terminate your app if it seems it has become unresponsive - basically if your main thread blocks for a few seconds. This is also important when exiting - if you save on exit you have a very small window to complete the save which is compounded by the fact the OS may be doing other things. If you take too long to exit the OS kills your app which to the user appears as if your app is failing to save.</p>
<p>I would HIGHLY recommend that you test anything time related on hardware and not the simulator. The simulator is great for quick turnaround debugging but is not representative of performance on actual hardware.</p>
<p>If you have any heavy lifting to do, do it on a seperate thread so the UI stays responsive to the user and OS.</p>
|
Warning when using mysql_fetch_assoc in PHP <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/795746/warning-mysql-fetch-array-supplied-argument-is-not-a-valid-mysql-result">Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result</a> </p>
</blockquote>
<p>When I run my php page, I get this error and do not know what's wrong, can anyone help? If anyone needs more infomation, I'll post the whole code.</p>
<pre>Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in
H:\Program Files\EasyPHP 2.0b1\www\test\info.php on line 16</pre>
<pre><code><?PHP
$user_name = "root";
$password = "";
$database = "addressbook";
$server = "127.0.0.1";
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM tb_address_book";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ID'] . "<BR>";
print $db_field['First_Name'] . "<BR>";
print $db_field['Surname'] . "<BR>";
print $db_field['Address'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
?>
</code></pre>
|
<p>It generally means that you've got an error in your SQL.</p>
<pre><code>$sql = "SELECT * FROM myTable"; // table name only do not add tb
$result = mysql_query($sql);
var_dump($result); // bool(false)
</code></pre>
<p>Obviously, <code>false</code> is not a MySQL resource, hence you get that error.</p>
<p><strong>EDIT with the code pasted now</strong>:</p>
<p>On the line before your <code>while</code> loop, add this:</p>
<pre><code>if (!$result) {
echo "Error. " . mysql_error();
} else {
while ( ... ) {
...
}
}
</code></pre>
<p>Make sure that the <code>tb_address_book</code> table actually exists and that you've connected to the DB properly.</p>
|
How can I detect a held down mouse button over a PictureBox? <p>I need to fire an event when the mouse is above a PictureBox with the mouse button already clicked and held down.</p>
<p>Problems: </p>
<p>The MouseDown and MouseEnter event handlers do not work together very well.</p>
<p>For instance once a mouse button is clicked and held down, C# will fire the MouseDown event handler, but when the cursor moves over the PictureBox the MouseEnter event does not fire, until the mouse button is realeased.</p>
|
<p>When the mouse is pressed down most controls will then <em>Control.Capture</em> the mouse input. This means that all <em>MouseMove</em> events are sent to the original control that captured rather than the control the mouse happens to be over. This continues until the mouse loses capture which typically happens on the mouse up. </p>
<p>If you really need to know when the mouse is over your control even when another control has captured mouse input then you only really have one way. You need to snoop the windows messages destined for other controls inside your application. To do that you need add a message filter ...</p>
<pre><code>Application.AddMessageFilter(myFilterClassInstance);
</code></pre>
<p>Then you need to implement the IMessageFilter on a suitable class...</p>
<pre><code>public class MyFilterClass : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_MOUSEMOVE)
// Check if mouse is over my picture box!
return false;
}
}
</code></pre>
<p>Then you watch for mouse move events and check if they are over your picture box and do whatever it is you want to do.</p>
|
strcat() new line, duplicate string <p>I'm writing a function that gets the path environment variable of a system, splits up each path, then concats on some other extra characters onto the end of each path.</p>
<p>Everything works fine until I use the <code>strcat()</code> function (see code below).</p>
<pre><code>char* prependPath( char* exeName )
{
char* path = getenv("PATH");
char* pathDeepCopy = (char *)malloc(strlen(path) + 1);
char* token[80];
int j, i=0; // used to iterate through array
strcpy(pathDeepCopy, path);
//parse and split
token[0] = strtok(pathDeepCopy, ":"); //get pointer to first token found and store in 0
//place in array
while(token[i]!= NULL) { //ensure a pointer was found
i++;
token[i] = strtok(NULL, ":"); //continue to tokenize the string
}
for(j = 0; j <= i-1; j++) {
strcat(token[j], "/");
//strcat(token[j], exeName);
printf("%s\n", token[j]); //print out all of the tokens
}
}
</code></pre>
<p>My shell output is like this (I'm concatenating "/which" onto everything):</p>
<pre><code>...
/usr/local/applic/Maple/bin/which
which/which
/usr/local/applic/opnet/8.1.A.wdmguru/sys/unix/bin/which
which/which
Bus error (core dumped)
</code></pre>
<p>I'm wondering why <code>strcat</code> is displaying a new line and then repeating <code>which/which</code>.
I'm also wondering about the <code>Bus error (core dumped)</code> at the end.</p>
<p>Has anyone seen this before when using <code>strcat()</code>?
And if so, anyone know how to fix it?</p>
<p>Thanks</p>
|
<p>strtok() does not give you a new string.<br>
It mutilates the input string by inserting the char '\0' where the split character was.</p>
<p>So your use of strcat(token[j],"/") will put the '/' character where the '\0' was.<br>
Also the last token will start appending 'which' past the end of your allocated memory into uncharted memory.</p>
<p>You can use strtok() to split a string into chunks. But if you want to append anything onto a token you need to make a copy of the token otherwise what your appending will spill over onto the next token.</p>
<p>Also you need to take more care with your memory allocation you are leaking memory all over the place :-)</p>
<p>PS. If you must use C-Strings. use strdup() to copy the string.</p>
<pre><code>char* prependPath( char* exeName )
{
char* path = getenv("PATH");
char* pathDeepCopy = strdup(path);
char* token[80];
int j, i; // used to iterate through array
token[0] = strtok(pathDeepCopy, ":");
for(i = 0;(token[i] != NULL) && (i < 80);++i)
{
token[i] = strtok(NULL, ":");
}
for(j = 0; j <= i; ++j)
{
char* tmp = (char*)malloc(strlen(token[j]) + 1 + strlen(exeName) + 1);
strcpy(tmp,token[j]);
strcat(tmp,"/");
strcat(tmp,exeName);
printf("%s\n",tmp); //print out all of the tokens
free(tmp);
}
free(pathDeepCopy);
}
</code></pre>
|
Java EE -- is it just fluff or the real stuff? <p>I'm familiar with the LAMP stack and over the years have successfully deployed a handful of web sties based on it. I've used everything from Apache + modPerl, to PHP, to Ruby and Rails. With good use of caching my Rails site can sustain a pretty good load, but I'm not talking massive.</p>
<p>I never really liked Java as a language, or XML for that matter, and have very much been ignoring the whole Java EE side of things. For those who have had real and direct experience in both worlds: is there something super cool about Java EE that I'm missing, or is just a bunch of hot air? What justifies the high price of the proprietary app servers?</p>
<p>I'm not trolling here: I'm looking for concrete examples of things that Java EE really nails that are missing from <em>modern</em> LAMP frameworks, if such differences exist. (Modern = Rails, Django, etc). Alternatively pipe in with those things that LAMP really does better (fewer XML sit ups for one).</p>
<p>+++++ Update October 16, 2008</p>
<p>I'm sad to report that most of the replies here are not helpful, and simply fall into one of two categories: "It scales because here are three examples of large web sites" and "It scales because it is really actually much better than the LAMP stack".</p>
<p>I've done quite a bit of reading, and have concluded that Java EE only has one really good trick: transactions (thanks Will) and as for the rest you can succeed or fail on your own merit, there is nothing intrinsically in the environment to cause you to create a scalable and reliable web site, indeed Java EE has quite a few traps that make it easy to fail (for instance it is easy to start using session beans without realizing that you are paying now for quite a bit of JMS traffic that perhaps could have been avoided with a different design.)</p>
<p>Useful discussion</p>
<ul>
<li><a href="http://www.subbu.org/blog/2007/10/large-scale-web-site-development" rel="nofollow">http://www.subbu.org/blog/2007/10/large-scale-web-site-development</a></li>
<li><a href="http://highscalability.com/" rel="nofollow">http://highscalability.com/</a></li>
<li><a href="http://www.oreillynet.com/onlamp/blog/2004/07/php_scales.html" rel="nofollow">http://www.oreillynet.com/onlamp/blog/2004/07/php_scales.html</a></li>
<li><a href="http://www.schlossnagle.org/~george/blog/index.php?/archives/29-Why-PHP-Scales-A-Cranky,-Snarky-Answer.html" rel="nofollow">http://www.schlossnagle.org/~george/blog/index.php?/archives/29-Why-PHP-Scales-A-Cranky,-Snarky-Answer.html</a> </li>
<li><a href="http://blogs.law.harvard.edu/philg/2003/09/20/" rel="nofollow">http://blogs.law.harvard.edu/philg/2003/09/20/</a></li>
</ul>
|
<p>The key differentiator that Java EE offers over the LAMP stack can be boiled down to a single word. Transactions.</p>
<p>Most smaller systems simply rely on the transaction system supplied by the database, and for many applications that is (obviously) quite satisfactory.</p>
<p>But each Java EE server includes a distributed transaction manager. This lets you do more complicated things, across diverse systems, safely and reliably.</p>
<p>The most simple example of this is the simple scenario of taking a record from a database, putting it on a messaging queue (JMS), and then deleting that row from the database. This simple case involves two separate systems, and can not reliably be done out side of a transaction. For example, you can put the row on to the message queue, but (due to a system failure) not remove the row from the database. You can see how having a transaction with the JMS provider and a separate transaction with the database doesn't really solve the problem, as the transactions are not linked together.</p>
<p>Obviously this simple scenario can be worked around, a dealt with, etc. The nice thing with Java EE, though, is that you don't have to deal with these kind of issues -- the container gets to deal with them.</p>
<p>And, again, not every problem requires this level o transaction handling. But for those that do, it's invaluable. And once you get used to using them, you'll find the transaction management of a Java EE server to be a great asset.</p>
|
2D animation in Python <p>I'm writing a simulator in Python, and am curious about options and opinions regarding basic 2D animations. By animation, I'm referring to rendering on the fly, not displaying prerendered images.</p>
<p>I'm currently using matplotlib (Wxagg backend), and it's possible that I'll be able to continue using it, but I suspect it won't be able to sufficiently scale in terms of performance or capabilities.</p>
<p>Requirements are:</p>
<ul>
<li>Cross-platform (Linux, MacOS X,
Windows)</li>
<li>Low complexity overhead</li>
<li>Plays well with wxpython (at least won't step on each other's toes unduly)</li>
<li>Interactivity. Detect when objects are clicked on, moused over, etc. </li>
</ul>
<p>Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good.</p>
<p>Your thoughts?</p>
|
<p>I am a fan of <a href="http://pyglet.org" rel="nofollow">pyglet</a> which is a completely self contained library for doing graphical work under win32, linux, and OS X. </p>
<p>It has very low overhead, and you can see this for yourself from the tutorial on the website. It <em>should</em> play well with wxpython, or at least I seem to recall posts to the mailing list about wxpython and pyglet being used together.</p>
<p>It however does not offer selection of objects via mouse clicks - this you will have to handle yourself. Generally speaking for a 2D application this is not too difficult to do.</p>
<p><a href="https://github.com/freespace/mactorii" rel="nofollow">mactorii</a> is an OS X application of mine written in pure python+pyglet, and has some basic animation (scrolling) and click detection. It doesn't use wxpython, but perhaps it will give you an idea of what is involved. Note however mactorii is using the old pyglet api, so the run loop I have in there is obsolete. I will get around to updating it one day... :P</p>
|
What are the differences between using the New keyword and calling CreateObject in Excel VBA? <p>What criteria should I use to decide whether I write VBA code like this:</p>
<pre><code>Set xmlDocument = New MSXML2.DOMDocument
</code></pre>
<p>or like this:</p>
<pre><code>Set xmlDocument = CreateObject("MSXML2.DOMDocument")
</code></pre>
<p>?</p>
|
<p>As long as the variable is not typed as object</p>
<pre><code>Dim xmlDocument as MSXML2.DOMDocument
Set xmlDocument = CreateObject("MSXML2.DOMDocument")
</code></pre>
<p>is the same as</p>
<pre><code>Dim xmlDocument as MSXML2.DOMDocument
Set xmlDocument = New MSXML2.DOMDocument
</code></pre>
<p>both use early binding. Whereas</p>
<pre><code>Dim xmlDocument as Object
Set xmlDocument = CreateObject("MSXML2.DOMDocument")
</code></pre>
<p>uses late binding. See MSDN <a href="http://support.microsoft.com/kb/245115">here</a>.</p>
<p>When youâre creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function.</p>
<p>New requires that a type library is referenced. Whereas CreateObject uses the registry.</p>
<p>CreateObject can be used to create an object on a remote machine.</p>
|
Benefits of using a Case statement over an If statement in a stored procedure? <p>Hi are there any pros / cons relating to the speed that a stored procedure executes when using an IF statement or choosing to use a CASE statement instead?</p>
|
<p>I try not to use <code>IF</code>s if I can avoid it, because they are non transactional, i.e. you have generally no guarantee that the condition of the <code>IF</code> will still be valid inside the <code>BEGIN... END</code> block of the <code>IF</code>.</p>
<p>I assume that you mean using <code>CASE</code> statements inside a SQL <code>SELECT</code>, for example. If the usage is meant to avoid an <code>IF</code> then, by all means, do it.</p>
<p>The golden rule of SQL is: <em>let the server figure out HOW to do things, tell the server what you WANT</em>.</p>
|
How do I add the interactive user to a directory in a localized Windows using WiX? <p>How do I add the Swedish interactive user, </p>
<pre><code>NT INSTANS\INTERAKTIV
</code></pre>
<p>or the English interactive user, </p>
<pre><code>NT AUTHORITY\INTERACTIVE
</code></pre>
<p>or any other localised user group with <strong>write</strong> permissions to a program folder's ACL?</p>
<p>Is this question actually "How do I use <strong>secureObject</strong>"? I cannot use the <strong>LockPermissions Table</strong> because I undestand inheritance is removed. <strong>secureObject</strong> permissions seem to require <strong>CreateDirectory</strong> rather than <strong>Directory</strong>... </p>
|
<p>With recent releases of Wix, you can retrieve the localized names of often-used built-in user and group names via a property. For example, <code>WIX_ACCOUNT_NETWORKSERVICE</code> contains the localized name of the Network Service account. Unfortunately, as of 3.0.4513 <code>NT AUTHORITY\INTERACTIVE</code> is not among them.</p>
<p>There exists a sample MSI custom action that creates properties for many of the built-in user and group names. <a href="http://www.installsite.org/files/iswi/SIDLookup.zip" rel="nofollow">Get it here</a>. Add the CA to your Wix installer and schedule it early in the install execute sequence.</p>
<p>Once you have the localized account name, add a PermissionEx element to modify your directory's ACL. For example:</p>
<pre><code><Directory ...>
<Component ...>
<CreateFolder>
<PermissionEx User="[SID_INTERACTIVE]" .../>
</CreateFolder>
</Component ...>
</Directory ...>
</code></pre>
|
Looping over elements in jQuery <p>I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though:</p>
<pre><code>function config() {
$("#frmMain").children().map(function() {
var child = $("this");
if (child.is(":checkbox"))
this[child.attr("name")] = child.attr("checked");
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
return null;
});
</code></pre>
<p>Neither does the following (inspired by jobscry's answer):</p>
<pre><code>function config() {
$("#frmMain").children().each(function() {
var child = $("this");
alert(child.length);
if (child.is(":checkbox")) {
this[child.attr("name")] = child.attr("checked");
}
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
});
}
</code></pre>
<p>The alert always shows that <code>child.length == 0</code>. Manually selecting the elements works:</p>
<pre>
>>> $("#frmMain").children()
Object length=42
>>> $("#frmMain").children().filter(":checkbox")
Object length=3
</pre>
<p>Any hints on how to do the loop correctly?</p>
|
<p>don't think you need quotations on this:</p>
<pre><code>var child = $("this");
</code></pre>
<p>try:</p>
<pre><code>var child = $(this);
</code></pre>
|
Why do thread functions need to be declared as '__cdecl'? <p>Sample code that shows how to create threads using MFC declares the thread function as both static and <code>__cdecl</code>. Why is the latter required? Boost threads don't bother with this convention, so is it just an anachronism?</p>
<p>For example (MFC):</p>
<pre><code>static __cdecl UINT MyFunc(LPVOID pParam)
{
...
}
CWinThread* pThread = AfxBeginThread(MyFunc, ...);
</code></pre>
<p>Whereas Boost:</p>
<pre><code>static void func()
{
...
}
boost::thread t;
t.create(&func);
</code></pre>
<p>(the code samples might not be 100% correct as I am nowhere near an IDE).</p>
<p>What is the point of __cdecl? How does it help when creating threads?</p>
|
<p>__cdecl tells the compiler to use the C calling convention (as opposed to the stdcall, fastcall or whatever other calling convention your compiler supports). I believe, VC++ uses stdcall by default.</p>
<p>The calling convention affects things such as how arguments are pushed onto the stack (or registers, in the case of fastcall) and who pops arguments off the stack (caller or callee).</p>
<p>In the case of Boost. I believe it uses template specialization to figure out the appropriate function type and calling convention.</p>
|
HowTo: Parse the UninstallString reg entry <p>In <code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\</code> is the list of installed programs in my machine (at least most of them).
There, there's a String Value called UninstallString which has what you need to run in order to uninstall the program.<br />
The thing is not every installer writes the same kind of info, yet Windows knows how to parse that string to run the uninstaller.<br />
My questions are: does anybody know how to parse that string?, meaning what are the possible values it might get? and if not, where can I find that kind of info? I googled around with no luck, I guess I'm not looking for the right terms.</p>
|
<p>Have a look at <a href="http://msdn.microsoft.com/en-us/library/ms954376.aspx" rel="nofollow">this link from MSDN explaining install/unistall procedures</a>, specifically item #6 "Support Add/Remove Programs Properly".</p>
<p>As an excerpt from the table there:</p>
<pre>
Key Name | Key Type | Description
UninstallPath | REG_EXPAND_SZ | Full path to the application's uninstall program
</pre>
<p>Despite the fact it says 'full path', alot of applications seem to shorten it if the program is in <code>$PATH</code>, especially with things like <code>msiexec.exe</code>.</p>
|
Stored procedure not being executed within another stored procedure <p>I have found that SP2 doesn't execute from within SP1 when SP1 is executed.</p>
<p>Below is the structure of SP1:</p>
<pre><code>ALTER PROCEDURE SP1 AS BEGIN
Declare c1 cursor....
open c1 fetch next from c1 ...
while @@fetch_status = 0 Begin
...
Fetch Next from c1 end
close c1
deallocate c1
exec sp2
end
</code></pre>
<hr>
<p>I see non of the PRINT statement outputs if they are printed in the 'Output window' in SQL Server 2005 management studio as the 'Output Window'is empty.</p>
|
<p>What happens if you run the Stored Procedure code as a single query? If you put a <code>PRINT</code> statement before and after the exec, do you see both outputs?</p>
<ul>
<li>If you do, then the stored procedure must have been executed. Probably it's not doing what you would like.</li>
<li>If you don't see any print output, then there's something wrong in the cycle</li>
<li>If you don't see the second output but you see the first, there's something wrong in the second Stored Procedure.</li>
</ul>
|
Language features to implement relational algebra <p>I've been trying to encode a relational algebra in Scala (which to my knowlege has one of the most advanced type systems) and just don't seem to find a way to get where I want.</p>
<p>As I'm not that experienced with the academic field of programming language design I don't really know what feature to look for.</p>
<p>So what language features would be needed, and what language has those features, to implement a statically verified relational algebra?</p>
<p>Some of the requirements:
A Tuple is a function mapping names from a statically defined set of valid names for the tuple in question to values of the type specified by the name. Lets call this name-type set the domain.</p>
<p>A Relation is a Set of Tuples with the same domain such that the range of any tuple is uniqe in the Set</p>
<p>So far the model can eaisly be modeled in Scala simply by</p>
<pre><code>trait Tuple
trait Relation[T<Tuple] extends Set[T]
</code></pre>
<p>The vals, vars and defs in Tuple is the name-type set defined above. But there should'n be two defs in Tuple with the same name. Also vars and impure defs should probably be restricted too.</p>
<p>Now for the tricky part:</p>
<p>A join of two relations is a relation where the domain of the tuples is the union of the domains from the operands tuples. Such that only tuples having the same ranges for the intersection of their domains is kept.</p>
<pre><code>def join(r1:Relation[T1],r2:Relation[T2]):Relation[T1 with T2]
</code></pre>
<p>should do the trick.</p>
<p>A projection of a Relation is a Relation where the domain of the tuples is a subset of the operands tuples domain.</p>
<pre><code>def project[T2](r:Relation[T],?1):Relation[T2>:T]
</code></pre>
<p>This is where I'm not sure if it's even possible to find a sollution. What do you think? What language features are needed to define project?</p>
<p>Implied above offcourse is that the API has to be usable. Layers and layers of boilerplate is not acceptable.</p>
|
<p>What your asking for is to be able to structurally define a type as the <em>difference</em> of two other types (the original relation and the projection definition). I honestly can't think of any language which would allow you to do that. Types can be structurally cumulative (<code>A with B</code>) since <code>A with B</code> is a structural sub-type of both <code>A</code> and <code>B</code>. However, if you think about it, a type operation <code>A less B</code> would actually be a <em>supertype</em> of <code>A</code>, rather than a sub-type. You're asking for an arbitrary, contravariant typing relation on naturally covariant types. It hasn't even been proven that sort of thing is sound with nominal existential types, much less structural declaration-point types.</p>
<p>I've worked on this sort of modeling before, and the route I took was to constraint projections to one of three domains: <code>P</code> == <code>T</code>, <code>P</code> == <code>{F} where F in T</code>, <code>P</code> == <code>{$_1} where $_1 anonymous</code>. The first is where the projection is equivalent to the input type, meaning it is a no-op (<code>SELECT *</code>). The second is saying that the projection is a single field contained within the input type. The third is the tricky one. It is saying that you are allowing the declaration of some anonymous type <code>$_1</code> which has no <em>static</em> relationship to the input type. Presumably it will consist of fields which delegate to the input type, but we can't enforce that. This is roughly the strategy that LINQ takes.</p>
<p>Sorry I couldn't be more helpful. I wish it were possible to do what you're asking, it would open up a lot of very neat possibilities.</p>
|
UNIX socket implementation for Java? <p>I realize that since UNIX sockets are platform-specific, there has to be some non-Java code involved. Specifically, we're interested in using JDBC to connect to a MySQL instance which only has UNIX domain sockets enabled. </p>
<p>It doesn't look like this is supported, but from what I've read it should be at least possible to write a SocketFactory for JDBC based on UNIX sockets <em>if</em> we can find a decent implementation of UNIX sockets for Java. </p>
<p>Has anyone tried this? Does anyone know of such an implementation?</p>
|
<p>Checkout the JUDS library. It is a Java Unix Domain Socket library...</p>
<p><a href="https://github.com/mcfunley/juds">https://github.com/mcfunley/juds</a></p>
|
Rich Text in Windows Forms application <p>I would like to update a Windows Forms application to provide the following features:</p>
<ul>
<li>spell checking</li>
<li>limited formatting of text: bold, italics, bulleted lists</li>
</ul>
<p>Ideally the formatted text could be accessed in a plain text way for reporting through tools that don't support the formatting, but could also be rendered as HTML for tools that support HTML tags when rendering text.</p>
<p>It seems to me that the WPF RichTextBox would provide this functionality. What is the best way to incorporate it? Would you suggest other alternatives?</p>
|
<p>You can add / create a drop-in spell checker for the Window Forms RichTextBox.</p>
<p>A ready to go <a href="http://www.c-sharpcorner.com/UploadFile/scottlysle/SpellCheckCC05152007084528AM/SpellCheckCC.aspx" rel="nofollow">richtextbox</a> custom control with spell checking.
An app for <a href="http://www.codeproject.com/KB/string/netspell.aspx" rel="nofollow">checking spelling</a> that could be easily integrated</p>
<p>Also <a href="http://www.c-sharpcorner.com/UploadFile/mahesh/WPFRichTextBox09072008194855PM/WPFRichTextBox.aspx" rel="nofollow">here</a> is a article on adding a WPF RichTextBox to your application, as well as getting spell checking working. (Requires .NET 3.0+)</p>
|
Can I put a caching server in front of my web site? <p>I have a web site using apache httpd as the server and mysql as the backend. It publishes a "thought for the day" that has gotten so popular that the server is crashing due to the number of requests. Since the same page is been requested (the thought only changes once a day), is it possible to put a caching server in front of my main server, so that when the same request is made by different clients, the caching server returns the page without having to go to the database?</p>
|
<p>For slow changing pages, a cache will definitely reduce CPU usage; but in your extreme case, where the page changes once a day, and it's perfectly predictable, it would be far easier to use a simple and fast static file server (<a href="http://www.lighttpd.net/" rel="nofollow">lighthttp</a>, <a href="http://nginx.net/" rel="nofollow">nginx</a>, etc) and a cron job to change your "thought of the day" every night.</p>
<p>In fact, a lot of non-interactive web pages can be done this way: periodically rebuild html files from database or any other source, and use simple, fast static web servers.</p>
|
Best way to use sessions with MVC and OO PHP <p>I've been working with sessions, MVC design and object oriented PHP. Where should I save or retrieve data from a session? I would like to retrieve it from within methods so I don't have to pass the data to the methods. Whats the best practice?</p>
|
<p>I typically put this inside the controller. It just makes sense.. The controller decides what happens and why not let it decide if people are allowed to do the requested actions.
Typically you have multiple controllers in a MVC system. Eg. BaseController (abstract - common), NonSessionController extends BaseController (eg: used for static pages), SessionController extends BaseController (primary session handing here - this could be abstract). If you have for example different user types, you may want to polymorph this controller ones such as: AdminController, UserController, Etc.</p>
|
Embedding HWND into external process using SetParent <p>I'm trying to embed a window from my process into the window of an external process using the <strong>SetParent</strong> function and have encountered a few problems that I'm hoping someone can help me out with. First off, here is an outline of what I am currently doing to embed my window into the application:</p>
<pre><code>HWND myWindow; //Handle to my application window
HWND externalWindow; //Handle to external application window
SetParent(myWindow,externalWindow);
//Remove WS_POPUP style and add WS_CHILD style
DWORD style = GetWindowLong(myWindow,GWL_STYLE);
style = style & ~(WS_POPUP);
style = style | WS_CHILD;
SetWindowLong(myWindow,GWL_STYLE,style);
</code></pre>
<p>This code works and my window appears in the other application, but introduces the following issues:</p>
<ul>
<li>When my window gains input focus, the main application window of the external process loses focus (i.e. title bar changes color)</li>
<li>Keyboard shortcut commands of the main application do not work while my window has focus</li>
</ul>
<p>Does anybody know a workaround for this? I would like my window to be treated as just another child window of the main application.</p>
|
<p>Well, I finally found the answer to my question.</p>
<p>To fix the issue with the main app losing focus you need to use the <strong>AttachThreadInput</strong> function to attach the embedded window thread to the main app thread.</p>
<p>Also, one can use the <strong>TranslateAccelerator</strong> function in response to WM_KEYDOWN messages to ensure accelerator messages of the main app are triggered.</p>
|
Parsing T-SQL to Parameterize a Query <p>The application I am currently working on generates a lot of SQL inline queries. All generated SQL is then handed off to a database execution class. I want to write a parsing service for the data execution class that will take a query like this:</p>
<pre><code>SELECT field1, field2, field3 FROM tablename WHERE foo=1 AND bar="baz"
</code></pre>
<p>and turn it into something like this:</p>
<pre><code>SELECT field1, field2, field3 FROM tablename WHERE foo=@p1 AND bar=@p2 blah blah blah
</code></pre>
<p>Any thing already written that will accomplish this for me in c# or vb.net? This is intended as a stop gap prior to refactoring the DAL for this project.</p>
<p><strong>UPDATE:</strong> Guys I have a huge application that was ported from Classic ASP to ASP.NET with literally thousands of lines of inline SQL. The only saving grace is all of the generated sql is handed off to a data execution class. I want to capture the sql prior to execution and parameterize them on the fly as a stop gap to rewriting the whole app. </p>
|
<p>Don't do this. This is way too much work. Plus, there are loads of security risks with this approach.</p>
<p>Look into Command objects and parameterized queries, at the minimum.</p>
<p><a href="http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx" rel="nofollow">Here is a small tutorial.</a></p>
|
How can I avoid duplicate content in ASP.NET MVC due to case-insensitive URLs and defaults? <blockquote>
<p><strong>Edit</strong>: Now I need to solve this problem for real, I did a little more
investigation and came up with a
number of things to reduce duplicate
content. I posted detailed code
samples on my blog: <a href="http://blog.dantup.me.uk/2009/04/reducing-duplicate-content-with-aspnet.html">Reducing
Duplicate Content with ASP.NET MVC</a></p>
</blockquote>
<p>First post - go easy if I've marked this up wrong or tagged it badly :P</p>
<p>In Microsoft's new ASP.NET MVC framework it seems there are two things that could cause your content to be served up at multiple URLs (something which Google penalize for and will cause your PageRank to be split across them):</p>
<ul>
<li>Case-insensitive URLs</li>
<li>Default URL</li>
</ul>
<p>You can set the default controller/action to serve up for requests to the root of your domain. Let's say we choose HomeController/Index. We end up with the following URLs serving up the same content:</p>
<ul>
<li>mydomain.com/</li>
<li>mydomain.com/Home/Index</li>
</ul>
<p>Now if people start linking to both of these then PageRank would be split. Google would also consider it duplicate content and penalize one of them to avoid duplicates in their results.</p>
<p>On top of this, the URLs are not case sensitive, so we actually get the same content for these URLs too:</p>
<ul>
<li>mydomain.com/Home/Index</li>
<li>mydomain.com/home/index</li>
<li>mydomain.com/Home/index</li>
<li>mydomain.com/home/Index</li>
<li>(the list goes on)</li>
</ul>
<p>So, the question... How do I avoid these penalties? I would like:</p>
<ul>
<li>All requests for the default action to be redirected (301 status) to the same url</li>
<li>All URLs to be case sensitive</li>
</ul>
<p>Possible?</p>
|
<p>I was working on this as well. I will obviously defer to ScottGu on this. I humbly offer my solution to this problem as well though.</p>
<p>Add the following code to <strong>global.asax</strong>:</p>
<pre><code>protected void Application_BeginRequest(Object sender, EventArgs e)
{
// If upper case letters are found in the URL, redirect to lower case URL.
if (Regex.IsMatch(HttpContext.Current.Request.Url.ToString(), @"[A-Z]") == true)
{
string LowercaseURL = HttpContext.Current.Request.Url.ToString().ToLower();
Response.Clear();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location",LowercaseURL);
Response.End();
}
}
</code></pre>
<p>A great question!</p>
|
Find out what is the new data from an RSS feed, compared with entries already in the database. Then put new entries in db. How? <p>Let's say I have a database, and an RSS feed. I have to find out what is the new data from an RSS feed, that isn't already in the database. How would you go about approaching this problem?</p>
|
<p>How about generating a hashcode or some unique identifier to each RSS item, then storing it in the database? Then you just generate the hashcode for each item in the new RSS, and check it against the database.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.