input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
Give DROP PROCEDURE a parameter <p>I'm using SqlServer for the first time, and in every single one of our create procedure scripts there is a block of code like below to remove the procedure if it already exists:</p>
<pre><code>IF EXISTS (SELECT *
FROM information_schema.routines
WHERE routine_name = 'SomeProcedureName'
AND routine_type = 'PROCEDURE'
BEGIN
DROP PROCEDURE SomeProcedureName
END
//then the procedure definition
</code></pre>
<p>To stop cutting and pasting this boilerplate code in every file I would like to put this code in its own stored procedure so that instead the scripts would look like this:</p>
<pre><code>DropIfRequired('SomeProcedureName')
//then the procedure definition
</code></pre>
<p>My attempt at a solution is:</p>
<pre><code>CREATE PROCEDURE DropIfRequired
(
@procedureName varchar
)
AS
IF EXISTS (SELECT * FROM information_schema.routines
WHERE routine_name = @procedureName
AND routine_type = 'PROCEDURE')
BEGIN
DROP PROCEDURE @procedureName
END
</code></pre>
<p>But I then get the following error:</p>
<p>Msg 102, Level 15, State 1, Procedure DeleteProcedure, Line 10
Incorrect syntax near '@procedureName'.</p>
<p>Any ideas how to do what I want?</p>
|
<p>The full answer is:
<PRE>
DECLARE @SQL VARCHAR(8000)
SELECT @SQL = 'USE ' + DB_NAME() + CHAR(10)
SET @SQL = @SQL + 'DROP PROCEDURE ' + @procName
--PRINT @SQL
EXEC(@SQL)
</PRE></p>
<p>The one given by Andrew will only work if the default database for your login is set to the database you want. When using dynamic sql you get a new database context. So if you do not have a default database set you will execute the command from master.</p>
|
C# Generics won't allow Delegate Type Constraints <p>Is it possible to define a class in C# such that</p>
<pre><code>class GenericCollection<T> : SomeBaseCollection<T> where T : Delegate
</code></pre>
<p>I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using</p>
<p><code>delegate, Delegate, Action<T> and Func<T, T></code></p>
<p>It seems to me that this should be allowable in some way. I'm trying to implement my own EventQueue.</p>
<p>I ended up just doing this [primitive approximation mind you].</p>
<pre><code>internal delegate void DWork();
class EventQueue {
private Queue<DWork> eventq;
}
</code></pre>
<p>But then I lose the ability to reuse the same definition for different types of functions.</p>
<p>Thoughts?</p>
|
<p>A number of classes are unavailable as generic contraints - Enum being another.</p>
<p>For delegates, the closest you can get is ": class", perhaps using reflection to check (for example, in the static constructor) that the T <em>is</em> a delegate:</p>
<pre><code> static GenericCollection()
{
if (!typeof(T).IsSubclassOf(typeof(Delegate)))
{
throw new InvalidOperationException(typeof(T).Name + " is not a delegate type");
}
}
</code></pre>
|
How to resolve incorrect "Ambiguous reference" from ReSharper on class inheritance? <p>In my project I have a class that is inherited by many other classes. We'll call it ClassBase.</p>
<pre><code>public class ClassInheritFromBase : ClassBase
</code></pre>
<p>When ClassBase is being inherited, <a href="http://en.wikipedia.org/wiki/ReSharper" rel="nofollow">ReSharper</a> throws an "Ambiguous reference" warning on the ClassBase, and anything inside the new class that inherited from ClassBase does not have IntelliSense and gets warnings that it cannot find it.</p>
<p>The project compiles and runs fine.</p>
<p>If I change the namespace ClassBase is in and then change the inheriting classes, they find it fine and ReSharper has no problem, IntelliSense works ... until it is compiled. After the compile it goes back to having the ambiguous reference warnings and everything else.</p>
<p>Has this been seen before and how can it be fixed? I saw an entry in JetBrains bug tracking for an issue just like this, but they closed it as unable to reproduce.</p>
|
<p>For those who still have a problem with this, (I still get it from time to time) here's the steps I did to get rid of the ambiguous reference warning in ReSharper.</p>
<ol>
<li>First I went to all my class libraries and made sure that all references to my other class libraries had the <em>Copy Local</em> property set to false.</li>
<li>In the project where I actually got the ambiguous reference warning, I went to my bin catalog and deleted all .dll and .pdb files for all the libraries that had their own project.</li>
<li>After a new build, or in my case "update reference" on the .dll files in VS, the errors from Resharper were gone.</li>
</ol>
<p>I'm using Resharper 5.1 in Visual Studio 2008 with only a reference to the dlls I'm using which is why I had to "update reference"</p>
|
NT AUTHORITY\NETWORK SERVICE issue when deploying on remote server SQL 2005 <p>I am getting a very non specific error when trying to connect to SQL server on remote server. I feel like I have made all the correct settings, allow TCP/IP, restarted the service, added rights to NT AUTHORITY\NETWORK SERVICE and other related users for the database. I can get to the aspx page, but as soon as I hit submit on the login I get: </p>
<p>Exception information:
Exception type: SqlException
Exception message: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) </p>
<p>Thank you for your help. </p>
|
<p>on the remote server, create an alias for the server instance that forces TCP/IP and the port, and use that alias in the connection string. That way it wont even try to use DBNMP</p>
<p>Also you can try forcing the issue int he connection string.
<a href="http://connectionstrings.com/article.aspx?article=howtodefinewichnetworkprotocoltouse" rel="nofollow">http://connectionstrings.com/article.aspx?article=howtodefinewichnetworkprotocoltouse</a></p>
|
In an MFC application, what's the easiest way to copy a file from one directory to another? <p>Should I create two CFile objects and copy one into the other character by character? Or is there something in the library that will do this for me?</p>
|
<p>I would just use the <a href="http://msdn.microsoft.com/en-us/library/aa363851(VS.85).aspx">CopyFile</a> Win32 API function, but the example code in the <a href="http://msdn.microsoft.com/en-us/library/hwbccf8z(VS.71).aspx">CFile::Open</a> documentation shows how to copy files with CFile (using pretty much the method you suggest).</p>
|
Firefox Links to local or network pages do not work <p>I have a .asp application where image files (.PDF) are stored in a directory (fed by a copier/scanner). The created file names are stored in a database table. When a query is launched from the web page a link to the file is created. When clicked the image should be displayed.
This functionality works 100% in Internet Explorer. No such luck in Firefox (and I have some Firefox users). The created hyperlink looks like this <code>file://Server/Scanner/XYZ.pdf</code></p>
<p>The Firefox helps suggest the reason is this: </p>
<blockquote>
<p>Links to local or network pages do not work. As a security precaution, Firefox forbids sites on the Internet to link to files that are stored in your local computing environment. These files may include files on your computer, mapped network drives, and UNC network paths</p>
</blockquote>
<p>None of the suggestions for a workaround seem to work (or I am not understanding the steps to create the image display)
Any Suggestions?</p>
|
<p>This is the default Firefox behavior designed for security .The assumption is probably that most web sites don't know what and where are you local files (including UNC paths).</p>
<p>This could be turned off in firefox:</p>
<ul>
<li>type "about:config" in the address bar and accept "i'll be careful"</li>
<li>find "security.checkloaduri" in older versions or "security.fileuri.strict_origin_policy" in newer versions of firefox and change the value to "false"</li>
<li>restart firefox</li>
</ul>
<p>That should do it for you. You have more information here:</p>
<ul>
<li><a href="http://kb.mozillazine.org/Security.fileuri.strict_origin_policy">http://kb.mozillazine.org/Security.fileuri.strict_origin_policy</a></li>
<li><a href="http://kb.mozillazine.org/Security.fileuri.origin_policy">http://kb.mozillazine.org/Security.fileuri.origin_policy</a></li>
</ul>
|
How do you design a functional program? <p>From day 1 of my programming career, I started with object-oriented programming. However, I'm interested in learning other paradigms (something which I've said here on SO a number of times is a good thing, but I haven't had the time to do). I think I'm not only ready, but have the time, so I'll be starting functional programming with F#.</p>
<p>However, I'm not sure how to structure much less design applications. I'm used to the one-class-per-file and class-noun/function-verb ideas in OO programming. How do you design and structure functional applications?</p>
|
<p>Read the <a href="http://mitpress.mit.edu/sicp/">SICP</a>.</p>
<p>Also, there is a <a href="http://deptinfo.unice.fr/~roy/sicp.pdf">PDF Version</a> available.</p>
|
Is there a way to extract .NET 2.0 from the .NET 3.5? <p>.NET Framework 3.5 SP1 installs the .NET Framework 2.0 SP2 and the .NET Framework 3.0 SP2 behind the scenes. These installation packages (especially .NET Framework 2.0 SP2) are not available directly from Microsoft.</p>
<p>Is there a way to extract them from the .NET Framework 3.5 SP1 installation package?</p>
|
<p>Take a look on <a href="http://msdn.microsoft.com/en-us/vs2008/bb898654.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/vs2008/bb898654.aspx</a> or download <a href="http://go.microsoft.com/fwlink/?LinkID=127832" rel="nofollow">.NET Frameworks 2.0 SP2 and 3.0 SP2 bootstrapper packages</a>. These packages give you separate .NET Framework 2.0 SP2 and .NET Framework 3.0 SP2 installation packages.</p>
|
Are there caveats to dynamicly creating a form with javascript? <p>I have to do a cross site POST (with a redirection, so not using a XMLHTTPRequest), and the base platform is ASP.NET. I don't want to POST all of the controls in the ASP.NET FORM to this other site, so I was considering dynamicly creating a new form element using javascript and just posting that.</p>
<p>Has anyone tried this trick? Is there any caveats?</p>
|
<p>I do this all the time. Works really well. You will have to look through the Request's parameters manually, though, unless you get creative with what you pass as the parameters won't map onto controls on that page. You could also do this in a REST way by passing the parameters in the query string, but I prefer the forms approach to keep my URLs clean. Note that ASP.NET ignores all forms but it's own on postback so I don't bother removing them.</p>
<p>Example from a GridView template field for below code:</p>
<pre><code> <asp:TemplateField HeaderText="Station" SortExpression="Name">
<ItemTemplate>
<a href="javascript:void(0);" onclick='Redirector.redirect_with_id("StationDetail.aspx", <%# Eval("StationID") != null ? Eval("StationID") : "-1" %>);return false;'>
<asp:Label ID="nameLabel" runat="server" Text='<%# Bind("Name") %>' /></a>
</ItemTemplate>
</asp:TemplateField>
</code></pre>
<p>Code below -- requires Prototype:</p>
<pre><code> // JScript File
var Redirector = Class.create();
Redirector.prototype = {
initialize: function(url,target) {
this.url = url;
this.parameters = new Hash();
this.target = target;
},
addParameter: function(id,value) {
this.parameters.set(id, value);
},
redirect: function() {
var form = document.createElement('form');
document.body.appendChild(form);
form.action = this.url;
form.method = "post";
if (this.target) {
form.target = this.target;
}
this.parameters.each( function(pair) {
var input = document.createElement('input');
input.id = pair.key;
input.name = pair.key;
input.value = pair.value;
input.style.display = 'none';
form.appendChild(input);
});
form.submit();
}
};
Redirector.redirect_with_id = function(url,id,target) {
var redirector = new Redirector( url, target );
redirector.addParameter( 'ID', id );
redirector.redirect();
};
Redirector.redirect_with_tag = function(url,tag_name,tag,target) {
var redirector = new Redirector( url, target );
redirector.addParameter( tag_name, tag );
redirector.redirect();
};
Redirector.redirect_with_tags = function(url,tag_names_comma_separated,tag_values_comma_separated,target) {
var redirector = new Redirector( url, target );
var tags = tag_names_comma_separated.split( "," );
var values = tag_values_comma_separated.split( ",");
for( var i = 0; i< tags.length; i++ )
{
redirector.addParameter( tags[i], values[i] );
}
redirector.redirect();
};
</code></pre>
|
What is the most efficient/elegant way to parse a flat table into a tree? <p>Assume you have a flat table that stores an ordered tree hierarchy:</p>
<pre><code>Id Name ParentId Order
1 'Node 1' 0 10
2 'Node 1.1' 1 10
3 'Node 2' 0 20
4 'Node 1.1.1' 2 10
5 'Node 2.1' 3 10
6 'Node 1.2' 1 20
</code></pre>
<p>Here's a diagram, where we have <code>[id] Name</code>. Root node 0 is fictional.</p>
<pre>
[0] ROOT
/ \
[1] Node 1 [3] Node 2
/ \ \
[2] Node 1.1 [6] Node 1.2 [5] Node 2.1
/
[4] Node 1.1.1
</pre>
<p>What minimalistic approach would you use to output that to HTML (or text, for that matter) as a correctly ordered, correctly indented tree? </p>
<p>Assume further you only have basic data structures (arrays and hashmaps), no fancy objects with parent/children references, no ORM, no framework, just your two hands. The table is represented as a result set, which can be accessed randomly. </p>
<p>Pseudo code or plain English is okay, this is purely a conceptional question.</p>
<p>Bonus question: Is there a fundamentally better way to store a tree structure like this in a RDBMS?</p>
<hr>
<p><strong>EDITS AND ADDITIONS</strong></p>
<p>To answer one commenter's (<a href="http://stackoverflow.com/users/17826/mark-bessey">Mark Bessey</a>'s) question: A root node is not necessary, because it is never going to be displayed anyway. ParentId = 0 is the convention to express "these are top level". The Order column defines how nodes with the same parent are going to be sorted.</p>
<p>The "result set" I spoke of can be pictured as an array of hashmaps (to stay in that terminology). For my example was meant to be already there. Some answers go the extra mile and construct it first, but thats okay.</p>
<p>The tree can be arbitrarily deep. Each node can have N children. I did not exactly have a "millions of entries" tree in mind, though.</p>
<p>Don't mistake my choice of node naming ('Node 1.1.1') for something to rely on. The nodes could equally well be called 'Frank' or 'Bob', no naming structure is implied, this was merely to make it readable.</p>
<p><em>I have posted my own solution so you guys can pull it to pieces.</em></p>
|
<p>There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods: </p>
<ul>
<li><strong>Adjacency List</strong> (the "parent" column) and </li>
<li><strong>Path Enumeration</strong> (the dotted-numbers in your name column). </li>
</ul>
<p>Another solution is called <strong>Nested Sets</strong>, and it can be stored in the same table too. Read "<a href="http://rads.stackoverflow.com/amzn/click/1558609202">Trees and Hierarchies in SQL for Smarties</a>" by Joe Celko for a lot more information on these designs.</p>
<p>I usually prefer a design called <strong>Closure Table</strong> (aka "Adjacency Relation") for storing tree-structured data. It requires another table, but then querying trees is pretty easy.</p>
<p>I cover Closure Table in my presentation <a href="http://www.slideshare.net/billkarwin/models-for-hierarchical-data">Models for Hierarchical Data with SQL and PHP</a> and in my book <a href="http://pragprog.com/book/bksqla/sql-antipatterns">SQL Antipatterns: Avoiding the Pitfalls of Database Programming</a>.</p>
<pre><code>CREATE TABLE ClosureTable (
ancestor_id INT NOT NULL REFERENCES FlatTable(id),
descendant_id INT NOT NULL REFERENCES FlatTable(id),
PRIMARY KEY (ancestor_id, descendant_id)
);
</code></pre>
<p>Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question:</p>
<pre><code>INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES
(1,1), (1,2), (1,4), (1,6),
(2,2), (2,4),
(3,3), (3,5),
(4,4),
(5,5),
(6,6);
</code></pre>
<p>Now you can get a tree starting at node 1 like this:</p>
<pre><code>SELECT f.*
FROM FlatTable f
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1;
</code></pre>
<p>The output (in MySQL client) looks like the following:</p>
<pre><code>+----+
| id |
+----+
| 1 |
| 2 |
| 4 |
| 6 |
+----+
</code></pre>
<p>In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1.</p>
<hr>
<p>Re: comment from e-satis about immediate children (or immediate parent). You can add a "<code>path_length</code>" column to the <code>ClosureTable</code> to make it easier to query specifically for an immediate child or parent (or any other distance).</p>
<pre><code>INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES
(1,1,0), (1,2,1), (1,4,2), (1,6,1),
(2,2,0), (2,4,1),
(3,3,0), (3,5,1),
(4,4,0),
(5,5,0),
(6,6,0);
</code></pre>
<p>Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose <code>path_length</code> is 1.</p>
<pre><code>SELECT f.*
FROM FlatTable f
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
AND path_length = 1;
+----+
| id |
+----+
| 2 |
| 6 |
+----+
</code></pre>
<hr>
<p>Re comment from @ashraf: "How about sorting the whole tree [by name]?"</p>
<p>Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as <code>name</code>, and sort by the name.</p>
<pre><code>SELECT f.name
FROM FlatTable f
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
ORDER BY f.name;
</code></pre>
<hr>
<p>Re comment from @Nate:</p>
<pre><code>SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs
FROM FlatTable f
JOIN ClosureTable a ON (f.id = a.descendant_id)
JOIN ClosureTable b ON (b.descendant_id = a.descendant_id)
WHERE a.ancestor_id = 1
GROUP BY a.descendant_id
ORDER BY f.name
+------------+-------------+
| name | breadcrumbs |
+------------+-------------+
| Node 1 | 1 |
| Node 1.1 | 1,2 |
| Node 1.1.1 | 1,2,4 |
| Node 1.2 | 1,6 |
+------------+-------------+
</code></pre>
<hr>
<p>A user suggested an edit today. SO moderators approved the edit, but I am reversing it.</p>
<p>The edit suggested that the ORDER BY in the last query above should be <code>ORDER BY b.path_length, f.name</code>, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2".</p>
<p>If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to <a href="http://stackoverflow.com/questions/8252323/mysql-closure-table-hierarchical-database-how-to-pull-information-out-in-the-c">MySQL Closure Table hierarchical database - How to pull information out in the correct order</a>.</p>
|
Calculating a date around working days/hours? <p>I am currently working on a website to track projects. In it, it is possible to create Service Level Agreements (SLAs). These are configurable with days of the week that a project can be worked on and also the timespan on each of those days. Eg. on Monday it might be between 08:00 and 16:00 and then on friday from 10:00 to 14:00. They are also configured with a deadline time depending on priority. Eg. a project created with the "Low" priority has a deadline time of two weeks, and a project with "High" priority has a deadline of four hours.</p>
<p>The problem I'm having is calculating the deadline AROUND the hours described earlier. Say I create a project on Monday at 14:00 with a "High" priority. That means I have four hours for this project. But because of the working hours, I have two hours on monday (untill 16:00) and then another two hours on Friday. That means the Deadline must be set for Friday at 12:00.</p>
<p>I've spent quite some time googling this, and I can find quite a few examples of finding out how many working hours there are between a given start end ending date. I just can't figure out how to convert it into FINDING the ending datetime, given a starting time and an amount of time untill the deadline.</p>
<p>The day/timespans are stored in an sql database in the format:</p>
<p>Day(Eg. 1 for Monday) StartHour EndHour</p>
<p>The StartHour/EndHour are saved as DateTimes, but of course only the time part is important.</p>
<p>The way I figure it is, I have to somehow iterate through these times and do some datetime calculations. I just can't quite figure out what those calculations should be, what the best way is.</p>
<p>I found <a href="http://stackoverflow.com/questions/5260/what-is-the-best-way-to-wrap-time-around-the-work-day">this Question</a> here on the site as I was writing this. It is sort of what I want and I'm playing with it right now, but I'm still lost on how exactly to make it work around my dynamic work days/hours.</p>
|
<p>Here's some C# code which might help, it could be much cleaner, but it's a quick first draft.</p>
<pre><code> class Program
{
static void Main(string[] args)
{
// Test
DateTime deadline = DeadlineManager.CalculateDeadline(DateTime.Now, new TimeSpan(4, 0, 0));
Console.WriteLine(deadline);
Console.ReadLine();
}
}
static class DeadlineManager
{
public static DateTime CalculateDeadline(DateTime start, TimeSpan workhours)
{
DateTime current = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, 0);
while(workhours.TotalMinutes > 0)
{
DayOfWeek dayOfWeek = current.DayOfWeek;
Workday workday = Workday.GetWorkday(dayOfWeek);
if(workday == null)
{
DayOfWeek original = dayOfWeek;
while (workday == null)
{
current = current.AddDays(1);
dayOfWeek = current.DayOfWeek;
workday = Workday.GetWorkday(dayOfWeek);
if (dayOfWeek == original)
{
throw new InvalidOperationException("no work days");
}
}
current = current.AddHours(workday.startTime.Hour - current.Hour);
current = current.AddMinutes(workday.startTime.Minute - current.Minute);
}
TimeSpan worked = Workday.WorkHours(workday, current);
if (workhours > worked)
{
workhours = workhours - worked;
// Add one day and reset hour/minutes
current = current.Add(new TimeSpan(1, current.Hour * -1, current.Minute * -1, 0));
}
else
{
current.Add(workhours);
return current;
}
}
return DateTime.MinValue;
}
}
class Workday
{
private static readonly Dictionary<DayOfWeek, Workday> Workdays = new Dictionary<DayOfWeek, Workday>(7);
static Workday()
{
Workdays.Add(DayOfWeek.Monday, new Workday(DayOfWeek.Monday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));
Workdays.Add(DayOfWeek.Tuesday, new Workday(DayOfWeek.Tuesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));
Workdays.Add(DayOfWeek.Wednesday, new Workday(DayOfWeek.Wednesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));
Workdays.Add(DayOfWeek.Thursday, new Workday(DayOfWeek.Thursday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));
Workdays.Add(DayOfWeek.Friday, new Workday(DayOfWeek.Friday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 14, 0, 0)));
}
public static Workday GetWorkday(DayOfWeek dayofWeek)
{
if (Workdays.ContainsKey(dayofWeek))
{
return Workdays[dayofWeek];
}
else return null;
}
public static TimeSpan WorkHours(Workday workday, DateTime time)
{
DateTime sTime = new DateTime(time.Year, time.Month, time.Day,
workday.startTime.Hour, workday.startTime.Millisecond, workday.startTime.Second);
DateTime eTime = new DateTime(time.Year, time.Month, time.Day,
workday.endTime.Hour, workday.endTime.Millisecond, workday.endTime.Second);
if (sTime < time)
{
sTime = time;
}
TimeSpan span = eTime - sTime;
return span;
}
public static DayOfWeek GetNextWeekday(DayOfWeek dayOfWeek)
{
int i = (dayOfWeek == DayOfWeek.Saturday) ? 0 : ((int)dayOfWeek) + 1;
return (DayOfWeek)i;
}
private Workday(DayOfWeek dayOfWeek, DateTime start, DateTime end)
{
this.dayOfWeek = dayOfWeek;
this.startTime = start;
this.endTime = end;
}
public DayOfWeek dayOfWeek;
public DateTime startTime;
public DateTime endTime;
}
</code></pre>
|
Firefox 'Error loading script' loading Google Analytics in FF2 <p>The project I'm working on uses a window.onerror event handler to report user problems. I've noticed a single user that just cannot seem to load the Google Analytics script. Our site doesn't see a lot of traffic so I'm not sure how widespread this is, but so far it seems to just effect one user. </p>
<p>His user agent is: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17".<br />
The error message Firefox gives is: "Error loading script".</p>
<p><strong>Additional note</strong>: The site references several other javascript files. However, the analytics reference is the only one to an external domain and the only script reference at the bottom of the page, just before the closing body tag.</p>
<p>Has anybody else run across this, or have any idea what could be the issue? Thanks!</p>
|
<p>This problem occurs when leaving a page in Firefox before all scripts have finished loading. So I assume that it is safe to ignore the error.</p>
<p>You don't see this error in the Firefox error console, but you can make it visible by binding an alert to the window.onerror event. Then you will be able to see the alert box for a small amount of time and get the following error in the error console:</p>
<pre><code>[11:35:57.428] uncaught exception: [Exception... "prompt aborted by user" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 462" data: no]
</code></pre>
<p>I'm using the following check to ignore this error in my onerror handler:</p>
<pre><code>if (navigator.userAgent.search('Firefox') != -1 && message === 'Error loading script') {
// Firefox generates this error when leaving a page before all scripts have finished loading
return;
}
</code></pre>
|
SVN checkout filtered by file extension? <p>I have a home-grown automated build script in the form of a DOS batch file. In part of that script, I check out (with "svn checkout") a section of our SVN repository that includes a bunch of third-party stuff that's used in our projects. This batch file performed pretty well for a long time, but now people have checked in lots of fluff (docs, sample code, etc.) into the third-party area and the checkout part of this script has gotten lots slower. I'd like to mitigate this by checking out only the stuff we need -- mostly dll files in our case. So, my question is this: what's the best way to check out an SVN repository filtered by file extension?</p>
<p>I didn't see any obvious way to do this in the svn help. I have a .NET utility library that wraps svn.exe in some ways, and I was thinking of extending this to retrieve only content that matched my extensions of interest. But I'd prefer to use an easier or existing method if one exists.</p>
|
<p>This is possible: you can <code>svn checkout</code> an empty directory, and then <code>svn update filename</code> for each file that you <em>do</em> want.</p>
<p>Your script can do something like:</p>
<ol>
<li><code>svn checkout svn://path/to/repos/directory --depth empty</code></li>
<li><code>svn list --recursive svn://path/to/repos/directory</code></li>
<li>Pipe that result through a filter that removes the forbidden file extensions, e.g. <code>grep</code></li>
<li>Iterate over this new filtered list and <code>svn update --parents</code> each file</li>
</ol>
<p>That would give your desired result of a working copy without certain files or file extensions.</p>
<p>Of course, there is also the issue that you mention of âpeople [checking] in lots of fluffâ but thatâs a separate matter.</p>
|
Wait cursor over entire html page <p>Is it possible to set the cursor to 'wait' on the entire html page in a simple way? The idea is to show the user that something is going on while an ajax call is being completed. The code below shows a simplified version of what I tried and also demonstrate the problems I run into:</p>
<ol>
<li>if an element (#id1) has a cursor style set it will ignore the one set on body (obviously) </li>
<li>some elements have a default cursor style (a) and will not show the wait cursor on hover </li>
<li>the body element has a certain height depending on the content and if the page is short, the cursor will not show below the footer</li>
</ol>
<p>The test:</p>
<pre><code><html>
<head>
<style type="text/css">
#id1 {
background-color: #06f;
cursor: pointer;
}
#id2 {
background-color: #f60;
}
</style>
</head>
<body>
<div id="id1">cursor: pointer</div>
<div id="id2">no cursor</div>
<a href="#" onclick="document.body.style.cursor = 'wait'; return false">Do something</a>
</body>
</html>
</code></pre>
<p>Later edit...<br />
It worked in firefox and IE with: </p>
<pre><code>div#mask { display: none; cursor: wait; z-index: 9999;
position: absolute; top: 0; left: 0; height: 100%;
width: 100%; background-color: #fff; opacity: 0; filter: alpha(opacity = 0);}
<a href="#" onclick="document.getElementById('mask').style.display = 'block'; return false">
Do something</a>
</code></pre>
<p>The problem with (or feature of) this solution is that it will prevent clicks because of the overlapping div (thanks Kibbee)</p>
<p>Later later edit...<br />
A simpler solution from Dorward:</p>
<pre><code>.wait, .wait * { cursor: wait !important; }
</code></pre>
<p>and then </p>
<pre><code><a href="#" onclick="document.body.className = 'wait'; return false">Do something</a>
</code></pre>
<p>This solution only shows the wait cursor but allows clicks.</p>
|
<p>If you use this slightly modified version of the CSS you posted from Dorward,</p>
<pre><code>html.wait, html.wait * { cursor: wait !important; }
</code></pre>
<p>you can then add some really simple <a href="http://api.jquery.com/" rel="nofollow">jQuery</a> to work for all ajax calls:</p>
<pre><code>$(document).ready(function () {
$(document).ajaxStart(function () { $("html").addClass("wait"); });
$(document).ajaxStop(function () { $("html").removeClass("wait"); });
});
</code></pre>
<p>or, for older jQuery versions (before 1.9):</p>
<pre><code>$(document).ready(function () {
$("html").ajaxStart(function () { $(this).addClass("wait"); });
$("html").ajaxStop(function () { $(this).removeClass("wait"); });
});
</code></pre>
|
Generating a globally unique identifier in Java <p><strong>Summary:</strong> I'm developing a persistent Java web application, and I need to make sure that all resources I persist have globally unique identifiers to prevent duplicates.</p>
<p><strong>The Fine Print:</strong></p>
<ol>
<li>I'm not using an RDBMS, so I don't have any fancy sequence generators (such as the one provided by Oracle)</li>
<li>I'd like it to be fast, preferably all in memory - I'd rather not have to open up a file and increment some value</li>
<li>It needs to be thread safe (I'm anticipating that only one JVM at a time will need to generate IDs)</li>
<li>There needs to be consistency across instantiations of the JVM. If the server shuts down and starts up, the ID generator shouldn't re-generate the same IDs it generated in previous instantiations (or at least the chance has to be really, really slim - I anticipate many millions of presisted resources)</li>
<li>I have seen the examples in the EJB unique ID pattern article. They won't work for me (I'd rather not rely solely on System.currentTimeMillis() because we'll be persisting multiple resources per millisecond).</li>
<li>I have looked at the answers proposed in <a href="http://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string-in-java">this question</a>. My concern about them is, what is the chance that I will get a duplicate ID over time? I'm intrigued by the suggestion to use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html" rel="nofollow">java.util.UUID</a> for a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" rel="nofollow">UUID</a>, but again, the chances of a duplicate need to be infinitesimally small.</li>
<li>I'm using JDK6</li>
</ol>
|
<p>Pretty sure UUIDs are "good enough". There are 340,282,366,920,938,463,463,374,607,431,770,000,000 UUIDs available.</p>
<p><a href="http://www.wilybeagle.com/guid_store/guid_explain.htm">http://www.wilybeagle.com/guid_store/guid_explain.htm</a></p>
<p>"To put these numbers into perspective, one's annual risk of being hit by a meteorite is estimated to be one chance in 17 billion, that means the probability is about 0.00000000006 (6 Ã 10â11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. The probability of one duplicate would be about 50% if every person on earth owns 600 million UUIDs"</p>
<p><a href="http://en.wikipedia.org/wiki/Universally_Unique_Identifier">http://en.wikipedia.org/wiki/Universally_Unique_Identifier</a></p>
|
Storing PCRE compiled regexes in C/C++ <p>Is there an efficient way to store the compiled regexes (compiled via regcomp(), PCRE) in a binary file, so that later I can just read from the file and call regexec()?</p>
<p>Or is it just a matter of dumping the compiled regex_t structs to the file and reading them back when needed?</p>
|
<p>Unless you have a <a href="http://phi.lho.free.fr/programming/RETutorial.en.html" rel="nofollow" title="e-mail address">super-complex regex</a>, I hardly see an advantage of serializing the compiled regex, the compilation time shouldn't be that big. Unless you are on a super-tight embed system?</p>
<p>In any case, indeed dumping the structure might be a solution, at least you can try...<br />
[EDIT] I just looked at the source I have (6.7) and as I feared, it is not so simple, the structure starts with a void *... You can't serialize pointers, they have to be recomputed.</p>
|
TListBox Drag and Drop problems with MultiSelect enabled <p>I have a TListBox with multiselect and ExtendedSelect both set to true. I need to be able to drag multiple items in the list box to re-arrange them. My problem is what happens when the user clicks on an item that is already selected without holding down the CTRL or SHIFT key.</p>
<p>Case 1: DragMode is set to dmManual
The selection is cleared before the mouse down. This will not allow multiple items to be dragged.</p>
<p>Case 2: DragMode is set to dmAutomatic
The MouseDown event never fires. The selection is not cleared so dragging is OK, but the user cannot clear the selection by clicking on one of the selected items. This really causes a problem if all the items are selected or the next item the user wants to select was part of the current selection.</p>
<p>Note that this problem only happens if you assign something to the DragObject in the OnStartDrag procedure. I think the problem would go away if OnStartDrag would only start after the user moves the mouse. I have Mouse.DragImmediate := false set but I still get the StartDrag fired as soon as I click on an item in the list box.</p>
<p>I am using Delphi 7 for this project but I see the same behavior in Delphi 2007.</p>
|
<p>I have played with this for a while. And observe the same effects.</p>
<p>I would use Case2 and add a (Select All/Deselect All) button to the list. It even adds extra functionality and solves the most annoying part of the problem.</p>
|
Boiler plate code replacement - is there anything bad about this code? <p>I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing.</p>
<p>(from memory)</p>
<pre><code>static class SafeInvoker
{
//Utility to avoid boiler-plate InvokeRequired code
//Usage: SafeInvoker.Invoke(myCtrl, () => myCtrl.Enabled = false);
public static void Invoke(Control ctrl, Action cmd)
{
if (ctrl.InvokeRequired)
ctrl.BeginInvoke(new MethodInvoker(cmd));
else
cmd();
}
//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void RaiseEvent(object sender, EventHandler evnt)
{
var handler = evnt;
if (handler != null)
handler(sender, EventArgs.Empty);
}
}
</code></pre>
<p>EDIT: See related question <a href="http://stackoverflow.com/questions/258409/how-to-get-information-about-an-exception-raised-by-the-target-of-controlinvoke">here</a></p>
<p><strong>UPDATE</strong></p>
<p>Following on from deadlock problems (related in <a href="http://stackoverflow.com/questions/2055960/control-invoke-getting-stuck-in-hidden-showdialog">this question</a>), I have switched from Invoke to BeginInvoke (see an explanation <a href="http://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke/229558#229558">here</a>).</p>
<p><strong>Another Update</strong></p>
<p>Regarding the second snippet, I am increasingly inclined to use the 'empty delegate' pattern, which fixes this problem 'at source' by declaring the event directly with an empty handler, like so:</p>
<pre><code>event EventHandler MyEventRaised = delegate {};
</code></pre>
|
<p>This is good stuff. Make them extension methods though to clean up your code a little more. For example:</p>
<pre><code>//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void Raise(this EventHandler eventToRaise, object sender)
{
EventHandler eventHandler = eventToRaise;
if (eventHandler != null)
eventHandler(sender, EventArgs.Empty);
}
</code></pre>
<p>Now on your events you can call: myEvent.Raise(this);</p>
|
How do I use constants from a Perl module? <p>If I define a constant in a Perl module, how do I use that constant in my main program? (Or how do I call that constant in the main program?)</p>
|
<p>Constants can be exported just like other package symbols. Using the standard <a href="http://search.cpan.org/~ferreira/Exporter-5.63/lib/Exporter.pm">Exporter</a> module, you can export constants from a package like this:</p>
<pre><code>package Foo;
use strict;
use warnings;
use base 'Exporter';
use constant CONST => 42;
our @EXPORT_OK = ('CONST');
1;
</code></pre>
<p>Then, in a client script (or other module)</p>
<pre><code>use Foo 'CONST';
print CONST;
</code></pre>
<p>You can use the <code>%EXPORT_TAGS</code> hash (see the Exporter documentation) to define groups of constants that can be exported with a single import argument.</p>
<p>Update: Here's an example of how to use the <code>%EXPORT_TAGS</code> feature if you have multiple constants. </p>
<pre><code>use constant LARRY => 42;
use constant CURLY => 43;
use constant MOE => 44;
our @EXPORT_OK = ('LARRY', 'CURLY', 'MOE');
our %EXPORT_TAGS = ( stooges => [ 'LARRY', 'CURLY', 'MOE' ] );
</code></pre>
<p>Then you can say</p>
<pre><code>use Foo ':stooges';
print "$_\n" for LARRY, CURLY, MOE;
</code></pre>
|
HOWTO: specify in app.config to call a function before Main() is called? <p>I really want to put in some sort of section handler into App.config that will execute some code before the application actually starts executing at Main. Is there any way to do such a thing?</p>
|
<p>Not sure what you're trying to accomplish...but, I'm not aware of anyway you can have a console application run any other method before Main(). Why not do something like this:</p>
<pre><code>static void Main(string[] args)
{
//read your app.config variable
callAlternate = GetConfigSettings();
if(callAlternate)
AltMain();
///...rest of Main()
}
</code></pre>
|
How do I share a javascript object between different pages in Adobe AIR? <p>I'd like to have a custom object attached to the application so I can preserve state in it between different html pages in adobe air. Is this possible?</p>
<p><hr /></p>
<p>I was asking for a fullblown solution to store a custom js object in memory and persist it between pages loaded from the application sandbox, but this cannot be done unless I use iframes which is not very pleasant, since I have to add a lot of stuff to the bridge. Anoter way may be to do partial rendering of the page filled with html read from files, but this exposes a lot of unpleasant bugs + you cant write script tags in the dom dynamically. It's a crippled platform.</p>
|
<p>Perhaps you could try attaching the object on the user's machine. There is a tutorial online that seems like it could help:</p>
<p><a href="http://corlan.org/2008/09/02/storing-data-locally-in-air/" rel="nofollow">http://corlan.org/2008/09/02/storing-data-locally-in-air/</a></p>
<p>Example from the site:</p>
<pre><code>//write an Object to a file
private function writeObject():void {
var object:Object = new Object();//create an object to store
object.value = asObject.text; //set the text field value to the value property
//create a file under the application storage folder
var file:File = File.applicationStorageDirectory.resolvePath("myobject.file");
if (file.exists)
file.deleteFile();
var fileStream:FileStream = new FileStream(); //create a file stream
fileStream.open(file, FileMode.WRITE);// and open the file for write
fileStream.writeObject(object);//write the object to the file
fileStream.close();
}
</code></pre>
|
Apache htaccess on Win2k is not being processed <p>I am trying to rewrite URLs using mod_rewrite. It is enabled in httpd.conf and url rewriting works if the lines are in the httpd.conf file. However, I would like the rules to be in the .htaccess file.
It doesn't appear that .htaccess is being processed at all by Apache on Win2k.</p>
<p>I have ReWriteLogging turned all the way up, but the log file isn't being created. The last line in httpd.conf is </p>
<pre><code>AccessFileName .htaccess
</code></pre>
<p>.htaccess contents</p>
<pre><code>RewriteEngine on
RewriteLog "c:/rewrite.log"
RewriteLogLevel 15
RewriteRule /alice.html$ /bob.html
</code></pre>
<p>Thanks</p>
<p>edit : Apache version 2.2 on Windows 2k </p>
|
<p>Check that <code>AllowOverride FileInfo</code> is enabled in <code>httpd.conf</code> for the directories affected; see also <a href="http://httpd.apache.org/docs/2.2/mod/core.html#allowoverride" rel="nofollow">http://httpd.apache.org/docs/2.2/mod/core.html#allowoverride</a>. You might also check permissions on the <code>.htaccess</code> files themselves, to ensure there's nothing preventing Apache from reading them.</p>
|
Subversion & switching between tags <p>My automated deployment system updates a latest version of my site trough subversion. Instead of having my live site point to the trunk (which is always almost a work in progress version), I have my live site point to a tag.</p>
<p>E.g. I work on trunk and when my v1.0 is finished I create a tag called 1.0 and do a checkout of that tag which is then my live site. Now, I keep working on trunk and after a while there is a v2.0. I create a tag called 2.0 and I want my live site to resemble this 2.0 tag.</p>
<p>I could wipe the current live site and do a checkout of this 2.0 tag. Which sounds easy enough, however. My site is about 1GB is size because it has all kinds of PDF documents and video in it. I can safely say that most of the time I do updates it will be copy changes or bug fixes. This means that maybe only 1% of my site changes per update. And since my version control is only accessable to my webserver through on off site http connection it would mean that I need to download that whole site over and over again.</p>
<p>Is there an easy way to switch between tags and have subversion only update the differences between those tags?</p>
|
<p>There actually is a switch function that does just that. I use TortiseSVN which is a windows shell/gui for Subversion, so I'm not familiar with how to do it manually, but this looks like it should help:</p>
<p><a href="http://svnbook.red-bean.com/en/1.1/ch04s05.html">http://svnbook.red-bean.com/en/1.1/ch04s05.html</a></p>
|
Good examples or documentation of XIFF implementation? <p><a href="http://www.igniterealtime.org/projects/xiff/" rel="nofollow">XIFF</a> is an implemenation of the <a href="http://en.wikipedia.org/wiki/Jabber" rel="nofollow">XMPP</a> protocol in actionscript.</p>
<p>So far, all the examples and documentation I have seen are sparse. Does anyone know a good explanation of the most recent version of XIFF and/or good examples of working Flex/AIR applications? </p>
|
<p>Yeah, there are not a ton of good examples / docs online.</p>
<p>Check out:</p>
<p><a href="http://www.mikechambers.com/blog/index.php?s=xiff" rel="nofollow">http://www.mikechambers.com/blog/index.php?s=xiff</a></p>
<p>for a couple of examples that show how to get started.</p>
<p>mike</p>
|
Simplifying VisualSVN Server's URLs <p>We're currently running an <code>svnserve</code> instance as NT service. While this works, it's needlessly cumbersome to administer, and I'd like to move on to the much simpler VisualSVN Server. (Bonus side benefits include Windows-integrated authentication and, thanks to HTTP/WebDAV, browsing of the latest revision.)</p>
<p>That said, the current server offers up URLs that look like this:</p>
<pre><code>svn://oldserver/path/to/some/file.foo
</code></pre>
<p>Rather memorable.</p>
<p>The new one, as set up through VSVNS:</p>
<pre><code>https://newserver:8443/svn/Repos/path/to/some/file.foo
</code></pre>
<p>Ouch. For one, the <code>/svn</code> bit is <em>entirely</em> unnecessary. Since VSVNS runs its own HTTP server (that's why it's on the special port <code>8443</code>, after all), <em>of course</em> everything is related to <code>svn</code>. Moreover, we only have one repository (and no real need for more), so the repository name in <code>/Repos</code> shouldn't be there either â we could turn this off with <code>svnserve</code>, so there should be a way to do it now, too.</p>
<ul>
<li>Is it possible to configure VisualSVN Server to drop the <code>/svn</code>? (Why is it there to begin with?)</li>
<li>Given that there is only one repository, can I tell it not to make the repository name part of the URL?</li>
</ul>
|
<p>You can configure the apache location to use <strong>SVNPath</strong> instead of <strong>SVNParentPath</strong>.
It is inside the <Location>-Block of your httpd.conf
you also should rename this block to the name of your repository. Then the ../svn/.. part of your URL is gone.</p>
|
What will the pNext pointer be in the following case using C? <pre><code>func()
{
Object* pNext;
func1(pNext);
}
func1(Object* pNext)
{
pNext = Segement->GetFirstPara(0);
}
</code></pre>
<p>I was expecting it to be pointer to firstpara returned from func1() but I'm seeing NULL can some explain and how to fix it to actually return the firstpara() pointer?</p>
|
<p>For C++ only, you can make the parameter a reference</p>
<pre><code>func()
{
Object* pNext;
func1(pNext);
}
func1(Object*& pNext)
{
pNext = Segement->GetFirstPara(0);
}
</code></pre>
<p>What is going on here is the difference between passing parameters by value and passing by reference. C always passes by value. In order to get a value back, the value needs to be a reference value (e.g. Object** refers to Object* as a pointer). C++ adds reference parameters (signified by the &).
Pass by value only passes a copy of the data and never the actual data itself. That is why the variable used in the function call was not updated in the function.</p>
|
Has anyone used/created "fisheye" table columns? <p>Has anyone ever given table columns the "fisheye" effect? Im talking about an expanding effect of the table columns when hovering the mouse over them. I'd love to see some code if anyone has tried this.</p>
<p>EDIT: ...or an accordian effect</p>
|
<p>It's not for a table, but here is the effect:</p>
<p><a href="http://safalra.com/web-design/javascript/mac-style-dock/" rel="nofollow">http://safalra.com/web-design/javascript/mac-style-dock/</a></p>
|
Writing a compiler in its own language <p>Intuitively, it would seems that a compiler for language Foo, cannot itself be written in Foo. More specifically, the <em>first</em> compiler for language Foo cannot be written in Foo, but any subsequent compiler could be written for Foo.</p>
<p>But is this actually true? I have some very vague recollection of reading about a language whose first compiler was written in "itself". Is this possible, and if so how?</p>
|
<p>This is called "bootstrapping". You must first build a compiler (or interpreter) for your language in some other language (usually Java or C). Once that is done, you can write a new version of the compiler in language Foo. You use the first bootstrap compiler to compile the compiler, and then use this compiled compiler to compile everything else (including future versions of itself).</p>
<p>Most languages are indeed created in this fashion, partially because language designers like to use the language they are creating, and also because a non-trivial compiler often serves as a useful benchmark for how "complete" the language may be.</p>
<p>An example of this would be Scala. Its first compiler was created in Pizza, an experimental language by Martin Odersky. As of version 2.0, the compiler was completely re-written in Scala. From that point on, the old Pizza compiler could be completely discarded, due to the fact that the new Scala compiler could be used to compile itself for future iterations.</p>
|
Best approach for using AJAX loaders? <p>I've implemented a few poor solutions for bringing up an AJAX loader before dynamically updating a content DIV, but none seem to be "universal", and I find each time I do it I'm reworking it. If I have a DIV with content that updates depending on what a user clicks on the page, and I want to display the loader over this content DIV, what is the best approach? I've seen some developers have the loader always on the page, and they just display it block or none, and I've seen others append it to the DIV. What about when you also have multiple areas that can update? I'm thinking something repeatable that I can call with a function, maybe passing a few parameters.</p>
|
<p>Some JavaScript libraries allow listening to opening and closing requests. Check out Prototype's request Responder <a href="http://www.prototypejs.org/api/ajax/responders" rel="nofollow">http://www.prototypejs.org/api/ajax/responders</a>.</p>
<p>You would do something like this:</p>
<pre><code>Ajax.Responders.register({
onCreate: function() {
$('loader').show();
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
if (Ajax.activeRequestCount < 1) $('loader').hide();
}
});
</code></pre>
<p>As for visual representation of loading, you may want to identify the different parts of your page which may require separate loading graphics and subclass the Request object, each time indicating the type of request.</p>
<p>E.g.<br />
Is it a field being saved? <code>new FieldUpdateRequest(field)</code><br />
Is it the page being loaded? <code>new Request();</code><br />
Is a container being updated? <code>new PartialRequest(div);</code></p>
<p>Then capture each subclasses type and show or hide a different loader graphic.</p>
<p>There is unfortunately no quick solution, hal. You could build a generic script for appending loader graphics to containers, that should save you some repetition. If you do, mind posting it here :)?</p>
|
IIS 6 Tuning Guide? <p>I have been a developer for 10+ years and so far my IIS knowledge is just enough for deploying stuff on it and get it running. Recently I have been playing with IIS 6 and realize the huge difference on the worker process model. I think I would need some good guide to update my knowledge in this area. Any good article/book recommendation?</p>
|
<p><a href="http://iistuner.codeplex.com" rel="nofollow">IIS Tuner</a> is an open source tool for tuning IIS 6, 7 and 7.5 </p>
|
How to find all the tables in MySQL with specific column names in them? <p>I have 2-3 different column names that I want to look up in the entire DB and list out all tables which have those columns. Any easy script?</p>
|
<p>To get all tables with columns <code>columnA</code> or <code>ColumnB</code> in the database <code>YourDatabase</code>:</p>
<pre><code>SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('columnA','ColumnB')
AND TABLE_SCHEMA='YourDatabase';
</code></pre>
|
How can I upload files without using an HTML <form>? <p>in a web application I am building I need to upload photos without using a form, otherwise it will come up with form embedded in an outer from which is not permitted in XHTML.</p>
<p>I think uploading files is what jQuery.post should be able to do, but I currently can't figure out how to do this using jQuery.</p>
|
<p>take a look at <a href="http://swfupload.org/" rel="nofollow">swfupload</a>, it's a pretty nifty little app that should accomplish what you want. otherwise, you could separate out the forms, and just use css/javascript to reposition them if necessary.</p>
|
Flexibility in the project scope? <p>How flexible should a programmer be if a client requests requirements that is not in the project scope?</p>
|
<p>General perspective:</p>
<p>You need to earn a living; the client needs a computing solution: the client has the right to make sure that the solution you will supply fits his needs. Changes and additions after and agreement has been reached, reflects on your ability to analyze the user's requirements into a system design, in that failed to investigate those requirements to sufficient depth and detail: you need to do this meticulously and obtain a written sign-off agreement on your system design from the client.</p>
<p>Legal perspective:</p>
<p>You should pin the scope of the project down, and get the client to sign an agreement of that scope. Once you have that agreement, anything not covered by it constitutes a new project.</p>
<p>Business perspective:</p>
<p>Do you want to continue doing business (with the current as well as future clients)? You need to do an evaluation of the impact adding the new required functionality will have on the current project: if the impact is small, then do it, but tell the client - in writing - that you are doing him a favor; if the impact is larger then you must negotiate with the client, outlining the issues, and either adapt your current agreement, or make a new one. What you do not want to do is to antagonize your client.</p>
<p>Lastly: "The client is always right." - (up to the point where you have to give up and just go away.)</p>
|
Check if SoundChannel is playing sound <p>How to check reliably if a SoundChannel is still playing a sound? </p>
<p>For example,</p>
<pre><code>[Embed(source="song.mp3")]
var Song: Class;
var s: Song = new Song();
var ch: SoundChannel = s.play();
// how to check if ch is playing?
</code></pre>
|
<p>I've done a little research and I can't find a way to query any object to determine if a sound is playing. You'll have to write a wrapper class and manage it yourself it seems.</p>
<pre><code>
package
{
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
public class SoundPlayer
{
[Embed(source="song.mp3")]
private var Song:Class;
private var s:Song;
private var ch:SoundChannel;
private var isSoundPlaying:Boolean;
public function SoundPlayer()
{
s = new Song();
play();
}
public function play():void
{
if(!isPlaying)
{
ch = s.play();
ch.addEventListener(
Event.SOUND_COMPLETE,
handleSoundComplete);
isSoundPlaying = true;
}
}
public function stop():void
{
if(isPlaying)
{
ch.stop();
isSoundPlaying = false;
}
}
private function handleSoundComplete(ev:Event):void
{
isSoundPlaying = false;
}
}
}
</code></pre>
|
How do I properly store and retrieve internationalized Strings in properties files? <p>I'm experimenting with internationalization by making a Hello World program that uses properties files + ResourceBundle to get different strings.</p>
<p>Specifically, I have a file "messages_en_US.properties" that stores "hello.world=Hello World!", which works fine of course.</p>
<p>I then have a file "messages_ja_JP.properties" which I've tried all sorts of things with, but it always appears as some type of garbled string when printed to the console or in Swing. The problem is obviously with the reading of the content into a Java string, as a Java string in Japanese typed directly into the source can print fine.</p>
<p>Things I've tried:</p>
<ul>
<li>The .properties file in UTF-8 encoding with the Japanese string as-is for the value. Something I read indicates that Java expects a properties file to be in the native encoding of the system...? It didn't work either way.</li>
<li>The file in default encoding (ISO-8859-1) and the value stored as escaped Unicode created by the native2ascii program included with Java. Tried with a source file in various Japanese encodings... SHIFT-JIS, EUC-JP, ISO-2022-JP.</li>
</ul>
<p><strong>Edit:</strong></p>
<p>I actually figured this out while I was typing this, but I figured I'd post it anyway and answer it in case it helps anyone.</p>
|
<p>I realized that native2ascii was assuming (surprise) that it was converting from my operating system's default encoding each time, and as such not producing the correct escaped Unicode string.</p>
<p>Running native2ascii with the "-encoding <em>encoding_name</em>" option where <em>encoding_name</em> was the name of the source file's encoding (SHIFT-JIS in this case) produced the correct result and everything works fine.</p>
<p>Ant also has a native2ascii task that runs native2ascii on a set of input files and sends output files wherever you want, so I was able to add a builder that does that in Eclipse so that my source folder has the strings in their original encoding for easy editing and building automatically puts converted files of the same name in the output folder.</p>
|
"suggest" feature for textboxes in a rails app <p>I'm looking for an easiest way how to implement the "suggest" feature for a text entry field in a Rails application. The idea is to complete names stored in a database column, giving the user a drop-down menu of possible matches as he types.</p>
<p>Thanks for any suggestions!</p>
|
<p>Rails makes 'suggest'-style auto completion on text fields really easy using the <code>text_field_with_auto_complete</code> method.</p>
<p>In Rails 1.x this method was built into <a href="http://api.rubyonrails.com/classes/ActionView/Helpers/JavaScriptMacrosHelper.html"><code>ActionView::Helpers::JavaScriptMacrosHelper</code></a>, but for Rails 2.x it was moved to <a href="http://github.com/rails/auto_complete.git/">a separate plugin</a>.</p>
<p>Let's say you have a model called <code>Post</code> which has a text field called <code>title</code>. In your view, where you would normally use <code>text_field_tag</code> (or <code>f.text_field</code>), just use <code>text_field_with_auto_complete</code> instead:</p>
<pre><code><%= text_field_with_auto_complete :post, :title %>
</code></pre>
<p>Additionally, in <code>PostsController</code>, you have to make a corresponding declaration:</p>
<pre><code>class PostsController < ApplicationController
auto_complete_for :post, :title
end
</code></pre>
<p>What this does behind the scenes is dynamically add an action called <code>auto_complete_for_[object]_[method]</code> to the controller. In the above example this action will be called <code>auto_complete_for_post_title</code>. </p>
<p>It's worth pointing out that the <code>find</code> call used by this auto-generated action will act across <em>all</em> model objects, e.g. <code>Post.find(:all, ...)</code>. If this isn't the behaviour you want (for example, if want to restrict the search to a specific subset of <code>Post</code>s based on the logged in user) then you have to define your own <code>auto_complete_for_[object]_[method]</code> action in your controller.</p>
|
How to parse a .xfa file <p>Hoping that someone has some info on how to parse a xfa file. I can parse csv or xml files just fine, but an xfa one has come along and I'm not familar with the format. Looks like tab delimited body with column metadata at the top.</p>
<p>Anyone dealt with these before or can give me a steer on how to parse them?</p>
<p>I use vb.net but the language of any solution isn't too relevant.</p>
<p>Much appreciated.</p>
|
<p>Mmm, looks like nobody has a clue. The problem is that .xfa doesn't look like a "standard" extension: after all, anybody can create its own extension names, from .xyz to .something...</p>
<p>I looked around a bit, found, unsurprisingly (the 'x') an XML format with this extension, not much more.</p>
<p>Indicating where this kind of file come from, what kind of data it holds, might help. Or not.</p>
<p>You describe the file as being a simple TSV (tab separated values) with a header. It is quite trivial to parse, with a tokenizer or some regex, so I am not sure where you are stuck.</p>
|
Creating standalone Lua executables <p>Is there an easy way to create standalone .exe files from Lua scripts? Basically this would involve linking the Lua interpreter and the scripts.</p>
<p>I believe it is possible (PLT Scheme allows the creation of standalone executables in the same way), but how, exactly?</p>
|
<p>Check out for <a href="http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#srlua">srlua</a>. It does what you need. </p>
<p>It's from one of the Lua authors. On this address there is also pre-compiled Windows binaries, so that would be even easier for you I think.</p>
|
2D Javascript array <p>Simply put, is there a way to create a 2D javascript array using similar syntax to this?</p>
<pre><code>var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
</code></pre>
|
<p>You can create any n-dimensional arrays using <em>exactly</em> the format you suggest as in the following sample:</p>
<pre><code><script>
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
var newArray3d =
[[[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]],
[[10, 11, 12],[13, 14, 15],[16, 17, 18]],
[[20, 21, 22],[23, 24, 25],[26, 27, 28]]]
alert(newArray[0]);
alert(newArray[0][2]);
alert(newArray3d[0]);
alert(newArray3d[1][0]);
alert(newArray3d[1][0][2]);
</script>
</code></pre>
<p>The alert boxes return, in sequence:</p>
<pre><code>0,1,2
2
0,1,2,3,4,5,6,7,8
10,11,12
12
</code></pre>
|
HTML in an ASP.NET Dynamic Data MultilineText Control <p>I'm trying to enter a little bit of HTML into an ASP.NET Dynamic Data MultilineText_Edit control, just a couple of <code><br></code> tags to have line breaks when I output the value of the column on a web page. </p>
<p>However, when I try to click the "Update" link on the Dynamic Data edit page, nothing happens. I don't even get an error message, which I would expect if HTML input were not allowed via some rule the control has built in. As soon as I remove the tag, the update link works correctly. It's not a column size issue, I can add a bunch more characters to the input and everything works fine. </p>
<p>Is HTML input not allowed in these controls, or is there something else going on? If there is some kind of validation rule, can it be turned off? Or is there something in the database that I need to set? Should I use something other than the default multiline text template?</p>
|
<p>Input validation is a built in feature in ASP.NET 2.0 or later. I don't know why you are not getting an error, but check this out to see if it helps:</p>
<p><a href="http://www.asp.net/learn/whitepapers/request-validation/" rel="nofollow">http://www.asp.net/learn/whitepapers/request-validation/</a></p>
<p>Check these settings, on the page:</p>
<pre><code><%@ Page validateRequest="false" %>
</code></pre>
<p>or the web.config:</p>
<pre><code><configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
</code></pre>
|
In agile like development, who should write test cases? <p>Our team has a task system where we post small incremental tasks assigned to each developer. </p>
<p>Each task is developed in its own branch, and then each branch is tested before being merged to the trunk.</p>
<p>My question is: Once the task is done, who should define the <strong>test cases</strong> that should be done on this task? </p>
<p>Ideally I think the developer of the task himself is best suited for the job, but I have had a lot of resistance from developers who think it's a waste of their time, or that they simply don't like doing it. </p>
<p>The reason I don't like having my QA people do it, is because I don't like the idea of them creating their own work. For example they might leave out things that are simply too much work to test, and they may not know the technical detail that is needed. </p>
<p>But likewise, the down part of developers doing the test cases, is that they may leave out things that they think will break. (even subconsciously maybe) </p>
<p>As the project manager, I ended up writing the test cases for each task myself, but my time is taxed and I want to change this.</p>
<p>Suggestions?</p>
<p><strong>EDIT: By test cases I mean the description of the individual QA tasks that should be done to the branch before it should be merged to the trunk. (Black Box)</strong></p>
|
<h2>The Team.</h2>
<p>If a defect gets to a customer, it is <strong><em>the team's</em></strong> fault, therefore <strong><em>the team</em></strong> should be writing test cases to assure that defects don't reach the customer.</p>
<ol>
<li><p><strong>The Project Manager (PM)</strong> should understand the domain better than anyone on the team. Their domain knowledge is <em>vital</em> to having test cases that make sense with regard to the domain. They will need to provide example inputs and answer questions about expectations on invalid inputs. They need to provide at least the 'happy path' test case.</p></li>
<li><p><strong>The Developer(s)</strong> will know the code. You suggest the developer may be best for the task, but that you are looking for black box test cases. Any tests that a developer comes up with are white box tests. That is the advantage of having developers create test cases – they know where the seams in the code are. </p>
<p>Good developers will also be coming to the PM with questions "What should happen when...?" – each of these is a test case. If the answer is complex "If <em>a</em> then <em>x</em>, but if <em>b</em> then <em>y</em>, except on Thursdays" – there are multiple test cases.</p></li>
<li><p><strong>The Testers (QA)</strong> know how to test software. Testers are likely to come up with test cases that the PM and the developers would not think of – that is why you have testers.</p></li>
</ol>
|
Show file tree in visual studio 2005? <p>I have a large project that I want to start using visual studio 2005 to edit. I want to tell it "Here are all the files I want you to track, now get on with it" and have them displayed as a directory tree, for example:</p>
<pre><code>Folder 1
- File A
- File B
- File C
Folder 2
- Folder 3
- File X
- File Y
- File D
- File E
</code></pre>
<p>Right now it's just showing all the header files in one big list, and all the source files in one big list, which I find unhelpful. I also don't want to spend ages creating a folder in the project for each folder on the disk.</p>
<p>Is there any way I can get VS to show me a source tree of everything in the solution, organised by where it is on the actual disk?</p>
<p>Thanks.</p>
|
<p>click on the 'show all files' icon in the solution explorer, then select the folders you want to include, right click and select 'include in project'.</p>
|
How do I use LINQ Contains(string[]) instead of Contains(string) <p>I got one big question.</p>
<p>I got a linq query to put it simply looks like this:</p>
<pre><code>from xx in table
where xx.uid.ToString().Contains(string[])
select xx
</code></pre>
<p>The values of the <code>string[]</code> array would be numbers like (1,45,20,10,etc...)</p>
<p>the Default for <code>.Contains</code> is <code>.Contains(string)</code>.</p>
<p>I need it to do this instead: <code>.Contains(string[])</code>...</p>
<p><strong>EDIT :</strong> One user suggested writing an extension class for <code>string[]</code>. I would like to learn how, but any one willing to point me in the right direction?</p>
<p><strong>EDIT :</strong> The uid would also be a number. That's why it is converted to a string.</p>
<p>Help anyone?</p>
|
<p>spoulson has it nearly right, but you need to create a <code>List<string></code> from <code>string[]</code> first. Actually a <code>List<int></code> would be better if uid is also <code>int</code>. <code>List<T></code> supports <code>Contains()</code>. Doing <code>uid.ToString().Contains(string[])</code> would imply that the uid as a string contains all of the values of the array as a substring??? Even if you did write the extension method the sense of it would be wrong. </p>
<p><strong>[EDIT]</strong></p>
<p>Unless you changed it around and wrote it for <code>string[]</code> as Mitch Wheat demonstrates, then you'd just be able to skip the conversion step. </p>
<p><strong>[ENDEDIT]</strong> </p>
<p>Here is what you want, if you don't do the extension method (unless you already have the collection of potential uids as ints -- then just use <code>List<int>()</code> instead). This uses the chained method syntax, which I think is cleaner, and
does the conversion to int to ensure that the query can be used with more providers.</p>
<pre><code>var uids = arrayofuids.Select(id => int.Parse(id)).ToList();
var selected = table.Where(t => uids.Contains(t.uid));
</code></pre>
|
How can I split multiple joined words? <p>I have an array of 1000 or so entries, with examples below:</p>
<pre><code>wickedweather
liquidweather
driveourtrucks
gocompact
slimprojector
</code></pre>
<p>I would like to be able to split these into their respective words, as:</p>
<pre><code>wicked weather
liquid weather
drive our trucks
go compact
slim projector
</code></pre>
<p>I was hoping a regular expression my do the trick. But, since there is no boundary to stop on, nor is there any sort of capitalization that I could possibly key on, I am thinking, that some sort of reference to a dictionary might be necessary? </p>
<p>I suppose it could be done by hand, but why - when it can be done with code! =) But this has stumped me. Any ideas? </p>
|
<p>The <a href="http://en.wikipedia.org/wiki/Viterbi_algorithm">Viterbi algorithm</a> is much faster. It computes the same scores as the recursive search in Dmitry's answer above, but in O(n) time. (Dmitry's search takes exponential time; Viterbi does it by dynamic programming.)</p>
<pre><code>import re
from itertools import groupby
def viterbi_segment(text):
probs, lasts = [1.0], [0]
for i in range(1, len(text) + 1):
prob_k, k = max((probs[j] * word_prob(text[j:i]), j)
for j in range(max(0, i - max_word_length), i))
probs.append(prob_k)
lasts.append(k)
words = []
i = len(text)
while 0 < i:
words.append(text[lasts[i]:i])
i = lasts[i]
words.reverse()
return words, probs[-1]
def word_prob(word): return dictionary.get(word, 0) / total
def words(text): return re.findall('[a-z]+', text.lower())
dictionary = dict((w, len(list(ws)))
for w, ws in groupby(sorted(words(open('big.txt').read()))))
max_word_length = max(map(len, dictionary))
total = float(sum(dictionary.values()))
</code></pre>
<p>Testing it:</p>
<pre><code>>>> viterbi_segment('wickedweather')
(['wicked', 'weather'], 5.1518198982768158e-10)
>>> ' '.join(viterbi_segment('itseasyformetosplitlongruntogetherblocks')[0])
'its easy for me to split long run together blocks'
</code></pre>
<p>To be practical you'll likely want a couple refinements:</p>
<ul>
<li>Add logs of probabilities, don't multiply probabilities. This avoids floating-point underflow.</li>
<li>Your inputs will in general use words not in your corpus. These substrings must be assigned a nonzero probability as words, or you end up with no solution or a bad solution. (That's just as true for the above exponential search algorithm.) This probability has to be siphoned off the corpus words' probabilities and distributed plausibly among all other word candidates: the general topic is known as smoothing in statistical language models. (You can get away with some pretty rough hacks, though.) This is where the O(n) Viterbi algorithm blows away the search algorithm, because considering non-corpus words blows up the branching factor.</li>
</ul>
|
What is the best way to use JavaDoc to document a Java enum? <p>I've just started using Java's enums in my own projects (I have to use JDK 1.4 at work) and I am confused as to the best practice of using JavaDoc for an enum.</p>
<p>I have found that this method works, but the resultant code is a little unrefined:</p>
<pre><code>/**
* Doc for enum
*/
public enum Something {
/**
* First thing
*/
FIRST_THING,
/**
* Second thing
*/
SECOND_THING;
//could continue with more
}
</code></pre>
<p>Is there any way I could break up the enum declarations on their own lines without chaining them by commas, or is this the best approach for using JavaDoc for an enum?</p>
|
<p>To answer the first part of your question, you do have to separate each enum value with a comma. As far as I know, there's no way around that.</p>
<p>Personally I don't have a problem with the code the way you've presented it. Seems like a perfectly reasonable way to document an enum to me.</p>
|
What is the quickest way to detect an unreachable host in Java? <p>I would like the fastest and most accurate function <code>boolean isReachable(String host, int port)</code> that passes the following JUnit tests under the conditions below. Timeout values are specified by the JUnit test itself, and may be considered "unreachable."</p>
<p><strong>Please note:</strong> All answers must be platform-independent. This means that <code>InetAddress.isReachable(int timeout)</code> is not going to work, since it relies on port <code>7</code> to do a ping on Windows (ICMP ping being an undocumented function on Windows), and this port is blocked in this setup.</p>
<p>LAN Setup:</p>
<ul>
<li><code>thisMachine</code> (<code>192.168.0.100</code>)</li>
<li><code>otherMachine</code> (<code>192.168.0.200</code>)</li>
<li><strong>no</strong> machine is called <code>noMachine</code> or has the IP <code>192.168.0.222</code> (always unreachable)</li>
<li>both machines are running Apache Tomcat on port <code>8080</code>; all other ports are unreachable (including port <code>7</code>)</li>
<li><code>example.com</code> (<code>208.77.188.166</code>) is running a webserver on port <code>80</code> and is only reachable when the LAN is connected to the Internet</li>
</ul>
<p>Occasionally, the LAN is disconnected from the Internet in which case only local machines called by IP address are reachable (all others are unreachable; there's no DNS).</p>
<p><strong>All tests are run on <code>thisMachine</code>.</strong></p>
<pre><code>@Test(timeout=1600) // ~320ms per call (should be possible to do better)
public void testLocalhost() {
// We can always reach ourselves.
assertTrue(isReachable("localhost", 8080));
assertTrue(isReachable("127.0.0.1", 8080));
assertTrue(isReachable("thisMachine", 8080)); // Even if there's no DNS!
assertTrue(isReachable("192.168.0.100", 8080));
assertFalse(isReachable("localhost", 80)); // Nothing on that port.
}
@Test(timeout=5500) // ~1867ms per call (should be able to do better)
public void testLAN() {
assertTrue(isReachable("192.168.0.200", 8080)); // Always connected to the LAN.
assertFalse(isReachable("192.168.0.222", 8080)); // No such a machine.
assertFalse(isReachable("noMachine", 8080)); // No such machine.
}
</code></pre>
<p>The following test is only run when the LAN is <strong>disconnected</strong> from the Internet.</p>
<pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testNoDNS() {
assertFalse(isReachable("otherMachine", 8080)); // No DNS.
assertFalse(isReachable("example.com", 80)); // No DNS & no Internet.
assertFalse(isReachable("208.77.188.166", 80)); // No Internet.
}
</code></pre>
<p>The following test is only run when the LAN is <strong>connected</strong> to the Internet.</p>
<pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testHaveDNS() {
assertTrue(isReachable("otherMachine", 8080)); // DNS resolves local names.
assertTrue(isReachable("example.com", 80)); // DNS available.
assertTrue(isReachable("208.77.188.166", 80)); // Internet available.
}
</code></pre>
|
<p>Firstly you need to recognise that you have <em>potentially</em> conflicting requirements; IP sockets are not time deterministic. The quickest you can ever detect unreachability is after your elapsed timeout. You can only detect reachability quicker.</p>
<p>Assuming reachability/isReachable is your real objective, you should just use a straightforward non-blocking socket IO as shown in the <a href="http://java.sun.com/j2se/1.4.2/docs/guide/nio/example/Ping.java" rel="nofollow">Java Ping</a> simulator, the example connects to the time service but would work equally well on 8080.</p>
|
How to raise an event from a SWF in a SWFLoader to a parent Flex application? <p>How can I raise an event from a SWF file loaded into a Flex application (using SWFLoader)?</p>
<p>I want to be able to detect</p>
<pre><code>a) when a button is pressed
b) when the animation ends
</code></pre>
|
<p>You'll need to do 2 things:</p>
<ol>
<li>Dispatch an event from the loaded swf. Make sure the event bubbles if you sent it from nested views. Bubbling can be set through the bubbles property of the event.</li>
<li><p>Listen to the event from your main application. I think you should be able to do that on the content property of the SWFLoader instance.</p>
<pre><code>mySWFLoader.content.addEventListener("myEvent", myEventHandler);
</code></pre></li>
</ol>
|
How do I check if a tag exists in XSLT? <p>I have the following template</p>
<pre><code><h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>
</code></pre>
<p>I would like to only display the headers (one,two,three) if there is at least one member of the corresponding template. How do I check for this?</p>
|
<pre><code><xsl:if test="one">
<h2>one</h2>
<xsl:apply-templates select="one"/>
</xsl:if>
<!-- etc -->
</code></pre>
<p>Alternatively, you could create a named template,</p>
<pre><code><xsl:template name="WriteWithHeader">
<xsl:param name="header"/>
<xsl:param name="data"/>
<xsl:if test="$data">
<h2><xsl:value-of select="$header"/></h2>
<xsl:apply-templates select="$data"/>
</xsl:if>
</xsl:template>
</code></pre>
<p>and then call as:</p>
<pre><code> <xsl:call-template name="WriteWithHeader">
<xsl:with-param name="header" select="'one'"/>
<xsl:with-param name="data" select="one"/>
</xsl:call-template>
</code></pre>
<p>But to be honest, that looks like more work to me... only useful if drawing a header is complex... for a simple <code><h2>...</h2></code> I'd be tempted to leave it inline.</p>
<p>If the header title is always the node name, you could simplifiy the template by removing the "$header" arg, and use instead:</p>
<pre><code><xsl:value-of select="name($header[1])"/>
</code></pre>
|
Professional jQuery based Combobox control? <p>Are there any <strong>professional</strong> Combobox controls (dropdown list with autosuggestion) based on the jQuery library?</p>
<p>It should be able to handle <strong>large datasets</strong> and have some <strong>skinning</strong> options. A <strong>multi-column result list</strong> would be great too. I'm working with ASP.NET, but it's a not a problem if I had to write a wrapper for it.</p>
<p><img src="http://i.stack.imgur.com/ilhvD.png" alt="alt text"></p>
<p><em>I'm already using a third-party control, but I ran into some compatibilty issues between two vendor's controls. Well, I want to get rid of this kind of dependencies.</em></p>
|
<p>Here's one that looks very promising. It's a true combo - you see what you type. Has a cool feature I haven't seen elsewhere: paging results. </p>
<p><a href="http://www.codeplex.com/flexbox">FlexBox</a></p>
|
ASP.NET, XSLT and dynamic controls <p>I wish to use xml and xsl to generate controls on an asp.net page.</p>
<p>I currently have a asp.net content page that contains a xml control. When the page is loaded, an xml file is loaded and the required element is extracted and set as the xml control's DocumentContent and the xml control's TransformSource is set to the appropriate xsl file.</p>
<p>In the xsl file, I wish to use templates to create asp.net controls depending upon the contents of the xml. Is there an easy way of doing this with the xml control on the content page?</p>
|
<p>Register a namespace in your XSL so that you can put .NET server-side tags into it. Run your XSL transform against your XML. Run the result of your transform through Page.ParseControls(). This will give you a nice control hierarchy. Add the output of that function to your Controls collection (or the controls collection of your placeholder) and you're good to go.</p>
<p>There are LOTS of caveats to using dynamic controls in .NET, so beware.</p>
|
How to log in an Oracle database? <p>I am interested in what methods of logging is frequent in an Oracle database.
Our method is the following:</p>
<p>We create a log table for the table to be logged. The log table contains all the columns of the original table plus some special fields including timestamp, modification type (insert, update, delete), modifier's id. A trigger on the original table creates one log row for each insertion and deletion, and two rows for a modification. Log rows contain the data before and after the alteration of the original one.</p>
<p>Although state of the records can be mined back in time using this method, it has some drawbacks:</p>
<ul>
<li>Introduction of a new column in the original table does not automatically involves log modification.</li>
<li>Log modification affects log table and trigger and it is easy to mess up.</li>
<li>State of a record at a specific past time cannot be determined in a straightforward way.</li>
<li>...</li>
</ul>
<p>What other possibilities exist?
What kind of tools can be used to solve this problem?</p>
<p>I only know of <a href="http://log4plsql.sourceforge.net/" rel="nofollow">log4plsql</a>. What are the pros/cons of this tool?</p>
<p>Edit: Based on Brian's answer I have found the following <a href="http://www.oracle-base.com/articles/10g/Auditing_10gR2.php" rel="nofollow">reference</a> that explains standard and fine grain auditing.</p>
|
<p>It sounds like you are after 'auditing'. Oracle has a built-in feature called Fine Grain Auditing (FGA). In a nutshell you can audit everything or specific conditions. What is really cool is you can 'audit' selects as well as transactions. Simple command to get started with auditing:</p>
<pre><code>audit UPDATE on SCOTT.EMP by access;
</code></pre>
<p>Think of it as a 'trigger' for select statements. For example, you create policies:</p>
<pre><code>begin
dbms_fga.add_policy (
object_schema=>'BANK',
object_name=>'ACCOUNTS',
policy_name=>'ACCOUNTS_ACCESS'
);
end;
</code></pre>
<p>After you have defined the policy, when a user queries the table in the usual way, as follows:</p>
<pre><code>select * from bank.accounts;
</code></pre>
<p>the audit trail records this action. You can see the trail by issuing:</p>
<pre><code>select timestamp,
db_user,
os_user,
object_schema,
object_name,
sql_text
from dba_fga_audit_trail;
TIMESTAMP DB_USER OS_USER OBJECT_ OBJECT_N SQL_TEXT
--------- ------- ------- ------- -------- ----------------------
22-OCT-08 BANK ananda BANK ACCOUNTS select * from accounts
</code></pre>
|
TransactionScope bug in .NET? More information? <p>I have read (or perhaps heard from a colleague) that in .NET, TransactionScope can hit its timeout and then VoteCommit (as opposed to VoteRollback). Is this accurate or hearsay? I couldn't track down information on the web that talked about this issue (if it IS an issue), so I wonder if anyone has any direct experience with it and can shed some light?</p>
|
<p>The behaviour that Marc Gravell described has been changed in .Net 4.0. Instead of the operation being autocommitted, it will now throw an InvalidOperationException. So in 4.0 you no longer need to use Explicit Unbind.</p>
|
Do you use the 'My' namespace in VB.NET? <p>VB.NET has the "my" namespace, but how many VB.NET developers actually use it?</p>
<ul>
<li>if you don't, why? </li>
<li>if you are using it, why?</li>
</ul>
<p>I'm considering building a framework for VB.NET, and using the My namespace to plug it into VB seems like a reasonable idea. Is it?</p>
|
<p>The purpose of My, as I understand it, is to be an easy shortcut to certain API tasks that are common but hard-to-find or hard-to-use. You probably shouldn't completely subsume your framework under My. (For one thing, C# people using your framework may get grouchy.)</p>
<p>Instead, you should design it as a normal framework. When you're finished, make a list of some common tasks that people might want to use your framework for. See whether any of those could be useful to have under My, especially where there are classes or methods that can be used in a number of ways, but they have one or two really common usages that can be abbreviated with My.</p>
<p>This article shows how to extend My, and it has a section at the end that describes a few design guidelines to follow: <a href="http://msdn.microsoft.com/en-us/magazine/cc188706.aspx#S10">Simplify Common Tasks by Customizing the My Namespace</a></p>
<p>As to your main question, when coding in VB .NET, I use My as often as I can. It reduces a number of operations to one line of code.</p>
|
Unit testing a module that checks internet connectivity <p>I have a C# module responsible for acquiring the list of network adapters that are "connected to the internet" on a windows Vista machine. The module uses the "<a href="http://msdn.microsoft.com/en-us/library/aa370803(VS.85).aspx" rel="nofollow">Network List Manager API</a>" (or NLM API) to iterate over all network connections and returns all those for which the IsConnectedToInternet value is true.</p>
<p>I received some suggestions for the implementation of this module in this <a href="http://stackoverflow.com/questions/38864/how-do-you-find-out-which-nic-is-connected-to-the-internet">SO question</a></p>
<p>To test this module I've decided to write a helper that returns the list of internet connected interfaces based on another logic, so it would be a sort of a "reality check" for the original module's logic. Note that for the test helper I am willing to use detection methods that might be considered bad practice for production code (e.g. relying on some internet resource like "Google" to be available - in case it shuts down, blocked by our internal firewall etc. it's relatively easy to fix the test as opposed to a deployed product base).</p>
<p>The alternative detection method I chose was to try to connect to "www.google.com:80" with a TcpClient. My problem: When I have more than one connected adapter (e.g. both wireless and LAN) the detection method fails for one of them with the error "A connect request was made on an already-connected socket".</p>
<p>My question is three fold:</p>
<ol>
<li><p>How would you go about testing such a module in general? Do you support the idea of doing the same thing in a different way and comparing the results or is it an overkill and I should rely on the system's API? My main problem here, is that it's very hard to pre-configure the system so that I'll know what the expected results are in advance.</p></li>
<li><p>What alternative logic would you suggest? One thing that was suggested in the aforementioned question was looking at the routing table - what about considering each adapter that has a routing entry with a destination of 0.0.0.0 as "connected to the internet"? Other suggestions?</p></li>
<li><p>Do you understand why I get the "already-connected" error with the current test logic?</p></li>
</ol>
|
<p>I can only answer your question about the unit test.</p>
<p>The code you're testing is, in your own words, "a C# module responsible for acquiring the list of network adapters that are 'connected to the internet' on a windows Vista machine. The module uses the 'Network List Manager API' (or NLM API) to iterate over all network connections and returns all those for which the IsConnectedToInternet value is true."</p>
<p>If I were writing this module, I would first use an interface for the NLM API, call it...NLMAPIService. Now, for the real code, create an Adapter that implements NLMAPIService and adapts the real NLM API. </p>
<p>For testing, create a class FakeNLMAPI that implements NLMAPIService and has all of its data in-memory somewhere, or in an XML file, or whatever. Your module calls methods only on the NLMAPIService, so you don't have to change any "real" code depending on whether you're testing or not.</p>
<p>Therefore, in your test setup method, you can instantiate FakeNLMAPI and pass it to your module, and in production, instantiate your NLM API Adapter.</p>
<p>I'm going to assume that you can instantiate and modify the object that represents a network connection. If not, you can follow the same pattern for faking the actual network connection object.</p>
|
History data from IE <p>Where does Internet Explorer store the history data, i.e. the list of URL that have been visited? I am using Windows XP SP3 and IE7. Basically I would like to read the list of URL and make some statistics on how often what pages are visited.</p>
|
<p>Internet Explorer seems to keep its history in hidden directories under C:\Documents and Settings\USERNAME\Local Settings\History\History.IE5. Note that some directories in this path are also marked hidden or system. The history's format is opaque, but <a href="http://www.codeproject.com/KB/system/IECache.aspx" rel="nofollow">there's code at CodeProject</a> that can decode the contents. You can also find a list of typed URLs under HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\TypedURLs. </p>
<p>An easier alternative might be to setup an HTTP proxy between the IE and the internet, and then examine the proxy's log.</p>
|
What is spaghetti code? <p>Can you post a short example of real, overdone spaghetti code, possibly saying what it does? Can you show me a little debugger's nightmare?</p>
<p>I don't mean <a href="http://www0.us.ioccc.org/main.html" rel="nofollow">IOCCC</a> code, that is science fiction. I mean real life examples that happened to you...</p>
<h3>Update</h3>
<p>The focus has changed from "post some spaghetti code" to "what is <em>exactly</em> spaghetti code?". From a historical perspective, the current choices seem to be:</p>
<ul>
<li>old Fortran code using computed gotos massively</li>
<li>old Cobol code using the ALTER statement</li>
</ul>
|
<p>To me, a more <strong>modern</strong> example of spaghetti code is when you have 20 dlls and every DLL references each other in one way or another. Your dependency graph looks like a huge blob, and your code hops all over the place with no real order. Everything is inter-dependent.</p>
|
What is a SQL "pseudocolumn"? <p>I accidentally coded <code>SELECT $FOO..</code> and got the error "Invalid pseudocolumn "$FOO".</p>
<p>I can't find any documentation for them. Is it something I should know?</p>
<p>Edit: this is a MS SQL Server specific question.</p>
|
<p>Pseudocolumns are symbolic aliases for actual columns, that have special properties, for example, $IDENTITY is an alias for the column that has the IDENTITY assigned, $ROWGUID for the column with ROWGUIDCOL assigned. It's used for the internal plumbing scripts.</p>
|
Locating a file on the path <p>Does anybody know how to determine the location of a file that's in one of the folders specified by the PATH environmental variable other than doing a dir filename.exe /s from the root folder?</p>
<p>I know this is stretching the bounds of a programming question but this is useful for deployment-related issues, also I need to examine the dependencies of an executable. :-)</p>
|
<p>You can use the <code>where.exe</code> utility in the <code>C:\Windows\System32</code> directory.</p>
|
How do you do relative time in Rails? <p>I'm writing a Rails application, but can't seem to find how to do relative time, i.e. if given a certain Time class, it can calculate "30 seconds ago" or "2 days ago" or if it's longer than a month "9/1/2008", etc.</p>
|
<p>Sounds like you're looking for the <a href="http://apidock.com/rails/ActionView/Helpers/DateHelper/time_ago_in_words"><code>time_ago_in_words</code></a> method (or <a href="http://apidock.com/rails/ActionView/Helpers/DateHelper/distance_of_time_in_words"><code>distance_of_time_in_words</code></a>), from ActiveSupport. Call it like this:</p>
<pre><code><%= time_ago_in_words(timestamp) %>
</code></pre>
|
Test Driven Design for iPhone Native apps <p>I'm experimenting with the iPhone SDK and doing some TDD ala Dr. Nic's rbiPhoneTest project. I'm wondering how many, if any, have been successful using this or any other testing framework for iPhone/Cocoa? More important, I'd like to know how to best assert a proprietary binary request/response protocol. The idea is to send a binary request over the network and receive a binary response. Requests and responses are created using byte and'ing and or'ing. I'm using the golden copy pattern to test my request. Here's what I have so far. Don't laugh as I'm new to btoh Objective C and Ruby:</p>
<pre><code>require File.dirname(__FILE__) + '/test_helper'
require 'fileutils'
require 'io'
require "MyModel.bundle"
OSX::ns_import :MyModel
module MyTestExtensions
def is_absolute_path(path)
return /^\/.*/.match(path)
end
def parent_directory(file)
dir = file
if(! is_absolute_path(dir))
dir = File.expand_path(dir)
end
dir = File.dirname(dir)
assert is_absolute_path(dir), "Expecting an absolute path with #{dir}"
return dir
end
def assert_NSData_contains_bytes_from_file(file, data)
assert_not_nil data, "Data should not be nil."
assert data.bytes, "data should have bytes"
data.length.times { |i|
expected = file.getc
assert_not_nil expected, "Expected only #{i} bytes. Actual data contains more."
actual = data.bytes.int8_at(i)
assert_equal expected, actual, "Bytes should be equal at offset #{i} expected #{expected.chr} but was #{actual.chr}"
}
expected = file.getc
raise AssertionFailedError, "Expecting #{expected.chr} at offset #{data.length}" unless expected == nil
end
end
class TestMyModel < Test::Unit::TestCase
include OSX
include MyTestExtensions
def this_files_dir
return parent_directory(__FILE__)
end
def setup
@expectedReq = File.new("#{this_files_dir}/ExpectedMyReq")
# @expectedReq = File.new("#{this_files_dir}/hello.txt")
assert File.exist?("#{this_files_dir}/ExpectedMyReq"), "The file [#{@expectedReq.path}] should exist."
end
def test_my_model_class_exists
MyModel
end
def test_can_init_instance
assert MyModel.instancesRespondToSelector(:init), "MyModel Should define :init"
end
def test_my_model_can_request_my_data
myModel = MyModel.alloc.init
data = myModel.requestMyData 'Some query text'
assert_NSData_contains_bytes_from_file @expectedReq, data
end
end
</code></pre>
|
<p>I donât know much about Ruby or binary protocols, but if Youâre interested in unit testing on iPhone, You might want to check out the <a href="http://code.google.com/p/google-toolbox-for-mac/" rel="nofollow">Google Toolbox for Mac</a>. I am having great success testing my OpenGLÂ ES application with it.</p>
|
What are the main differences between XHTML and HTML? <p>What are the main differences between XHTML and HTML? Which one is better in your opinion, and why? Do most browsers support both?</p>
|
<p>This is probably the best article I've read on the differences and relative merits of each:</p>
<h2><a href="http://www.webstandards.org/learn/articles/askw3c/oct2003/">HTML Versus XHTML</a><br></h2>
<p><em>Which should we use, HTML or XHTML, and why?</em></p>
<p>There is also a rather technical comparison on the <a href="http://wiki.whatwg.org/wiki/HtmlVsXhtml">WHATWG wiki</a>.</p>
|
JavaScript slider <p>I need to create a 'slider' for a client's site. The slider should allow people to select how many items they want of x item, and show what the price will be based on that. The weird(ish) part is that the ratio of the price increase will go down as the amount of items goes up:</p>
<ul>
<li>1 item: $100</li>
<li>2 items: +90 = $190</li>
<li>3 items: + 80 = $270</li>
<li>4 items: + 70 = $340</li>
<li>5 items: + 60 = $400</li>
<li>6 items: + 50 = $450</li>
<li>7 items: + 50 = $500</li>
</ul>
<p>And all increases from then on are +50. This probably seems like an overly simplistic question, but does anyone know how I could go about doing this? I have almost no experience with JavaScript :( </p>
|
<p>Check out Yahoo! UI. they have a slider widget: <a href="http://developer.yahoo.com/yui/slider/">http://developer.yahoo.com/yui/slider/</a></p>
<p>The following example should get you started: <a href="http://developer.yahoo.com/yui/examples/slider/slider-ticks.html">http://developer.yahoo.com/yui/examples/slider/slider-ticks.html</a>.</p>
<p>All JavaScript frameworks (<a href="http://docs.jquery.com/UI/Slider">jQuery</a>, <a href="http://demos.mootools.net/Slider">MooTools</a>) seem to offer a slider. The YUI will give you a lot of control and a loader so you don't have to host the script on your server. Beware that YUI does not make implementation as painless as with the two other i mentioned.</p>
<p>Here is a MooTools example:</p>
<pre><code>// First example of http://demos.mootools.net/Slider
<div class="slider" id="myslider">
<div class="knob" style="position: relative;"/>
</div>
</code></pre>
<p>And the JavaScript:</p>
<pre><code>var el = $('myslider'); // The slider graphic
new Slider(el, el.getElement('.knob'), {
steps: 7, // There are 7 choices
range: [1, 7], // Minimum value is 1, maximum is 7
onChange: function(value){
// Calculation of the value goes here
}
});
</code></pre>
|
Programmatically send keystrokes to GLUT application <p>I have an OpenGL/GLUT program running on my linux machine that views a 3D model from various angles and can take screenshots, and everything is controlled from the keyboard. I want to write a script that moves around the model in a particular way, taking screenshots at every step. It seems there should be a simple way in Linux to send keystrokes to this application from a script. Anyone know how?</p>
|
<p>Take the GLUT source-code and make it remote controllable. One way to do this is to remove the function that polls the keyboard and let it poll a socket instead. Link the program with the existing program with the new library.</p>
<p>Afterwards you can establish a connection to the now remote-controllable program and set key-codes programmatically from your app.</p>
|
Is there a way I can retrieve sa password in sql server 2005 <p>I just forgot the password. Can anyone help me how to get back the password.</p>
|
<p>There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).</p>
<p>Start the SQL service again and use the new created login (recovery in my example)
Go via the security panel to the properties and change the password of the SA account.</p>
<p><img src="http://i.stack.imgur.com/6LttD.png" alt="enter image description here"></p>
<p>Now write down the new SA password.</p>
|
Java version names in Sun's bug database <p>In
<a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6525150" rel="nofollow">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6525150</a>
it says
Release Fixed 7(b14), 6u2(b01) (Bug ID:2147561)</p>
<p>What does 6u2 mean? (Am I right in assuming it as 1.6.0_02 ?) </p>
|
<p>yes, release 6 update 2. Also, (b01) is build 01</p>
|
Should I only store fixed-size data elements in a database? <p>If the amount of data stored within a given field of a database is unknown, and could be very large, should I store it in an external file rather than within a field in the database?</p>
|
<p>Do you need transactional semantics (commit, rollback) for the data? If so, then using the external file system greatly complicates life -- use the DBMS. If you don't need transactional semantics, then the file system may make sense.</p>
|
Can you write a block of c++ code inside C#? <p>I heard somewhere that you can drop down to C++ directly inside C# code.
How is this done? Or did I hear wrong?</p>
<p>Note: I do not mean C++ / CLI.</p>
|
<p>You might be thinking of <a href="http://msdn.microsoft.com/en-us/library/chfa2zb8(VS.71).aspx" rel="nofollow"><code>unsafe</code> blocks</a> where you can write code that looks a lot like C++, since you can use pointers.</p>
|
What's the best way to use SqlBulkCopy to fill a really large table? <p>Nightly, I need to fill a SQL Server 2005 table from an ODBC source with over 8 million records. Currently I am using an insert statement from linked server with syntax select similar to this:</p>
<pre><code>Insert Into SQLStagingTable from Select * from OpenQuery(ODBCSource, 'Select * from SourceTable')
</code></pre>
<p>This is really inefficient and takes hours to run. I'm in the middle of coding a solution using SqlBulkInsert code similar to the code found in <a href="http://stackoverflow.com/questions/127152/how-to-change-slow-parametrized-inserts-into-fast-bulk-copy-even-from-memory">this question</a>. </p>
<p>The code in that question is first populating a datatable in memory and then passing that datatable to the SqlBulkInserts WriteToServer method. </p>
<p>What should I do if the populated datatable uses more memory than is available on the machine it is running (a server with 16GB of memory in my case)?</p>
<p>I've thought about using the overloaded ODBCDataAdapter <a href="http://msdn.microsoft.com/en-us/library/59wzthcw(VS.80).aspx" rel="nofollow">fill</a> method which allows you to fill only the records from x to n (where x is the start index and n is the number of records to fill). However that could turn out to be an even slower solution than what I currently have since it would mean re-running the select statement on the source a number of times.</p>
<p>What should I do? Just populate the whole thing at once and let the OS manage the memory? Should I populate it in chunks? Is there another solution I haven't thought of?</p>
|
<p>The easiest way would be to use ExecuteReader() against your odbc data source and pass the <a href="http://msdn.microsoft.com/en-us/library/system.data.idatareader.aspx" rel="nofollow">IDataReader</a> to the <a href="http://msdn.microsoft.com/en-us/library/434atets.aspx" rel="nofollow">WriteToServer(IDataReader)</a> overload.</p>
<p>Most data reader implementations will only keep a very small portion of the total results in memory.</p>
|
Identify full vs half yearly datasets in SQL <p>I have a table with two fields of interest for this particular exercise: a CHAR(3) ID and a DATETIME. The ID identifies the submitter of the data - several thousand rows. The DATETIME is not necessarily unique, either. (The primary keys are other fields of the table.)</p>
<p>Data for this table is submitted every six months. In December, we receive July-December data from each submitter, and in June we receive July-June data. My task is to write a script that identifies people who have only submitted half their data, or only submitted January-June data in June.</p>
<p>...Does anyone have a solution?</p>
|
<p>from your description, i wouldn't worry about the efficiency of the query since apparently it only needs to run twice a year!</p>
<p>there are a few ways to do this, which one is 'best' depends on the data that you have. the datediff (on max/min date values) you suggested should work, another option is to just count records for each submitted within each date range, e.g.</p>
<pre><code>select * from (
select T.submitterId,
(select count(*)
from TABLE T1
where T1.datefield between [july] and [december]
and T1.submitterId = T.submitterId
group by T1.submitterId) as JDCount,
(select count(*)
from TABLE T2
where T2.datefield between [december] and [june]
and T2.submitterId = T.submitterId
group by T2.submitterId) as DJCount
from TABLE T) X
where X.JDCount <= 0 OR X.DJCount <= 0
</code></pre>
<p>caveat: untested query off the top of my head; your mileage may vary</p>
|
Configuring WordPress .htaccess to view subfolders <p>I have a WordPress installation with an <code>.htaccess</code> file that looks like this:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I tried installing a fresh copy of WordPress into a subdirectory for a separate blog and am getting 404 errors within the root WordPress when I try to view it. I'm assuming this is because of the <code>.htaccess</code> file. </p>
<p>How do I change it so that I can view the subfolder?</p>
|
<p>For future reference, you may want to try this:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /blog2/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /blog2/index.php [L]
</IfModule>
# END WordPress
</code></pre>
|
PHP: Best way to extract text within parenthesis? <p>What's the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string "text" from the string "ignore everything except this (text)" in the most efficient manner possible.</p>
<p>So far, the best I've come up with is this:</p>
<pre><code>$fullString = "ignore everything except this (text)";
$start = strpos('(', $fullString);
$end = strlen($fullString) - strpos(')', $fullString);
$shortString = substr($fullString, $start, $end);
</code></pre>
<p>Is there a better way to do this? I know in general using regex tends to be less efficient, but unless I can reduce the number of function calls, perhaps this would be the best approach? Thoughts?</p>
|
<p>i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)</p>
<pre><code>$text = 'ignore everything except this (text)';
preg_match('#\((.*?)\)#', $text, $match);
print $match[1];
</code></pre>
|
Java: Triple Curly Bracing <p>I've been given some code with commenting unlike anything I've come across before:</p>
<pre><code>//{{{ Imports
import imports;
//}}}
</code></pre>
<p>It is the same for each method block, </p>
<pre><code>//{{{ above the code block
//}}} below the code block
</code></pre>
<p><br>
<strong>ALSO SEE: <a href="http://en.wikipedia.org/wiki/Folding_editor" rel="nofollow">http://en.wikipedia.org/wiki/Folding_editor</a></strong></p>
|
<p>A quick search for <em>"triple curly" comment</em> suggests it's "<a href="http://www.emacswiki.org/cgi-bin/wiki/FoldingMode" rel="nofollow">Emacs folding mode</a>".</p>
<p>Or some other code folding marker in any case.</p>
|
Best way to extract the second level domain from the HTTP_Host Variable in VBScript <p>I need to extract only the 2nd level part of the domain from request.servervariables("HTTP_HOST") what is the best way to do this?</p>
|
<pre><code>If Len(strHostDomain) > 0 Then
aryDomain = Split(strHostDomain,".")
If uBound(aryDomain) >= 1 Then
str2ndLevel = aryDomain(uBound(aryDomain)-1)
strTopLevel = aryDomain(uBound(aryDomain))
strDomainOnly = str2ndLevel & "." & strTopLevel
End If
End If
</code></pre>
<p>works for what I need but it doesn't handle .co.uk or other domains that have two parts expected for the top level.</p>
|
How to add NUnit in Visual Studio <p>I need to write test cases for my application. I've chosen NUnit. Please let me know how to add NUnit to my Visual Studio IDE. where can I download them?</p>
|
<p>Best place to start would probably be: <a href="http://testdriven.net/">http://testdriven.net/</a></p>
<p>They have NUnit, and a host of other unit testing suites that can integrate with various versions of Visual Studio, as well as some documentation on them.</p>
|
Cross-platform editor control <p>I need a cross-platform editor control to use as GUI-part in an in-house tool. The control may be commercial, but with reasonable price.</p>
<p>Required features:</p>
<ul>
<li>Platforms: Win32, OS X, Linux</li>
<li>UTF-8 support</li>
<li>Fine-grained run-time control to the text style (or at least color)</li>
<li>Nice low-level plain C API without usual horrible bloat</li>
<li>Should not prevent me to have these features (even if I'll have to implement them myself):
<ul>
<li>Undo / Redo</li>
<li>Copy / Paste</li>
<li>Context menu, depending on click position in text</li>
<li>Toolbar, depending on cursor position in text</li>
<li>Sidebar panel, depending on cursor position in text</li>
</ul></li>
</ul>
<p>Actually above requires not simple control, but whole cross-platform GUI library.</p>
<p>Discarded options:</p>
<ul>
<li>Scintilla and descendants</li>
<li>FLTK</li>
<li>Fox-toolkit</li>
<li>gtksourceview</li>
</ul>
<p><strong>Update:</strong> </p>
<p>Note: I've slipped in some half-written discard reasoning here, I apologize. Scintilla indeed does work on OS X. However, if I get it correctly, Scintilla's API is in C++. </p>
<p>Use-case:</p>
<p>My use-case is to write custom "semi-rigid" logic editor, where user is free to copy-paste around, add comments where he wishes, even type in text directly if he wish. But text structure is a rigid natural language representation of logic tree (somewhat AST-like in nature). I plan to write something intellisense-like (or code-template-like) to be used as the main authoring tool (instead of typing logic by hand).</p>
<p>BTW, storage format would not be plain text, but instead internal representation of mentioned logic tree (with comments and whitespaces etc. metainfo).</p>
<p>So, I have all necessary information to render text in needed colors by myself. I do not need any external lexers etc.</p>
|
<p>As John wrote, Scintilla is known to run on OS X.<br />
Now, it is not a rich text component, if that's what you are looking for. It is a source code editor: you can't apply arbitrary colors to arbitrary segments of text, it uses a lexer to style the content.</p>
<p>You didn't tell us what is your use case.</p>
<p>[EDIT] Thanks for adding the use case.</p>
<p>Disclaimer 1: I don't try to "sell" Scintilla, I just try to provide you information about a component I know well, hoping that helps you... :-D<br />
Note that the <a href="http://scintilla.sourceforge.net/ScintillaRelated.html" rel="nofollow" title="Related Sites">Related Sites</a> page lists a number of alternative Editing Components which can be interesting (or not, lot of them are for Win32 only).<br />
Disclaimer 2: I have no experience of using Scintilla outside of the Win32 platform.</p>
<p>But looking at the source tree, I see a scintilla/macosx folder. Among other things, it has a SciTest sub-folder with a main.cpp file. Despite its extension, it strongly looks like pure C for me. So it can be an example of how to use Scintilla in C.</p>
<p>Note that by design, Scintilla API is very limited: it was initially made to be used as most traditional Win32 components, by sending messages to it. The <a href="http://scintilla.sourceforge.net/ScintillaDoc.html" rel="nofollow" title="Scintilla Documentation">Scintilla Documentation</a> page only lists these messages and their parameters. The main.cpp example creates the window with the component in MacOS X style and sends commands with lines like <code>scintilla->WndProc(SCI_STYLESETFORE, 0, 0x808080);</code></p>
<p>I won't claim it does everything you need, or even that it works flawlessly on MacOS X, you have to experiment (or ask the author of the adaptation) to be sure.<br />
Also Scintilla won't provide a toolbar nor a sidebar panel (this belongs more to the application itself). But I think it can provide enough notifications to help you keeping these side components on context.<br />
You will need also to write a specific lexer (C++ here) for your syntax. It isn't hard if you look how works other lexers. Perhaps you will find one for a language close enough to be used as a starting point.<br />
Perhaps of interest too is a feature to set some portions of document as read-only, although I believe this haven't been thoroughly tested.</p>
<p>HTH.</p>
|
What is the easiest/best/most correct way to iterate through the characters of a string in Java? <p><code>StringTokenizer</code>? Convert the <code>String</code> to a <code>char[]</code> and iterate over that? Something else?</p>
|
<p>I use a for loop to iterate the string and use <code>charAt()</code> to get each character to examine it. Since the String is implemented with an array, the <code>charAt()</code> method is a constant time operation.</p>
<pre><code>String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
</code></pre>
<p>That's what I would do. It seems the easiest to me.</p>
<p>As far as correctness goes, I don't believe that exists here. It is all based on your personal style.</p>
|
Drop Down List with WPF Menu Controls <p>I am looking for a way to add a drop down list in WPF to a menu. This used to be really easy in winforms and so I am expecting you experts to know just now to do it in WPF. Thanks.</p>
<p>Sorry if this is a bad question, it is late and I don't want to think.</p>
|
<p>It is very easy to add any UIElement to any control, You can just add Combobox to a Menu control and create menu as bellow</p>
<pre><code> <Menu >
<MenuItem Header="File">
<MenuItem Header="Open"/>
<MenuItem Header="Close"/>
<Separator/>
<ComboBox Width="85" Height="21.96" />
</MenuItem>
</Menu>
</code></pre>
|
Java2D Performance Issues <p>I'm having performance oddities with Java2D. I know of the sun.java2d.opengl VM parameter to enable 3D acceleration for 2D, but even using that has some weird issues. </p>
<p>Here are results of tests I ran:</p>
<p>Drawing a 25x18 map with 32x32 pixel tiles on a JComponent<br>
Image 1 = .bmp format, Image 2 = A .png format</p>
<h2>Without -Dsun.java2d.opengl=true</h2>
<p>120 FPS using .BMP image 1<BR>
13 FPS using .PNG image 2</p>
<h2>With -Dsun.java2d.opengl=true</h2>
<p>12 FPS using .BMP image 1<BR>
700 FPS using .PNG image 2</p>
<p>Without acceleration, I'm assuming some kind of transformation is taking place with every drawImage() I do in software, and is pulling down the FPS considerably in the case of .PNG. Why though, with acceleration, would the results switch (and PNG actually performs incredibly faster)?! Craziness!</p>
<p>.BMP Image 1 is translated to an image type of TYPE_INT_RGB. .PNG Image 2 is translated to an image type of TYPE_CUSTOM. In order to get consistent speed with and without opengl acceleration, I have to create a new BufferedImage with an image type of TYPE_INT_ARGB, and draw Image 1 or Image 2 to this new image. </p>
<p>Here are the results running with that:</p>
<h2>Without -Dsun.java2d.opengl=true</h2>
<p>120 FPS using .BMP image 1<BR>
120 FPS using .PNG image 2</p>
<h2>With -Dsun.java2d.opengl=true</h2>
<p>700 FPS using .BMP image 1<BR>
700 FPS using .PNG image 2</p>
<p>My real question is, can I assume that TYPE_INT_ARGB will be the native image type for all systems and platforms? I'm assuming this value could be different. Is there some way for me to get the native value so that I can always create new BufferedImages for maximum performance? </p>
<p>Thanks in advance...</p>
|
<p>I think I found a solution by researching and putting bits and pieces together from too many Google searches. </p>
<p>Here it is, comments and all:</p>
<pre><code>private BufferedImage toCompatibleImage(BufferedImage image)
{
// obtain the current system graphical settings
GraphicsConfiguration gfx_config = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
/*
* if image is already compatible and optimized for current system
* settings, simply return it
*/
if (image.getColorModel().equals(gfx_config.getColorModel()))
return image;
// image is not optimized, so create a new image that is
BufferedImage new_image = gfx_config.createCompatibleImage(
image.getWidth(), image.getHeight(), image.getTransparency());
// get the graphics context of the new image to draw the old image on
Graphics2D g2d = (Graphics2D) new_image.getGraphics();
// actually draw the image and dispose of context no longer needed
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
// return the new optimized image
return new_image;
}
</code></pre>
<p>In my previous post, GraphicsConfiguration was what held the information needed to create optimized images on a system. It seems to work pretty well, but I would have thought Java would automatically do this for you. Obviously you can't get too comfortable with Java. :) I guess I ended up answering my own question. Oh well, hopefully it'll help some of you I've seen trying to make use of Java for 2D games.</p>
|
How do I change OutDir variable in Visual C++? <p>In the linker the binary destination is specified as:</p>
<p>$(OutDir)\$(ProjectName).exe</p>
<p>I've looked through every setting and I can't see where OutDir is defined. How do I change this?</p>
|
<p>First option in the "General" section underneath "Configuration Properties".</p>
|
How to check if OS is Vista in Python? <p>How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and <a href="http://python.net/crew/mhammond/win32/Downloads.html">pywin32</a> or <a href="http://www.wxpython.org/">wxPython</a>?</p>
<p>Essentially, I need a function that called will return True iff current OS is Vista:</p>
<pre><code>>>> isWindowsVista()
True
</code></pre>
|
<p>Python has the lovely 'platform' module to help you out.</p>
<pre><code>>>> import platform
>>> platform.win32_ver()
('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')
>>> platform.system()
'Windows'
>>> platform.version()
'5.1.2600'
>>> platform.release()
'XP'
</code></pre>
<p>NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.</p>
|
Can you list the keyword arguments a Python function receives? <p>I have a dict, which I need to pass key/values as keyword arguments.. For example..</p>
<pre><code>d_args = {'kw1': 'value1', 'kw2': 'value2'}
example(**d_args)
</code></pre>
<p>This works fine, <em>but</em> if there are values in the d_args dict that are not accepted by the <code>example</code> function, it obviously dies.. Say, if the example function is defined as <code>def example(kw2):</code></p>
<p>This is a problem since I don't control either the generation of the <code>d_args</code>, or the <code>example</code> function.. They both come from external modules, and <code>example</code> only accepts some of the keyword-arguments from the dict..</p>
<p>Ideally I would just do</p>
<pre><code>parsed_kwargs = feedparser.parse(the_url)
valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2)
PyRSS2Gen.RSS2(**valid_kwargs)
</code></pre>
<p>I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: <strong>Is there a way to programatically list the keyword arguments the a specific function takes?</strong></p>
|
<p>A little nicer than inspecting the code object directly and working out the variables is to use the inspect module.</p>
<pre><code>>>> import inspect
>>> def func(a,b,c=42, *args, **kwargs): pass
>>> inspect.getargspec(func)
(['a', 'b', 'c'], 'args', 'kwargs', (42,))
</code></pre>
<p>If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by:</p>
<pre><code>def getRequiredArgs(func):
args, varargs, varkw, defaults = inspect.getargspec(func)
if defaults:
args = args[:-len(defaults)]
return args # *args and **kwargs are not required, so ignore them.
</code></pre>
<p>Then a function to tell what you are missing from your particular dict is:</p>
<pre><code>def missingArgs(func, argdict):
return set(getRequiredArgs(func)).difference(argdict)
</code></pre>
<p>Similarly, to check for invalid args, use:</p>
<pre><code>def invalidArgs(func, argdict):
args, varargs, varkw, defaults = inspect.getargspec(func)
if varkw: return set() # All accepted
return set(argdict) - set(args)
</code></pre>
<p>And so a full test if it is callable is :</p>
<pre><code>def isCallableWithArgs(func, argdict):
return not missingArgs(func, argdict) and not invalidArgs(func, argdict)
</code></pre>
<p>(This is good only as far as python's arg parsing. Any runtime checks for invalid values in kwargs obviously can't be detected.)</p>
|
Can anyone recommend a Java rich text editor? <p>The rich text editor must be implemented in Java, provide Swing support, and preferably be open source.</p>
<p>I'm looking to integrate it into an existing Java/Swing application. </p>
<p>Thanks.</p>
|
<p>This is probably not as drop-in-place as what you were after... but JTextPane supports rich text and HTML.
Its trivial to get it to <em>display</em> rtf or html, just set the encoding type before you fill it with content. </p>
<p>As for making the little "B" and "<em>I</em>" etc style-modifying buttons, well if it came down to it, in a pinch that wouldnt be very hard to make yourself.
Think JButtons with Icons set. Their listeners get JTextPane's current selection start and end index positions like this :
<code>jpane.getSelectionStart()</code> or <code>jpane.getSelectionEnd()</code>
and then insert opening and closing html/rtf tags at those locations. </p>
<p>Undo is easy too - maintain a simple stack of the string contents of the Jpanel, every time the user does an edit action, a simple history.push(jpane.getText()) would store the state, and the undo button would be as simple as jpane.setText(history.pop()).</p>
<p>I/you could make one with B, <em>I</em> & undo in around 30 min I reckon - other buttons like lists will take longer, but not much so.</p>
|
Eclipse Abstract Syntax Tree Programmatic Access <p>Could you provide an example of accessing the Eclipse Abstract Syntax Tree programmatically for a given piece of code?</p>
<p>eg getting the AST for:</p>
<p><hr /></p>
<h2>Class1.java</h2>
<pre><code>package parseable;
public class Class1 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello world!");
}
</code></pre>
<p>}</p>
|
<p>It is not an <em>exact</em> answer, that may give you a place where to start:</p>
<p>As said in this <a href="http://stackoverflow.com/questions/160382/extract-all-string-from-a-java-project#161145">question</a>, </p>
<p>A full example is available in this <a href="http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html" rel="nofollow">eclipse corner article</a>, also more details in the <a href="http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/dom/ASTParser.html" rel="nofollow">eclipse help</a>. And in the slide 59 of <a href="http://www1.cs.columbia.edu/~aho/cs4117/lectures/Static%20Analysis%20for%20Java%20in%20Eclipse.pdf" rel="nofollow">this presentation</a>, you see how to apply a change to your source code.</p>
|
What is the best implementation of STL for VS2005? <p>I'm currently using default implementation of STL for VS2005 and I'm <a href="http://stackoverflow.com/questions/186494/ifstr1str2-versus-ifstr1lengthstr2length-str1str2">not really satisfied</a> with it. Perhaps there is something better?</p>
|
<p>The Dinkumware STL implementation (supplied with VS2005) is actually quite good. The STL is a general purpose library and so it is almost always possible to write something better for very specific use cases.</p>
<p>I'm aware of the following alternative implementations, but I've never used them with VS2005:</p>
<p>SGI Standard Template Library 3.3:
<a href="http://www.sgi.com/tech/stl/" rel="nofollow">http://www.sgi.com/tech/stl/</a></p>
<p>STLport 5.1.6 (derived from SGI implementation):
<a href="http://www.stlport.org/" rel="nofollow">http://www.stlport.org/</a></p>
<p>Both SGI and STLport implement the size/length check as the first test in operator== and so you might like it. They are also both free to download and use.</p>
<p>Changing from one STL implementation to another, in theory, should be easy. However, I've heard from some colleagues that it is not always so. They've tripped over compiler bugs, found that they've inadvertently used non-standard features, or unknowingly relied on some behaviour specific to a particular STL implementation.</p>
<p>One good thing about the Dinkumware STL implementation is that it has been well tested with the VS2005 C++ compiler.</p>
<p>If you decide to try out these alternatives, good luck! And let us know how it goes.</p>
|
Skip file lines until a match is found, then output the rest <p>I can write a trivial script to do this but in my ongoing quest to get more familliar with unix I'd like to learn efficient methods using built in commands instead.</p>
<p>I need to deal with very large files that have a variable number of header lines. the last header line consists of the text 'LastHeaderLine'. I wish to output everything after this line. (I'm not worried about false positive matches.)</p>
|
<p>Similar to the answer of <a href="http://stackoverflow.com/questions/197150/skip-file-lines-until-a-match-is-found-then-output-the-rest#197169">Avi</a>, but without including the line with "LastHeaderLine".</p>
<pre><code>sed -e '1,/LastHeaderLine/d'
</code></pre>
|
How do you optimise your Javascript? <p>Well... simple question, right? But with no so simple answers.
In firefox i use firebug console (profile) but... what to do in other browsers? Like Internet Explorer / Opera / Safari (on windows)</p>
|
<p>This particular problem solves itself over time. ;-)</p>
<p>Version 8 of the Internet Explorer (currently in beta 2) ships with a built-in JavaScript profiler. The next Safari version will probably also include one since its rendering engine, WebKit, now has one as part of its <a href="http://webkit.org/blog/148/web-inspector-update/" rel="nofollow">Web Inspector</a>.</p>
|
VMWare ctrl-z key binding, how to remove <p>When I <kbd>Alt</kbd>+<kbd>Tab</kbd> to my VM from my host the VM does not get keyboard input until I click inside it. This is causing me an issue as it looks like the VM has control of the input (as the cursor is flashing away). If while in this state, VMWare server has the focus rather then the application inside it, if you do <kbd>ctrl</kbd>+<kbd>Z</kbd> (normally for undo) it <strong>suspends</strong> the VM.</p>
<p>This is driving me barmey. I have looked through all the options and preferences in VMWare Server and can't find anyway to disable this.</p>
<p>Anyone know how to disable this?</p>
|
<p>This will not remove the key binding from VmWare, but you could set the option to "Grab keyboard and mouse intput on key press" in the VmWare preferences. VmWare help explicitly states that this will disable the system accelerator key sequences.</p>
|
Why can't I use a type argument in a type parameter with multiple bounds? <p>So, I understand <i>that</i> the following doesn't work, but <i>why</i> doesn't it work?</p>
<pre><code>interface Adapter<E> {}
class Adaptulator<I> {
<E, A extends I & Adapter<E>> void add(Class<E> extl, Class<A> intl) {
addAdapterFactory(new AdapterFactory<E, A>(extl, intl));
}
}
</code></pre>
<p>The <code>add()</code> method gives me a compile error, "Cannot specify any additional bound Adapter<E> when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.</p>
<p>Clearly you're just Not Allowed to use the type parameter <code>I</code> there, before the <code>&</code>, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that <code>I</code> isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.</p>
<p>Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one <code>add()</code> method, so it's not like there's any ambiguity...</p>
<p>Can someone demonstrate the problem for me?</p>
|
<p>I'm also not sure why the restriction is there. You could try sending a friendly e-mail to the designers of Java 5 Generics (chiefly Gilad Bracha and Neal Gafter).</p>
<p>My guess is that they wanted to support only an absolute minimum of <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9" rel="nofollow">intersection types</a> (which is what multiple bounds essentially are), to make the language no more complex than needed. An intersection cannot be used as a type annotation; a programmer can only express an intersection when it appears as the upper bound of a type variable.</p>
<p>And why was this case even supported? The answer is that multiple bounds allow you to control the erasure, which allows to maintain binary compatibility when generifying existing classes. As explained in section 17.4 of the <a href="http://java-generics-book.dev.java.net/" rel="nofollow">book</a> by Naftalin and Wadler, a <code>max</code> method would logically have the following signature:</p>
<pre><code>public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)
</code></pre>
<p>However, this erases to:</p>
<pre><code>public static Comparable max(Collection coll)
</code></pre>
<p>Which does not match the historical signature of <code>max</code>, and causes old clients to break.
With multiple bounds, only the left-most bound is considered for the erasure, so if <code>max</code> is given the following signature:</p>
<pre><code>public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
</code></pre>
<p>Then the erasure of its signature becomes:</p>
<pre><code>public static Object max(Collection coll)
</code></pre>
<p>Which is equal to the signature of <code>max</code> before Generics.</p>
<p>It seems plausible that the Java designers only cared about this simple case and restricted other (more advanced) uses of intersection types because they were just unsure of the complexity that it might bring. So the reason for this design decision does not need to be a possible safety problem (as the question suggests).</p>
<p>More discussion on intersection types and restrictions of generics in an <a href="http://www.cs.rice.edu/~javaplt/papers/oopsla2008.pdf" rel="nofollow">upcoming OOPSLA paper</a>.</p>
|
SqlDataReader.HasRows returns false since SQL 2008 upgrade <p>I've got an ASP.NET 2.0 website that connects to a SQL database. I've upgraded the SQL server from 2000 to 2008 and since then, one page refuses to work. </p>
<p>I've worked out the problem is that the call to SqlDataReader.HasRows is returning false even though the dataset is not empty and removing the check allows the loop through reader.Read() to access the expected data. </p>
<pre><code> _connectionString = WebConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString;
SqlConnection connection = new SqlConnection(_connectionString);
SqlCommand command = new SqlCommand(searchtype, connection);
SqlParameter _parSeachTerm = new SqlParameter("@searchterm", SqlDbType.VarChar, 255);
_parSeachTerm.Value = searchterm;
command.Parameters.Add(_parSeachTerm);
command.CommandType = CommandType.StoredProcedure;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows) //this always returns false!?
{
while (reader.Read())
{...
</code></pre>
<p>Does anybody have any idea what's going on? There are similar code blocks on other pages where HasRows returns the correct value.</p>
<p>EDIT- Just to clarify, the stored procedure DOES return results which I have confirmed because the loop runs through fine if I remove the HasRows check. Changing just the name of the SQL server in the connection string to an identical database running on SQL 2000 makes the problem go away. I've checked that NOCOUNT is off, so what else could make HasRows return false when that's not the case??</p>
<p>EDIT2- Here's the SP</p>
<pre><code>CREATE PROCEDURE StaffEnquirySurnameSearch
@searchterm varchar(255)
AS
SELECT AD.Name, AD.Company, AD.telephoneNumber, AD.manager, CVS.Position, CVS.CompanyArea, CVS.Location, CVS.Title, AD.guid AS guid,
AD.firstname, AD.surname
FROM ADCVS AD
LEFT OUTER JOIN CVS ON
AD.Guid=CVS.Guid
WHERE AD.SurName LIKE @searchterm
ORDER BY AD.Surname, AD.Firstname
GO
</code></pre>
<p>Many thanks in advance.</p>
|
<p>Does the stored procedure work if you invoke it in directly, say in SSMS? I'd start by making sure that it does.</p>
|
Virtual 360º, stitching and presentation software, for use on PHP driven website? <p><strong>EDITED (after 1st answer):</strong></p>
<p>Can anyone help by pointing to some good references for the creation and presentation of a 3D environment (a real room) on a website.</p>
<p>Ideally it will not involve too much expense or too high a learning curve as this is a one off requirement for a small project.</p>
|
<p><a href="http://en.wikipedia.org/wiki/VRML" rel="nofollow">VRML</a>, <a href="https://java3d.dev.java.net/" rel="nofollow">Java3D</a>, or Flash depending on how adventurous you are.</p>
<p>See <a href="http://www.papervision3d.org/" rel="nofollow">Papervision3D</a> (<a href="http://www.papervision3d.org/demos/panorama/" rel="nofollow">panorama demo</a>) and <a href="http://www.360dof.com/" rel="nofollow">360 Degrees of Freedom</a>.</p>
|
Design question: How can I access an IPC mechanism transparently? <p>I want to do this (no particular language):</p>
<pre><code>print(foo.objects.bookdb.books[12].title);
</code></pre>
<p>or this:</p>
<pre><code>book = foo.objects.bookdb.book.new();
book.title = 'RPC for Dummies';
book.save();
</code></pre>
<p>Where foo actually is a service connected to my program via some IPC, and to access its methods and objects, some layer actually sends and receives messages over the network.</p>
<p>Now, I'm not really looking for an IPC mechanism, as there are plenty to choose from. It's likely not to be XML based, but rather s. th. like Google's protocol buffers, dbus or CORBA. What I'm unsure about is how to structure the application so I can access the IPC just like I would any object.</p>
<p>In other words, how can I have OOP that maps transparently over process boundaries?</p>
<p>Not that this is a design question and I'm still working at a pretty high level of the overall architecture. So I'm pretty agnostic yet about which language this is going to be in. C#, Java and Python are all likely to get used, though.</p>
|
<p>I think the way to do what you are requesting is to have all object communication regarded as message passing. This is how object methods are handled in ruby and smalltalk, among others. </p>
<p>With message passing (rather than method calling) as your object communication mechanism, then operations such as calling a method that didn't exist when you wrote the code becomes sensible as the object can do something sensible with the message anyway (check for a remote procedure, return a value for a field with the same name from a database, etc, or throw a 'method not found' exception, or anything else you could think of).</p>
<p>It's important to note that for languages that don't use this as a default mechanism, you can do message passing anyway (every object has a 'handleMessage' method) but you won't get the syntax niceties, and you won't be able to get IDE help without some extra effort on your part to get the IDE to parse your handleMessage method to check for valid inputs.</p>
|
Enterprise Library Database Trace Listener? <p>I'm using EntLib v4 for Logging and currently I'm saving the events to the default text file listener.</p>
<p>I would like to use MS SQL database as my event sink and I saw that the database listener is already provided, but I don't know how to create logging database and stored procedures?</p>
<p>After googling around I saw that in v3 the database creation scripts were shipped with the EntLib, but I can't find them in v4.</p>
|
<p>I just checked and its in the installation for the source. On my machine its in <code>C:\EntLib4Src\Blocks\Logging\Src\DatabaseTraceListener\Scripts</code>. </p>
<p>You can use the createloggingdb.cmd file or parse loggingdatabase.sql yourself for the relevant commands.</p>
|
What navigation control would you choose to use in your application? <p>ToolStrip with MenuStrip or RibbonBar? </p>
<hr>
<p>It combines both of the controls. It also have a TabPages navigation, contextual tabs, etc. However the RibbonBar is a very complex control and when you open a new document in for example Word2007 the half of the screen you see a Ribbon Bar. It is not cool. When you have toolStrips you can layout them to Top, Bottom, Left, Right and have more control of the UI look. We can also hide the toolstrips which we do not want to see and they no longer take any screen space. </p>
|
<p>Ribbon Bar</p>
|
Instantiating a C++ class in C# using P/Invoke via a pointer <p>I am importing the CreateICeeFileGen() function from the unmanaged DLL mscorpe.dll in a C# application, in order to generate a PE file. This function returns a pointer to an C++ object <a href="http://msdn.microsoft.com/en-us/library/ms404463.aspx" rel="nofollow">defined here</a>, is there any way I can access fields from this class via C# or do I need to write an unmanaged wrapper DLL?</p>
<p>The code I'm using currently is as follows:-</p>
<pre><code>[DllImport(@"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorpe.dll", EntryPoint = "CreateICeeFileGen")]
static extern void CreateICeeFileGen(out IntPtr iceeFileGenPointer);
...
IntPtr filePtr;
CreateICeeFileGen(out filePtr);
</code></pre>
<p><strong>N.B.</strong>: I know you can do similar things with .net libraries but I need to use unmanaged libraries for my purposes.</p>
<p>Thanks in advance!!</p>
|
<p>You need a wrapper library to be able to use the class from C#. </p>
<p>The best bet would be to create the wrapper using C++/CLI, which can directly call the unmanaged function and expose the details with a managed class. This will eliminate the need to use P/Invoke for anything.</p>
<p>(Well, technically if you know the class layout you could mess around with pointer arithmetic to access the fields, but this would be very fragile and messy, and trying to call virtual functions in this way would be extremely ugly).</p>
|
Beanstalk like Functionality <p>I'm finally getting my team to embrace source code management now that we're working on projects where more than one dev is touching the same codebase, and I setup a free/trial account on Beanstalk for hosted Subversion so people could get a taste of how it works.</p>
<p>That said, we've discussed a somewhat ambitious plan to put a lot of needed/wanted functionality into a single server we can run ourselves, and while I think that's great, we're still working without SCM as those plans slowly form.</p>
<p>In the interim, I'd like to setup a temporary SVN server, but was wondering if there are any F/OSS packages that we could setup that would provide Beanstalk like functionality (i.e. the nice web interface/management setup). I'm not overly concerned with the core-language of the package unless I'd need to hack on the code for the system itself, in which case I'm reasonably comfortable with PHP, Perl, and .NET, though I could probably pickup (an)other language(s) as needed. That said, I'd like to steer clear of .NET or any other technology that would necessitate a Windows license.</p>
|
<p>There are probably a lot of people on Stack Overflow who know lots about Subversion, but have never heard of Beanstalk and therefore can't help you. Specifically what web front-end functionality are you looking for?</p>
<p>My team only ever needs to browse our SVN repositories via a web browser (and compare revisions) and for that we use <a href="http://websvn.tigris.org/" rel="nofollow">WebSVN</a>. It's simple and not especially fully-featured, but it does the job for us. You can't use WebSVN to create repositories, but since that's a very simple job, and one that is done relatively infrequently, that's probably not an issue, is it?</p>
|
Windows workflow <p>Just want to learn 'Windows workflow' designer in .net right from the basics, can anyone suggest a good link please</p>
<p>thanks
sandeep</p>
|
<p>OdeToCode has several in depth articles on WWF written by Scott Allen, and in particular a good discussion of the instances where you should use <a href="http://www.odetocode.com/Articles/460.aspx" rel="nofollow">a state machine</a> to simply complex workflow logic.</p>
|
What is the best way to display one value and store another on .net comboboxes? <p>I can't seem to find an easy to use, .net native way to get Comboboxes on .net winforms to display one value and return another based on the selection without creating my own helper class, with the knowledge that winforms is going to display the ToString method on the object that you put in it.</p>
<p>This is how I'm doing it now, very generically. First, create the helper class.</p>
<pre><code> Public Class ListItem
Public Value As Object
Public DisplayString As String
Public Sub New(ByVal NewValue As Object, ByVal NewDisplayString As String)
Value = NewValue
DisplayString = NewDisplayString
End Sub
Public Overrides Function ToString() As String
Return DisplayString
End Function
End Class
</code></pre>
<p>then, to load the combobox from a collection or whatever.</p>
<pre><code> For Each o as WhateverObject In CollectionIwantToaddItemsFrom
li = New ListItem(o.ValueToReturn, o.ValueToDisplay)
Me.ComboBox1.Items.Add(li)
Next
</code></pre>
<p>and finally, to use the object</p>
<pre><code>Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.SelectedIndexChanged
if me.combobox1.selecteditem is nothing then exit sub
Dim li As ListItem = me.ComboBox1.SelectedItem
Dim o as object = li.value
'do stuff with o.
end sub
</code></pre>
<p>I'm sure there is something I'm better to use in the framework that I'm over looking. What is it?</p>
|
<p>This is a bit of a hack, but it means you don't have to write your own Name-Value pair class - not a big deal (could be there's something better already in the framework). But what you could do is use the DictionaryEntry class - which is effectively a name value pair. Add the items to a list, then use the DataMember and ValueMember properties on the combobox to bind to the key and value properties of the DictionaryEntry class. Like this:</p>
<pre><code> var list = new List<System.Collections.DictionaryEntry>();
list.Add(new System.Collections.DictionaryEntry("one", 1));
list.Add(new System.Collections.DictionaryEntry("two", 2));
list.Add(new System.Collections.DictionaryEntry("three", 3));
comboBox1.DataSource = list;
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
</code></pre>
<p>Just realised you prefer the vb dialect. The below does the same for VB :-)</p>
<pre><code>Dim list As List(Of DictionaryEntry)
list = New List(Of DictionaryEntry)
list.Add(New DictionaryEntry("One", 1))
list.Add(New DictionaryEntry("Two", 2))
list.Add(New DictionaryEntry("Three", 3))
ComboBox1.DataSource = list
ComboBox1.DisplayMember = "Key"
ComboBox1.ValueMember = "Value"
</code></pre>
|
Are there problems with rendering WPF over Remote Desktop under Windows XP? <p>I have heard that WPF primitives will not be supported by remote desktop on windows XP. The implication of this is that if you run a WPF application on a vista machine and display it on an XP machine (via remote desktop) the display will be sent as a compressed bitmap.</p>
<p>This issue is resolved in Vista-Vista comunication via DirectX 11 (?) but this will not be made available on XP. There is obviously a performance hit here, I would like to understand it before making any inroads into developing applications to WPF.</p>
<p>Some information on this topic can be found here:</p>
<p><a href="http://blogs.msdn.com/tims/archive/2007/01/05/comparing-wpf-on-windows-vista-v-windows-xp.aspx">http://blogs.msdn.com/tims/archive/2007/01/05/comparing-wpf-on-windows-vista-v-windows-xp.aspx</a></p>
<p>See comment from the above link (quote):</p>
<p><hr /></p>
<p>To SpongeJim's question, this is done by the MIL (media integration layer), which is the underlying core of WPF that handles composition. On a Vista/Vista remote desktop connection, the MIL primitives are remoted and then reconstituted. On other combinations (e.g. 2003/XP), what gets remoted is bitmaps, which is obviously far more bandwidth-intensive. More depth on this topic can be found on Greg Schechter's blog, and in this entry in particular: <a href="http://blogs.msdn.com/greg_schechter/archive/2006/06/09/623566.aspx">http://blogs.msdn.com/greg_schechter/archive/2006/06/09/623566.aspx</a></p>
<p><hr /></p>
<p>Does anyone have any experience or more up to date information on this issue?</p>
|
<p>As of .NET 3.5 SP1, all WPF graphics are remoted as bitmaps, even on Vista-to-Vista communication. From <a href="http://blogs.msdn.com/jgoldb/archive/2008/05/15/what-s-new-for-performance-in-wpf-in-net-3-5-sp1.aspx" rel="nofollow">http://blogs.msdn.com/jgoldb/archive/2008/05/15/what-s-new-for-performance-in-wpf-in-net-3-5-sp1.aspx</a>:</p>
<blockquote>
<p>We now remote as bitmaps in ALL cases.</p>
<p>The reason is that WPF 3.5 SP1 now
uses a new graphics DLL (wpfgfx.dll)
and certain changes could not be made
to Vistaâs existing graphics DLL
(milcore.dll) that is also used by
DWM.</p>
</blockquote>
<p>As other commenters have noted, the performance will greatly depend on the design of your applicationâs UI. The potential upshot is that you only have to test in one scenario; remoting performance should now be the same regardless of the client or server.</p>
|
How to Parsing "Event XML" in Java? <p>I'm looking to use Java to parse an ongoing stream of event drive XML generated by a remote device. Here's a simplified sample of two events:</p>
<pre><code><?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
<?xml version="1.0"?>
<Event> DeviceEventMsg
<Param1>SomeParmValue</Param1>
</Event>
</code></pre>
<p>It seems like SAX is more suited to this than DOM because it is an ongoing stream, though I'm not as familiar with Sax. Don't yell at me for the structure of the XML - I know it already and can't change it. </p>
<p>And yes the device DOES send the xml directive before every event. My first problem is that the second xml processing instruction is croaking the SAX parser. </p>
<p>Can anyone suggest a way to get around that?</p>
<hr>
<p>The code I'm using so far which is croaking on the second xml processing instruction is:</p>
<pre><code>public class TestMe extends HandlerBase {
public void startDocument () throws SAXException
{
System.out.println("got startDocument");
}
public void endDocument () throws SAXException
{
System.out.println("got endDocument");
}
public void startElement (String name, AttributeList attrs) throws SAXException
{
System.out.println("got startElement");
}
public void endElement (String name) throws SAXException
{
System.out.println("got endElement");
}
public void characters (char buf [], int offset, int len) throws SAXException
{
System.out.println("found characters");
}
public void processingInstruction (String target, String data) throws SAXException
{
System.out.println("got processingInstruction");
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
// using a file as test input for now
saxParser.parse( new File("devmodule.xml"), new TestMe() );
} catch (Throwable err) {
err.printStackTrace ();
}
}
}
</code></pre>
|
<p>Try to use <a href="http://en.wikipedia.org/wiki/StAX" rel="nofollow">StAX</a> instead of SAX. StAX allows much more flexibility and it is a better solution for streaming XML. There are few implementations of StAX, I am very happy with the <a href="http://stax.codehaus.org/Download" rel="nofollow">codehaus</a> one, but there is also one from <a href="https://sjsxp.dev.java.net/" rel="nofollow">Sun</a>.
It might solve you're problems. </p>
|
Linq to SQL class lifespan <p>As far as I can understand, when I new up a <em>Linq to SQL class</em>, it is the equivalent of new'ing up a <em>SqlConnection object</em>.</p>
<p>Suppose I have an object with two methods: <code>Delete()</code> and <code>SubmitChanges()</code>. Would it be wise of me to new up the <em>Linq to SQL class</em> in each of the methods, or would a private variable holding the <em>Linq to SQL class</em> - new'ed up by the constructor - be the way to go?</p>
<p>What I'm trying to avoid is a time-out.</p>
<p><strong>UPDATE:</strong></p>
<pre><code>namespace Madtastic
{
public class Comment
{
private Boolean _isDirty = false;
private Int32 _id = 0;
private Int32 _recipeID = 0;
private String _value = "";
private Madtastic.User _user = null;
public Int32 ID
{
get
{
return this._id;
}
}
public String Value
{
get
{
return this._value;
}
set
{
this._isDirty = true;
this._value = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public Comment()
{
}
public Comment(Int32 commentID)
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (comment != null)
{
this._id = comment.CommentsID;
this._recipeID = comment.RecipesID;
this._value = comment.CommentsValue;
this._user = new User(comment.UsersID);
}
mdc.Dispose();
}
public void SubmitChanges()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null && this._isDirty)
{
comment.CommentsValue = this._value;
}
else
{
Madtastic.Entities.Comment c = new Madtastic.Entities.Comment();
c.RecipesID = this._recipeID;
c.UsersID = this._user.ID;
c.CommentsValue = this._value;
mdc.Comments.InsertOnSubmit(c);
}
mdc.SubmitChanges();
mdc.Dispose();
}
public void Delete()
{
Madtastic.DataContext mdc = new Madtastic.DataContext();
var comment = (from c in mdc.Comments
where c.CommentsID == this._id
select c).FirstOrDefault();
if (comment != null)
{
mdc.Comments.DeleteOnSubmit(comment);
mdc.SubmitChanges();
this._isDirty = false;
this._id = 0;
this._recipeID = 0;
this._value = "";
this._user = null;
}
mdc.Dispose();
}
}
}
</code></pre>
<p><strong>REFACTORED CODE (according to Grank's spec):</strong></p>
<pre><code>namespace Madtastic
{
public sealed class CommentNew : IDisposable
{
private Madtastic.DataContext _mdc;
private Madtastic.Entities.Comment _comment;
private Madtastic.User _user;
public Int32 ID
{
get
{
return this._comment.CommentsID;
}
}
public String Value
{
get
{
return this._comment.CommentsValue;
}
set
{
this._comment.CommentsValue = value;
}
}
public Madtastic.User Owner
{
get
{
return this._user;
}
}
public void Comment(Int32 commentID)
{
this._mdc = new Madtastic.DataContext();
this._comment = (from c in _mdc.Comments
where c.CommentsID == commentID
select c).FirstOrDefault();
if (this._comment == null)
{
this._comment = new Madtastic.Entities.Comment();
this._mdc.Comments.InsertOnSubmit(this._comment);
}
else
{
this._user = new Madtastic.User(this._comment.User.UsersID);
}
}
public void SubmitChanges()
{
this._mdc.SubmitChanges();
}
public void Delete()
{
this._mdc.Comments.DeleteOnSubmit(this._comment);
this.SubmitChanges();
}
void IDisposable.Dispose()
{
this._mdc.Dispose();
}
}
}
</code></pre>
|
<p>Depends on to what you refer by a "LINQ-to-SQL class", and what the code in question looks like.<br />
If you're talking about the DataContext object, and your code is a class with a long lifetime or your program itself, I believe it would be best to initialize it in the constructor. It's not really like creating and/or opening a new SqlConnection, it's actually very smart about managing its database connection pool and concurrency and integrity so that you don't need to think about it, that's part of the joy in my experience so far with LINQ-to-SQL. I've never seen a time-out problem occur.<br />
One thing you should know is that it's very difficult to share table objects across DataContext scope, and it's really not recommended if you can avoid it. Detach() and Attach() can be bitchy. So if you need to pass around a LINQ-to-SQL object that represents a row in a table on your SQL database, you should try to design the life cycle of the DataContext object to encompass all the work you need to do on any object that comes out of it. <br />
Furthermore, there's a lot of overhead that goes into instantiating a DataContext object, and a lot of overhead that is managed by it... If you're hitting the same few tables over and over it would be best to use the same DataContext instance, as it will manage its connection pool, and in some cases cache some things for efficiency. However, it's recommended to not have every table in your database loaded into your DataContext, only the ones you need, and if the tables being accessed are very separate in very separate circumstances, you can consider splitting them into multiple DataContexts, which gives you some options on when you initialize each one if the circumstances surrounding them are different. </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.