input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Tools for programming tutorials? <p>I engage in lot of training sessions and I would like to create video tutorials of all my sessions so that I can distribute it. What are the best Windows-based tools to add my PowerPoint slides, notes, voice and video (tutorials of code I write) and compile them into one video?</p>
| <p><a href="http://www.techsmith.com/camtasia.asp" rel="nofollow">Camtasia</A>, if you're on Windows.</p>
|
Creating a class to use for populating drop-down lists, grids, etc., in C# <p>Please keep in mind that I'm new to C# and OOP so I apologize in advance if this seems like an easy question to some. I'm going back through my code and looking for ways to objectify repetitive code and create a class for it so that I can simply reuse the class. That being said, I'm not looking to learn NHibernate or any other ORM just yet. I'm not even looking to learn LINQ. I want to hack through this to learn.</p>
<p>Basically I use the same bit of code to access my database and populate a drop-down list with the values that I get. An example:</p>
<pre><code> protected void LoadSchools()
{
SqlDataReader reader;
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
var conn = new SqlConnection(connectionString);
var comm = new SqlCommand("SELECT * FROM [Schools] ORDER BY [SchoolName] ASC", conn);
try
{
conn.Open();
reader = comm.ExecuteReader();
cmbEditSchool.DataSource = reader;
cmbEditSchool.DataBind();
cmbEditSchool.Text = "Please select an existing school to edit...";
if (reader != null) reader.Close();
}
finally
{
conn.Dispose();
}
}
</code></pre>
<p>I use this same bit of code, over and over again throughout my program, on different pages. Most often, I'm populating a drop-down list or combo box, but sometimes I will populate a gridview, only slightly altering the query.</p>
<p><strong>My question is how can I create a class that will allow me to call a stored procedure</strong>, instead of manually using queries like my example, and populate my different controls? Is it possible to do with only 1 method? I only need to start with selects. I've been reading up on IEnumerable which seems like the appropriate interface to use, but how do I use it?</p>
<p><strong><em>Edited to add:</em></strong></p>
<p>I marked Rorschach's answer as THE answer because s/he addressed my IEnumerable question. I also understand the need for a proper DAL and perhaps BLL layer. What I was trying to get to was that. I can build a DAL using datasets and table adapters which, in the end, gets me a strongly typed dataset. However, I feel a bit removed from the code. I was after a straight-forward way of building the DAL myself starting with the code that I gave above. Perhaps I'm not wording my question, or what I'm after, correctly.</p>
<p>At any rate, Rorschach came closest to answering my actual question. Thanks.</p>
| <p>This is a down and dirty method of reducing your code duplication. It's not really the right way to go about setting up a Data Access Layer (DAL) and a Business Logic Layer (BLL), which I'd suggest learning about instead.</p>
<pre><code>protected void FillFromDatabase( string sql, BaseDataBoundControl dataControl)
{
SqlDataReader reader = null;
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
var conn = new SqlConnection( connectionString );
var comm = new SqlCommand( sql, conn );
try
{
conn.Open();
reader = comm.ExecuteReader();
dataControl.DataSource = reader;
dataControl.DataBind();
}
finally
{
if( reader != null )
reader.Dispose();
conn.Dispose();
}
}
</code></pre>
<p>then you could call it like </p>
<pre><code>const string sql = "SELECT * FROM [Schools] ORDER BY [SchoolName] ASC";
FillFromDatabase( sql, cmbEditSchool );
</code></pre>
|
Is there a way to avoid errors when releasing an object while code is still running? <p>I have a UIView subclass that draws itself when <code>-drawRect:</code> is called. It only takes a moment, but under extreme circumstances, such as low memory and deletion of the instance when going to another view controller, the draw function doesn't complete before the the object is deallocated.</p>
<p>How am I supposed to deal with this issue? The deallocation causes any calls to [self ...] to throw a EXC_BAD_ACCESS, which the drawing function does to determine how to draw itself.</p>
<p><b>Note:</b></p>
<p>I'm largely using the framework to handle memory management. The issue lies in the asynchronous calls to <code>-drawRect:</code> from the CATiledLayer that the UIView uses, which come in before the UIView is released. However, since it's asynchronous, the <code>-didReceiveMemoryWarning</code> runs while it's drawing, causing the view to be released in the middle of the drawing.</p>
| <p>Start by reading Apple's Memory Management Rules:</p>
<p><a href="http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html" rel="nofollow">Cocoa Memory Management Rules</a></p>
<p>The bottom line: the way to "deal" with the issue is to make sure you manage your objects and their memory use properly. A crash because of a deallocation is not something to be trapped but a flat-out bug in your app that needs fixed.</p>
|
Next and Previous to navigate text fields <p>I have a sign-up form in my application with several UITextFields. In order to speed up the process I would like to add a next and previous button to a toolbar pinned above the keyboard and allow the user to "tab" between the fields using these buttons.</p>
<p>I know I can navigate through the subviews collection on my view, but I was wondering if there was a cleaner way to do this?</p>
<p>This functionality is implemented in safari as seen in the following screenshot:</p>
<p><img src="https://dl.getdropbox.com/u/22784/keyboardToolbar.png" alt="alt text" /></p>
| <p>If you want to add this type of functionality to your app, you need to create a custom view with the next/previous buttons and position it properly when the keyboard appears. Then handle any touches to those buttons.</p>
|
How to build Apple's GCC on Linux/Windows? <p>I don't have a Mac, but I have an iPhone. I want to develop applications for iPhone.
After some research I think I need just the headers and library from the free SDK, and a GCC build that supports ARM/Mach-O.
Apple released the code for GCC used in the iPhone SDK (they had to), So I think if I could build it on Windows or Linux, I can use it with the headers and libs from the SDK to develop iPhone apps.</p>
<p>I can then install the app on any Jailbroken iPhone.</p>
<p>How to build it on any non Apple machine?</p>
| <p>Look into winchain - this tool builds the iphone chain on windows allowing you to compile iphone apps on windows:</p>
<p><a href="http://code.google.com/p/winchain/wiki/HowToUse" rel="nofollow">http://code.google.com/p/winchain/wiki/HowToUse</a></p>
|
Real time scripting language + MS DLR? <p>For starters I should let you guys know what I'm trying to do. The project I'm working on has a requirement that requires a custom scripting system to be built. This will be used by non-programmers who are using the application and should be as close to natural language as possible. An example would be if the user needs to run a custom simulation and plot the output, the code they would write would need to look like</p>
<p>variable input1 is 10;
variable input2 is 20;</p>
<p>variable value1 is AVERAGE(input1, input2);</p>
<p>variable condition1 is true;
if condition1 then PLOT(value1);</p>
<p>Might not make a lot of sense, but its just an example. AVERAGE and PLOT are functions we'd like to define, they shouldn't be allowed to change them or really even see how they work. Is something like this possible with DLR? If not what other options would we have(start with ANTRL to define the grammar and then move on?)? In the future this may need to run using XBAP and WPF too, so this is also something we need to consider, but haven't seen much if anything on dlr & xbap. Thanks, and hopefully this all makes sense.</p>
<p><HR>
Lua is not an option as it is to different from what they are already accustomed to. </p>
<p>Ralf, its going to reactive, and to be honest the timeframe for when the results should get back to the user may be 1/100 of a second all the way up to 2 weeks or a month(very complex mathematical functions).</p>
<p>Basically they already have a system they purchased that does some of what they need, and included a custom scripting language that does what I mentioned above and they don't want to have to learn a new one, they basically just want us to copy it and add functionality. I think I'll just start with ANTRL and go from there.</p>
| <p><a href="http://www.lua.org" rel="nofollow">Lua</a></p>
<p>it's small, fast, easy to embed, portable, extensible, and fun!</p>
|
Retrieving original values of modified references <p>I've figured out how to use the <code>ObjectStateManager</code> and <code>ObjectStateEntries</code> to determine original values of scalar properties for a given entity. </p>
<p>What I need to know now is how to do the same for navigation properties. The <code>GetModifiedProperties</code> method on <code>ObjectStateEntry</code> doesn't return navigation properties. </p>
| <p>Just get all added or deleted ObjectStateEntries and then use LINQ to only get those that represent relationships:</p>
<pre><code>private IEnumerable<ObjectStateEntry> GetModifiedRelationshipEntries()
{
return ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Deleted)
.Where(e => e.IsRelationship);
}
</code></pre>
<p>I found these two blog entries by Daniel Simmons very useful when writing audit log for EF:</p>
<p><a href="http://blogs.msdn.com/b/dsimmons/archive/2008/01/16/ef-extension-method-extravaganza-part-i-objectstateentry.aspx" rel="nofollow">http://blogs.msdn.com/b/dsimmons/archive/2008/01/16/ef-extension-method-extravaganza-part-i-objectstateentry.aspx</a></p>
<p><a href="http://blogs.msdn.com/b/dsimmons/archive/2008/01/17/ef-extension-methods-extravaganza-part-ii-relationship-entry-irelatedend.aspx" rel="nofollow">http://blogs.msdn.com/b/dsimmons/archive/2008/01/17/ef-extension-methods-extravaganza-part-ii-relationship-entry-irelatedend.aspx</a></p>
|
How Do I Run Sutton and Barton's "Reinforcement Learning" Lisp Code? <p>I have been reading a lot about <a href="http://en.wikipedia.org/wiki/Reinforcement%5FLearning" rel="nofollow">Reinforcement Learning</a> lately, and I have found <a href="http://www.cs.ualberta.ca/~sutton/book/the-book.html" rel="nofollow">"Reinforcement Learning: An Introduction"</a> to be an excellent guide. The author's helpfully provice <a href="http://www.cs.ualberta.ca/~sutton/book/code/code.html" rel="nofollow">source code</a> for a lot of their worked examples.</p>
<p>Before I begin the question I should point out that my practical knowledge of lisp is minimal. I know the basic concepts and how it works, but I have never really used lisp in a meaningful way, so it is likely I am just doing something incredibly n00b-ish. :)</p>
<p>Also, the author states on his page that he will not answer questions about his code, so I did not contact him, and figured Stack Overflow would be a much better choice.</p>
<p>I have been trying to run the code on a linux machine, using both GNU's CLISP and SBCL but have not been able to run it. I keep getting a whole list of errors using either interpreter. In particular, most of the code appears to use a lot of utilities contained in a file 'utilities.lisp' which contains the lines</p>
<pre><code>(defpackage :rss-utilities
(:use :common-lisp :ccl)
(:nicknames :ut))
(in-package :ut)
</code></pre>
<p>The :ccl seems to refer to some kind of Mac-based version of lisp, but I could not confirm this, it could just be some other package of code.</p>
<pre><code>> * (load "utilities.lisp")
>
> debugger invoked on a
> SB-KERNEL:SIMPLE-PACKAGE-ERROR in
> thread #<THREAD "initial thread"
> RUNNING {100266AC51}>: The name
> "CCL" does not designate any package.
>
> Type HELP for debugger help, or
> (SB-EXT:QUIT) to exit from SBCL.
>
> restarts (invokable by number or by
> possibly-abbreviated name): 0:
> [ABORT] Exit debugger, returning to
> top level.
>
> (SB-INT:%FIND-PACKAGE-OR-LOSE "CCL")
</code></pre>
<p>I tried removing this particular piece (changing the line to</p>
<pre><code> (:use :common-lisp)
</code></pre>
<p>but that just created more errors.</p>
<pre><code>> ; in: LAMBDA NIL ; (+
> RSS-UTILITIES::*MENUBAR-BOTTOM* ;
> (/ (- RSS-UTILITIES::MAX-V
> RSS-UTILITIES::V-SIZE) 2)) ; ; caught
> WARNING: ; undefined variable:
> *MENUBAR-BOTTOM*
>
> ; (-
> RSS-UTILITIES::*SCREEN-HEIGHT*
> RSS-UTILITIES::*MENUBAR-BOTTOM*) ; ;
> caught WARNING: ; undefined
> variable: *SCREEN-HEIGHT*
>
> ; (IF RSS-UTILITIES::CONTAINER ;
> (RSS-UTILITIES::POINT-H ;
> (RSS-UTILITIES::VIEW-SIZE
> RSS-UTILITIES::CONTAINER)) ;
> RSS-UTILITIES::*SCREEN-WIDTH*) ; ;
> caught WARNING: ; undefined
> variable: *SCREEN-WIDTH*
>
> ; (RSS-UTILITIES::POINT-H
> (RSS-UTILITIES::VIEW-SIZE
> RSS-UTILITIES::VIEW)) ; ; caught
> STYLE-WARNING: ; undefined function:
> POINT-H
>
> ; (RSS-UTILITIES::POINT-V
> (RSS-UTILITIES::VIEW-SIZE
> RSS-UTILITIES::VIEW)) ; ; caught
> STYLE-WARNING: ; undefined function:
> POINT-V
</code></pre>
<p>Anybody got any idea how I can run this code? Am I just totally ignorant of all things lisp?</p>
<p><strong>UPDATE [March 2009]:</strong> I installed Clozure, but was still not able to get the code to run.</p>
<p>At the CCL command prompt, the command</p>
<pre><code>(load "utilities.lisp")
</code></pre>
<p>results in the following error output:</p>
<pre><code>;Compiler warnings :
; In CENTER-VIEW: Undeclared free variable *SCREEN-HEIGHT*
; In CENTER-VIEW: Undeclared free variable *SCREEN-WIDTH*
; In CENTER-VIEW: Undeclared free variable *MENUBAR-BOTTOM* (2 references)
> Error: Undefined function RANDOM-STATE called with arguments (64497 9) .
> While executing: CCL::READ-DISPATCH, in process listener(1).
> Type :GO to continue, :POP to abort, :R for a list of available restarts.
> If continued: Retry applying RANDOM-STATE to (64497 9).
> Type :? for other options.
1 >
</code></pre>
<p>Unfortuately, I'm still learning about lisp, so while I have a sense that something is not fully defined, I do not really understand how to read these error messages.</p>
| <p>My guess is that the code is CCL-dependent, so use <a href="http://www.cliki.net/CCL" rel="nofollow">CCL</a> instead of CLISP or SBCL. You can download it from here: <a href="http://trac.clozure.com/openmcl" rel="nofollow">http://trac.clozure.com/openmcl</a></p>
|
Reloading/Refreshing Spring configuration file without restarting the servlet container <p>How can I refresh Spring configuration file without restarting my servlet container?</p>
<p>I am looking for a solution other than JRebel.</p>
| <p>Well, it can be useful to perform such a context reload while testing your app.</p>
<p>You can try the <code>refresh</code> method of one of the <code>AbstractRefreshableApplicationContext</code> class: it won't refresh your previously instanciated beans, but next call on the context will return refreshed beans.</p>
<pre><code>import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class ReloadSpringContext {
final static String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\"\n" +
" \t\"http://www.springframework.org/dtd/spring-beans.dtd\">\n";
final static String contextA =
"<beans><bean id=\"test\" class=\"java.lang.String\">\n" +
"\t\t<constructor-arg value=\"fromContextA\"/>\n" +
"</bean></beans>";
final static String contextB =
"<beans><bean id=\"test\" class=\"java.lang.String\">\n" +
"\t\t<constructor-arg value=\"fromContextB\"/>\n" +
"</bean></beans>";
public static void main(String[] args) throws IOException {
//create a single context file
final File contextFile = File.createTempFile("testSpringContext", ".xml");
//write the first context into it
FileUtils.writeStringToFile(contextFile, header + contextA);
//create a spring context
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
new String[]{contextFile.getPath()}
);
//echo the bean 'test' on stdout
System.out.println(context.getBean("test"));
//write the second context into it
FileUtils.writeStringToFile(contextFile, header + contextB);
//refresh the context
context.refresh();
//echo the bean 'test' on stdout
System.out.println(context.getBean("test"));
}
}
</code></pre>
<p>And you get this result</p>
<pre><code>fromContextA
fromContextB
</code></pre>
<p>Another way to achieve this (and maybe a more simple one) is to use the Refreshable Bean feature of Spring 2.5+
With dynamic language (groovy, etc) and spring you can even change your bean behavior. Have a look to the <a href="http://static.springsource.org/spring/docs/2.5.x/reference/dynamic-language.html" rel="nofollow">spring reference for dynamic language</a>:</p>
<blockquote>
<p>24.3.1.2. Refreshable beans</p>
<p>One of the (if not the) most
compelling value adds of the dynamic
language support in Spring is the
'refreshable bean' feature.</p>
<p>A refreshable bean is a
dynamic-language-backed bean that with
a small amount of configuration, a
dynamic-language-backed bean can
monitor changes in its underlying
source file resource, and then reload
itself when the dynamic language
source file is changed (for example
when a developer edits and saves
changes to the file on the
filesystem).</p>
</blockquote>
|
Deferred EL in JSP 2.0 <p>Is there a way to use something like deferred EL in JSP 2.0 / J2EE 1.4? The idea is to pass a test to a tag file and have it display an item in a list (or not) based on the value of the expression. Basically, I'd like to do something like this:</p>
<p>JSP:</p>
<pre><code><x:myTag items="${myCollection}" test="${item.visible}"/>
</code></pre>
<p>myTag.tag</p>
<pre><code><c:forEach var="item" items="${collection}">
<c:if test="${test}">
${item}
</c:if>
</c:forEach>
</code></pre>
<p>Upgrading our JSP container is not an option. Any ideas?</p>
<p><strong>Update:</strong></p>
<p>I tried doing this with JSP fragments, but the EL in the fragment was evaluated once in the JSP, rather than once per iteration in the tag.</p>
| <p>You should be able to do this with <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bnaln.html#bnalq" rel="nofollow">jsp fragments</a>. I believe it will not be the extremely elegant solution you would appreciate, but it does allow the execution of the expression to be deferred until inside the tag. </p>
<p>Edit:
You could check out the <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bnamu.html#bnank" rel="nofollow">variable</a> with the "name-given" setting.</p>
<p>(I will readily admit I did <em>something</em> like what you're trying to do about 2 years ago. I have not touched it since. I remember I thought it was quite arcane)</p>
|
MSSQL Select statement with incremental integer column... not from a table <p>I need, if possible, a t-sql query that, returning the values from an arbitrary table, also returns a incremental integer column with value = 1 for the first row, 2 for the second, and so on.</p>
<p>This column does not actually resides in any table, and must be strictly incremental, because the ORDER BY clause could sort the rows of the table and I want the incremental row in perfect shape always...</p>
<p>Thanks in advance.</p>
<p>--EDIT
Sorry, forgot to mention, must run on SQL Server 2000</p>
| <p>For SQL 2005 and up</p>
<pre><code>SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
FROM YourTable
</code></pre>
<p>for 2000 you need to do something like this</p>
<pre><code>SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0
INSERT INTO #Ranks
SELECT SomeColumn FROM YourTable
ORDER BY SomeColumn
SELECT * FROM #Ranks
Order By Ranks
</code></pre>
<p>see also here <a href="http://wiki.lessthandot.com/index.php/Row_Number">Row Number</a></p>
|
Updating all ListView items together instead of one-by-one? <p>I have a invoice entry form in ASP.Net 3.5. I have a FormView for the main invoice form and a ListView for the invoice line items. I don't want to commit each line item to the database individually when the user edits them. I want to commit them all as a group when the user clicks a button to update the FormView. I suppose I could bind to a datatable and manually retrieve the value from every control. However, I would prefer to use a LinqDataSource or ObjectDataSource if possible.</p>
<p>Is there an easy way to accomplish what I am trying to do there? I'm not married to the FormView/ListView approach, if there is an easier way.</p>
| <p>If you are using LinqDataSource if the use action has made changes to the entity just invoke the SubmitChanges method will commit the data changes back to the Database in a single transaction.</p>
|
.getJSON produce a Download of a File ASP.NET MVC <p>I code a .getJSon, It does the job but I get IE to asked to download the file. Here is the code</p>
<pre><code><script type="text/javascript">
$(function() {
$('#id').click(function() {
var dateReport = "01/01/2009";
$.getJSON('/Report/SendReport', { date: dateReport},
function(response) {
if (response.result == "OK") {
$('#OKSendReport').toggle();
$('#OKSendReport').html("OK");
}
});
});
});
</code></pre>
<p></p>
<p>The code in the controller is</p>
<pre><code> public ActionResult SendReport(string date) {
//DO Stuff
return new JsonResult {
Data = new { result = "OK" }
};
}
</code></pre>
<p>Any ideas?</p>
| <p>Try adding the <code>event.preventDefault();</code> on the click event:</p>
<pre><code>$(function() {
$('#id').click(function(event) {
var dateReport = "01/01/2009";
event.preventDefault(); // added this
$.getJSON('/Report/SendReport', { date: dateReport},
function(response) {
if (response.result == "OK") {
$('#OKSendReport').toggle();
$('#OKSendReport').html("OK");
}
});
});
});
</code></pre>
|
Reading the g:datePicker-value in Grails without using the "new Object(params)"-method <p>Let's say I have a datePicker called "foobar":</p>
<pre><code><g:datePicker name="foobar" value="${new Date()}" precision="day" />
</code></pre>
<p>How do I read the submitted value of this date-picker?</p>
<p>One way which works but has some unwanted side-effects is the following:</p>
<pre><code>def newObject = new SomeClassName(params)
println "value=" + newObject.foobar
</code></pre>
<p>This way of doing it reads all submitted fields into newObject which is something I want to avoid. I'm only interested in the value of the "foobar" field.</p>
<p>The way I originally assumed this could be done was:</p>
<pre><code>def newObject = new SomeClassName()
newObject.foobar = params["foobar"]
</code></pre>
<p>But Grails does not seem to automatically do the translation of the foobar field into a Date() object.</p>
<p><b>Updated:</b> Additional information can be found in the <a href="http://jira.codehaus.org/browse/GRAILS-3740" rel="nofollow">Grails JIRA</a>.</p>
| <p>Use the <a href="http://grails.org/Command+objects+and+Form+Validation" rel="nofollow">command object</a> idiom. In the case of your example, I will assume that your form calls the action <code>handleDate</code>. Inside the controller:</p>
<pre><code>
def handleDate = { FoobarDateCommand dateCommand ->
def theNextDay = dateCommand.foobar + 1
}
</code></pre>
<p>Here's <code>FoobarDateCommand</code>. Notice how you name the field the same as in the view:</p>
<pre><code>
class FoobarDateCommand {
Date foobar
}
</code></pre>
<p>Command objects are a handy way to encapsulate all validation tasks for each of your forms, keeping your controllers nice and small.</p>
|
Multiple Parameter Search in SQL Server 2000 <p>I have a search screen in a Visual Basic .Net App that has text boxes for:</p>
<ol>
<li>First Name Varchar(50)</li>
<li>Last Name Varchar(50)</li>
<li>Middle Name Varchar(50)</li>
<li>DOB DateTime</li>
<li>Home Phone Varchar(10)</li>
<li>Work Phone Varchar(10)</li>
</ol>
<p>How would I create a stored procedure in SQL Server 2000 that would allow me to be able to search on all/some/one of the fields. If user only enters data on say first name and home phone number what would I need to do for the rest of the parameters where data was not entered. I tried the select statement below but it doesn't work properly.</p>
<pre><code> Select Last_Name, First_Name, Mid_Name, DOB, Home_Phone, Work_Phone from dbo.tblClient
Where Last_Name Like '%@LastName' and
First_Name Like '%@FirstName' and
Mid_Name Like '%@MiddleName' and
DOB Like '%DOB' and
Home_Phone Like '%@HomePhone' and
Work_Phone Like '%@WorkPhone'
</code></pre>
| <p>I use this pattern a lot:</p>
<p><code></p>
<pre><code>Select Last_Name, First_Name, Mid_Name, DOB, Home_Phone, Work_Phone from dbo.tblClient
Where (@LastName is null or Last_Name Like '%'+ @LastName)
and (@FirstName is null or First_Name Like '%'+ @FirstName)
and (@HomePhone is null or Home_Phone Like '%'+ @HomePhone)
-- etc...
</code></pre>
<p></code></p>
<p>It will ignore anything that's not supplied, while still giving good performance. Better still, it doesn't resort to dynamic SQL to pull it off.</p>
|
Bulk upgrade VS2005 solutions to VS2008 <p>Is it possible to bulk upgrade (many at the same time) VS 2005 projects to VS 2008.</p>
<p>I know that I can open one at a time, however, I would like to select say 10 at a time to upgrade and add to a new solution.</p>
| <p>I recently came across the same problem and used a Windows Powershell script to get Visual Studio to do the upgrading for me using the <a href="http://msdn.microsoft.com/en-us/library/w15a82ay.aspx" rel="nofollow">/upgrade</a> command line switch</p>
<pre><code>$slnFiles = ls C:\source -Filter *.sln -Recurse
$devenv = "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe"
$i = 1
foreach ($sln in $slnFiles)
{
"Upgrading Solution " + $i++ + ": " + $sln.FullName
&$devenv /upgrade $sln.FullName
}
"Done!"
</code></pre>
|
Yahoo Finance API like chart <p>I want to create a chart very similar to <a href="http://finance.yahoo.com/echarts?s=%5EDJI#chart1%3asymbol=%5Edji;range=6m;indicator=volume;charttype=line;crosshair=on;ohlcvalues=0;logscale=on;source=undefined" rel="nofollow">yahoo Finance interactive chart</a> in a .NET application. The interactive chart on Yahoo finance is not included in their developer API. Has anyone tried to leverage their API to create a similar chart? Although the chart is very much like the one used on Yahoo, the data used for my analysis is not Stock data. So, I will not be able to call the Yahoo Url by feeding any query params. </p>
<p>Any suggestions?</p>
| <p>If your looking at a web based chart, the <i>flot</i> graphs for jQuery are a good option IMHO. They look pretty schnazzy, are interactive and are very simple to get working.</p>
<p><a href="http://plugins.jquery.com/project/flot" rel="nofollow">http://plugins.jquery.com/project/flot</a></p>
|
Limiting the data returned by a controller <p>I need advice on how to return a limited set of data from an MVC controller.</p>
<p>Lets say I have a class that is constructed like so:</p>
<pre><code>public interface ICustomerExpose
{
string Name {get; set;}
string State {get; set;}
}
public interface ICustomer: ICustomerExpose
{
int Id {get; set;}
string SSN {get; set;}
}
public class Customer: ICustomer
{
...
}
</code></pre>
<p>In my MVC project I have a controller action that returns customer data. The project is actually more like a web service as there is no View associated with the data... we use the XmlResult (provided by the <a href="http://www.codeplex.com/MVCContrib" rel="nofollow">MVCContrib</a> project). The controller action looks like this:</p>
<pre><code> // GET: /Customer/Show/5
public ActionResult Show(int id)
{
Customer customer = Customer.Load(id);
... // some validation work
return new XmlResult((ICustomerExpose)customer);
}
</code></pre>
<p>The above controller code does not work like I want it to. What I want to happen is that only the Name and State properties are serialized and returned in the XmlResult. In practice the whole customer object is serialized including the data I definitely don't want exposed.</p>
<p>I know the reason this doesn't work: you can't serialize an interface.</p>
<p>One idea floated around the office was to simply mark the properties Name and State as [XmlIgnore]. However, this doesn't seem like a good solution to me. There might be other instances where I want to serialize those properties and marking the properties on the class this way prohibits me.</p>
<p>What is the best way to achieve my goal of only serializing the properties in the ICustomerExpose interface?</p>
<p>Addendum:</p>
<p>For those interested in what XmlResult does here are the relevant parts of it:</p>
<pre><code> public class XmlResult : ActionResult
{
private object _objectToSerialize;
public XmlResult(object objectToSerialize)
{
_objectToSerialize = objectToSerialize;
}
/// <summary>
/// Serialises the object that was passed into the constructor
/// to XML and writes the corresponding XML to the result stream.
/// </summary>
public override void ExecuteResult(ControllerContext context)
{
if (_objectToSerialize != null)
{
var xs = new XmlSerializer(_objectToSerialize.GetType());
context.HttpContext.Response.ContentType = "text/xml";
xs.Serialize(context.HttpContext.Response.Output, _objectToSerialize);
}
}
}
</code></pre>
| <p>You can try this, however I am not sure if it works with xml serializers:</p>
<pre><code>return new XmlResult(new { customer.Name, customer.State });
</code></pre>
|
Return anonymous type results? <p>Using the simple example below, what is the best way to return results from multiple tables using Linq to SQL?</p>
<p>Say I have two tables:</p>
<pre><code>Dogs: Name, Age, BreedId
Breeds: BreedId, BreedName
</code></pre>
<p>I want to return all dogs with their <code>BreedName</code>. I should get all dogs using something like this with no problems:</p>
<pre><code>public IQueryable<Dog> GetDogs()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select d;
return result;
}
</code></pre>
<p>But if I want dogs with breeds and try this I have problems:</p>
<pre><code>public IQueryable<Dog> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result;
}
</code></pre>
<p>Now I realize that the compiler won't let me return a set of anonymous types since it's expecting Dogs, but is there a way to return this without having to create a custom type? Or do I have to create my own class for <code>DogsWithBreedNames</code> and specify that type in the select? Or is there another easier way?</p>
| <p>I tend to go for this pattern:</p>
<pre><code>public class DogWithBreed
{
public Dog Dog { get; set; }
public string BreedName { get; set; }
}
public IQueryable<DogWithBreed> GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new DogWithBreed()
{
Dog = d,
BreedName = b.BreedName
};
return result;
}
</code></pre>
<p>It means you have an extra class, but it's quick and easy to code, easily extensible, reusable and type-safe.</p>
|
Can I have a Django model that has a foreign key reference to itself? <p>Okay, how would I do this?</p>
<pre><code>class Example(models.Model):
parent_example = models.ForeignKey(Example)
</code></pre>
<p>I want to have a model have a foreign key reference to itself. When I try to create this I get a django validation error that Example is not yet defined.</p>
| <p>You should use</p>
<pre><code>models.ForeignKey('self')
</code></pre>
<p>as mentioned <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey">here</a>.</p>
|
How to refer to current node value in XSL for-each test? <p>Let's say I have an XML doc like this:</p>
<pre><code><books>
<book>1110</book>
<book>1111</book>
<book>1112</book>
<book>1113</book>
</books>
</code></pre>
<p>I'm trying to setup a condition that tests the value of the current node in the <code>for-each</code>, but I'm doing something wrong:</p>
<pre><code><xsl:for-each select="/books/book">
<xsl:if test=".[='1112']">
Success
</xsl:if>
</xsl:for-each>
</code></pre>
<p>What am I doing incorrectly?</p>
| <p>Using <code>.</code> can, indeed, refer to the current (or "context") node, but not the way you're using it here. In XPath, <code>.[foo]</code> is not valid syntax â you need to use <code>self::node()[foo]</code> instead. Also, the <code>=</code> operator needs something to match against, in this case the <code>text()</code> selector to access the element's text contents:</p>
<pre><code><xsl:for-each select="/books/book">
<xsl:if test="self::node()[text()='1112']">
Success
</xsl:if>
</xsl:for-each>
</code></pre>
<p>As stated in the other answers, however, unless your <code>for-each</code> is performing other operations as well, you don't need to iterate at all and can use just <code>if</code> to accomplish the same task:</p>
<pre><code><xsl:if test="/books/book[. = 1112]">
Success
</xsl:if>
</code></pre>
|
Zend Form: How do I make it bend to my will? <p>I've read the manual many times, I've scoured the posts offered by Google on the subject, I have even bought a couple of books that deal with ZF. Now, why am I still confused?</p>
<p>I can, using Zend_Form, make a form that validates and functions fine. What I cannot do it make a form that looks exactly like I want it to look with the error messages that I want it to have. I want custom buttons, I want funky layouts, I want to insert text in the midst of the form, etc. </p>
<p>Does anyone have a simple way of achieving these sorts of things? Something that makes me feel like the framework is saving me time rather than costing? I could forego Zend Form... make my own form, have its action hit a page to validate and process the posted data and I could do it about as fast as I can type but I really want to "get" this and be able to use it as it was apparently intended. </p>
<p>Any advice? Any simple "how to's" for custom buttons, funky layouts and basic (or rather advanced as there are tons of basic tutorials that skip over the harder issues) "getting things done" with zend form?</p>
| <p>Barrett Conrad's advice is what I would have suggested. Also, keep in mind that you don't need to use a form object to render your form.</p>
<p>One thing you could do is create a form in your view script that has elements with the same name as a form class.</p>
<p>Your HTML form:</p>
<pre><code><form action="/login/" method="post">
<fieldset>
<label for="username">Username:</label>
<input type="text" size="10" name="username" />
<label for="password">Password:</label>
<input type="password" size="10" name="password" />
<input type="submit" />
</fieldset>
</form>
</code></pre>
<p>Your class:</p>
<pre><code>class LoginForm extends Zend_Form
{
public function init()
{
$username = $this->createElement('text','username');
$username->setRequired(true);
$this->addElement($username);
$password = $this->createElement('password','password');
$password->setRequired(true);
$this->addElement($password);
}
}
</code></pre>
<p>Your form class reflects your HTML form, each element in your class has its own validators and requirements. Back in your action you can create an instance of your form class and validate your post/get vars against that form:</p>
<pre><code>$form = new LoginForm();
if ($this->_request->isPost()) {
if ($form->isValid($this->_request->getParams())) {
// do whatever you need to do
} else {
$this->view->errors = $form->getMessages();
}
}
</code></pre>
<p>You can display the the error messages at the top of your form in one group, using this method. </p>
<p>This is a basic example, but it allows you to have total control over the presentation of your form without spending the time to learn to use decorators. Much of the strength of Zend_Form is in its validation and filtering properties, in my opinion. This gives you that strength. The main draw back to a solution like this is that your view script HTML form can become out-of-sync with your form class.</p>
|
Best way to learn about .net MVC for a php programmer <p>Ok i know theres a ton of questions around books and tutorials to learn MVC in dot net, BUT after I started reading some of that stuff i realized they are not oriented to people like me. </p>
<p>I have been working with php on Zend in a MVC configuration and done some ruby on rails so i do have a good idea of the pattern, but i have absolutly no idea about: IIS, Visual Studio and asp/C#... so, what is the best way(could be 1 book, a couple of tutorials, a guide, a manual, a blog-post) to get a very good idea of this technology. </p>
<p>At least i would except being able to know(first hand) the pros and cons of all this!</p>
| <p>Screencasts help me more than anything. Seeing someone actually do something is many times more instructive than reading. Watch the screencasts on <a href="http://www.asp.net/learn/mvc-videos/#howdoi" rel="nofollow">http://asp.net/mvc</a>. Scott Hanselman's preview 3 videos are still relevant, as there haven't been many huge, sweeping changes since then. They show you how to drag data around, use LINQ, and other .NET specific things. After watching and coding along with those, check out the others.</p>
|
Where can I find a map control for Delphi? <p>I am trying to build an option in a application that let user see a map. This map must be editable, and tag enabled. It should also be possible to see sub regions in different colors, and highlight the one under the mouse.</p>
| <p>TGlobe is good one, but hasn't updated since 2004, If you need more than showing a map, and build a GIS like application I suggest use one of these:</p>
<ol>
<li><a href="http://www.tatukgis.com/Home/home.aspx" rel="nofollow">TatukGIS</a> (very powerful GIS Components and writing as Native VCL).</li>
<li><a href="http://cartovcl.com/" rel="nofollow">CartoVCL</a>.</li>
<li><a href="http://www.esri.com/software/mapobjects/index.html" rel="nofollow">MapObjects</a> (the Leading GIS Company, but the components are ActiveX).</li>
</ol>
|
Where can I find an image watermark control for Delphi? <p>Is there a good image watermark control for Delphi? It would be nice if it could receive both text and images to insert in a base photo.</p>
<p>I would also prefer it was free.</p>
| <p>I couldn't find any pre-packaged controls. But watermarking is not very hard at all. All you simply need to do is draw an image on top of another image with the use of alpha blending. <a href="http://www.efg2.com/Lab/Library/Delphi/Graphics/Algorithms.htm" rel="nofollow">This</a> site has a whole section on alpha blending in Delphi. They provide links to graphics libraries which have implemented it.</p>
<p>However if you're using Delphi.NET, and can access the relevant classes in the framework, there is an easier way using only framework methods.</p>
|
Tracking the script execution time in PHP <p>PHP must track the amount of CPU time a particular script has used in order to enforce the max_execution_time limit. </p>
<p>Is there a way to get access to this inside of the script? I'd like to include some logging with my tests about how much CPU was burnt in the actual PHP (the time is not incremented when the script is sitting and waiting for the database).</p>
<p>I am using a Linux box. </p>
| <p>If all you need is the wall-clock time, rather than the CPU execution time, then it is simple to calculate: </p>
<pre><code>//place this before any script you want to calculate time
$time_start = microtime(true);
//sample script
for($i=0; $i<1000; $i++){
//do anything
}
$time_end = microtime(true);
//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;
//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';
</code></pre>
<p>Note that this will include time that PHP is sat waiting for external resources such as disks or databases, which is not used for max_execution_time.</p>
|
How to add NSDebug.h and use NSZombie in iPhone SDK <p>I want to enable NSZombies for my iPhone app.</p>
<p>I have read several articles online and I am still unsure of the exact procedure.</p>
<p>I know I have to set the Environment Variables, which I have done:</p>
<pre><code>NSZombieEnabled = YES
NSDebugEnabled = YES
NSDeallocateZombies = NO
</code></pre>
<p>I think (I'm not sure), I have to import NSDebug.h.
When I check the headers of the Foundation Framework in my project, there is no NSDebug.h.</p>
<p>After some research, I found them in the iPhoneSimulator Foundation Framework.
So (and I'm not sure if this is correct), I imported the iPhoneSimualtor Foundation Framework into my project.
I noticed that the file STILL does not show up in the project window, even though I can locate it in the Finder.(Is this normal behavior?).</p>
<p>So I opened up main and added:</p>
<pre><code>#ifdef TARGET_IPHONE_SIMULATOR
#import <Foundation/NSDebug.h>
#endif
</code></pre>
<p>I am not sure if that is right either. After this I still can't get the NSZombie to work (unless I have misunderstood what it is supposed to do)
I am expecting to see a log of " NSZombie sent a release... " or something. But I don't see anything</p>
<p>I'm sure I'm just not doing this right, a good step by step would be appreciated.
Thanks</p>
<p>Also of note, I have also enabled:</p>
<pre><code>NSMallocStacklLogging = YES
MallocStackLoggingNoCompact = YES
</code></pre>
| <p>Are you setting the environment variable correctly? The step by step guide is</p>
<ol>
<li>Double-click an executable in the Executables group of your Xcode project.</li>
<li>Click the Arguments tab.</li>
<li>In the "Variables to be set in the environment:" section, make a variable called "NSZombieEnabled" and set its value to "YES".</li>
</ol>
<p>You don't need to #import NSDebug.h</p>
|
Alternative to Lattice's GAL and ispGAL chips <p>I took a class last semester about programming with embedded hardware, mainly using GAl chips from Lattice and ABEL to program them. I'd like to continue this for fun outside of the class, but I find things to be cost prohibitive due to the high costs of buying a programmer.</p>
<p>Are there any free or low-cost ways that I can program something similar to a GAL chip? Please don't suggest AVR or PIC chips, as my main project is I want to actually program and build a CPU out of smaller chips.</p>
<p>I've looked into ispGAL chips, but the cables to program them ISP (USB at least) are $150 or more.</p>
<p>Thanks for any help guys!</p>
| <p>Try a Xilinx evaluation board, the education priced ones are pretty cheap. And you're a student!</p>
<p>I'd guess based on the AUD price, of $150 about USD$100 with all the tools.</p>
<p>This is a bit pricey, but the chip is big enough to do a whole computer in gates.
The eval board has ethernet, PS/2, serial, usb and VGA: and they all connect to the gate array!</p>
<p>For <em>really</em> cheap, Slipway ?</p>
<p><a href="http://research.cs.berkeley.edu/project/slipway/" rel="nofollow">http://research.cs.berkeley.edu/project/slipway/</a></p>
|
Is if (variable) the same as if (variable != nil) in Objective-C <p>I am getting a EXC_BAD_ACCESS (SIGBUS) on this line in my iPhone project:</p>
<pre><code>if (timeoutTimer) [timeoutTimer invalidate];
</code></pre>
<p>The thing that has me stumped is that I don't understand how that line could crash, since the if statement is meant to be checking for nil. Am I misunderstanding the way Objective-C works, or do line numbers in crash statements sometime have the wrong line in them?</p>
| <p>Just because a variable is set to a value other than <code>nil</code> doesn't mean it's pointing to a valid object. For example:</p>
<pre><code>id object = [[NSObject alloc] init];
[object release];
NSLog(@"%@", object); // Not nil, but a deallocated object,
// meaning a likely crash
</code></pre>
<p>Your timer has probably already been gotten rid of (or possibly hasn't been created at all?) but the variable wasn't set to nil.</p>
|
JQuery , set attribute for <a> tag <p>i am use $(expr).attr("hash",value) to set a "hash" attribute for HTML anchor element "a"
but the Jquery would not do that. but if i change expr to "div", then i can set
"hash" attribute to "div" tag.</p>
<p>is this behavior a xhtml specification? i can set "id" of "a" tag attribute. since id is a built in attribute for html "a" tag. </p>
| <blockquote>
<p>to set a "hash" attribute for HTML anchor element "a"</p>
</blockquote>
<p>The <a> element (HTMLLinkElement) already has a DOM Level 0 <code>hash</code> property. It is used like window.location.hash to read or set the â...#anchorâ part at the end of the URL being referred to by the element's <code>href</code>.</p>
<p>Setting <code>a.hash</code>, whether directly or through jQuery's <code>attr()</code> wrapper, merely sets the anchor name in the link's URL. You <em>could</em> deliberately say you want an actual attribute by calling the DOM method <code>a.setAttribute('hash', value)</code>, except that this doesn't work in IE6/7 due to a long-standing bug where it confuses attributes and properties.</p>
<p>This is one of the problems with adding custom non-standard attributes to elements, you never know when it's going to clash with an existing name. HTML5 will suggest you limit your custom attributes to names starting with âdata-â, but in general it's best to find another way of storing data if you can.</p>
|
Adding new methods to LINQ to SQL generated classes <p>I am new to LINQ. I just dragged all my database tables onto the designer in a LINQ to SQL dbml. All my relationships are correct and look nice in the designer. I am able to pull data using simple LINQ code. I want to add my own methods now but don't want to blow away my changes if (when) I need to regenerate my dbml. I am guessing I just create a new class file and setup partial classes of the generated classes. Is this correct? For example, I have a generated class called <strong>SystemUser</strong> which contains the columns <strong><em>SystemUserId, Username, Password, PersonId, SecurityQuestionId, SecurityQuestionResponse</em></strong>. I want to add a method called <strong><em>void Authenticate()</em></strong> and a new property called <strong><em>bool Authenticated</em></strong>. Basically I want to pass in a username and password to <strong><em>Authenticate()</em></strong> and set the <strong><em>Authenticated</em></strong> property based on finding a matching user, etc. Where and how would I do this?</p>
| <p>The LINQ-generated classes are partial classes, meaning you can extend them by creating your own <a href="http://msdn.microsoft.com/en-us/library/bb882671.aspx">partial classes</a> or <a href="http://msdn.microsoft.com/en-us/library/bb546176.aspx">partial methods</a>.</p>
<p>In your case, you can create a partial class for your SystemUser, and then add your method(s) in there. They will not be overwritten if the DBML file is regenerated. </p>
<p>Something like:</p>
<pre><code>public partial class SystemUser
{
public bool Authenticated { get; set; }
void Authenticate()
{
//Perform custom logic here.
}
}
</code></pre>
|
Techniques for steming a possible flood of automatically generated e-mail when a website encounters errors <p>For my current web development project I'm implementing a back end system that will flag errors and send an email to the administrator automatically with details about what occurred. Trapping the error and generating the email with appropriate error information is pretty straight forward; but a problem arises when one considers certain groups of error types especially if the site is being visited frequently.</p>
<p>Consider a couple of examples:</p>
<ol>
<li>An unplanned database outage that prevents all of the scripts on the web server from being able to connect. If it takes say 2 minutes (120 seconds) for the database server to come back online, and the web server is receiving <em>unique</em> requests at a rate of 10/second, in the time it takes the database server to come back online the admins email would be flooded with 1200 identical emails all screaming about a failure to connect to the database.</li>
<li>A bug in a script somewhere managed to sneak by testing and is of the variety that completely screws up content generation and occurs only in a specific set of circumstances (say once every 100 requests). Using the <em>unique</em> request rate of 10/second again means the administrator is going to be getting the same email every 10 seconds about the same bug until it is fixed.</li>
</ol>
<p><strong>What are some approaches/strategies I can use to prevent this scenario from occurring? (I am only interested in monitoring of errors generated by the script, infrastructure issues are beyond the scope of this solution)</strong></p>
<p>I going to assume that I can almost always uniquely identify errors using a digest of some of the values passed to the error handler callback set by <a href="http://ca.php.net/manual/en/function.set-error-handler.php" rel="nofollow">set_error_handler</a>.</p>
<p>The first and probably most obvious solution is recording in a database and only send the email if a reasonable minimum period of time has passed since it last occurred. This isn't the ideal approach especially if the database is causing the problem. Another solution would be to write files to disk when errors occur and check if a reasonable minimum period of time has passed since the file was last modified. <strong>Is there any mechanism to solve this problem beyond the two methods I have described?</strong></p>
| <p>Why not simply allow them all to be sent out and then collect and store them in a database on the recipient end. That way you bypass the possibility of the database being the problem in the server.</p>
<p>Also, a greater advantage in my opinion, is that you don't arbitrarily throw out valuable forensic data. Post hoc analysis is very important and any kind of filtering could make it incredibly difficult, or impossible.</p>
|
How do you ActiveRecord query caching at the application level? <p>ActiveRecord query caching is enabled when a controller's action is invoked. I also know that you can do something like this to temporarily enable caching for a given Model for a given code block:</p>
<pre><code>User.cache do
....
end
</code></pre>
<p>But is there a way to enable query caching for other contexts (e.g. when a script is run under the rails environment using ./script/runner)?</p>
| <p>An ActiveRecord query cache lives only for the duration of a particular action (i.e. request). If you want a cached object to survive longer or be used between processes you need to look at something like memcached. </p>
|
Is there a .NET Culture-dependent 'Today' string? <p>I am writing a month calendar-style control, and need to display a string that indicates today's date. So on an English-culture machine it would show <code>'Today : 11/02/2009'</code>. </p>
<p>If a different culture happens to be used, such as French, then I would like to use the French word for 'Today'. </p>
<p>Does the .NET platform expose this word as part of the culture information so I can retrieve it automatically? I cannot find anything exposed but maybe I am not looking in the right place.</p>
| <p>Old.. but still useful (how old? VB6 old).</p>
<p>Basically Windows keeps a localized version of "Today" in Comctl32.dll. You can fish it out with a a loadstringex call:</p>
<pre><code>Private Const IDM_TODAY As Long = 4163
Private Const IDM_GOTODAY As Long = 4164
Public Function GetTodayLocalized(ByVal LocaleId As Long) As String
Static hComCtl32 As Long
Static hComCtl32Initialized As Boolean
Static hComCtl32MustBeFreed As Boolean
Dim s As String
If Not hComCtl32Initialized Then
hComCtl32 = GetModuleHandle("Comctl32.dll")
If hComCtl32 <> 0 Then
hComCtl32MustBeFreed = False
hComCtl32Initialized = True
Else
hComCtl32 = LoadLibrary("Comctl32.Dll")
If Not hComCtl32 = 0 Then
hComCtl32MustBeFreed = True
hComCtl32Initialized = True
End If
End If
End If
If hComCtl32Initialized = False Then
s = "Today"
Else
s = LoadStringEx(hComCtl32, IDM_TODAY, LocaleId)
If s = "" Then
s = "Today"
End If
End If
If hComCtl32MustBeFreed Then
FreeLibrary hComCtl32
hComCtl32MustBeFreed = False
hComCtl32Initialized = False
hComCtl32 = 0
End If
s = Replace(s, "&", "")
If Right(s, 1) = ":" Then
s = Left(s, Len(s) - 1)
End If
GetTodayLocalized = s
End Function
</code></pre>
|
What does it mean to do/determine something "programmatically"? <p>Programmatically. (alt. programmically)</p>
<p>I've never used it, but I see it in questions a lot, i.e. "How to programmatically determine [insert task here]". Firefox immediately tells me that neither of these two words are real (at least, it doesn't recognize them). I've also never seen them used anywhere but here.</p>
<p>1) What does it mean to do/determine something "programmatically"?</p>
<p>2) Why do so many people ask how to do/determine something "programmatically"? Isn't it <em>assumed</em> that, if you're asking how to do something on a programming help board, you're asking how to do it "programmatically"?</p>
<p>3) Why is it that I've never seen the word "programmatically" anywhere else?</p>
| <p>Doing something programatically generally means that you can do it using source code, rather than via direct user interaction or a macro.</p>
<p>For example, consider the problem of resizing columns to fit in Excel.</p>
<p>You could do it manually by double clicking between the columns, but that requires user interaction.</p>
<p>You could use the excel macro recorder, but that is fairly complicated.</p>
<p>Or, you could use VBA to write code that would do it.</p>
<p>I doubt it's actually in the dictionary.</p>
|
Type initializer exception - C# <pre><code>namespace X{ public static class URLs
{
public static TabController tabIdLookUp = new TabController();
public static string DASHBOARD_AUDIT_PAGE = tabIdLookUp.GetTabByName("View My Safety", 2).TabID.ToString();
public static string URL_GENERATE_WITH_MID(String TabName, int PortalId){ {
return tabIdLookUp.GetTabByName(TabName, PortalId).TabID.ToString();
}
}}
</code></pre>
<p>...
in my user control i do this:</p>
<pre><code>Response.Redirect("/" + X.URLs.URL_GENERATE_WITH_MID("test", 1)); // this causes the error
</code></pre>
<p>the error is: The type initializer for 'X.URLs' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object. at X.URLs..cctor() </p>
<p>can't debug because it works on my local box, but throws that error on the server.</p>
<p>any ideas?</p>
<p>P.S. the problem ended up being a trivial NUllReferenceException - GetTabByName() was returing NULL </p>
| <p>Rather than having your initializer for "DASHBOARD AUDIT PAGE" refer to tabIdLookUp directly, why not instead initialize both of those variables in a static constructor and see if that fixes the error?</p>
<pre><code>namespace X{ public static class URLs
{
public static TabController tabIdLookUp;
public static string DASHBOARD_AUDIT_PAGE;
public static string URL_GENERATE_WITH_MID(String TabName, int PortalId){ {
return tabIdLookUp.GetTabByName(TabName, PortalId).TabID.ToString();
}
static URLs() {
tabIdLookUp = new TabController();
DASHBOARD_AUDIT_PAGE = tabIdLookUp.GetTabByName("View My Safety", 2).TabID.ToString();
}
}}
</code></pre>
<p>Another problem you could be having is if GetTabByName is returning a NULL reference, you're not protecting against that and just referencing the .TabID property. You should probably ensure that you're getting back a valid reference before referring to the property.</p>
|
Ruby email check (RFC 2822) <p>Does anyone know what the regular expression in Ruby is to verify an email address is in proper RFC 2822 email format?</p>
<p>What I want to do is:</p>
<pre><code>string.match(RFC_2822_REGEX)
</code></pre>
<p>where "RFC_2822_REGEX" is the regular expression to verify if my string is in valid RFC 2882 form.</p>
| <p>You can use the <a href="http://rubygems.org/gems/mail">mail</a> gem to parse any string according to RFC2822 like so:</p>
<pre><code>def valid_email( value )
begin
return false if value == ''
parsed = Mail::Address.new( value )
return parsed.address == value && parsed.local != parsed.address
rescue Mail::Field::ParseError
return false
end
end
</code></pre>
<p>This checks if the email is provided, i.e. returns <code>false</code> for an empty address and also checks that the address contains a domain.</p>
|
Pattern for Accessing Web Services <p>I need to access a Web-svc, run a bunch of queries and save the data to a store as part of an analysis. On top of this, there is a web-site that will query the datastore and show this data.</p>
<p>We have features like this getiing added every month. How can I reduce the amount of boilerplate code that get's written.</p>
<ol>
<li>Add web svc ref</li>
<li>Wrap methods in provider layer to handle exceptions</li>
<li>Prepare request</li>
<li>Send request</li>
<li>Store data locally.</li>
<li>Retrive and show data through aspx.</li>
</ol>
<p>This is such a pain.</p>
| <p>I have found two things useful for lowering the tedious coding of the scenario<br />
- <a href="http://www.microsoft.com/biztalk/technologies/wcflobadaptersdk.mspx" rel="nofollow">WCF Line of Business Adapter SDK</a>: This provides a very powerful base for building an WCF adapter (basically like a BizTalk adapter). It is a bit tough the first time but adding to it later is much nicer.<br />
- <a href="http://www.codeplex.com/servicefactory" rel="nofollow">p&p Web Service Factory</a>: This is nice for the database stuff especially since it provides some great wizards to do automatic generation. Not to say you can't use it for other things.</p>
|
jQuery dialog not working after server-side redirect <p>I have an ASP.NET website which uses the jQuery dialog to present the user with a downloads terms dialog. Once the user has agreed to the terms in the dialog, the I perform a server-side postback which issues a Response.Redirect call to a page on another website which is responsible for serving the download to the browser. The problem is that once the Response.Redirect call has been made, the dialog can no longer be shown.</p>
<p>I initialize the dialog in the document.ready event using the following code :-</p>
<pre><code>$("#terms-dialog").dialog({
modal: true,
autoOpen: false,
autoResize: false,
height: 420,
width: 500,
overlay: {
opacity: 0.5,
background: "black"
}
});
</code></pre>
<p>The code to show the dialog is as follows :-</p>
<pre><code>function showTermsDialog(snippetid, title, agreement, url)
{
$("#terms-dialog-text").html(agreement);
$("#terms-dialog-controls").attr("style", "display: block;");
$("#<%= this.SnippetID.ClientID %>").attr("value", snippetid);
$("#<%= this.DownloadUrl.ClientID %>").attr("value", url);
$("#terms-dialog").data("title.dialog", title);
$("#terms-dialog").dialog("open");
}
</code></pre>
<p>This code allows me to successfully show the dialog multiple times, but the call to dialog("open") no longer works after the Response.Redirect call has been made. </p>
<p>Has anyone done anything similar to what I am attempting to do here? Alternatively, if anyone can offer any jQuery dialog debugging tips, these would also be appreciated.</p>
| <p>The problem seemed to be caused by an extension function my dialog was using which was positioning the jQuery dialog into the form section of the page, to ensure server-side postbacks would work correctly. I changed the behaviour of this code to instead simply close the dialog and then invoke the serverside callback manually using the following</p>
<pre><code><%= this.Page.ClientScript.GetPostBackEventReference(btnAgree, "") %>;
</code></pre>
|
C# Equivalent of Java anonymous inner classes with init blocks <p>In Java, i like to use constructs such as</p>
<pre><code>List<String> list = new ArrayList<String>() {{add("foo");}};
</code></pre>
<p>Is there a way to do this in 1 line in C#, too?</p>
| <p>This is called a <em>collection initializer</em> and it's part of C# 3.0.</p>
<p>As well as lists, you can initialize collections of more complicated types, so long as they implement IEnumerable and have approprate Add methods for each element in the collection initializer. For example, you can use the <code>Add(key, value)</code> method of <code>Dictionary<TKey, TValue></code> like this:</p>
<pre><code>var dict = new Dictionary<string, int>
{
{"first", 10 },
{"second", 20 }
};
</code></pre>
<p>More details can be found in chapter 8 of C# in Depth, which can be downloaded free from <a href="http://manning.com/skeet">Manning's web site</a>.</p>
|
Java sockets with out of band data <p>Does anybody know how to receive (how to know that you received) out-of-band data with Java sockets? In particular I've read the documentation for <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/net/Socket.html#sendUrgentData(int)" rel="nofollow">sendUrgentData</a> and <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/Socket.html#setOOBInline(boolean)" rel="nofollow">setOOBInline</a> which states that:</p>
<blockquote>
<p>Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between normal data and urgent data unless provided by a higher level protocol.</p>
</blockquote>
<p>But I'm still hoping that somebody has a solution :-)</p>
<p>More details:</p>
<p>I'm sending serialized objects trough the socket and I'm not really seeing how I can find a "random" OOB byte inserted in the stream (other than the fact that Java will give me an exception when I'll try to deserialize the object).</p>
| <p>It looks like Java, up to Java 6 (I didn't investigate Java 7 since I don't know if they've decided for sure what will go in or not) and it looks like Java does not provide any support at all for reading urgent TCP information in an out-of-band manner. And it looks like this is a deliberate choice, thus far.</p>
<p>However, I <strong>did</strong> find one user who <a href="http://www.geocities.com/SiliconValley/Vista/2013/JavaOOB.html" rel="nofollow">implemented his own</a> solution, using JNI, to successfully read urgent data out of stream. This hack is very old and may or may not work on recent JDK's. I have not tried this myself! Your milage may vary. :) But hopefully this will help you.</p>
|
How do you call those little annoying cases you have to check all the time? <p>How do you call those little annoying cases that has to be checked , like "it's the first time someone entered a record / delete the last record in a linked list (in c implementation) / ... " ? </p>
<p>The only term I know translates not-very-nicely to "end-cases" . Does it have a better name? </p>
| <p>Edge cases.</p>
|
Automated test with Ruby: select an option from drop-down list <p>I write automated test with Ruby(Selenium framework) and I need to know how can I select an option from drop-down list.</p>
<p>Thanks in advance!</p>
| <p>building on <a href="http://stackoverflow.com/questions/535880/automated-test-with-ruby-select-an-option-from-drop-down-list/538254#538254">floehopper's answer</a>:</p>
<pre><code>selenium.addSelection(locator, value)
or
selenium.select(locator, value)
</code></pre>
<p>You almost certainly want "id=my_select_box_id" (with the quotes) for <code>locator</code>, though other CSS selectors will work. <code>value</code> is the literal text value (not the display value) of the <code>option</code> to be selected.</p>
|
Check browser's cache for a js file <p>How can I check for a javascript file in user's cache. If he refreshed the page or visits the site after sometime. I need not download that js file again. Does the js files get cleaned up after a site is closed. </p>
| <p>Whether a javascript file is cached depends on how your web server is setup, how the users browser is setup and also how any HTTP proxy servers between your server and the user are setup. The only bit you can control is how your server is setup.</p>
<p>If you want the best chance of your javascript being cached then you server needs to be sending the right HTTP headers with the javascript file. Exactly how you do that depends on what web server you are using.</p>
<p>Here are a couple of links that might help:</p>
<p>Apache - <a href="http://httpd.apache.org/docs/2.0/mod/mod_expires.html">http://httpd.apache.org/docs/2.0/mod/mod_expires.html</a></p>
<p>IIS - <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0fc16fe7-be45-4033-a5aa-d7fda3c993ff.mspx?mfr=true">http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/0fc16fe7-be45-4033-a5aa-d7fda3c993ff.mspx?mfr=true</a></p>
|
UI design and cultural sensitivity/awareness <p>When designing a user interface for an application that is going to be used internationally it is possible to accidentally design an aspect of the UI that is offensive to or inappropriate in another culture.</p>
<p>Have you ever encountered such an issue and if so, how did you resolve the design problem?</p>
<p>Some examples:</p>
<ol>
<li>A GPS skyplot in a surveying application to be used in Northern Ireland. Satellites had to be in a different colour to indicate whether they were in ascent or descent in the sky. Lots of satellites in ascent are considered good as it indicates that GPS coverage will be getting better in the next few hours.<br/>I chose green for ascent and orange for descent. I had not <a href="http://www.infoplease.com/spot/irishflag1.html" rel="nofollow">realised</a> that these colours are associated with Irish Catholics and Irish Protestants. It was suggested that we change the colours. In the end blue and a deep pink were chosen.</li>
<li>For applications that are going to be translated into German, I've found that you should add about 50% extra space for the German text compared to the English text.</li>
<li>A friend was working on a battlefield planning application for a customer in the Middle East. It was mandated that all crosshairs should take the form of a diagonal cross, to avoid any religious significance.</li>
<li>(Edit - added this) In the UK a tick mark (something like â) means <em>yes</em> whereas a cross (x) means <em>no</em>. In Windows 3.1 selected checkboxes used a cross, which confused me the first time I saw it. Since Windows 95 they've used (what I would call) a tick mark. As far as I can tell both a tick and a cross are called a check mark in the US, and mean the same thing</li>
</ol>
<h2>Edit</h2>
<p>Please ensure that any reply you add to this question is as culturally sensitive as the user interfaces we're all trying to build! Thanks.</p>
| <p>You should try to follow the i18n and l10n pointers provided by the look and feel guidelines for the UI library you're using, or platform you're delivering to. They often contain hints on how to avoid cultural issues, and may even contain icon libraries that have had extensive testing for such potential banana skins.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/aa511258.aspx" rel="nofollow">Windows User Experience Interaction Guidelines</a></li>
<li><a href="http://java.sun.com/products/jlf/ed2/book/index.html" rel="nofollow">Java Look and Feel Design Guidelines</a></li>
<li><a href="http://developer.apple.com/documentation/UserExperience/index.html" rel="nofollow">Apple Human Interface Guidelines</a></li>
<li><a href="http://library.gnome.org/devel/hig-book/stable/" rel="nofollow">GNOME Human Interface Guidelines</a></li>
<li><a href="http://developer.kde.org/documentation/design/ui/index.html" rel="nofollow">KDE User Interface Guidelines</a></li>
</ul>
<p>I guess the most important thing is designing your application with i18n in mind from the ground up, so that your UI can be resized depending on the translated text; mnemonics are appropriate for different languages; labels are to the left for latin languages, but on the right for Hebrew and Arabic, etc, etc.</p>
<p>Designing with i18n and l10n in mind means that shipping your product to a location with a different culture, language or currency will not require a re-write, or a different version, just different resources.</p>
<p>Generally speaking, I believe you'll run into more problems with graphics and icons that you will with text (apart from embarrassing translations) simply because people identify more strongly with symbols than particular passages of text.</p>
|
How does Excel VSTO Work? <p>How does Excel VSTO Work? If I create an Excel Workbook solution in Visual Studio 2005 I can then happily code away with full access to the Excel object model and even treat the Excel sheet as a design surface. When I build the solution I get a <code>.XLS</code> file and a <code>.DLL</code> (containing my C# code).</p>
<p>I can now start up the Excel sheet just by double clicking on the <code>.XLS</code> and there is my sheet functioning with all my C# code and any controls I dropped on the sheet etc.</p>
<p>How is the sheet referencing the <code>.DLL</code>? What part of the excel workbook/sheet tells it that it needs to fire up the CLR and host my assembly? </p>
| <p>According to <a href="http://msdn.microsoft.com/en-us/library/zcfbd2sk.aspx">this</a> (thanks PintSizedCat) for Excel 2003 the following happens:</p>
<blockquote>
<p>The Microsoft Office application
checks the custom document properties
to see whether there are managed code
extensions associated with the
document. For more information, see
Custom Document Properties Overview.</p>
<p>If there are managed code extensions,
the application loads AddinLoader.dll.
This is an unmanaged DLL that is the
loader component for the Visual Studio
2005 Tools for Office Second Edition
runtime. For more information, see
Visual Studio Tools for Office Runtime
Overview.</p>
<p>AddinLoader.dll loads the .NET
Framework and starts the managed
portion of the Visual Studio Tools for
Office runtime.</p>
<p>The Visual Studio Tools for Office
runtime creates an application domain,
sets policy for the application domain
not to trust the My Computer Zone, and
checks the code access security policy
store to find a policy for the
customization assembly.</p>
<p>The .NET Framework validates the
evidence presented by the assembly
against the policy. If it fails, an
error is raised. If it passes, the
process continues.</p>
<p>If the customization uses a deployment
manifest, the Visual Studio Tools for
Office runtime uses it to check for
assembly updates. If any updates are
necessary, they are performed now. </p>
<p>The Visual Studio Tools for Office
runtime loads the assembly into the
application domain.</p>
<p>The Visual Studio Tools for Office
runtime calls the Startup event
handler in your customization
assembly. For more information, see
Visual Studio Tools for Office Project
Events.</p>
</blockquote>
<p>In my test project's Excel workbook I have two custom properties:</p>
<p>_AssemblyName, value = *
_AssemblyLocation, value = {533b2c13-a125-418a-bfff-9546b0762807}</p>
<p>I suppose these are the properties which direct the VSTO runtime to my assembly.</p>
|
How can I find the free space available on mounted volumes using Perl? <p>I'm trying to untar a file. Before untarring I would like to know free space available on the mounted volume. The plan is if there is not enough space I will not untar it! So how can I find the free space available on a mounted volume using Perl? By the way, I'm using Perl for tar and untar.</p>
<p>Everybody is saying about <code>df</code> and <code>dh</code> but these commands doesn't work on the mount points. What if I want to find the free space that I can write into on a mounted point?</p>
| <p>You likely want the CPAN module <a href="http://search.cpan.org/dist/Filesys-DiskFree">Filesys::DiskFree</a>.</p>
|
resource for learning about predicates <p>are there any good tutorials online for learning about the c# 2.0 language feature "predicates"?</p>
<p>i'm trying to learn how to use predicates along with linq to sql to modify my queries</p>
<p>what i am trying to do is query a table of customers and filter it based on changing criteria. for example</p>
<ul>
<li>find all customers who have zipcode = 90210</li>
<li>find all customers who are male</li>
<li>find all customers who are male AND > have zipcode = 90210</li>
</ul>
<p>right now i am doing this using if/else statements which feels pretty wrong</p>
<p>also, it's possible that i'll have to add other filters so i want a flexible solution to this problem that's easy to extend without breaking anything (open closed principle i think)</p>
| <p>A predicate is simply a method with the following signature :</p>
<pre><code>bool Predicate<T>(T item)
</code></pre>
<p>It represents a condition that can be verified or not by objects of type T.</p>
<p>It is use in link to filter enumerables in the <code>.Where</code> clause.</p>
<p>You can also use lambdas that return a boolean value :</p>
<pre><code>item => item.Nickname == "ThinkBeforeCoding";
</code></pre>
|
Search file content on iphone <p>Is there an Iphone SDK API to search resource files?</p>
<p>I have a set of html file resources that I'd like the user to be able to search in, but I want to avoid reading the files into memory and searching them one by one.</p>
<p>Is there any API that can help me do this?</p>
| <p>No, you'll have to read the files in to search them. There's nothing like "Spotlight" on the phone.</p>
|
What is the shortest perceivable application response delay? <p>A delay will always occur between a user action and an application response.</p>
<p>It is well known that the lower the response delay, the greater the feeling of the application responding instantaneously. It is also commonly known that a delay of up to 100ms is generally not perceivable. But what about a delay of 110ms?</p>
<p>What is the shortest application response delay that can be perceived?</p>
<p>I'm interested in any solid evidence, general thoughts and opinions.</p>
<p>I'm also running some simple online tests to examine these questions and would appreciate the participation of the SO community:<br>
> <a href="http://webignition.net/research/response-times/which-is-faster/">http://webignition.net/research/response-times/which-is-faster/</a></p>
| <p>The 100 ms threshold was established over 30 yrs ago. See:</p>
<p>Card, S. K., Robertson, G. G., and Mackinlay, J. D. (1991). The information visualizer: An information workspace. Proc. ACM CHI'91 Conf. (New Orleans, LA, 28 April-2 May), 181-188.</p>
<p>Miller, R. B. (1968). Response time in man-computer conversational transactions. Proc. AFIPS Fall Joint Computer Conference Vol. 33, 267-277.</p>
<p>Myers, B. A. (1985). The importance of percent-done progress indicators for computer-human interfaces. Proc. ACM CHI'85 Conf. (San Francisco, CA, 14-18 April), 11-17.</p>
|
Simple WPF UI databinding <p>I'm trying to write a simple WPF app that has two ellipses, joined by a line, like you might see in a network graph. When the ellipses are animated, I just want the joining line to automagically 'stick' to the canvas locations of the two ellipses that the line joins. The XAML is just a canvas:</p>
<pre><code><Window x:Class="UIDataBindingDemo.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="400" Width="400">
<Grid>
<Canvas x:Name="cnvExample" />
</Grid>
</code></pre>
<p></p>
<p>...and I'm just doing some really simple stuff in the constructor here:</p>
<pre><code>using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace UIDataBindingDemo
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
// create 2 ellipses, one next to the other, and add them to the canvas
Ellipse el1 = new Ellipse();
Canvas.SetTop(el1, 100);
Canvas.SetLeft(el1, 100);
el1.Width = 20;
el1.Height = 20;
el1.Fill = Brushes.Red;
el1.Stroke = Brushes.Black;
Ellipse el2 = new Ellipse();
Canvas.SetTop(el2, 100);
Canvas.SetLeft(el2, 200);
el2.Width = 20;
el2.Height = 20;
el2.Fill = Brushes.Blue;
el2.Stroke = Brushes.Black;
cnvExample.Children.Add(el1);
cnvExample.Children.Add(el2);
// create a line that connects the 2 ellipses. Bind the two points that define this line to the
// locations of our ellipses, so the line always connects them, through animations, drag and drop
// operations, whatever.
Line line = new Line();
line.StrokeThickness = 3;
line.Stroke = Brushes.Black;
line.SetBinding(Line.X1Property, new Binding("(Canvas.Left)") { Source = el1 });
line.SetBinding(Line.X1Property, new Binding("(Canvas.Top)") { Source = el1 });
line.SetBinding(Line.X1Property, new Binding("(Canvas.Left)") { Source = el2 });
line.SetBinding(Line.X1Property, new Binding("(Canvas.Top)") { Source = el2 });
cnvExample.Children.Add(line);
// animate the second ellipse, so it moves down and to the right, nice and slow
var moveTheBlueOne = new DoubleAnimation(300, TimeSpan.FromSeconds(10));
el2.BeginAnimation(Canvas.LeftProperty, moveTheBlueOne);
el2.BeginAnimation(Canvas.TopProperty, moveTheBlueOne);
}
}
</code></pre>
<p>I'm pretty new to WPF, and I'm sure I'm missing something simple. Why am I not seeing the line?</p>
| <p>I don't know if it's a cut and paste error but youre assigning each binding to the same DependencyProperty "Line.X1Property", you should use all four X and Y properties to define a starting point and an ending one for a line.</p>
<pre><code>line.SetBinding(Line.X1Property, new Binding("(Canvas.Left)") { Source = el1 });
line.SetBinding(Line.Y1Property, new Binding("(Canvas.Top)") { Source = el1 });
line.SetBinding(Line.X2Property, new Binding("(Canvas.Left)") { Source = el2 });
line.SetBinding(Line.Y2Property, new Binding("(Canvas.Top)") { Source = el2 });
</code></pre>
<p>this way it works for me.</p>
|
Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement <p>Is there any way in which I can clean a database in SQl Server 2005 by dropping all the tables and deleting stored procedures, triggers, constraints and all the dependencies in one SQL statement?</p>
<p><strong>REASON FOR REQUEST:</strong></p>
<p>I want to have a DB script for cleaning up an existing DB which is not in use rather than creating new ones, especially when you have to put in a request to your DB admin and wait for a while to get it done!</p>
| <p>this script cleans all views, SPS, functions PKs, FKs and tables.</p>
<pre><code>/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])
WHILE @name is not null
BEGIN
SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Procedure: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped View: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Function: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
WHILE @name is not null
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint IS NOT NULL
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
EXEC (@SQL)
PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
WHILE @name IS NOT NULL
BEGIN
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
WHILE @constraint is not null
BEGIN
SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
EXEC (@SQL)
PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO
/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])
WHILE @name IS NOT NULL
BEGIN
SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
EXEC (@SQL)
PRINT 'Dropped Table: ' + @name
SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO
</code></pre>
|
Execute arbitrary python code remotely - can it be done? <p>I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally.</p>
<p>Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. **arguments), however I need to implement something that works a bit like this:</p>
<pre><code>rapply = Rapply( server_hostname ) # Set up a connection
result = rapply( fn, args, kwargs ) # Remotely call the function
assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value.
</code></pre>
<p>Rapply should be a class which can be used to remotely execute some arbitrary code (<code>fn</code> could be literally anything) on a remote server. It will send back the result which the <code>rapply</code> function will return. The "result" should have the same value as if I had called the function locally.</p>
<p>Now let's suppose that <code>fn</code> is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? </p>
<p>What if <code>fn</code> might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating <code>fn</code> and everything that <code>fn</code> requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it.</p>
<p>Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client & server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. </p>
<p>I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment. </p>
| <p>Take a look at <a href="http://pyro.sourceforge.net/">PyRO</a> (Python Remote objects) It has the ability to set up services on all the computers in your cluster, and invoke them directly, or indirectly through a name server and a publish-subscribe mechanism. </p>
|
Entity attachment issues in LINQ <p>I am trying to attach a LINQ entity to the data context after I receive it from a form POST. However, all I get is the following exception:</p>
<pre><code>An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy.
</code></pre>
<p>I have also tried attaching the original row, like so:</p>
<pre><code>dataContext.People.Attach(person, originalPerson);
</code></pre>
<p>In this case, I get the following exception:</p>
<pre><code>Object reference not set to an instance of an object.
</code></pre>
<p>Here's the code in my controller:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, Person person) {
var prevPerson = dataContext.People.Single(p => p.ID == id);
dataContext.People.Attach(person, prevPerson);
dataContext.SubmitChanges();
return Redirect("~/People/Index");
}
</code></pre>
<p>Any ideas on what I'm doing wrong here? I can post the entity code if needed.</p>
| <p>Try following:</p>
<pre><code>dataContext.People.Attach(person);
dataContext.Refresh(RefreshMode.KeepCurrentValues, person);
dataContext.SubmitChanges();
</code></pre>
|
Simple way to change 180 to 03:00 <p>Hey! I am trying to change a number of seconds in to a proper time stamp format.
Like I do this to change 180 to 03:00</p>
<pre><code>private void writeTime(int tempo)
{
TimeSpan otempo = new TimeSpan(0, 0, tempo);
string minutos = ((otempo.Minutes <= 9) ? "0" : "") + otempo.Minutes.ToString();
string segundos = ((otempo.Seconds <= 9) ? "0" : "") + otempo.Seconds.ToString();
label1.Text = minutos + ":" + segundos;
centrarLabel();
}
</code></pre>
<p>This does give me 180 into a proper format. I just want to know if there is a simpler way.
This function might be called many many times and I don't want to create a new instance of TimeSpan every single time as I think this might pose a problem with memory etc. I tried using the DateTime class but... I just simply don't see how I can pass it the seconds and it gives me the proper format :(</p>
<p>I am not that great with c#. I am really trying to learn :)
Thanks</p>
| <pre><code> int tempo = 180;
TimeSpan time = TimeSpan.FromSeconds(tempo);
string txt = string.Format(
"{0:00}:{1:00}", time.Minutes, time.Seconds);
</code></pre>
<p>(edit) As has already been observed - there are no immediate memory concerns with <code>TimeSpan</code>, since it is a <code>struct</code>. However, if you want to be paranoid:</p>
<pre><code>int tempo = 180;
string txt = new StringBuilder(5)
.Append((tempo / 60).ToString().PadLeft(2, '0')).Append(':')
.Append((tempo % 60).ToString().PadLeft(2, '0')).ToString();
</code></pre>
|
What is the XAML syntax for setting a Trigger on a Label? <p>I have a DataTemplate that is displaying objects with three fields, e.g.:</p>
<pre><code>Name = "Font Color"
Value = "Orange"
Editable = "True"
</code></pre>
<p>but I want to display them as e.g.:</p>
<p><strong><em>Font Color: Orange Editable</em></strong></p>
<p>But I'm having trouble finding the syntax to use Triggers here in order to e.g. display "Editable" when the field Editable="True"</p>
<p>Does anyone know the syntax to do this?</p>
<p>The following code results in "Binding cannot be used in Property":</p>
<pre><code><DataTemplate x:Key="settingsItemTemplate">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding XPath=Name}" ContentStringFormat=" {0}:"/>
<Label Content="{Binding XPath=Value}"/>
<Label>
<Label.Triggers>
<Trigger Property="{Binding XPath=Editable}" Value="True">
<Setter Property="Content" Value="Editable"/>
</Trigger>
<Trigger Property="{Binding XPath=Editable}" Value="False">
<Setter Property="Content" Value="NOT Editable"/>
</Trigger>
</Label.Triggers>
</Label>
</StackPanel>
</DataTemplate>
</code></pre>
| <p>Would it work to use a <code>TextBlock</code> instead of a <code>Label</code>? <code>TextBlock</code> does have a <code>Text</code> property that you should be able to bind to in this case.</p>
<p>If you really want to use a <code>Label</code>, another approach would be to create two <code>DataTemplate</code>'s - one for the editable case, and another for non-editable. You can then bind the <code>ContentTemplate</code> property to the appropriate template.</p>
<p><strong>Update</strong>: After looking into it some more, it looks like <code>Trigger</code> does not support binding for its <code>Property</code> attribute. However, <code>DataTrigger</code> does support this:</p>
<pre><code><StackPanel>
<CheckBox Name="EditableCheckBox">Is Editable</CheckBox>
<Label>
<Label.Resources>
<Style TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=EditableCheckBox, Path=IsChecked}" Value="True">
<Setter Property="Content" Value="Editable" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=EditableCheckBox, Path=IsChecked}" Value="False">
<Setter Property="Content" Value="NOT Editable" />
</DataTrigger>
</Style.Triggers>
</Style>
</Label.Resources>
</Label>
</StackPanel>
</code></pre>
<p>You should be able to modify the <code>Binding</code> attribute to bind to your XML data source instead of do the value of another control.</p>
|
QThread to send large queries to the database <p>I have created this class that inherits from QThread for send data to the database server, what do you think about it? Could be impreved?</p>
<p>Thanks</p>
<pre>#ifndef QUERYTHREAD_H
#define QUERYTHREAD_H
#include
class QSqlQuery;
class QueryThread : public QThread {
public slots:
bool exec(QSqlQuery *query, Priority priority=InheritPriority);
protected:
virtual void run();
private:
bool m_hasError;
QSqlQuery *q;
};
#endif // QUERYTHREAD_H</pre>
<pre>#include "querythread.h"
#include
#include
bool QueryThread::exec(QSqlQuery *query, Priority priority)
{
q=query;
start(priority);
while(isRunning()) qApp->processEvents();
return m_hasError;
}
void QueryThread::run()
{ m_hasError=q->exec(); }</pre>
| <p>A couple of opinions:</p>
<p>That <code>while</code> loop in <code>exec</code> elimiates the advantages of having a separate thread. You should pass the query in at the constructor, have one thread per query, <strong>don't</strong> override <code>exec</code>, prefer to just use <a href="http://doc.qt.nokia.com/latest/qthread.html#start" rel="nofollow">start</a> and use signals to asynchronously report any error.</p>
<p>You should also pass the QSqlQuery by value or store it in a managed pointer such as <code>std::auto_ptr</code> (or <code>std::unique_ptr</code> for C++11). Many Qt classes are <a href="http://doc.qt.nokia.com/latest/implicit-sharing.html" rel="nofollow">implicitly shared</a> (although not this one) but managed pointers gain you exception safety.</p>
<p>Personally, I would have simply done something like this</p>
<pre><code>class Query : public QThread {
QSqlQuery m_query;
// I prefer values unless there's a particular reason to use pointers.
public:
Query (const QSqlQuery & query)
: m_query (query)
{
}
void run ()
{
emit finished (m_query .exec ());
deleteLater ();
}
public signals:
void finished (bool);
};
Query * q = new Query ("SELECT foo FROM bar");
connect (q, SIGNAL (finished (bool), ...);
q -> start ();
</code></pre>
|
ruby on rails : adding child records to an existing parent without visiting the parent <p>How would you handle allowing users to add child objects to parents without requiring them to navigate to the parent?</p>
<p>For example adding a journal article without having to navigate to the journal and issue first? The parent also may not exist yet.</p>
<p>I'd prefer not to make data entry to onerous for users so making them find a journal or create it and then find or create an issue seems a bit much. I would rather just have a single form with journal and issue fields. The logic would simple if were not for the fact that users are interested in the article and not the journal or issue. </p>
<p>Would you just modify a create for the child so it finds or creates the parents ?</p>
| <p>I'm assuming you have a journal model that has many articles and an article model that belongs to a journal. First, you should create routes to the articles controller that go through journals and not through journals:</p>
<pre><code>ActionController::Routing::Routes.draw do |map|
map.resources :journals, :has_many => :articles
map.resources :articles
end
</code></pre>
<p>Now you can get to the new action of your articles controller with the URL <code>/articles/new</code> or <code>/journals/1/articles/new</code>. Then in the new action in your articles controller, you do this:</p>
<pre><code>@article = Article.new(:journal_id => params[:journal_id])
</code></pre>
<p>Which set the <code>journal_id</code> of the article to whatever parameter is passed in. If no parameter is passed, the journal_id will be nil.</p>
<p>In the ERB template, you just do this to create the drop down:</p>
<pre><code><%= f.collection_select :journal_id, Journal.all(:order => "name"), :id, :name, :include_blank => true %>
</code></pre>
<p>And then a user can select a journal, but if one was passed in, it will be pre-selected to the correct value.</p>
|
Block commenting in Ruby <p>Does Ruby have block comments?</p>
<p>If not, is there an efficient way of inserting <code>#</code> in front of a block of highlighted code in TextMate?</p>
| <p>You can do</p>
<pre><code>=begin
[Multi line comment]
=end
</code></pre>
<p><code>=begin</code> and <code>=end</code> must be at the beginning of the line (not indented at all).</p>
<p><a href="http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#embed_doc">Source</a></p>
<p>Also, in TextMate you can press <kbd>Command</kbd> + <kbd>/</kbd> to toggle regular comments on a highlighted block of code.</p>
<p><a href="http://v1.garrettdimon.com/archives/trick-your-textmate-the-series">Source</a></p>
|
WPF databinding IsEnabled Property <p>So I am learning WPF right now, and want to do a simple databind between a bool value, and whether or not a <code>MenuItem</code> is enabled or not. </p>
<p>I have coded it like this:</p>
<pre><code><MenuItem Name="miSaveFile" Header="Save" Click="miSaveFile_Click"
IsEnabled="{Binding}" />
</code></pre>
<p>And in the .cs file I set:</p>
<pre><code>miSaveFile.DataContext = dataChanged;
</code></pre>
<p>For some reason the <code>MenuItem</code> doesn't seem to be properly reflecting the state of dataChanged. </p>
<p>What am I missing?</p>
| <p>You are better off binding to an object than to a primitive type. This object is often referred to as the "model" for your view. </p>
<p>WPF uses the INotifyPropertyChanged interface for the model (or often view-model) to notify the view that the model has changed states.</p>
<p>So you will first want to define a data class as the model that implements the INotifyPropertyChanged interface and fires the PropertyChanged event whenever a property is changed.</p>
<p>When you set a binding, you have 5 main elements on the binding to worry about. The binding has a source object, a source path on the source object, a target object, a target property on the target object, and an optional converter.</p>
<p>If you do not specify the source, it defaults to the DataContext of the control the binding is set on. There are other options for setting the source. <a href="http://msdn.microsoft.com/en-us/library/ms746695.aspx" rel="nofollow">Here</a> is a Microsoft article on setting the source. You can then set the path of a property to pull out of the source for the binding. In your case, the source is a boolean and there is no path because the binding is using the whole source object.</p>
<p>The target is always the control that you set the binding on, and the target property is the property on this control that you are binding to. In this case, MenuItem and IsEnabled.</p>
<p>A converter can optionally convert the source value into a value that is compatible with the target property. You can use any object for a converter that implements IValueConverter or IMultiValueConverter (for MutliBindings).</p>
<p>In your case, I would first create a model that implements INotifyPropertyChanged. Next, I would assign the DataContext of the menu to an instance of the model. Then I would set the binding to: </p>
<pre><code>IsEnabled="{Binding Path=EnableFlag}"
</code></pre>
<p>(Where EnableFlag is a boolean property in the model that you want to menu to bind to)</p>
<p>If you set up the INotifyPropertyChanged interface correctly, the menu item will be enabled/disabled whenever you change this property on the model.</p>
|
Is there a tool to automate/stress POST calls to my site for testing? <p>I would like to stress (not sure this is the right word, but keep reading) the [POST] actions of my controllers. Does a tool exist that would generate many scenarios, like omitting fields, adding some, generating valid and invalid values, injecting attacks, and so on ? Thx</p>
<p><strong>Update</strong>: I don't want to benchmark/performance test my site. Just <strong>automatically filling/tampering</strong> forms and see what happens</p>
| <p>WebInspect from Spidynamics (HP bought them).</p>
<p>I've used this one in my previous job (I recommended it to my employer at the time) and I was overwhelmed with the amount of info and testing I could do with it.</p>
<p>https://download.spidynamics.com/webinspect/default.htm</p>
|
How to connect to a secure website using SSL in Java with a pkcs12 file? <p>I have a pkcs12 file. I need to use this to connect to a webpage using https protocol. I came across some code where in order to connect to a secure web page i need to set the following system properties:</p>
<pre><code>System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStore", "new_cert.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "newpass");
</code></pre>
<p>I have the p12(pkcs12) file. All I need is a truststore file.</p>
<p>I extracted the certificates using:</p>
<pre><code>openssl.exe pkcs12 -in c:/mykey.p12 -out c:/cert.txt -nokeys -clcerts
</code></pre>
<p>Now converted the cert PEM file to der</p>
<pre><code>openssl.exe x509 -in c:/cert.txt -outform DER -out c:/CAcert.der
</code></pre>
<p>Now adding the der file to a keystore</p>
<pre><code>keytool -import -file C:/Cacert.der -keystore mytruststore
</code></pre>
<p>Now I have the truststore, but when I use it, I get the following error</p>
<pre><code>Exception in thread "main" java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: com.sun.net.ssl.internal.ssl.DefaultSSLContextImpl)
</code></pre>
<p>Update:
After removing certain properties and setting only the "trustStore", "trustStorePassword" and "trustStoreType" property, I got the following exception</p>
<pre><code>java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
</code></pre>
<p>Please Help.</p>
| <p>For anyone encountering a similar situation I was able to solve the issue above as follows:</p>
<ol>
<li><p>Regenerate your pkcs12 file as follows:</p>
<pre><code>openssl pkcs12 -in oldpkcs.p12 -out keys -passout pass:tmp
openssl pkcs12 -in keys -export -out new.p12 -passin pass:tmp -passout pass:newpasswd
</code></pre></li>
<li><p>Import the CA certificate from server into a TrustStore ( either your own, or the java keystore in <code>$JAVA_HOME/jre/lib/security/cacerts</code>, password: <code>changeit</code>).</p></li>
<li><p>Set the following system properties:</p>
<pre><code>System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
System.setProperty("javax.net.ssl.keyStore", "new.p12");
System.setProperty("javax.net.ssl.keyStorePassword", "newpasswd");
</code></pre></li>
<li><p>Test ur url.</p></li>
</ol>
<p>Courtesy@ <a href="http://forums.sun.com/thread.jspa?threadID=5296333">http://forums.sun.com/thread.jspa?threadID=5296333</a></p>
|
jQuery: CSS Selectors <p>How would I use jQuery CSS Selectors to find for instance:</p>
<p>css class name: "Text" which is a div inside of dom object "wrapper"?</p>
| <p>$('#wrapper div.Text') or $('#wrapper .Text'), depending on how specific you want to be.</p>
|
Default Windows Languages? <p>Is there some default Windows scripting language that comes pre-installed on XP and Vista (Similar to how OS X comes with Python and/or Linux comes with Perl)? </p>
<p>I am aware of Batch scripting but I am hoping for something a little more robust. Thanks</p>
<p><strong>note -</strong> I am on a Linux box so if you guys could give your 2 cents on the Windows scripting languages, it would be appreciated, thanks.</p>
<p><strong>part deux -</strong> even though ebgreen hates me i accepted his answer because he gave me his 2 cents. </p>
| <p>Windows XP and Vista have VBScript and jscript engines installed by default. Windows 7 will also have Powershell installed.</p>
<p>As for my 2 cents, VBScript and jscript are both very mature technologies that have plenty of resources available. Neither of them give you a console if you are looking for that.</p>
<p>Powershell is newer and much much more powerful. It also has the advantage of having a console as well.</p>
|
What does a Flash object know about the page it's in? <p>The organization I work for has created a small flash widget that we're encouraging supporters to place on their website. I'm trying to determine if there are ways to improve the statistics we get from those embedded widgets.</p>
<p>Mostly I would like to get the domain of the site that loaded the widget. Right now I'm able to see the referrer in the server logs, but that includes the full URL, and I don't want to have to write my own log processing system just to pull out domains.</p>
<p>I know very little ActionScript, but I've looked around the ActionScript documentation to see if I could find an obvious solution. I haven't found anything that allows the object to ask the browser for the page URL. The System.Capabilities class seems to provide a lot of information about the player's environment, but not where the player was called from (as far as I can tell, but maybe I'm missing something).</p>
| <pre><code>Steps:
1. Import external interface into your file: import flash.external.ExternalInterface;
2. Initialize a variable to store the url path: var urlPath;
3. Create a function to call external interface and assign the html page path to your variable: urlPath = ExternalInterface.call(âwindow.location.href.toStringâ);
4. Call the function when/if needed.
</code></pre>
<p>Example:</p>
<p>With javascript: window.location.href or window.location.href.toString();
With actionscript: ExternalInterface.call(âwindow.location.href.toStringâ);
External Interface html Example</p>
<p>Source: <a href="http://blog.circlecube.com/2008/01/02/get-current-url-to-flash-swf-using-an-external-interface-call/" rel="nofollow">http://blog.circlecube.com/2008/01/02/get-current-url-to-flash-swf-using-an-external-interface-call/</a></p>
<p>To Get The Query String See This Article: <a href="http://blog.circlecube.com/2008/03/20/get-current-url-and-query-string-parameters-to-flash-tutorial/" rel="nofollow">http://blog.circlecube.com/2008/03/20/get-current-url-and-query-string-parameters-to-flash-tutorial/</a></p>
|
Extracting text from an IEnumerable<T> <p>I have a <code>IEnumerable<T></code> collection with Name, FullName and Address.</p>
<p>The Address looks like this:</p>
<pre><code>Street1=54, Street2=redfer street, Pin=324234
Street1=54, Street2=fdgdgdfg street, Pin=45654
Street1=55, Street2=tryry street, Pin=65464
</code></pre>
<p>I want to loop through this collection and print only those Names, FullNames whose Street1=54 </p>
<p>How can i do it in LINQ?</p>
<p>Ok I was able to do this to extract Street1 of the Address</p>
<pre><code>coll.Address.Split(",".ToCharArray())[0]returns me Street1=54 .
</code></pre>
<p>Now how do I add this to the condition and print only those Name, FullName whose Street1=54 </p>
| <p>Based on your update, you can adapt Jared Par's code this way:</p>
<pre><code>var result = collection.Where(x => x.Address.Contains("Street1=54"));
foreach ( var cur in result ) {
Console.WriteLine(string.Format("{0}, {1}", cur.Name, cur.FullName));
}
</code></pre>
<p>If you want to be able to plug in your Street1 value with a variable, then do this:</p>
<pre><code>var street1 = "54";
var result = collection.Where(x => x.Address.Contains("Street1=" + street1 ));
foreach ( var cur in result ) {
Console.WriteLine(string.Format("{0}, {1}", cur.Name, cur.FullName));
}
</code></pre>
<p>BTW, you really should update your question or add a comment to a specific answer rather than adding a new answer that isn't.</p>
|
Multiple project management <p>Given a situation where you have 2 projects that in total will provide enough work for a month for 6 developers in a ratio of 2:1. </p>
<p>Is it better to assign developers to each project and then they work on that project for the whole month or is it preferable for the whole team to work each project in turn?</p>
<p>What reasons do you have for your opinions?</p>
<p><strong>Edit</strong>
To clarify, they are entirely separate systems.</p>
| <p>It depends a lot on how related the two projects are. If they have a lot of similarities, I would say tackle them as two projects within one large group.</p>
<p>If they mostly unrelated from a code and architecture standpoint, it would make more sense to split into two teams for the duration of the two projects, perhaps cross-training some of the developers as is possible.</p>
<p>If you're an Agile shop, just run two concurrent iterations.</p>
|
How can a convex polygon be broken down into right triangles aligned on the X- and Y- axes? <p>Given a convex polygon represented by a set of vertices (we can assume they're in counter-clockwise order), how can this polygon be broken down into a set of right triangles whose legs are aligned with the X- and Y-axes?</p>
<p>Since I probably lack some math terminology, "legs" are what I'm calling those two lines that are <em>not</em> the hypotenuse (apologies in advance if I've stabbed math jargon in the face--brief corrections are extra credit).</p>
| <p>I'm not sure about writing an algorithm to do this but it seems entirely possible to do this for any convex polygon on a piece of paper. For each vertex project a line vertically or horizontally from that vertex until it meets another of these vertical or horizontal lines. For vertices with small changes in angle, where adjacent sides are both travelling in the same direction in terms of x and y, you will need to add two lines from the vertex, one horizontal and one vetical.
Once you have done this, you should be left with a polygon in the centre of the origonal polygon but with sides that are either vertical or horizontal because the sides have been formed by the lines drawn from the vertices of the original polygon. Because these sides are either vertical or horizontal, this shape can easily be sub-divided into a number of triangles with one horizontal side, one vertical side and one hypotenuse. </p>
|
Multiple action for Loadrunner script? <p>there is init, action and end functions. is it possible to have multiple action method? i want it to run on a separate execution thread.</p>
| <p>Adding actions in VuGen is easy, but it does not allow you to execute them in parallel within the same vuser. If you want to execute things in parallel you need to run more than one vuser on the controller for the script. </p>
<p>Instantiating a new thread within a vuser is very difficult and requires you to use the Win API for creating threads - definitely not recommended.</p>
<p>If you want 2 different actions to execute in parallel use multiple scripts instead. You will not be able to share variables or data between the vusers thou.</p>
|
How to download multiple files in VB6 with progress bar? <p>I want to download multiple files (mostly images) from VB6 application. presently i m using URLDownloadToFile but it allows only one file at a time and there is no progress bar. I want to download multiple files and with progress bar. please help. thanks in advance.</p>
<p>my present code:</p>
<pre><code>Dim lngRetVal As Long
lngRetVal = URLDownloadToFile(0, URL, LocalFilename, 0, 0)
If lngRetVal = 0 Then DownloadFile = True
</code></pre>
| <p>You want to download the file asynchronously, so that your VB code continues executing while the download happens. There <strong>is</strong> a little-known way to do this with native VB6, using the <a href="http://msdn2.microsoft.com/en-us/library/aa277589.aspx" rel="nofollow">AsyncRead</a> method of UserControl and UserDocument objects - no need for API calls. </p>
<p>Here's an excellent <a href="http://visualstudiomagazine.com/articles/2008/03/27/simple-asynchronous-downloads.aspx" rel="nofollow">explanation and VB6 code for multiple simultaneous downloads</a>, from the renowned VB6 guru <a href="http://vb.mvps.org/" rel="nofollow">Karl Peterson</a>. The AsyncReadProgress event gives you the BytesRead and BytesMax, which will allow you to display a progress bar.</p>
|
Eclipse: How can I attach JavaDoc to multiple JAR files? <p>I am using Eclipse 3.4.1.</p>
<p>I have an external library that consists of a bunch of JAR files, and some HTML JavaDoc. I know that I can attach the HTML JavaDoc to individual JARs by going to their Properties page, JavaDoc location, and setting it there.</p>
<p>But it would be a pain to do this for each individual JAR. Is it possible to do them all at once somehow? The JavaDoc location is the same for them all.</p>
| <p>Not really a recommended solution, but you could set it for one of them and then manually edit your project's <code>.classpath</code> file, copy the relevant part and paste it into the other elements. Not that much easier than setting it for each one separately, though.</p>
<p>Also, if you have access to the source files, you could use these instead of the Jar files, which will provide the Javadocs.</p>
|
Tools to manage semantic webs <p>I've seen a lot frameworks to create a semantic web (or rather the model below it). What tools are there to create a small semantic web or repository on the desktop, for example for personal information management.</p>
<p>Please include information how easy these are to use for a casual user, (in contrast to someone who has worked in this area for years). So I'd like to hear which tools can create a repository without a lot of types and where you can type the nodes later, as you learn about your problem domain.</p>
| <p>For personal semantic information management on the desktop there is NEPOMUK. There are two versions, one embedded in kde4, this lets you tag, rate and comment things such as files, folders, pictures, mp3s, etc. on the desktop across all applications.
Another version is written in Java and is OS independent, this is more of a research prototype. It has more features, but is overall less stable. </p>
<p>For KDE-Nepomuk see <a href="http://nepomuk.kde.org/" rel="nofollow">http://nepomuk.kde.org/</a>
For Java-Nepomuk see <a href="http://dev.nepomuk.semanticdesktop.org/" rel="nofollow">http://dev.nepomuk.semanticdesktop.org/</a> and <a href="http://dev.nepomuk.semanticdesktop.org/download/" rel="nofollow">http://dev.nepomuk.semanticdesktop.org/download/</a> for downloads (the DFKI version is better)</p>
|
Differences between WPF Frame and WebBrowser controls <p>I'm working on a web-enabled media center which will be able to load video feeds into a gallery style view. (like Cooliris)</p>
<p>Rather than loading thumbnail images of each video, I plan to load the actual video so it can be played in-place and/or popped out to fullscreen.</p>
<p>This means I need to host a bunch of flash-player instances 'inside' my WPF Page.</p>
<p>Is there any advantage to using a Frame control rather than an SP1 WebBrowser control? I know that, while the WebBrowser is technically a wrapped Windows Forms control and the Frame control is 'native' wpf, even the Frame control uses a win32 MS.Internal.Controls.WebBrowser to show content. </p>
<p>Given this fact, are the two controls roughly equivalent, especially as performance is concerned?</p>
| <p>The big difference is that Frame can host WPF or HTML content. How it does this is by piping the content to either WPF or IE, so it's not doing any rendering itself and WPF never renders the HTML natively. So if you have (or may have in the future) a need to seamlessly host WPF or HTML content in the same control then Frame is definitely what you want. That said, I don't know of a downside to using Frame so that's what I use even if it's exclusively for HTML.</p>
|
Direct3D9ex and Direct3D10 resource sharing <p>It is possible, with the Direct3D9ex, to share resources between devices. Is it also possible to use those shared resources with Direct3D10 devices?</p>
| <p>Yes, you can share resources between D3D9Ex and D3D10 devices using the technique described here:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb219800%28VS.85%29.aspx#Sharing%5FResources" rel="nofollow">Feature Summary (Direct3D 9 for Windows Vista) - Sharing Resources</a></p>
<p>Note that GPU access to shared surfaces is not synchronized - for example, if you render to the same render surface on two devices simultaneously, expect all sorts of corruptions and races.</p>
<p>To work around it, make sure one device is completed rendering to the shared surface before the other one uses it. One option is event query (IDirect3DQuery9) , the other is doing a StretchRect to a small surface and Lock it (if Lock succeeds, GPU completed all previous work)</p>
|
getting the value of a form field after keypress event <p>myInput.value is one keystroke behind when I examine it in a keyPress event handler. So if the users types "a", myInput.value gives me "". Then when the user types "b", myInput.value gives me "a", and so it. The value doesn't seem to get updated with the character input by the keystroke that triggered the event. What am I doing wrong?
thanks
-Morgan</p>
| <p>Use the keyUp event, it should definitely give you the value you are looking for.</p>
|
How can I determine the content type of a file in .NET? <p>I'm given a filename and I have to be able to read it from disk and send its contents over a network. I need to be able to determine whether the file is text or binary so I know whether to use a StreamReader or BinaryReader. Another reason why I need to know the content type is because if it is binary, I have to MIME encode the data before sending it over the wire. I'd also like to be able to tell the consumer what the content type is (including the encoding if it is text).</p>
<p>Thanks!</p>
| <p>The <a href="http://en.wikipedia.org/wiki/Filename_extension" rel="nofollow">filename extension</a> provides your best hint at the content type of a file.</p>
<p>It's not perfect, but I've used the following with some success:</p>
<pre><code>private static string GetContentTypeFromRegistry(string file)
{
RegistryKey contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type");
foreach (string keyName in contentTypeKey.GetSubKeyNames())
{
if (System.IO.Path.GetExtension(file).ToLower().CompareTo((string)contentTypeKey.OpenSubKey(keyName).GetValue("Extension")) == 0)
{
return keyName;
}
}
return "unknown";
}
private static string GetFileExtensionFromRegistry(string contentType)
{
RegistryKey contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType);
if (contentTypeKey != null)
{
string extension = (string)contentTypeKey.GetValue("Extension");
if (extension != null)
{
return extension;
}
}
return String.Empty;
}
</code></pre>
|
What's the best way to manage a dependency tree in .NET? <p>In my last project we used MSBuild as a scripting language. (yeah, really!) We also wrote hundreds of custom MSBuild tasks, for the parts that made more sense in C#. (I even wrote an MSBuild task to generate the boilerplate code for an MSBuild task. Yes, it consumed itself.)</p>
<p>While I don't recommend anyone else take this same approach, one of the things I found very helpful was the built-in dependency management. As you'd expect, it was easy to express dependency relationships and let MSBuild take care of satisfying them. For example, almost every step in our software required that a certain set of files be copied to a certain location. You could easily write:</p>
<pre><code>Step1: CopyFiles
Step2: CopyFiles, Step1
</code></pre>
<p>and when you execute <code>Step2</code>, it would only copy the files once.</p>
<p><strong>Building and satisfying a dependency tree is a pretty common in software</strong>. I wish the MSBuild team would take their dependency management code, decouple it from MSBuild, and move it in to the .NET Framework where anyone can use it. Baring that, <strong>what do you think is the best option for managing dependencies this way</strong>? </p>
| <p>I think you could use an IOC container like Spring to get this kind of behavior.</p>
<p>Instantiate any task that must only run once as a singleton and have the constructor of the task object run the task. Then any object that comes along later with a dependency on that task will get a reference to the task that already ran and be able to get the results of that task or be able to infer that that task has already been run successfully.</p>
<p>In the spring config you would end up with many tasks chained together, each one references other tasks in its constructor config.
This approach is the most flexible and you are not restricted to "tasks" or anything too heavy for that matter.</p>
<p>I'm guessing any workflow library also has similar concepts. But I am not really familiar with these.</p>
<p>I think for anything smaller, people must just roll their own object graph and interface using the visitor pattern and maybe a Dictionary to hold state.</p>
|
What's a good HTML template engine for C++? <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/355650/c-html-template-framework-templatizing-library-html-generator-library">C++ HTML template framework, templatizing library, HTML generator library</a> </p>
</blockquote>
<p>Planning to write a website in C++. Would like to use a template system like Clearsilver, but maybe there's a better alternative? </p>
| <p><a href="http://www.webtoolkit.eu/wt">Wt</a> (pronounced 'witty') is a C++ library and application server for developing and deploying web applications. It is not a 'framework', which enforces a way of programming, but a library.</p>
|
JQuery event.target error <p>I've a box from divs (price_item) with several child divs (date, price etc.). I'm using it as a caroussel for showing prices. If one clicks on any child, the parent's background color must be changed to red. I wrote it like:</p>
<pre><code>$(...selectquery...).click(function() {
var $tgt = $(event.target);
$tgt.parent().css("backgroundColor", "red");
});
</code></pre>
<p>on Chrome, event.target is working as expected, on Firefox 3.0.1 it says "event is not defined". How can I work around this?</p>
<p>I've tried the following:</p>
<pre><code>$(this).parent().css()
</code></pre>
<p>it says <code>'object is not a function'</code></p>
<p>thanks!</p>
| <p>The <code>event</code> object gets passed into your click handler by jQuery, so you need to specify it as a parameter.</p>
<p>You also may be able to add the click handler to the parent object and use "$(this)" instead of event.target:</p>
<pre><code>$(...select the parent...).click(function() {
$(this).css("backgroundColor", "red");
});
</code></pre>
<p>If the user clicks the parent, or any of its children, it will call your click handler. If you need to only change the background if they actually click on one of the children (not between them, for example) this won't work.</p>
|
Best practice of writing a program which has too many data collection processes C# <p>I have to login in to various elements to retrieve some data, problem is each element has its own login credentials, I want to write all such data collection processes into one single program so that I dont have 10 different scheduled processes to look at.</p>
<p>Did any of you have such a challenge, if so how did you go about it? I am right now doing it the top down way, so its after the first data collection process gets implemented the program goes for the next...</p>
<p>I know that this is not the right way, I have threads and processes in mind, but being a beginner I'm kinda lost now. </p>
| <p>if the process of collecting data of the different sources is taking longer you could get faster results if you do it with multithreading and callbacks, but if in normal case it takes not really long, why not make it as simple as possible.</p>
|
App_Data - Web application's data directory. How secure is it? <p>In many places in msdn documentation you can find references to App_Data directory. For example <a href="http://msdn.microsoft.com/en-us/library/system.web.security.authorizationstoreroleprovider.aspx">here</a> we can read:</p>
<blockquote>
<p>To improve security when using a local data file in an ASP.NET application, you should store the data file in the App_Data directory. </p>
</blockquote>
<p>and</p>
<blockquote>
<p>Files stored in the App_Data directory
will not be served to the Web.</p>
</blockquote>
<p>I could not find a direct reference that would specify how is that security guaranteed. Are there any IIS settings etc. that I should watch out to ensure that the files we put in the App_Data directory suddenly do not become available to everyone.</p>
| <p>The files are protected by a forbidden file handler. That is safe so long as everything is running. There are possibilities that the ASP.NET handlers can go down leaving only IIS running. In those cases your web.config files and aspx files will be served as straight text files. </p>
<p>If you data isn't really sensitive, it is a good place to store data. If you have highly sensitive data, store it on another machine.</p>
<p>Edit: More information
You can read more about forbidden file handlers here <a href="http://msdn.microsoft.com/en-us/library/bya7fh0a.aspx">http://msdn.microsoft.com/en-us/library/bya7fh0a.aspx</a>. Scrolling down you will notice there is an entry in the "root web.config" file for mdfs. You can typically find this file on your machine at C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG</p>
<p>I couldn't find too much info about bringing down asp.net while still leaving iis running, but if you google around for terms like "asks to download aspx" or something like that you can find reports of people having issues (typically asp.net not being configured properly) which would allow for an exploit to occur. I haven't seen it happen very much, but it is possible.</p>
|
Why does use of pens with dash patterns cause huge (!) performance degredation in WPF custom 2D drawing? <p>Hope anyone can shed light on this so I can use pens with dash patterns? </p>
<p>I am writing a scrollable chart (a <code>Panel</code> inside <code>ScrollViewer</code> that implements <code>IScrollInfo</code>) in WPF using <code>DrawingVisual</code>'s <code>DataContext.Draw</code><em>X</em>. I have several thousand <code>DrawingVisual</code>s that get scrolled by using <code>TranslateTransform</code> on the <code>Panel</code> that hosts them. I implemented a grid by placing a <code>Panel</code> on top of it and drawing simple horizontal lines from one edge to the other using <code>DataContext.DrawLine(pen, new Point(0, y), new Point(widthOfPanel, y));</code> //(note: these lines are always static, they never move). </p>
<p>The scroll performance is absolutely insane (i.e. DrawingVisual's are drawn instantly and scrolling is instant). But if I use a <code>Pen</code> that uses dash patterns (see below for example) to draw the grid lines, then scrolling is very jerky and the performance seems to have been decreased by a factor of 100 (an estimate). Can anyone explain why that happens and how I can workaround this?</p>
<p>Example of Pen with dash pattern:</p>
<pre><code><Pen x:Key="PenUsingDashPatterns" Brush="Black" Thickness="1">
<Pen.DashStyle >
<DashStyle Dashes="3, 3" />
</Pen.DashStyle>
</Pen>
</code></pre>
| <p>Here's a possible workaround - if you're only drawing horizontal and/or vertical lines you could try creating your <code>Pen</code> with a checker pattern <code>DrawingBrush</code> such as:</p>
<pre><code> <Pen x:Key="PenUsingDashPatterns" Thickness="1">
<Pen.Brush>
<DrawingBrush TileMode="Tile"
Viewport="0 0 6 6" ViewportUnits="Absolute">
<DrawingBrush.Drawing>
<GeometryDrawing Brush="Black">
<GeometryDrawing.Geometry>
<GeometryGroup>
<RectangleGeometry Rect="0 0 3 3"/>
<RectangleGeometry Rect="3 3 3 3"/>
</GeometryGroup>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
</Pen.Brush>
</Pen>
</code></pre>
<p>Alternatively, you could use different brushes for verical and horizontal lines, or, possibly, an <code>ImageBrush</code> for better performance. </p>
|
My app edits a file in SharePoint via Web Client/WebDAV(WebDAV redirector). How can I check out/check in? <p>I'm integrating my application so that it can edit files stored in SharePoint. I'm using the Web Client service AKA WebDAV Redirector(webclnt.dll) which does a wonderful job of letting the normal CreateFile/read/write Windows api calls be redirected from their normal drive I/O path out to the network via WebDAV. However, I can only get read-only access to the file if it's checked in. </p>
<p>Using the Web Client service, how can I cause the file to be checked out when I edit it, and then cause it to be checked in when I'm finished editing it?</p>
<p>Edit: I tried using the GetFileAttributes and SetFileAttributes to test for FILE_ATTRIBUTE_READONLY, hoping that I could use that flag to determine when the file was not checked out, and then to check it out (by unsetting that flag to check out, then setting it to check it in). No luck there; the file always appears as not read-only.</p>
| <p>Well to perform check-in/check-out a file you need to use the following code:</p>
<pre><code>SPSite oSite = new SPSite ("http://<sitename>/");
SPWeb oWeb = oSite.OpenWeb();
SPList oList = oWeb.Lists["Shared Documents"];
SPListItem oListItem = oList.Items[0]; //taking the first list item
oListItem.File.CheckOut();
oListItem["Name"] = "xyz";
oListItem.Update();
oListItem.File.CheckIn("file name has been changed");
</code></pre>
<p>If you need to do check-in/check-out via the SharePoint WebService then you should take a look at the code on Brad McCable's blog on <a href="http://blogs.msdn.com/brad_mccabe/archive/2005/03/01/382432.aspx" rel="nofollow">Windows Sharepoint Services Web Service Example</a>.</p>
|
Use aspectj to profile selected methods <p>I'd like to use aspectj to profile a library. My plan was to mark methods that require profiling with an annotation:</p>
<p><code>@Profiled("logicalUnitOfWork")</code></p>
<p>And then have an aspect that would fire before and after methods that would use the <code>logicalUnitOfWork</code> to highlight the profiled content.</p>
<p>So, my pointcut to start with looks like this. Note that I don't have the argument for the annotation here; that's one of the things I'm not sure how to do:</p>
<pre><code>pointcut profiled() : execution(@Profiled * *());
before() : profiled () {
// : the profiled logical name is in this variable:
String logicalEventType;
Profiler.startEvent (logicalEventType);
}
after() returning : profiled() {
// : the profiled logical name is in this variable:
String logicalEventType;
Profiler.endEvent (logicalEventType);
}
</code></pre>
<p>The methods being profiled would be defined like this:</p>
<pre><code>@Profiled("someAction")
public void doAction (args...) {}
</code></pre>
<p>In short, how can I get the value of the <code>@Profiled</code> annotation into the aspect? I don't need to restrict which profiling occurs based on the value, I just need it to be visible to the advice. Also, do I need to have the annotation's retention set to runtime for this to work, or can I have class-level retention instead?</p>
| <p>I am not sure if this is the best way to do it, but you could try something like:</p>
<pre>
<code>
pointcut profiledOperation(Profiled p) :
execution(@Profiled * *()) && @annotation(p);
before(Profiled p): profiledOperation(p)
{
System.out.println("Before " + p.value());
}
after(Profiled p): profiledOperation(p)
{
System.out.println("After " + p.value());
}
</code>
</pre>
<p>Since you need to access the annotation value at runtime you will have to set the <code>@Retention</code> to <code>RUNTIME</code>.</p>
|
Yellow Dog Linux 6.1 and PS3 GameOS Versions? <p>I'm working on installing linux on a PS3 to do some development work and I've run across a bit of a snag. The current version of the firmware on my PS3 is 2.50. The Yellow Dog website <a href="http://us.fixstars.com/support/advisories.shtml" rel="nofollow">specifically mentions</a> that there are problems with this release. The <a href="http://us.fixstars.com/support/installation/ydl6.0_ps3_guide.pdf" rel="nofollow">official Yellow Dog install guide</a> (PDF!) also mentions that I should update my PS3 to the newest version (which is now 2.60). So does any body have any experience with this? </p>
| <p>Ok, so I updated the firmware to 2.60 and everything seems to work (other than some network stuff, but I think that is specific to my environment, not this configuration of distro/ps3).</p>
|
Proper use of the IDisposable interface <p>I know from reading <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx">the MSDN documentation</a> that the "primary" use of the IDisposable interface is to clean up unmanaged resources.</p>
<p>To me, "unmanaged" means things like database connections, sockets, window handles, etc. But, I've seen code where the Dispose method is implemented to free <em>managed</em> resources, which seems redundant to me, since the garbage collector should take care of that for you.</p>
<p>For example:</p>
<pre><code>public class MyCollection : IDisposable
{
private List<String> _theList = new List<String>();
private Dictionary<String, Point> _theDict = new Dictionary<String, Point>();
// Die, clear it up! (free unmanaged resources)
public void Dispose()
{
_theList.clear();
_theDict.clear();
_theList = null;
_theDict = null;
}
</code></pre>
<p>My question is, does this make the garbage collector free memory used by MyCollection any faster than it normally would?</p>
<p><strong>edit</strong>: So far people have posted some good examples of using IDisposable to clean up unmanaged resources such as database connections and bitmaps. But suppose that _theList in the above code contained a million strings, and you wanted to free that memory <em>now</em>, rather than waiting for the garbage collector. Would the above code accomplish that?</p>
| <p>The point of Dispose <strong>is</strong> to free unmanaged resources. It needs to be done at some point, otherwise they will never be cleaned up. The garbage collector doesn't know <strong>how</strong> to call <code>DeleteHandle()</code> on a variable of type <code>IntPtr</code>, it doesn't know <strong>whether</strong> or not it needs to call <code>DeleteHandle()</code>.</p>
<blockquote>
<p><strong>Note</strong>: What is an <em>unmanaged resource</em>? If you found it in the Microsoft .NET Framework: it's managed. If you went poking around MSDN yourself, it's unmanaged. Anything you've used P/Invoke calls to get outside of the nice comfy world of everything available to you in the .NET Framwork is unmanaged â and you're now responsible for cleaning it up.</p>
</blockquote>
<p>The object that you've created needs to expose <em>some</em> method, that the outside world can call, in order to clean up unmanaged resources. The method can be named whatever you like: </p>
<pre><code>public void Cleanup()
public void Shutdown()
</code></pre>
<p>But instead there is a standardized name for this method:</p>
<pre><code>public void Dispose()
</code></pre>
<p>There was even an interface created, <code>IDisposable</code>, that has just that one method:</p>
<pre><code>public interface IDisposable
{
void Dispose()
}
</code></pre>
<p>So you make your object expose the <code>IDisposable</code> interface, and that way you promise that you've written that single method to clean up your unmanaged resources:</p>
<pre><code>public void Dispose()
{
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
}
</code></pre>
<p>And you're done. <strong>Except you can do better.</strong></p>
<hr>
<p>What if your object has allocated a 250MB <strong><a href="http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx">System.Drawing.Bitmap</a></strong> (i.e. the .NET managed Bitmap class) as some sort of frame buffer? Sure, this is a managed .NET object, and the garbage collector will free it. But do you really want to leave 250MB of memory just sitting there â waiting for the garbage collector to <em>eventually</em> come along and free it? What if there's an <a href="http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.aspx">open database connection</a>? Surely we don't want that connection sitting open, waiting for the GC to finalize the object.</p>
<p>If the user has called <code>Dispose()</code> (meaning they no longer plan to use the object) why not get rid of those wasteful bitmaps and database connections?</p>
<p>So now we will:</p>
<ul>
<li>get rid of unmanaged resources (because we have to), and </li>
<li>get rid of managed resources (because we want to be helpful)</li>
</ul>
<p>So let's update our <code>Dispose()</code> method to get rid of those managed objects:</p>
<pre><code>public void Dispose()
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
//Free managed resources too
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose();
this.databaseConnection = null;
}
if (this.frameBufferImage != null)
{
this.frameBufferImage.Dispose();
this.frameBufferImage = null;
}
}
</code></pre>
<p>And all is good, <strong>except you can do better</strong>!</p>
<hr>
<p>What if the person <strong>forgot</strong> to call <code>Dispose()</code> on your object? Then they would leak some <strong>unmanaged</strong> resources! </p>
<blockquote>
<p><strong>Note:</strong> They won't leak <strong>managed</strong> resources, because eventually the garbage collector is going to run, on a background thread, and free the memory associated with any unused objects. This will include your object, and any managed objects you use (e.g. the <code>Bitmap</code> and the <code>DbConnection</code>).</p>
</blockquote>
<p>If the person forgot to call <code>Dispose()</code>, we can <em>still</em> save their bacon! We still have a way to call it <em>for</em> them: when the garbage collector finally gets around to freeing (i.e. finalizing) our object.</p>
<blockquote>
<p><strong>Note:</strong> The garbage collector will eventually free all managed objects.
When it does, it calls the <strong><code>Finalize</code></strong>
method on the object. The GC doesn't know, or
care, about <em>your</em> <strong>Dispose</strong> method.
That was just a name we chose for
a method we call when we want to get
rid of unmanaged stuff.</p>
</blockquote>
<p>The destruction of our object by the Garbage collector is the <em>perfect</em> time to free those pesky unmanaged resources. We do this by overriding the <code>Finalize()</code> method. </p>
<blockquote>
<p><strong>Note:</strong> In C#, you don't explicitly override the <code>Finalize()</code> method.
You write a method that <em>looks like</em> a <strong>C++ destructor</strong>, and the
compiler takes that to be your implementation of the <code>Finalize()</code> method:</p>
</blockquote>
<pre><code>~MyObject()
{
//we're being finalized (i.e. destroyed), call Dispose in case the user forgot to
Dispose(); //<--Warning: subtle bug! Keep reading!
}
</code></pre>
<p>But there's a bug in that code. You see, the garbage collector runs on a <strong>background thread</strong>; you don't know the order in which two objects are destroyed. It is entirely possible that in your <code>Dispose()</code> code, the <strong>managed</strong> object you're trying to get rid of (because you wanted to be helpful) is no longer there:</p>
<pre><code>public void Dispose()
{
//Free unmanaged resources
Win32.DestroyHandle(this.gdiCursorBitmapStreamFileHandle);
//Free managed resources too
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose(); //<-- crash, GC already destroyed it
this.databaseConnection = null;
}
if (this.frameBufferImage != null)
{
this.frameBufferImage.Dispose(); //<-- crash, GC already destroyed it
this.frameBufferImage = null;
}
}
</code></pre>
<p>So what you need is a way for <code>Finalize()</code> to tell <code>Dispose()</code> that it should <strong>not touch any managed</strong> resources (because they <em>might not be there</em> anymore), while still freeing unmanaged resources.</p>
<p>The standard pattern to do this is to have <code>Finalize()</code> and <code>Dispose()</code> both call a <strong>third</strong>(!) method; where you pass a Boolean saying if you're calling it from <code>Dispose()</code> (as opposed to <code>Finalize()</code>), meaning it's safe to free managed resources.</p>
<p>This <em>internal</em> method <em>could</em> be given some arbitrary name like "CoreDispose", or "MyInternalDispose", but is tradition to call it <code>Dispose(Boolean)</code>:</p>
<pre><code>protected void Dispose(Boolean disposing)
</code></pre>
<p>But a more helpful parameter name might be:</p>
<pre><code>protected void Dispose(Boolean itIsSafeToAlsoFreeManagedObjects)
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
//Free managed resources too, but only if I'm being called from Dispose
//(If I'm being called from Finalize then the objects might not exist
//anymore
if (itIsSafeToAlsoFreeManagedObjects)
{
if (this.databaseConnection != null)
{
this.databaseConnection.Dispose();
this.databaseConnection = null;
}
if (this.frameBufferImage != null)
{
this.frameBufferImage.Dispose();
this.frameBufferImage = null;
}
}
}
</code></pre>
<p>And you change your implementation of the <code>IDisposable.Dispose()</code> method to:</p>
<pre><code>public void Dispose()
{
Dispose(true); //I am calling you from Dispose, it's safe
}
</code></pre>
<p>and your finalizer to:</p>
<pre><code>~MyObject()
{
Dispose(false); //I am *not* calling you from Dispose, it's *not* safe
}
</code></pre>
<blockquote>
<p><strong>Note</strong>: If your object descends from an object that implements <code>Dispose</code>, then don't forget to call their <strong>base</strong> Dispose method when you override Dispose:</p>
</blockquote>
<pre><code>public Dispose()
{
try
{
Dispose(true); //true: safe to free managed resources
}
finally
{
base.Dispose();
}
}
</code></pre>
<p>And all is good, <strong>except you can do better</strong>!</p>
<hr>
<p>If the user calls <code>Dispose()</code> on your object, then everything has been cleaned up. Later on, when the garbage collector comes along and calls Finalize, it will then call <code>Dispose</code> again. </p>
<p>Not only is this wasteful, but if your object has junk references to objects you already disposed of from the <strong>last</strong> call to <code>Dispose()</code>, you'll try to dispose them again! </p>
<p>You'll notice in my code I was careful to remove references to objects that I've disposed, so I don't try to call <code>Dispose</code> on a junk object reference. But that didn't stop a subtle bug from creeping in.</p>
<p>When the user calls <code>Dispose()</code>: the handle <strong>CursorFileBitmapIconServiceHandle</strong> is destroyed. Later when the garbage collector runs, it will try to destroy the same handle again.</p>
<pre><code>protected void Dispose(Boolean iAmBeingCalledFromDisposeAndNotFinalize)
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle); //<--double destroy
...
}
</code></pre>
<p>The way you fix this is tell the garbage collector that it doesn't need to bother finalizing the object â its resources have already been cleaned up, and no more work is needed. You do this by calling <code>GC.SuppressFinalize()</code> in the <code>Dispose()</code> method:</p>
<pre><code>public void Dispose()
{
Dispose(true); //I am calling you from Dispose, it's safe
GC.SuppressFinalize(this); //Hey, GC: don't bother calling finalize later
}
</code></pre>
<p>Now that the user has called <code>Dispose()</code>, we have:</p>
<ul>
<li>freed unmanaged resources</li>
<li>freed managed resources</li>
</ul>
<p>There's no point in the GC running the finalizer â everything's taken care of.</p>
<h2>Couldn't I use Finalize to cleanup unmanaged resources?</h2>
<p>The documentation for <a href="https://msdn.microsoft.com/en-us/library/system.object.finalize.aspx"><code>Object.Finalize</code></a> says:</p>
<blockquote>
<p>The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed.</p>
</blockquote>
<p>But the MSDN documentation also says, for <a href="https://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx"><code>IDisposable.Dispose</code></a>:</p>
<blockquote>
<p>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</p>
</blockquote>
<p>So which is it? Which one is the place for me to cleanup unmanaged resources? The answer is: </p>
<blockquote>
<p>It's your choice! But choose <code>Dispose</code>.</p>
</blockquote>
<p>You certainly could place your unmanaged cleanup in the finalizer:</p>
<pre><code>~MyObject()
{
//Free unmanaged resources
Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
//A C# destructor automatically calls the destructor of its base class.
}
</code></pre>
<p>The problem with that is you have no idea when the garbage collector will get around to finalizing your object. Your un-managed, un-needed, un-used native resources will stick around until the garbage collector <em>eventually</em> runs. Then it will call your finalizer method; cleaning up unmanaged resources. The documentation of <strong>Object.Finalize</strong> points this out:</p>
<blockquote>
<p>The exact time when the finalizer executes is undefined. To ensure deterministic release of resources for instances of your class, implement a <strong>Close</strong> method or provide a <a href="https://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx"><code>IDisposable.Dispose</code></a> implementation.</p>
</blockquote>
<p>This is the virtue of using <code>Dispose</code> to cleanup unmanaged resources; you get to know, and control, when unmanaged resource are cleaned up. Their destruction is <em>"deterministic"</em>.</p>
<hr>
<p>To answer your original question: Why not release memory now, rather than for when the GC decides to do it? I have a facial recognition software that <em>needs</em> to get rid of 530 MB of internal images <strong>now</strong>, since they're no longer needed. When we don't: the machine grinds to a swapping halt.</p>
<h2>Bonus Reading</h2>
<p>For anyone who likes the style of this answer (explaining the <em>why</em>, so the <em>how</em> becomes obvious), I suggest you read Chapter One of Don Box's Essential COM: </p>
<ul>
<li>Direct link: <a href="http://ptgmedia.pearsoncmg.com/images/0201634465/samplechapter/chap01.pdf">Chapter 1 sample by Pearson Publishing</a></li>
<li>magnet: 84bf0b960936d677190a2be355858e80ef7542c0</li>
</ul>
<p>In 35 pages he explains the problems of using binary objects, and invents COM before your eyes. Once you realize the <em>why</em> of COM, the remaining 300 pages are obvious, and just detail Microsoft's implementation.</p>
<p>I think every programmer who has ever dealt with objects or COM should, at the very least, read the first chapter. It is the best explanation of anything ever.</p>
|
Maven package .bat script: how to add a delay? <p>I have this .bat script which I use to maven package my application. Problem is, just after it ends execution, it closes the console window. The last 2 lines somehow are completely ignored.</p>
<p>Does anyone know the trick to make this work?
I just want to have a quick check if the build was successful.</p>
<pre><code>@echo off
cls
cd C:\svn\project
mvn package -o -P local
sleep 3
pause
</code></pre>
| <p>You could try to write</p>
<pre><code>call mvn package -o -P local
</code></pre>
|
Factory Model in C# and not using default constructor <p>I've been using the factory model to create child forms to add to a MDI form. This is the code I've been using:</p>
<pre><code> /// <summary>
/// This uses the Factory Model to create the child node and then add it to the MDI Parent (this)
/// </summary>
/// <param name="childName">String class name of the child, i.e. RentalEase.PropertyGrid must extend Form or SingleInstance</param>
/// <param name="singleInstance">bool If this class is to be a single instance and restricted to only on instance. Must extend SingleInstance</param>
public void createChild(string childName, bool singleInstance) {
if (singleInstance) {
try {
BaseAndSingleInstanceForm f = BaseAndSingleInstanceForm.getInstanceByType(this, Type.GetType(childName));
f.MdiParent = this;
f.Show();
f.BringToFront();
this.Refresh();
} catch (Exception ex) {
MessageBox.Show("Could not create child: " + ex.ToString());
}
} else {
try {
object o = Activator.CreateInstance(Type.GetType(childName));
if (o is Form) {
Form f = (Form)o;
f.MdiParent = this;
f.Show();
f.BringToFront();
this.Refresh();
} else {
throw new ArgumentException("Invalid Class");
}
} catch (Exception ex) {
MessageBox.Show("Could not create child: " + ex.ToString());
}
}
}
</code></pre>
<p>However, a situation has arose that I have to add an integer parameter to the constructor of a specific form. How can I change this and make it reflect it while still maintaining the pattern at it's current ease of use (or nearly).</p>
| <p>You could add a <code>Object[]</code> parameter to the method that would represent the parameters to the constructor of the object you wish to instantiate. Then when you call <code>Activator.CreateInstance</code> you could pass that array in and <code>Activator</code> would do its best to find a constructor on the type you specified that matches the types in the <code>Object</code> array.</p>
<p>Here is a much simplified example of what I mean:</p>
<pre><code>using System;
class Program
{
static void Main()
{
Foo foo = (Foo)create("Foo", new Object[] { });
Bar bar = (Bar)create("Bar", new Object[] { "hello bar" });
Baz baz = (Baz)create("Baz", new Object[] { 2, "hello baz" });
}
static Object create(String typeName, Object[] parameters)
{
return Activator.CreateInstance(Type.GetType(typeName), parameters);
}
}
class Foo
{
public Foo() { }
}
class Bar
{
public Bar(String param1) { }
}
class Baz
{
public Baz(Int32 param1, String param2) { }
}
</code></pre>
<p>We have three types that all have different constructors - if the caller is responsible for sending in the type name then they will also be responsible for supplying an array of <code>Objects</code> that will satisfy a non-default constructor.</p>
|
Java GUI Problems <p>I'm designing a really simple GUI but without any luck. Basically the outer layout has two columns which is a splitter pane (this is for an IRC client I'm writing). On the left-hand side is the server/channel/user tree and on the right is the chat pane. Now I break this down so on the right-hand side there's the output pane at the top, and a single-lined input box at the bottom.</p>
<p>This is the code for creating the GUI on a whole (this is just a snippet)</p>
<pre><code>ChatModel cm = new ChatModel();
ChatView cv = new ChatView(cm);
treeViewChatSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, serverTreeView, cv);
treeViewChatSplitPane.setSize(500, 500);
treeViewChatSplitPane.setBorder(null);
treeViewChatSplitPane.setDividerSize(3);
this.getContentPane().add(treeViewChatSplitPane);
this.setSize(500, 500);
</code></pre>
<p>The ChatView constructor has this in it (it extends java.awt.Container)</p>
<pre><code>this.model = model;
this.setLayout(new BorderLayout());
mainTextArea = new JTextArea();
mainTextArea.setLineWrap(true);
mainTextArea.setBackground(new Color(255, 255, 255));
inputField = new JTextField();
this.add(mainTextArea, BorderLayout.CENTER);
this.add(inputField, BorderLayout.PAGE_END);
</code></pre>
<p>Now it looks fine initially, but the problem I'm having with it is that you can move the splitter to the left, but not to the right. In fact, if you move it left, you can no longer move it right. I did have it working earlier, but the implementation wasn't as good and I've forgotten what I had done.</p>
<p>Any ideas? I can't see why this wouldn't work.</p>
| <p>If I remember correctly, <code>JSplitPanes</code> always respect the minimum size of their components. Try explicitly setting the minimum size of the <code>ChatView</code> to <code>(0,0)</code> and see if that helps. If so, you can then look at each of the components inside it to see which is causing the problem.</p>
|
Adding text (actually, barcodes) to a Postscript file <p>I would like to be able to add barcodes to generated postscript files. The postscript files are generated by another program and I am unable to change how that program works.</p>
<p>I've found several threads that suggest this might be done this by converting the Postscript files to PDF (<a href="http://stackoverflow.com/questions/465271/gluing-imposition-pdf-documents">Gluing (Imposition) PDF documents</a>; <a href="http://stackoverflow.com/questions/310441/create-two-pdfs-from-one-ps-file">Create two pdfs from one .ps file?</a>; <a href="http://stackoverflow.com/questions/501723/overlay-one-pdf-or-ps-file-on-top-of-another">Overlay one pdf or ps file on top of another</a>).</p>
<p>I'd like to know if there is a way to do this without the PDF conversion (to keep things simple, to keep things fast, and to avoid loss of quality). If it turns out that PDF conversion is the only reasonable solution, is there any loss of quality going from Postscript to PDF?</p>
| <p>If the generated Postscript is sufficiently nice, you could write something to dig through it, find the showpage command, and just insert some additional drawing commands before it.
After all, you don't need to handle the general case, just output from this one program, which should always spit Postscript out the same way.</p>
<p>More generally, you could convert the PS to EPS programmatically, and then embed it into another Postscript file that will draw it, and then the barcode. (Now that I mention this one, it might actually be easier.)</p>
<p>The <a href="http://www.google.com/search?q=postscript+language+reference+manual" rel="nofollow">Postscript Language Reference Manual</a> would come in handy for both of those tasks.</p>
|
check what number a string ends with in C++ <p>In a C++ MD2 file loader, I have a lot of frames, each with a name that ends with a number, such as</p>
<ul>
<li>stand0</li>
<li>stand1</li>
<li>stand2</li>
<li>stand3</li>
<li>stand4</li>
<li>...</li>
<li>stand10</li>
<li>stand11</li>
<li>run0</li>
<li>run1</li>
<li>run2</li>
</ul>
<p>etc.</p>
<p>How do I get what the string is without the number behind? e.g. a function that changed "stand10" to just "stand"</p>
| <p>Just to show another way, reverse iterators:</p>
<pre><code>string::reverse_iterator rit = str.rbegin();
while(isdigit(*rit)) ++rit;
std::string new_str(str.begin(), rit.base());
</code></pre>
<p>If you have boost::bind, you can make your life easier</p>
<pre><code>std::string new_str(str.begin(),
std::find_if(str.rbegin(), str.rend(),
!boost::bind(::isdigit, _1)).base());
</code></pre>
|
Ruby addict looking for PHP subexpressions in strings <h2>Context</h2>
<ul>
<li>PHP 5.3.x</li>
</ul>
<h2>Overview</h2>
<p>After doing a code-review with an associate who uses both php and ruby routinely, a fun challenge came up on string interpolation in php compared to ruby.</p>
<h2>Question</h2>
<p>Assume color = "orange";</p>
<p><strong>Ruby:</strong></p>
<pre><code>puts("My favorite color is #{color.downcase() + 'ish'} -- at least for now.");
</code></pre>
<p><strong>PHP:</strong></p>
<pre><code>print("My favorite color is {strtolower( $color ) + 'ish'} -- at least for now.");
</code></pre>
<p><strong>Challenge:</strong> can anyone specify a way to get the PHP version behave like Ruby?</p>
<h2>Caveat</h2>
<p>This challenge is intended as a fun exercise with the constraint of using only straight PHP. This is not intended for serious PHP projects. For serious PHP projects, the developer will want to consider addon libraries, such as TWIG. </p>
| <p>You're close, you can embed variables in strings, but not function calls. </p>
<p>I use <code>printf()</code> (and <code>sprintf()</code>) for that, which is a thin wrapper around the C function of the same name: </p>
<pre><code>printf('My favorite color is %sish -- at least for now.', strtolower( $color ));
</code></pre>
<p>See that <code>%s</code> in there? That's the placeholder for the string data type that you're passing in as the 2nd argument. </p>
<p><code>sprintf()</code> works the same way, but it returns the formatted string instead of print'ing it. </p>
<p>The only other options are: </p>
<p>A. Performing the function calls first and assigning the end-result to the variable: </p>
<pre><code>$color = strtolower( $color );
print("My favorite color is {$color}ish -- at least for now.");
</code></pre>
<p>B. Using concatenation, which is a little ugly IMO: </p>
<pre><code>print('My favorite color is ' . strtolower( $color ) . 'ish -- at least for now.');
</code></pre>
<p>You may have noticed my use of single quotes (aka ticks), and double quotes. </p>
<p>In PHP, literals inside double quotes are parsed for variables, as you see in "A" above. </p>
<p>Literals inside single quotes are not parsed. Because of this, they're faster. You should, as a rule, only use double-quotes around literals when there's a variable to be parsed. </p>
|
How to implement an offline reader writer lock <p>Some context for the question</p>
<ul>
<li>All objects in this question are persistent.</li>
<li>All requests will be from a Silverlight client talking to an app server via a binary protocol (Hessian) and not WCF.</li>
<li>Each user will have a session key (not an ASP.NET session) which will be a string, integer, or GUID (undecided so far). </li>
</ul>
<p>Some objects might take a long time to edit (30 or more minutes) so we have decided to use pessimistic offline locking. Pessimistic because having to reconcile conflicts would be far too annoying for users, offline because the client is not permanently connected to the server.</p>
<p>Rather than storing session/object locking information in the object itself I have decided that any aggregate root that may have its instances locked should implement an interface ILockable</p>
<pre><code>public interface ILockable
{
Guid LockID { get; }
}
</code></pre>
<p>This LockID will be the identity of a "Lock" object which holds the information of which session is locking it.</p>
<p>Now, if this were simple pessimistic locking I'd be able to achieve this very simply (using an incrementing version number on Lock to identify update conflicts), but what I actually need is ReaderWriter pessimistic offline locking.</p>
<p>The reason is that some parts of the application will perform actions that read these complex structures. These include things like</p>
<ul>
<li>Reading a single structure to clone it.</li>
<li>Reading multiple structures in order to create a binary file to "publish" the data to an external source.</li>
</ul>
<p>Read locks will be held for a very short period of time, typically less than a second, although in some circumstances they could be held for about 5 seconds at a guess.</p>
<p>Write locks will mostly be held for a long time as they are mostly held by humans.</p>
<p>There is a high probability of two users trying to edit the same aggregate at the same time, and a high probability of many users needing to temporarily read-lock at the same time too. I'm looking for suggestions as to how I might implement this.</p>
<p>One additional point to make is that if I want to place a write lock and there are some read locks, I would like to "queue" the write lock so that no new read locks are placed. If the read locks are removed withing X seconds then the write lock is obtained, if not then the write lock backs off; no new read-locks would be placed while a write lock is queued.</p>
<p>So far I have this idea</p>
<ol>
<li>The Lock object will have a version number (int) so I can detect multi-update conflicts, reload, try again.</li>
<li>It will have a string[] for read locks</li>
<li>A string to hold the session ID that has a write lock</li>
<li>A string to hold the queued write lock</li>
<li>Possibly a recursion counter to allow the same session to lock multiple times (for both read and write locks), but not sure about this yet.</li>
</ol>
<p>Rules:</p>
<ul>
<li>Can't place a read lock if there is a write lock or queued write lock.</li>
<li>Can't place a write lock if there is a write lock or queued write lock.</li>
<li>If there are no locks at all then a write lock may be placed.</li>
<li>If there are read locks then a write lock will be queued instead of a full write lock placed. (If after X time the read locks are not gone the lock backs off, otherwise it is upgraded).</li>
<li>Can't queue a write lock for a session that has a read lock.</li>
</ul>
<p>Can anyone see any problems? Suggest alternatives? Anything? I'd appreciate feedback before deciding on what approach to take.</p>
| <p>Have you considered an <a href="http://en.wikipedia.org/wiki/Multiversion_concurrency_control" rel="nofollow">mvcc</a> implementation:</p>
<p>Granted, it would be harder to implement but seems much more concurrent than what you have explained. Just throwing the idea out there.</p>
|
Pros and Cons of Various Java Web Presentation Layer Technologies <p>I'm currently working on a web app that makes heavy use of JSF and IceFaces. We've had some discussions of moving to another presentation layer, and I thought I'd take the discussion out into SO and see what the experts think. </p>
<p>I'm curious if anyone could weigh in on the pros and cons of the various Java presentation layer technologies. If you've only worked with one, say why you love it or hate it. If you've worked with several, give your impressions of how they stack up against each other.</p>
<p>Our technologies under consideration are: </p>
<ul>
<li>IceFaces</li>
<li>JSF (without IceFaces)</li>
<li>GWT (Google Web Toolkit)</li>
<li>Wicket</li>
<li>Tapestry</li>
</ul>
<p>And if I'm missing anything from my list, let me know. </p>
<p>Thanks!</p>
| <p>My opinions are quite heavily biased towards Wicket because I've been using it for a while after tripping over JSP mines far too many times.</p>
<p><strong>Wicket PROs:</strong></p>
<ul>
<li>True separation of layout and code.</li>
<li>Component based which means high reusability of site elements; For example you can create prettified form with automatic labeling and CSS styles and everything and just by changing it's DAO object in the component's constructor it's completely reusable in another project.</li>
<li>Excellent support for things like Ajax, Portlets and various frameworks in general directly out-of-the-box AND more importantly it doesn't rely on anything else than slf4j/log4j to work, everything's optional!</li>
</ul>
<p><strong>Wicket CONs:</strong></p>
<ul>
<li>Development has some confusion about things in general and Wicket generics are a bit of a mess right now although they've been cleaned a lot in 1.4</li>
<li>Some components (like <code>Form.onSubmit()</code>) require extensive subclassing or anonymous method overriding for injecting behaviour easily. This is partly due to Wicket's powerful event-based design but unfortunately it also means it's easy to make a code mess with Wicket.</li>
</ul>
<p><strong>Random CONs:</strong> (that is, I haven't used but these are my opionions and/or things I've heard)</p>
<ul>
<li>GWT is JavaScript based which sounds stupid to me. Main issue is that it reminds me too much of JSP:s and its autogenerated classes which are horrible.</li>
<li>Tapestry doesn't separate markup and code properly in a manner which could be easily validated between the two which will cause problems in the future.</li>
</ul>
|
Getting first byte in a char* buffer <p>I have a char* buffer and I am interested in looking at the first byte in the char* buffer, what is the most optimal way to go about this. </p>
<p>EDIT: Based on the negative votes I might want to explain why this question, I am aware of methods but in the code base that I have been looking for getting first byte people do all kinds of crazy things like do a copy of the buffer , copy it to a stream and then do a get. </p>
| <p>Just use</p>
<pre><code>char firstByte = buffer[0];
</code></pre>
|
Sorting Columns in a gridview whose data source is an oracle db <p>Can anyone tell the function to sort the columns of a gridview in c# asp.net.</p>
<p>The gridview is databound to an oracle database. I wanted to click the header of the column to sort the data.
i dont know how to refer to the header itself
is it using the sender argument of the gridview_sorting method?</p>
<p>Thanks</p>
| <p>In the gridview control set the AllowSorting property to true</p>
<pre><code><asp:GridView runat="server" ID="gvItems" AllowSorting="true" ...>
</code></pre>
<p>In the HeaderTemplate of the column you wish to sort set the SortExpression property to the field the tempate is bound to, if your not using a HeaderTemplate and using a BoundField there should also be a SortExpression property</p>
<pre><code><asp:TemplateField SortExpression="ItemDescription" HeaderText="Item">...
</code></pre>
<p>Implement the OnSorting method</p>
<p>Inside of OnSorting use the second paramerter (GridViewSortEventArgs) to know what the sort expression is and rebind your gridview</p>
<pre><code>protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
string fieldToSortOn = e.SortExpression;
//implement sort logic on datasource...
}
</code></pre>
<p>That should get you a good start</p>
|
What rails plugins are good, stable and *really* enhance your code? <p>Anyone have a list of rails plugins that are both <em>stable</em> and give you enough functionality to be worth the extra effort of supporting? </p>
<h2>Edit:</h2>
<p>I am mostly interested in the best, most complete list of plugins so I can use it the next I'm starting a rails app. I don't currently need a particular plugin.</p>
| <p>You can use <a href="http://github.com/fudgestudios/bort/tree/master" rel="nofollow">bort</a> as reference</p>
<blockquote>
<p><strong>Plugins Installed</strong></p>
<p>Bort comes with a few commonly used
plugins installed and already setup.</p>
<p><strong>RESTful Authentication</strong></p>
<p>RESTful Authentication is already
setup. The routes are setup, along
with the mailers and observers.
Forgotten password comes setup, so you
donât have to mess around setting it
up with every project.</p>
<p>The AASM plugin comes pre-installed.
RESTful Authentication is also setup
to use user activation. </p>
<p><strong>User Roles</strong></p>
<p>Bort now comes with Role Requirement
by Tim Harper. A default admin role is
predefined along with a default admin
user. See the migrations for the admin
login details. </p>
<p><strong>Open ID Authentication</strong></p>
<p>Bort, as of 0.3, has Open ID
integrated with RESTful
Authentication. Rejoice! </p>
<p><strong>Will Paginate</strong></p>
<p>We use will_paginate in pretty much
every project we use, so Bort comes
with it pre-installed. </p>
<p><strong>Rspec & Rspec-rails</strong></p>
<p>You should be testing your code, so
Bort comes with Rspec and Rspec-rails
already installed so youâre ready to
roll. </p>
<p><strong>Exception Notifier</strong></p>
<p>You donât want your applications to
crash and burn so Exception Notifier
is already installed to let you know
when everything goes to shit. </p>
<p><strong>Asset Packager</strong></p>
<p>Packages up your css/javascript so
youâre not sending 143 files down to
the user at the same time. Reduces
load times and saves you bandwidth.</p>
</blockquote>
<p>p/s: agree with @eric, specifics</p>
|
How bad is the following snippet? <p>My question is simple: how bad is the following snippet of code? How would <em>you</em> do it?</p>
<pre><code>CancelEventHandler _windowClosing;
private CancelEventHandler WindowClosing
{
set
{
clearEventHandlerList();
this.Closing += value;
_windowClosing = value;
/*
* if calling the method with null parameters,
* it will set up itself as the primary control on the Window
*/
_windowClosing(null,null);
}
get
{
return _windowClosing;
}
}
private readonly CancelEventHandler[] CONTROLS = null;
private int current = 0;
public InitializerForm()
{
InitializeComponent();
/*
* these are the handlers for the different controls,
* in the order of appereance to the user
*/
STATES = new CancelEventHandler[] { handler1, handler2, etc. };
WindowClosing = CONTROLS[0];
}
private void clearEventHandlerList()
{
foreach (CancelEventHandler c in CONTROLS)
{
this.Closing -= c;
}
}
private void handler1(object obj, CancelEventArgs e)
{
if (obj == null)
{
//hide every other control, but this one, also set up if necessary
}
else
{
//do something
WindowClosing = CONTROLS[++current]; // set the next control to show
e.Cancel = true;
}
}
</code></pre>
<p>The point would be that the code wouldn't close a form, but instead show another component on it, and the set the way to handle that (this is mobile platform, so clicking OK button on the top generates a closing event). This is because showing several forms (4 or 5) one after another to the user makes the app blink, and also very annoying, while replacing just components is much smoother. This model works, but seems very nasty, and I would like a cleaner way to handle this.</p>
<p><strong>Update:</strong>
I updated the code sample so that variable names are somewhat speaky. Still, I'm convinced this is awful, (a) but not sure how much, and more importantly, (b) how to do it better.</p>
<p><strong>Update 2:</strong>
So, it seems that the code is still a bit mysterious.</p>
<p>Now here's what the problem is:
I show the user a form, which instructs him what to do in several languages. He proceeds by clicking OK on the window. Next, I ask for his language, and then a few questions (where his/her GPS is, etc.) like this. After he could answer the questions (this shouldn't take more than a few seconds each), I show him a splash screen (I load stuff in a separate thread meanwhile), which has a picture. Showing these forms one after another makes the whole application start slow, and filled with UI lags.</p>
<p>Here's what I do to work around the lags: I put the content of the windows into panels, and put those panels one on another, and hide every one of them but the one that should be visible to the user. (<code>current</code> variable) Each of the windows does different things, so I need to change handler of the window <code>closing</code> event in addition. In this code the part which enables the panel is in the same function (<code>handler1</code>, <code>handler2</code>, etc.) with the part which handles the window closing event. If the arguments are <code>null</code>, it does the former, if it isn't (that means it was triggered by the user) it does the latter.</p>
<p>I need an extensible solution to this so that I can insert and remove dialogs anytime I want (the order and the pointers to the functions are stored in the <code>CONTROLS</code> field, and this seems to be very convenient, if you actually understand it. Although it is never easy to change the entire content of a form, there ought to be a simpler way to do this, as well a nicer one, that is what I'm looking for.</p>
<p>I hope this time I could explain how the model works.</p>
| <p>I think it might be theoretically possible to make that code more delightfully diverting, perilously puckish, jovially jeopardous, cheerily chancy and unwarily whimsical but it would require some serious thought.</p>
|
How to include metadata in a template file? <p>I have a system that filters template files through erb. Using convention over configuration, the output files get created in a file hierarchy that mirrors the input files. Many of the files have the same names, and I was able to use the directories to differentiate them.</p>
<p>That plan worked until I needed to associate additional info with each file. So I created a YAML file in each directory with the metadata. Now I have both convention <strong><em>and</em></strong> configuration. Yuck.</p>
<p>Then I learned <a href="http://webby.rubyforge.org" rel="nofollow">Webby</a>, and the way it includes a YAML metadata section at the top of each template file. They look like this:</p>
<pre><code>---
title: Baxter the Dog
filter: textile
---
All the best little blogs use Webby.
</code></pre>
<p>If I could implement a header like that, I could ditch my hierarchy and the separate YAML files. The Webby implementation is very generic, implementing a new MetaFile class that separates the header from the "real text", but it seems more complicated than I need.</p>
<p>Putting the metadata in an erb comment seems good -- it will be automatically ignored by erb, but I'm not sure how to access the comment data.</p>
<pre><code><%#
title: Baxter the Dog
%>
</code></pre>
<p>Is there a way to access the erb comments? Or maybe a different approach? A lot of my templates do a bunch of erb stuff, but I could run erb in a separate step if it makes the rest easier.</p>
| <p>How about if you dump your content as YAML too. Presumably the metadata is simply a Hash dumped to YAML. You could just append the content as string in a second YAML document in the same file :-</p>
<pre><code>---
title: Baxter the Dog
filter: textile
--- |
Content line 1
Content line 2
Content line 3
</code></pre>
<p>Dumping is as simple as :-</p>
<pre><code>File.open('file.txt', 'w') do |output|
YAML.dump(metadata, output)
YAML.dump(content, output)
end
</code></pre>
<p>Loading is as simple as :-</p>
<pre><code>File.open('file.txt') do |input|
stream = YAML.load_stream(input)
metadata, content = stream.documents
end
</code></pre>
<p>Note that the pipe character appears in the YAML <a href="http://www.yaml.org/YAML_for_ruby.html#single_ending_newline" rel="nofollow">so that newlines in the content string are preserved</a>.</p>
|
Why should I NOT use the GAC? <p>There have been a few questions asked along this line stackoverflow such as
<a href="http://stackoverflow.com/questions/23578/what-are-the-advantages-and-disadvantages-of-using-the-gac">What are the advantages and disadvantages of using the GAC</a>
and <a href="http://stackoverflow.com/questions/498361/when-and-when-not-to-install-into-the-gac">When and when-not to install into the GAC?</a> and a few people have asked it on the
web <a href="http://flimflan.com/blog/WhenShouldIUseTheGAC.aspx">expamle</a>. I can't any convincing arguments for not using the GAC. I am sure I am being naive but it seams like there are more benefits (such as performance and version control issues) to using the GAC then not using it. </p>
<p><strong>Why should I NOT use the GAC?</strong></p>
| <p>Chris Sells gives probably <a href="http://www.sellsbrothers.com/Posts/Details/12503">the best reason for avoiding the GAC</a> where you can:</p>
<blockquote>
<blockquote>
<p>What this boils down to is that any of the shared spots for updates, whether it's a COM CLSID, windows\system32 or the GAC, are dangerous and should be avoided. And this is why the preferred .NET deployment scenario is "xcopy deployment," i.e. having your own private copy of each DLL that you test and deploy with the rest of your application.</p>
<p>"Aha!" you say. "The GAC supports multiple version of an assembly! When a foo.dll is updated to v1.1, v1.0 sits right along side of it so that your app <em>doesn't</em> break!" Of course, that's absolutely true. But if that's the case, why do you care? I mean, if there's a new assembly available but your app isn't picking it up, what difference does it make?</p>
<p>"Aha again!, you say. "I can put a publisher policy into the GAC along with my assembly so that apps <em>are</em> updated automatically!" That's true, too, but now, like any of the machine-wide code replacement strategies of old, you're on the hook for an awesome responsibility: making sure that as close to 0% of apps, known to you or not, don't break. This is an awesome responsibility and one that takes MS hundreds of man-years at each new release of the .NET Framework. And even with those hundreds of man-years of testing, we still don't always get it right. If this is a testing responsibility that you're willing to live with, I admire you. Personally, I don't have the moral fortitude to shoulder this burden.</p>
</blockquote>
</blockquote>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.