input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
What is the best way to retrieve distinct / unique values using SPQuery? <p>I have a list that looks like:</p>
<pre><code>Movie Year
----- ----
Fight Club 1999
The Matrix 1999
Pulp Fiction 1994
</code></pre>
<p>Using CAML and the SPQuery object I need to get a distinct list of items from the Year column which will populate a drop down control.</p>
<p>Searching around there doesn't appear to be a way of doing this within the CAML query. I'm wondering how people have gone about achieving this?</p>
| <p>Another way to do this is to use DataView.ToTable-Method - its first parameter is the one that makes the list distinct.</p>
<pre><code> SPList movies = SPContext.Current.Web.Lists["Movies"];
SPQuery query = new SPQuery();
query.Query = "<OrderBy><FieldRef Name='Year' /></OrderBy>";
DataTable tempTbl = movies.GetItems(query).GetDataTable();
DataView v = new DataView(tempTbl);
String[] columns = {"Year"};
DataTable tbl = v.ToTable(true, columns);
</code></pre>
<p>You can then proceed using the DataTable tbl.</p>
|
Simple database-based instance synchronization <p>I'm working on a service that runs in a java app server farm that needs to do some periodic jobs (say, once every 2 minutes). The service must interface to external entities, and it is necessary to synchronize the different instances so that only one of them works on the job at a given time. Since the service uses a DB during this job, I thought of implementing the synchronization based on a simple DB table: </p>
<pre><code>id, owner, stamp
</code></pre>
<p>where id is the lock's id, owner is the current owner and stamp is the time it was locked.</p>
<p>The methods would be:</p>
<pre><code>tryLock(id, maxAge, owner) - to try to lock a record or break an old record
refresh(id, owner) - to update the stamp to signal we're still around working on the job
release(id, owner) - to release the lock
</code></pre>
<p>How would you implement this?</p>
<p>Edit: removed my implementation, I'll post it as an "answer"</p>
| <p>I came up with the following implementation, but I'm not sure if it handles all corner cases (and I'm not entirely sure I'm using the BeanManagedTransaction correctly). Also, if you think this syncronization problem could be handled in a simpler way, point me to the right direction.</p>
<pre><code>@Service(objectName=Sync.EjbName)
@Management(SyncMgt.class)
@TransactionManagement(value=TransactionManagementType.BEAN)
public class SyncSvc implements SyncMgt {
@PersistenceContext
protected EntityManager entityManager_;
@Resource
protected UserTransaction utx_;
@TransactionAttribute(TransactionAttributeType.REQUIRED)
private boolean update(SyncRecord sr, String owner) {
Date stamp = (owner != null) ? new Date() : null;
Query q;
if (sr.getOwner() != null) {
q = entityManager_.createQuery("UPDATE SyncRecord sr SET sr.owner = :newOwner, sr.stamp = :stamp WHERE sr.id = :id AND sr.owner = :origOwner AND sr.stamp = :origStamp");
q.setParameter("origOwner", sr.getOwner());
q.setParameter("origStamp", sr.getStamp()); // make it fail if someone refreshed in the meantime
}
else {
q = entityManager_.createQuery("UPDATE SyncRecord sr SET sr.owner = :newOwner, sr.stamp = :stamp WHERE sr.id = :id AND sr.owner IS NULL");
}
q.setParameter("id", sr.getId());
q.setParameter("newOwner", owner);
q.setParameter("stamp", stamp);
int res = q.executeUpdate();
if (res != 1) {
return false;
}
return true;
}
@TransactionAttribute(TransactionAttributeType.REQUIRED)
private boolean tryLockImpl(String id, long maxAge, String owner) {
SyncRecord sr = entityManager_.find(SyncRecord.class, id);
if (sr == null) {
// no record yet, create one
sr = new SyncRecord(id, owner);
sr.touch();
entityManager_.persist(sr);
entityManager_.flush();
return true;
}
// found a SyncRecord, let's see who owns it
if (owner.equals(sr.getOwner())) {
// log some warning, re-locking old lock, should use refresh instead
return update(sr, owner);
}
if (sr.getOwner() == null) {
// sr is not held by anyone, safe to grab it
return update(sr, owner);
}
// someone else holds it, let's check the age
if (maxAge >= 0) {
long maxAgeStamp = System.currentTimeMillis() - maxAge;
if (sr.getStamp().getTime() < maxAgeStamp) {
if (update(sr, owner)) {
return true;
}
return false;
}
}
return false;
}
// Sync impl:
/**
* Try to lock "id" for "owner"
* If the lock is held by someone else, but is older than maxAge, break it
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean tryLock(String id, long maxAge, String owner) {
if (id == null)
throw new IllegalArgumentException("id is null");
try {
utx_.begin();
if (tryLockImpl(id, maxAge, owner)) {
utx_.commit();
return true;
}
}
catch (EntityExistsException e) {
// failed to lock, someone beat us to it
}
catch (Throwable e) {
// some fishy error, raise alarm, log, etc
}
try {
utx_.rollback();
}
catch (Throwable e) {
// log the error, not much else we can do at this point
}
return false;
}
/**
* Refresh lock "id" belonging to "owner" (update its stamp)
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean refresh(String id, String owner) {
if (id == null)
throw new IllegalArgumentException("id is null");
try {
utx_.begin();
SyncRecord sr = entityManager_.find(SyncRecord.class, id);
if (sr == null || !owner.equals(sr.getOwner())) {
utx_.rollback();
return false;
}
if (update(sr, owner)) {
utx_.commit();
return true;
}
}
catch (Throwable e) {
// some fishy error, raise alarm, log, etc
}
try {
utx_.rollback();
}
catch (Throwable e) {
// log the error, not much else we can do at this point
}
return false;
}
/**
* release lock "id" held by "owner"
*/
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void release(String id, String owner) {
if (id == null)
throw new IllegalArgumentException("id is null");
try {
utx_.begin();
SyncRecord sr = entityManager_.find(SyncRecord.class, id);
if (sr == null || !owner.equals(sr.getOwner())) {
// we don't own it
utx_.rollback();
return;
}
if (update(sr, null)) {
utx_.commit();
return;
}
}
catch (Throwable e) {
// some fishy error, raise alarm, log, etc
}
try {
utx_.rollback();
}
catch (Throwable e) {
// log the error, not much else we can do at this point
}
}
// LifeCycle impl:
public void start() {}
public void stop() {}
}
</code></pre>
|
How to sort columns in Excel programmatically using vb.net? <p>we are generating an Excel report and we need to sort the data programmatically before saving the file.</p>
<p>Is it possible to sort a specific column of an Excel file programmatically using vb.net?</p>
<p>As per your suggestion, in order to generate excel report with sorting on specific column I just implemented the logic as below..</p>
<pre><code>Dim MyRange As Excel.Range
gobjExcelReportSheet.Activate()
MyRange = gobjExcelReportSheet.Range("A8", "L8")
MyRange.Select()
MyRange.Sort(Key1:=MyRange.Range("L8"), _
Order1:=XlSortOrder.xlAscending, _
Header:=XlYesNoGuess.xlGuess, _
MatchCase:=False, _
Orientation:=XlSortOrientation.xlSortColumns)
</code></pre>
<p>I tried this logic just before saving the file and even just after saving the file but it is not giving any result i.e. with sorting result or even I am not getting any error.</p>
<p>But the following code works....</p>
<p>gobjExcelReportSheet.Application.Selection.Autofilter()</p>
<p>But there is no option for sorting programmetically.</p>
<p>Please help me...</p>
<p>Thanks!</p>
| <p>Assuming you're using the interop assemblies this is how I do it:</p>
<pre><code>Dim myWorkSheet As Excel.Worksheet = myWorkbook.Worksheets(aSheetName)
myWorkSheet.Activate()
Dim myRange As Excel.Range
myRange = myWorkSheet.Range("A1", "L10")
myRange.Select()
myRange.Sort(Key1:=myRange.Range("D1"), _
Order1:=Excel.XlSortOrder.xlAscending, _
Orientation:=Excel.XlSortOrientation.xlSortColumns)
</code></pre>
<p>Basically you need to select a range (in this case A1:L10, then choose to sort it by a certain column (D). </p>
|
SQL query filtering <p>Using SQL Server 2005, I have a table where certain events are being logged, and I need to create a query that returns only very specific results. There's an example below:</p>
<pre>
<b>Log:</b>
Log_ID | FB_ID | Date | Log_Name | Log_Type
7 | 4 | 2007/11/8 | Nina | Critical
6 | 4 | 2007/11/6 | John | Critical
5 | 4 | 2007/11/6 | Mike | Critical
4 | 4 | 2007/11/6 | Mike | Critical
3 | 3 | 2007/11/3 | Ben | Critical
2 | 3 | 2007/11/1 | Ben | Critical
</pre>
<p>The query should do the following: return ONLY one row per each FB_ID, but this needs to be the one where Log_Name has changed for the first time, or if the name never changes, then the first dated row.</p>
<p>In layman's terms I need this to browse through a DB to check for each instance where the responsibility of a case (FB_ID) has been moved to another person, and in case it never has, then just get the original logger's name.</p>
<p>In the example above, I should get rows (Log_ID) 2 and 6.</p>
<p>Is this even possible? Right now there's a discussion going on whether the DB was just made the wrong way. :)</p>
<p>I imagine I need to somehow be able to store the first resulting Log_Name into a variable and then compare it with an IF condition etc. I have no idea how to do such a thing with SQL though.</p>
<p>Edit: Updated the date. And to clarify on this, the correct result would look like this:</p>
<pre>
Log_ID | FB_ID | Date | Log_Name | Log_Type
6 | 4 | 2007/11/6 | John | Critical
2 | 3 | 2007/11/1 | Ben | Critical
</pre>
<p>It's not the first date per FB_ID I'm after, but the row where the Log_Name is changed from the original.</p>
<p>Originally FB_ID 4 belongs to Mike, but the query should return the row where it moves on to John. However, it should NOT return the row where it moves further on to Nina, because the first responsibility change already happened when John got it.</p>
<p>In the case of Ben with FB_ID 3, the logger is never changed, so the first row for Ben should be returned.</p>
| <p>I guess that there is a better and more performant way, but this one seems to work:</p>
<pre><code>SELECT *
FROM log
WHERE log_id IN
( SELECT MIN(log_id)
FROM log
WHERE
( SELECT COUNT(DISTINCT log_name)
FROM log log2
WHERE log2.fb_id = log.fb_id ) = 1
OR log.log_name <> ( SELECT log_name
FROM log log_3
WHERE log_3.log_id =
( SELECT MIN(log_id)
FROM log log4
WHERE log4.fb_id = log.fb_id ) )
GROUP BY fb_id )
</code></pre>
|
Empty HTML tags <p>I have a lot of empty span tags and so on in my code, due to CSS image replacement techniques.
They trigger a HTML validation warning. Should I care?</p>
<p>Thanks.</p>
| <p>I agree with @Gumbo, but having lots of warnings that make no difference can hide the ones that you do need to pay attention to. If you can put something in the span that gets rid of the warning but doesn't break your UI, you should at least think about doing it.</p>
|
Out of memory error while parsing a specific excel file from a Perl Program <p>When the perl code is run the program generates some warnings and terminates. The output is as below:</p>
<pre><code>D:\Perl\bin\search tool>perl testa.pl
UTF-16 surrogate 0xdb79 at D:/Perl/site/lib/Spreadsheet/ParseExcel/FmtDefault.pm line 81.
UTF-16 surrogate 0xdbb1 at D:/Perl/site/lib/Spreadsheet/ParseExcel/FmtDefault.pm line 81.
UTF-16 surrogate 0xd83e at D:/Perl/site/lib/Spreadsheet/ParseExcel/FmtDefault.pm line 81.
UTF-16 surrogate 0xdff8 at D:/Perl/site/lib/Spreadsheet/ParseExcel/FmtDefault.pm line 81.
UTF-16 surrogate 0xdbff at D:/Perl/site/lib/Spreadsheet/ParseExcel/FmtDefault.pm line 81.
UTF-16 surrogate 0xdd98 at D:/Perl/site/lib/Spreadsheet/ParseExcel/FmtDefault.pm line 81.
substr outside of string at D:/Perl/site/lib/Spreadsheet/ParseExcel.pm line 1196.
Use of uninitialized value in unpack at D:/Perl/site/lib/Spreadsheet/ParseExcel.pm line 1196.
substr outside of string at D:/Perl/site/lib/Spreadsheet/ParseExcel.pm line 1196.
Use of uninitialized value in unpack at D:/Perl/site/lib/Spreadsheet/ParseExcel.pm line 1196.
Out of memory!
</code></pre>
<p>The system information is as below : </p>
<p>Perl version : 5.010000
OS name : MSWin32
Module versions: (not all are required)
Spreadsheet::ParseExcel 0.49
Scalar::Util 1.19
Unicode::Map (not installed)
Spreadsheet::WriteExcel (not installed)
Parse::RecDescent (not installed)
File::Temp 0.18
OLE::Storage_Lite 0.18
IO::Stringy 2.110</p>
<p>The perl code is as below :</p>
<pre><code>use strict;
use Spreadsheet::ParseExcel;
my $parser = Spreadsheet::ParseExcel->new(
CellHandler => \&cell_handler,
NotSetCell => 1
);
my $workbook = $parser->Parse('testfile.xls');
sub cell_handler {
my $workbook = $_[0];
my $sheet_index = $_[1];
my $row = $_[2];
my $col = $_[3];
my $cell = $_[4];
print $cell->unformatted(), "\n";
}
</code></pre>
<p>I have the sample testfile.xls also.</p>
| <p>This question was answered on the Spreadsheet::ParseExcel Google Group <a href="http://groups.google.com/group/spreadsheet-parseexcel/msg/93a9da1f650eded6" rel="nofollow">here</a>.</p>
<p>The problem is that the particular file is encrypted.</p>
<p>John.</p>
|
string.Format() parameters <p>How many parameters can you pass to a string.Format() method?</p>
<p>There must be some sort of theoretical or enforced limit on it. Is it based on the limits of the params[] type or the memory usage of the app that is using it or something else entirely?</p>
| <p>Not as far as I know...</p>
<p>well, the theoretical limit would be the int32 limit for the array, but you'd hit the string length limit long before that, I guess...</p>
<p>Just don't go mad with it ;-p It may be better to write lots of small fragments to (for example) a file or response, than one huge hit.</p>
<p><strong>edit</strong> - it <strong>looked</strong> like there was a limit in the IL (0xf4240), but apparently this isn't quite as it appears; I can make it get quite large (2^24) before I simply run out of system memory...</p>
<p><hr /></p>
<p>Update; it seems to me that the bounding point is the format string... those {1000001}{1000002} add up... a quick bit of math (below) shows that the maximum <strong>useful</strong> number of arguments we can use is 206,449,129:</p>
<pre><code> long remaining = 2147483647;// max theoretical format arg length
long count = 10; // i.e. {0}-{9}
long len = 1;
int total = 0;
while (remaining >= 0) {
for(int i = 0 ; i < count && remaining >= 0; i++) {
total++;
remaining -= len + 2; // allow for {}
}
count *= 10;
len++;
}
Console.WriteLine(total - 1);
</code></pre>
|
in jquery, match the first next element <p>I have a href tag, and next to it is a <b></b> tag. I want to put new text in between the bold tags.</p>
<pre><code><a href=""></a> <b>old text</b>
</code></pre>
<p>So in my click handler, how can I get a reference to the text between the bold tag?</p>
<p>I know there is $(this + b) but how do I make sure it only gets the first and not ALL next items (like in the jquery sample).</p>
| <p>Even though Magnar's answer has been marked as the accepted one, it doesn't actually answer the original question (necessarily). That's a problem when reaching this question from a search. Maybe the question needs to be reworded. Anyway, my point is that this will fail if there's another element in between 'a' and 'b'. To <em>really</em> match the 'first, next' element, use:</p>
<pre><code>$('a').nextAll('b:first')
</code></pre>
<p>Note that Tim Büthe's answer is also incorrect (it could match a previous sibling).</p>
|
c# using Array.ForEach Action Predicate with array of value type or string <p>Am I correct in thinking the following snippet does not work (the array items are not modified) <em>because</em> the array is of integer which is value type. </p>
<pre><code>class Program
{
public static void Main()
{
int[] ints = new int[] { 1,2 };
Array.ForEach(ints, new Action<int>(AddTen));
// ints is not modified
}
static void AddTen(int i)
{
i+=10;
}
}
</code></pre>
<p>The same would apply if the example used an array of string, presumably because string is immutable.</p>
<p>The question I have is:-</p>
<p>Is there a way around this? I can't change the signature of the callback method - for instance by adding the ref keyword and I don't want to wrap the value type with a class - which would work...</p>
<p>(Of course, I could simply write an old fashioned foreach loop to do this!)</p>
| <p>You are simply changing the local variable - not the item in the list. To do this, you want <code>ConvertAll</code>, which creates a new list/array:</p>
<pre><code> int[] ints = new int[] { 1,2 };
int[] newArr = Array.ConvertAll<int,int>(ints, AddTen);
</code></pre>
<p>with:</p>
<pre><code>static int AddTen(int i)
{
return i+10;
}
</code></pre>
<p>This can also be written with an anonymous method:</p>
<pre><code>int[] newArr = Array.ConvertAll<int,int>(ints,
delegate (int i) { return i+ 10;});
</code></pre>
<p>Or in C# 3.0 as a lambda:</p>
<pre><code>int[] newArr = Array.ConvertAll(ints, i=>i+10);
</code></pre>
<p>Other than that... a <code>for</code> loop:</p>
<pre><code>for(int i = 0 ; i < arr.Length ; i++) {
arr[i] = AddTen(arr[i]); // or more directly...
}
</code></pre>
<p>But one way or another, you are going to have to get a value <em>out</em> of your method. Unless you change the signature, you can't.</p>
|
Custom Image Handler: Caching Strategy <h1>The Scenario</h1>
<p>I am building a custom CMS for a communications application. The users can upload images to the server and then later reference them in posts they write using markdown. Images are stored in a database and referenced with a url of the form <code>images/{id}</code>. A custom image handler retrieves these and sets a far future expires header so they aren't fetched over and over again. Storing the images in the file system is not an option per the customer.</p>
<p>Posts are stored in the database as markdown and as html for performance.</p>
<h3>Markdown</h3>
<pre><code>###Header
Lorem Ipsum dolor sit amet. 
</code></pre>
<h3>HTML</h3>
<pre><code><h3>Header</h3>
<p>
Lorem Ipsum dolor sit amet. <img alt="funny cat" src="images/25" />
</p>
</code></pre>
<h1>The Problem</h1>
<p>These images are also editable. From a caching perspective this presents a problem. When an image is edited I need to ensure that the browser gets the latest version. I have come up with the following solutions, all of which I have found to be lacking.</p>
<h1>Possible Solutions</h1>
<h3>Version Field</h3>
<p>Store a version field with the image. Increment it when the image is edited producing urls of the form <code>images/{id}/version/{version}</code>.</p>
<p>This is nice if image urls are always generated from the database. However, I am storing urls in posts as text and would have to preprocess possibly large swaths of text for these requests. Also, linking an image would be troublesome since a url becomes stale after an image is edited. This is probably not a good idea.</p>
<h3>New Url</h3>
<p>When an image is edited, store it as a new entry in the database.</p>
<p>This means no version upkeep, but old links and old posts suffer from the same issues. They're never updated. The performance would be good, but the problem remains.</p>
<h3>304 - Not Modified</h3>
<p>Store a last edited field for each image. When a conditional request comes in return http status 304 - Not Modified, reducing bandwidth usage.</p>
<p>This seems like the best solution I've got so far. The image is cached unless edited, but I've never used this approach before. If there are 50 images on the page there are still 50 requests to the server. Bandwidth will be reduced, but the latency remains. Is this approach worth that cost?</p>
<h1>The Question</h1>
<p>I have very little experience in this area and I'm hoping all of you have more. Are any of the above solutions viable? If so what is your experience with them? If not what is a better approach?</p>
| <p>As you've said, Conditional GET it is the best option, as you only need to check one request header (If-None-Match or If-Modified-Since) and send back the corresponding status code (200 or 304) and a header (E-Tag or Last-Modified). Then the browser will deal with the image cache.</p>
<p>Also, depending on your server framework, if you store your images in the database you could cache them the first time you need them (for a finite amount of time, so you don't consume all your server memory). This helps when you need to read the same image repetitively, saving you database queries. Of course you need to remove your image from the server cache if you edit them.</p>
<p>EDIT: thanks for accepting the answer. In case you need it, here's a nice explanatory link: <a href="http://fishbowl.pastiche.org/2002/10/21/http%5Fconditional%5Fget%5Ffor%5Frss%5Fhackers/" rel="nofollow">HTTP Conditional Get for RSS Hackers</a>.</p>
|
How may I scroll with vim into a big file? <p>I have a big file with thousands of lines of thousands of characters.</p>
<p>I move the cursor to 3000th character.</p>
<p>If I use <kbd>PageDown</kbd> or <kbd>Ctrl</kbd>+<kbd>D</kbd>, the file will scroll but the cursor will come back to the first no-space character.</p>
<p>There's is an option to set to keep the cursor in the same column after a such scroll ?</p>
<p>I have the behavior with gvim on <i>Window</i>, vim on <i>OpenVMS</i> and <i>Cygwin</i>.</p>
| <pre><code>CTRL-E - scroll down
CTRL-Y - scroll up
</code></pre>
<p>100<code><CTRL-E></code> will scroll down 100 lines for example</p>
<p>If you like using <kbd>PageUp</kbd>, <kbd>PageDown</kbd> or <kbd>Ctrl</kbd>+<kbd>D</kbd> etc. you can set the "nostartofline" option</p>
<pre><code>:set nostartofline
</code></pre>
|
When is the 'javascript:' prefix valid syntax? <p>I know that you can use a javascript: pseudo protocol for URLs in an <code><a></code> tag. However, I've noticed that Firefox and IE will both allow '<code>javascript:</code>' to precede javascript code within a <code><script></code> tag. Is this valid syntax? Does it change the scoping rules?</p>
<p>Examples:
I've seen this many times:</p>
<pre><code><a onclick="javascript:alert('hello world!');">Hello World!</a>
</code></pre>
<p>But is this legal/valid syntax and does it do anything special:</p>
<pre><code><script type="text/javascript">
javascript:alert('hello world!');
</script>
</code></pre>
| <p>Outside of the <code>href</code> attribute (where it is a protocol specifier), <em>name</em>: just creates <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/Label">a label</a> (such as one might use with a <code>continue</code> or <code>break</code>).</p>
<h3>See: <a href="http://stackoverflow.com/questions/372159/do-you-ever-need-to-specify-javascript-in-an-onclick">Do you ever need to specify javascript: in an onclick?</a></h3>
|
Need two div's to line up correctly <p><a href="http://img410.imageshack.us/img410/1425/picture2ye4.png" rel="nofollow">Here is a screenshot of how both div's lineup</a>.</p>
<p>The left column is , the div that I want to line up to the right of it is </p>
<p>And both those div's are within </p>
<pre><code>.content-body {
padding:10px 15px;
font-size:.8em;
font-family:arial;
overflow:auto;
}
.col-left {
float:left;
position:relative;
overflow:auto;
height:100%;
width:20%;
padding:0 5px 0 0;
}
.col-middle {
width:auto;
height:auto;
float:left;
xmargin-top:5px;
xfont-size:.8em;
border:1px solid red;
font-family:arial;
}
</code></pre>
<p>How would I get the .col-middle div to line up properly?</p>
<p>Any help is appreciated.</p>
| <p>Change the width of <em>.col-middle</em> to <em>80% or less</em> so both divs can fit inside their container.</p>
<p>You could also make <em>.col-middle</em> float <em>right</em>.</p>
|
partial template specialization for dynamic dispatch <p>I am attempting to write a dynamic dispatcher for a function that's templated on integer values (not on types). While I could either write a code generator or use a big macro chain to create the dispatcher source, it seems that a templated solution would be more elegant.</p>
<p>I've stripped down my dispatcher to a simple form (which doesn't actually do any dispatching):</p>
<pre><code>// works fine with full template specialization
template <int N>
struct TestDispatcher1D {
int f(int n) {
if (n == N) return n; // replace me with actual dispatch
TestDispatcher1D<N-1> t;
return t.f(n);
}
};
template<>
struct TestDispatcher1D<-1> {
int f(int n) { return -1; }
};
// partial template specialization is problematic
template <int M, int N>
struct TestDispatcher2D {
int f(int m, int n);
};
template<int M>
struct TestDispatcher2D<M,-1> {
int f(int m, int n) { return -1; }
};
template<int N>
struct TestDispatcher2D<-1,N> {
int f(int m, int n) { return -1; }
};
template<>
struct TestDispatcher2D<-1,-1> {
int f(int m, int n) { return -1; }
};
template <int M, int N>
int TestDispatcher2D<M,N>::f(int m, int n) {
if ((n == N) && (m == M)) return n + m; // replace me with actual dispatch
if (m < M) {
if (n < N) {
TestDispatcher2D<M-1,N-1> t;
return t(m,n);
} else {
TestDispatcher2D<M-1,N> t;
return t(m,n);
}
} else {
TestDispatcher2D<M,N-1> t;
return t(m,n);
}
}
// test code
void testIt() {
{
TestDispatcher1D<16> t;
t.f(16);
}
{
TestDispatcher1D<16>t;
t.f(0);
}
{
TestDispatcher2D<16,16>t;
t.f(8,8);
}
}
</code></pre>
<p>When compiling this on gcc 4.1.1, I get the following errors:</p>
<pre>
t.cpp: In member function 'int TestDispatcher2D::f(int, int) [with int M = 16, int N = 16]':
t.cpp:63: instantiated from here
t.cpp:40: error: no match for call to '(TestDispatcher2D) (int&, int&)'
t.cpp:63: instantiated from here
t.cpp:43: error: no match for call to '(TestDispatcher2D) (int&, int&)'
t.cpp:63: instantiated from here
t.cpp:47: error: no match for call to '(TestDispatcher2D) (int&, int&)'
</pre>
<p>Apparently, when I try to create the recursive objects, the compiler isn't treating this as a request to instantiate a new template.</p>
<p>Any suggestions?</p>
| <p>You're simply not calling the <code>f()</code> function in your recursive call, you're trying to "call the object":</p>
<p>You write:</p>
<pre><code>TestDispatcher2D<...> t;
return t(m,n);
</code></pre>
<p>But you want:</p>
<pre><code>TestDispatcher2D<...> t;
return t.f(m,n);
</code></pre>
|
Does "tell, don't ask" apply to user input validation? <p>I somehow must have overlooked the "tell, don't ask" OOP principle all these years because I just learned about it a couple days ago for the first time.</p>
<p>But the context was a discussion about validation code that had been moved out of an ASP.NET web form page and into a data/business object, and there was no "Validate()" method, just a save method that itself did validation and (supposedly) raised an exception. I asked why this was designed in this way and I was directed to OOP's "tell, don't ask" principle, which I'd never heard of, so then we looked together at Google and I was immediately educated. ;)</p>
<p>Still, something doesn't smell right, shouldn't data be scrubbed before it gets handed off away from the user and into the business layer where it is processed and/or collected, rather than the other way around? I'm confused as to how this makes for good design.</p>
<p>It seems like the rule of "tell, don't ask" pertains to the idea that you shouldn't ask the target object about the target object's state, and that the principle was never really meant to apply to the data being passed <em>to</em> the target object.</p>
| <p>I thought it sounded like a load of "Best Practices" and "Design Methodologies" gone wrong, but now it kind of makes sense to me. Look at it this way:</p>
<p>Imagine putting validation in the Business Object, but the "what do I do if validation fails' in the presentation layer. This would allow multiple different presentation layers to reuse the same validation logic, but handle errors differently.</p>
<blockquote>
<pre><code>public Foo
{
Validate(Baz bar)
{
if(!is_number(bar)) throw numberexception();
}
AssignBar(Baz bar)
{
Validate(bar);
}
}
//...
try
{
foo.AssignBar(bar);
}
catch(numberexception e)
{
alert('Not a number!');
}
</code></pre>
</blockquote>
<p>n.b. you can argue all you want about throwing exceptions, it was meant as an example. Return states, bools, whatever you want.</p>
|
How many MySQL queries should I limit myself to on a page? PHP / MySQL <p>Okay, so I'm sure plenty of you have built crazy database intensive pages... </p>
<p>I am building a page that I'd like to pull all sorts of unrelated database information from. Here are some sample different queries for this one page:</p>
<ul>
<li>article content and info</li>
<li>IF the author is a registered user, their info</li>
<li>UPDATE the article's view counter</li>
<li>retrieve comments on the article</li>
<li>retrieve information for the authors of the comments</li>
<li>if the reader of the article is signed in, query for info on them</li>
<li>etc...</li>
</ul>
<p>I know these are basically going to be pretty lightning quick, and that I could combine some; but I wanted to make sure that this isn't abnormal?</p>
<p>How many fairly normal and un-heavy queries would you limit yourself to on a page?</p>
| <p>As many as needed, but not more.</p>
<p>Really: don't worry about optimization (right now). Build it first, measure performance second, and <strong>IFF</strong> there is a performance problem somewhere, then start with optimization.</p>
<p>Otherwise, you risk spending a lot of time on optimizing something that doesn't need optimization.</p>
|
What is a good naming convention for domain objects versus their relational tables? <p>I have seen this issue twice now and want to see what a best practice is for resolving this naming convention. Suppose I have an ORM (Linq to SQL in this case) and I map a table called User. Then I create my POCO called User also. Although the mapped table exists in something like</p>
<pre><code>MyApp.Data.User
</code></pre>
<p>and the POCO resides in something like</p>
<pre><code>MyApp.Objects.User
</code></pre>
<p>I realize one can do a full namespace identification for either throughout the code, but do you have a sensible naming convention so you can tell easily which is the table mapping and which is the POCO? Thanks!</p>
| <p>I use to call the Linq2SQL objects DbUser and so on.<br />
This makes it very easy to scan through the code and see which is which, and since the L2S data objects are only accessible in the DataTier, the wierd naming is less of a problem.</p>
|
Classic ASP, ASP.NET, IFrames and response.redirect issue <p>A client has an asp page with an iframe. The Iframe loads an asp.net page inside the asp classic page. </p>
<p>The ASP.NET page is responsible for connecting to a webservice, displaying some data, and then when the user clicks a button it does a response.redirect another classic asp page.</p>
<p>Since the asp.net page is in an iframe, the asp page loads inside the iframe when ideally it should be taking over the entire page.</p>
<p>I have tried putting javascript in the final asp page to break out of iframes but it does not seem to fire.</p>
<p>I tried doing onClientCLick() on the asp.net page and making it break out of the iframe using the following javascript </p>
<p>top.location = self.location.href</p>
<p>But since that sets the location it seems to refresh the page , breaks out of the iframe but does not fire the serverside onclick event which would then perform the backend calculations and do response.redirect.</p>
<p>Any ideas on how I can make sure that the final asp page does not appear inside the iframe and breaks out of it ?</p>
| <p>It sounds like you need to return control to your parent window. You can do this through javascript:</p>
<pre><code>function returnControl(returnPage).
{
parent.window.location.href = returnPage;
}
</code></pre>
|
Hide NSWindowToolbarButton <p>What do I have to do for hiding this <code>NSWindowToolbarButton</code> in windows with a <code>NSToolbar</code>?</p>
| <p>There's a checkbox for this in the appearance section of the attributes tab of the inspector for a window in Interface Builder.</p>
|
ASP.NET 2.0 - DataGrid with tbody / thead <p>Is there a way to get the DataGrid control to render the tbody and thead HTML elements?</p>
| <p>While I like the answer by "user186197", that blog post uses reflection, things might go wrong in non-full-trusted hosting environments. Here's what we use, no hacks:</p>
<pre><code>public class THeadDataGrid : System.Web.UI.WebControls.DataGrid
{
protected override void OnPreRender(EventArgs e)
{
this.UseAccessibleHeader = true; //to make sure we render TH, not TD
Table table = Controls[0] as Table;
if (table != null && table.Rows.Count > 0)
{
table.Rows[0].TableSection = TableRowSection.TableHeader;
table.Rows[table.Rows.Count - 1].TableSection = TableRowSection.TableFooter;
}
base.OnPreRender(e);
}
}
</code></pre>
|
In Java, how do I parse XML as a String instead of a file? <p>I have the following code: </p>
<pre><code>DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
</code></pre>
<p>How can I get it to parse XML contained within a String instead of a file?</p>
| <p>I have this function in my code base, this should work for you.</p>
<pre><code>public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
</code></pre>
<p>also see <a href="http://stackoverflow.com/questions/33262">this similar question</a></p>
|
Is this the proper way of denying remote connections to jssh on Linux? <p>I don't know if jssh has any security built-in. While testing web apps, I would only like to be able to connect to jssh from localhost. I added the following lines to iptables :</p>
<pre><code>
iptables -A INPUT -p tcp -s 0/0 --dport 9997 -j LOG
iptables -A INPUT -p tcp -s 0/0 --dport 9997 -j DROP
</code></pre>
<p>will they provide the security I need?</p>
<p>EDIT : this is related to programming. The test is written in ruby . But for the test to work, jssh must be enabled. By default, jssh runs on port 9997 and accepts all incoming connections. Once connected, it accepts commands from the connected user. Imagine the potential harm it could do if someone connects to a jssh shell that's being ran by an user with administrative priviledges .</p>
<p>EDIT2 : Just because I don't have a problem with the code I write, this doesn't mean that this question should be dismissed. I think it's a legitimate question. I would like to know if I have some control over one of the tools I'm using.</p>
| <p>Have you tested if the default configuration allows connections from outside localhost?</p>
<p>AFAIK, by default it binds to 127.0.0.1 (only localhost), and not to 0.0.0.0 (all interfaces).</p>
|
SQL Server 2005 LENfunction oddity <p>The following code:</p>
<pre><code>if (right(@eqlist,2) = ', ')
set @eqlist = left(@eqlist,len(@eqlist)-2)
</code></pre>
<p>produces different results (with the same data) on my production server than on my development server.</p>
<p>The problem is that the LEN function is 'supposed' to trim off the trailing spaces before calculating the length of a string, but it doesn't seem to be doing so on my development server.</p>
<p>On my development server, it works fine and strips off the trailing ', ' from a string, but on the production server, it's stripping off an extra character. Obviously, changing the "-2" to a "-1" fixes the problem for the production server, but then breaks it for the development server.</p>
<p>I rewrote the code so that it works consistently on both servers, but I'd still like to know why the LEN function behaves differently on each server.</p>
<p>The rewritten code:</p>
<pre><code>if (right(@eqlist,2) = ', ')
set @eqlist = left(rtrim(@eqlist),len(rtrim(@eqlist))-1)
</code></pre>
| <p>Have you checked the value of ANSI_PADDING when your table(s) were created? Without full specifics on your issue I can't say for sure, but if you're going against a table with VARCHAR columns this could cause it to act differently.</p>
|
Requested registry access is not allowed <p>I'm writing a tweak utility that modifies some keys under <code>HKEY_CLASSES_ROOT</code>.</p>
<p>All works fine under Windows XP and so on. But I'm getting error <code>Requested registry access is not allowed</code> under Windows 7. Vista and 2008 I guess too.</p>
<p>How should I modify my code to add UAC support?</p>
| <p><code>app.manifest</code> should be like this:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
</asmv1:assembly>
</code></pre>
|
Inheriting aliases inside UNIX /usr/bin/script <p>The UNIX "/usr/bin/script" command will create a running transcript of your shell session (see "man script" for more info).</p>
<p>However, when <em>inside</em> a script instance, it seems to forget the parent shell's env vars, aliases, etc.</p>
<p>The following example demonstrates how the "ll" alias I define is ignored inside "script":</p>
<pre><code>zsh> mkdir temp
zsh> cd temp
zsh> alias "ll=ls -alF"
zsh> ll
total 24
drwxr-xr-x 2 me mygroup 4096 Feb 18 13:32 ./
drwxr-xr-x 28 me mygroup 8192 Feb 18 13:32 ../
zsh> script a.out
Script started, file is a.out
</code></pre>
<blockquote>
<p>$ ll</p>
<pre><code>zsh: command not found: ll
</code></pre>
</blockquote>
<pre><code>$ exit
Script done, file is a.out
zsh> ll
total 32
drwxr-xr-x 2 me mygroup 4096 Feb 18 13:32 ./
drwxr-xr-x 28 me mygroup 8192 Feb 18 13:32 ../
-rw-r--r-- 1 me mygroup 182 Feb 18 13:32 a.out
</code></pre>
<p>So, how can I get the "script" process to inherit the env settings from the parent shell?</p>
<p>[EDIT:] Okay, env vars are <em>not</em> forgotten. Just the aliases. Re-sourcing the .profile or something would work... but how can I make that happen <strong>automatically</strong>?</p>
| <p>An alias isn't an environment variable. You could source your <code>.profile</code> or where ever you set up the alias. Also take a look at the $SHELL environment variable.</p>
<p>The <code>script</code> command isn't terribly complicated. It wouldn't be too difficult to replicate and make it work the way you expect.</p>
|
retrieving variable from intermed table <p>I need to retrieve institution name by going through an intermediate table. My view gets all the values except this one or at least it is not displaying in the template. Can someone please help with either revising my view or template statement?</p>
<p><a href="http://dpaste.com/122204/" rel="nofollow">http://dpaste.com/122204/</a></p>
<p>Thank you, </p>
<p>May</p>
| <p>To debug these kinds of problems do the following.</p>
<p>Run the view function's processing separate from any template or any other parts of Django.</p>
<p>Either interactively or with a VERY simple script run your query. For example, use a simple script like this to explore your model and make sure your model really works.</p>
<pre><code>from app.models import Contact, Institution, Whatever
results= Researchproject.objects.filter(restitlestrip__icontains='something').distinct()
for project in results:
print project.contact
print contact.institutionname
</code></pre>
<p>Note several things about your simple script and your template.</p>
<ol>
<li><p>Case matters. Project != project. </p></li>
<li><p>Navigation matters. In the script shown above, <code>contact</code> is undefined. <code>project.contact</code>, however, is defined. Perhaps that's what you meant.</p></li>
</ol>
<p>Your model appears incomplete. The <code>Contactintermed</code> table doesn't seem to be used anywhere in your query or view. It may have FK's to other tables, but you don't seem to have a sensible navigation from Project through Contact to Contactinterma to Institution.</p>
<p>Get your model to be correct in a stand-alone script. Add the template processing later.</p>
<p><hr /></p>
<p>Also, please post all the code here on StackOverflow. Chasing your code down all over the internet is a huge pain. It's far easier to simply ignore your question than it is to chase down your code.</p>
|
JNDI failing with NameNotFoundException <p>I'm writing regression tests for a in-house library (where the creators are looong gone) and I'm trying to validate the environment. A couple of the tests keep failing with that NameNotFoundException only when the jndi name is "complex".</p>
<p>This is a stand alone app and is not running with any web containers. The app uses a preference file and there is no LDAP involved. The environment is Java v1.4, and the app is installed with all the necessary libraries local to it. (lib dir with jndi.jar, jms.jar ... etc). Simple, right ?</p>
<p>Due to the complexity of the library and how it futzes around with lots of objects, I have a simple test and then ramp up the complexity adding in each piece as a separate test.</p>
<p>Setup:
File: c:\data\eclipse\workspace\APP\testfiles\jndi\jms\label\.bindings
<br>In file there is this entry: QReply/FactoryName=com.ibm.mq.jms.MQQueueFactory</p>
<p>UnitTest Class:
"simple" test has</p>
<pre><code>Hashtable ht = new Hashtable();
ht.put(Context.PROVIDER_URL,
"file:/data/eclipse/workspace/APP/testFiles/jndi/jms/label/");
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
ht.put(Context.SECURITY_AUTHENTICATION, "none");
Context ctx;
try {
ctx = new InitialContext(ht);
String jndiName = "QReply";
logger.debug("testFindRemoteObject_Simple",
"Invoking InitialContext.lookup(\"" + jndiName + "\")");
Object remoteObject = ctx.lookup(jndiName);
assertTrue(remoteObject != null);
} catch (NamingException e) {
e.printStackTrace();
fail(e.getMessage());
}
</code></pre>
<p>This passes. Because I was having so much trouble with the library I created another test that matches the actual data passed in; the Provider URL is shortened and the jndi name picks up a "path".</p>
<p>"Actual" data unit test:</p>
<pre><code>final Hashtable ht = new Hashtable();
ht.put(Context.PROVIDER_URL,
"file:/data/eclipse/workspace/APP/testFiles/jndi/");
ht.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.fscontext.RefFSContextFactory");
ht.put(Context.SECURITY_AUTHENTICATION, "none");
Context ctx;
try {
ctx = new InitialContext(ht);
String jndiName = "jms/label/QReply";
logger.debug("testFindRemoteObject_Actual",
"Invoking InitialContext.lookup(\"" + jndiName + "\")");
Object remoteObject = ctx.lookup(jndiName);
assertTrue(remoteObject != null);
} catch (NamingException e) {
e.printStackTrace();
fail(e.getMessage());
}
</code></pre>
<p>Which fails with </p>
<pre><code>javax.naming.NameNotFoundException: jms/label/QReply
at com.sun.jndi.fscontext.RefFSContext.getObjectFromBindings(
RefFSContext.java:400)
at com.sun.jndi.fscontext.RefFSContext.lookupObject(RefFSContext.java:327)
at com.sun.jndi.fscontext.RefFSContext.lookup(RefFSContext.java:146)
at com.sun.jndi.fscontext.FSContext.lookup(FSContext.java:127)
at javax.naming.InitialContext.lookup(InitialContext.java:347)
at com.advo.tests.services.UnitTestServiceLocator.testFindRemoteObject_Actual(
UnitTestServiceLocator.java:85)
</code></pre>
<p>where UnitTestServiceLocator.java:85 is the line of ctx.lookup(jndiname);</p>
<p>Why would the simple test pass but the more complex test fail ? Both use a classpath that points to the lib directory which is populated with the jms and mq jars (among other things).</p>
<p>The complex test matches what the library will fill in but using magic as the passed in values. The library code has a "few" more lines that extract the magic values from the preferences file(s).
What am I missing? The library code will work on the server but fail on my laptop (when developing).</p>
<p>I even created another jndi path - just in case the first test was mucking up the second. Still fails.</p>
<p>Since I don't have any desire (or permission to change the library code), the call to InitialContext(X); is that way BECAUSE that's the way the library does it. I've seen the other examples with nothing passed with InitialContext and I'm confused why that is better.</p>
<p>UPDATE:
I've created a jndi_test project on linux java1.5 and that successfully runs the failing test. Taking the same source and moving it to the windows environment - the test fails. There are a few changes to the classpath due to the fact that there is no C drive on linux but the data files are the same. (hmm delimiter issue ?)</p>
<p>I've also found out that I've got problems with that library IF i'm going to run it on 1.5, but that's a side issue.</p>
| <p>I think you're getting mixed up with JNDI names.</p>
<p>"QReply" is the JNDI name. You even say so:</p>
<blockquote>
<p>In file there is this entry: QReply/FactoryName=com.ibm.mq.jms.MQQueueFactory</p>
</blockquote>
<p>If the entry was: "jms/label/QReply" then your second test would work.</p>
|
Display a message in Visual Studio's output window when not debug mode? <p>In Java, you can use <code>System.out.println(message)</code> to print a message to the output window.</p>
<p>What's the equivalent in Visual Studio ?</p>
<p>I know when I'm in debug mode I can use this to see the message in the output window:</p>
<pre><code>Debug.WriteLine("Debug : User_Id = "+Session["User_Id"]);
System.Diagnostics.Trace.WriteLine("Debug : User_Id = "+Session["User_Id"]);
</code></pre>
<p>How can this be done without debugging in Visual Studio?</p>
| <p>The results are not in the Output window but in the Test Results Detail (TestResult Pane at the bottom, right click on on Test Results and go to TestResultDetails).</p>
<p>This works with Debug.WriteLine and Console.WriteLine.</p>
|
SMTP and Unicode/UTF-8 characters...? How do I send them? base64 everything? <p>Using SMTP, how do you send Unicode/UTF-8 e-mails? </p>
<p>Am I expected to base64 encode the UTF-8 body and specify that in the MIME header or...? How about the headers? </p>
<p>I'm sure there's a standard somewhere the describes this...</p>
| <p>Check out the <a href="http://tools.ietf.org/html/rfc2047">RFC 2047</a>.</p>
|
What advantages are there to developing a Win32 app in C++ over a .NET app in C#? <p>I learned windows programming using Visual C++, and the Win32 API. Nowadays, it seems most apps are being developed in .NET using C#. I understand that most of the time there isn't much performance difference between native code and managed code. So I'm wondering, if I were to start writing a new desktop app today, is there any reason (other than the fact that I'm more familiar with C++), that I might want to write it in non-managed C++ instead of .NET? Are there still some advantages to using C++ and native code? Or has that method been more-or-less replaced with .NET on the Windows platform? </p>
<p>Of course I know that people who are writing low-level device drivers and similar programs wouldn't do it in .NET. I'm asking with reference to typical client-facing apps that don't make direct hardware calls.</p>
| <p>IMO the most important one for small downloadable applications is that native code does not need the .NET runtime. While broadband becomes more and more common not nearly everybody has it yet. </p>
<p>Some people may be disappointed to see that your 2 MB application actually requires another 20MB of framework download and a bothersome installation process to run. If they are not sure whether or not they really need your application in the first place, they might just delete it before even giving it a try and turn to a competing product. </p>
|
What is your opinion of Groovy? <p>For your projects, did you have a favorable experience with Groovy? How big was the project? Were there issues with the language? Did you consider Jython, JRuby or Clojure?</p>
| <p><strong>I like</strong></p>
<ol>
<li>Closures</li>
<li>The slurpers</li>
<li>That there is no need of the typically redundant declaration <code>MyType x = new MyType()</code>, which can be reduced to simply <code>def x = MyType()</code>. However, the typing is moot in Groovy (and I don't like that).</li>
<li>That you can test quick and easy with the console (although, to be fair, you could do something similar with a Java class using the main(...) method).</li>
</ol>
<p><strong>I don't like</strong></p>
<ol>
<li><p>It is weak typed. That affects performance, and leads to bugs. Nothing stops you, nor even warn you, of doing the following:</p>
<pre><code>def x = new MyComplexClass()
// oops! accidentally made x equal to 1, that is, an integer
x = 1
// Many lines later ...
// big fat error. Now x is an Integer, so it doesn't know handle myComplexOperation
println "The result is ${x.myComplexOperation(a,b,c)}"
</code></pre></li>
</ol>
<p>It will fail at run time.</p>
<ol start="2">
<li><p>It's hard to maintain somebody else's code. Considering that you can inject attributes to objects, you suddenly find yourself with variables that you have no clue where they come from, or what type they are.</p></li>
<li><p>The type problem can be "alleviated" with more unit tests, but then, the time you save by writing the following method:</p>
<pre><code>def add(a, b) { a + b}
</code></pre>
<p>may be lost by other consideration:</p>
<ul>
<li>You need to decide if it will be acceptable that 'a' and 'b' are a String, an integer, or a matrix class that you created, or something else.</li>
<li>If you try</li>
</ul>
<p>def add(int a, int b) { a + b }</p></li>
</ol>
<p>Groovy will just ignore the types of the parameters. So anybody can still pass Strings or whatever to the method "add". The compiler will not complain.</p>
<p>So now you have to add some sort of validation if you want to ensure that the parameters are integers: </p>
<pre><code>def (Integer a, Integer b) {
assert a instanceof Integer
assert b instanceof Integer
a + b
}
</code></pre>
<p>As far as I can tell, the purpose of static language compilers was to avoid errors at <em>compile time</em>, not at run time.</p>
<ol start="4">
<li><p>If a method call is able to "throw" an error, the compiler doesn't warn you that you have to put a try-catch or add a "throws" to your main method. If you are not aware that a method can throw an exception, you can unknowingly compile a Groovy program without compilation errors, until it booms at run time!</p></li>
<li><p>The console is not that great, because it doesn't provide suggestions like an IDE like Eclipse does. So you need to have your browser or book open to see the available methods for a class. There is also another little trap: you don't need to use 'def' to define a variable in the console, but you need them in a program. So if copy and paste to your IDE from the console, but don forget the def's.</p></li>
<li><p>In my perception Groovy is great in limited amounts, but not for huge projects. This is because many possible errors are detected only at run time, so more unit tests and asserts are necessary, which defeats in part how quickly you can write Groovy programs.</p></li>
<li><p>By default, the properties in Groovy are public, and gets and sets are created automatically. You can override the default behavior, but it's just another thing that you can forget, and hinders the encapsulation of your classes. For example:</p>
<pre><code>âclass Test { String a, b }
class Test2 {
def t = new Test()
Test2 (String s) { t.a = s }
â}âââââââ
}
def t2=new Test2("I am public")
println t2.t.a
</code></pre></li>
</ol>
|
How is shared dll (GAC ) loaded to memory and used in comparison to private dll <p>I'd like to point out that I know how to add/remove assembles to/from GAC. What I am asking for is if someone could explain me how does it work from the technical point of view. What's the point in putting dll's there - from the point of view of saving the resources.</p>
<p>Kind Regards
pk</p>
| <p>The point of putting things in the GAC is so that multiple applications (even from different vendors) can access the same assembly. There is then one location where it can be updated and all applications which can properly access that version can use it. You also know that all assemblies in the GAC are digitally signed, so you know where the code came from (MS for example).</p>
<p>As far as loading into memory. Each application will have to load it on it's own. </p>
|
What methods/techniques/tools do you recommend for documenting systems and infrastructure (runbooks)? <h2>Background</h2>
<p>I recently joined a small start-up after working at a large company.</p>
<p>I'm not a professional system administrator, however, because of my programming and systems knowledge I am now the internal person managing our servers and infrastructure.</p>
<p>In the past, I never needed to document our system information: passwords (for servers, databases, routers, switches, etc), which servers were running which applications (both homemade and installed), server IP addresses, configuration file locations, etc...
The professional system admins always did this work, freeing me to focus on other areas.</p>
<h2>Event that triggered urgency</h2>
<p>I'd been a bit casual about moving this forward until I discovered that I didn't know <em>where</em> my main subversion configuration file was in /etc/apache2 (not to mention that the config file isn't under version control or backed up!) I realized that this needs to be addressed quickly.</p>
<h2>Next step</h2>
<p>I now have to figure out how to document all of this in a sane, elegant, access controlled manner.</p>
<p>I've heard of runbooks, but I don't know the best way or tools to manage them. My first thought was an excel/openoffice spreadsheet under version control.</p>
<p>Is there a good guide to maintaining runbooks? Good software? This must be a fairly common problem, how do you handle it?</p>
| <p>I've actually had good success with a Wiki. Use something where you can control logins easily â Mediawiki is okay, but requires some PHP hacking â and build some templates for processes, inventories, and so forth.</p>
<h3>Update</h3>
<p>Actually, I must have needed coffee. <a href="http://trac.edgewall.org/" rel="nofollow">Trac</a> is pretty nearly ideal; better access control, integrated issue tracking, and a somewhat stronger text model. You can even tie it directly to your subversion repository so that you can hook actual scripts to their runbook pages.</p>
|
How to enforce a "has a" relationship and protect the object that "is had" <p>Given the following code:</p>
<pre><code>Class User{
Task m_Task;
public function getTask("Do work") { return m_Task; }
}
Class Project{
Task m_Task;
public function getTask("Do work") { return m_Task; }
}
Class Task {
private m_Name;
public Task(name) { m_Name = name; }
}
Class Evil {
new Task = Error
}
</code></pre>
<p>In a language that does not support multiple inheritance, nested classes, or private classes, (private constructor not an option), how can you design a requirement that Task is only ever instantiated through User or Project? Ideally using only language constructs instead of code. Is there a design pattern?</p>
| <p>It seems somewhat quixotic, but I suppose you write Task a constructor that requires a User as an argument and does some handshaking back and forth to link the User to the Task, requiring that the User does not already have a Task.</p>
|
How can I reference an encapsulated javascript function from another encapsulated function? <p>I'm new to object oriented javascript. I have a set up method that I want to a) check if an element is null and if so wait and call itself again and b) observe the click event of a button.</p>
<pre><code>ErrorBox.prototype.setUpErrorBox = function(btnClientID) {
if (btnClientID == null) {
setTimeout("setUpErrorBox()", 1000)
return;
}
Event.observe(btnClientID, 'click', setValSummary);
}
</code></pre>
<p>I'm getting errors that setUpErrorBox and setValSummary don't exist (which they don't). How can I reference them? I tried this.setValSummary which didn't work.</p>
<p>In other words, how do I call the equivalent of a class's method from another method of the same class in javascript?</p>
| <p>Use closures to hold on to your execution context:</p>
<pre><code>ErrorBox.prototype.setUpErrorBox = function(btnClientID)
{
var box = this; // object context reference
if (btnClientID == null)
{
// use closure as event handler to maintain context
setTimeout(function() { box.setUpErrorBox() }, 1000)
return;
}
// again, use closure as event handler to maintain context
Event.observe(btnClientID, 'click', function() { box.setValSummary() });
}
</code></pre>
<h3>See also: <a href="http://stackoverflow.com/questions/183214/javascript-callback-scope">JavaScript Callback Scope</a></h3>
|
Best practices for multithreaded processing of database records <p>I have a single process that queries a table for records where <code>PROCESS_IND</code> = 'N', does some processing, and then updates the <code>PROCESS_IND</code> to 'Y'. </p>
<p>I'd like to allow for multiple instances of this process to run, but don't know what the best practices are for avoiding concurrency problems. </p>
<p>Where should I start?</p>
| <p>The pattern I'd use is as follows:</p>
<ul>
<li>Create columns "lockedby" and "locktime" which are a thread/process/machine ID and timestamp respectively (you'll need the machine ID when you split the processing between several machines)</li>
<li><p>Each task would do a query such as:</p>
<p>UPDATE taskstable SET lockedby=(my id), locktime=now() WHERE lockedby IS NULL ORDER BY ID LIMIT 10</p></li>
</ul>
<p>Where 10 is the "batch size". </p>
<ul>
<li>Then each task does a SELECT to find out which rows it's "locked" for processing, and processes those</li>
<li>After each row is complete, you set lockedby and locktime back to NULL</li>
<li>All this is done in a loop for as many batches as exist.</li>
<li>A cron job, or scheduled task, periodically resets the "lockedby" of any row whose locktime is too long ago, as they were presumably done by a task which has hung or crashed. Someone else will then pick them up</li>
</ul>
<p>The LIMIT 10 is MySQL specific but I think other databases have equivalents. The ORDER BY is import to avoid the query being nondeterministic.</p>
|
Fitting Flex Image in Canvas <p>How do I scale an Image in Flex to fit a Canvas? My code follows:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
horizontalAlign="center"
width="100" height="100"
verticalGap="0" borderStyle="solid"
initialize="onLoad()"
horizontalScrollPolicy="off"
verticalScrollPolicy="off">
<mx:Canvas width="100%" height="100%" id="PictureBox" horizontalScrollPolicy="off"
verticalScrollPolicy="off" />
<mx:Label id="NameLabel" height="20%" width="100%"/>
<mx:Script>
<![CDATA[
private function onLoad():void
{
var image:SmoothImage = data.thumbnail;
image.percentHeight = 100;
image.percentWidth = 100;
this.PictureBox.addChild(image);
var sizeString:String = new String();
if ((data.fr.size / 1024) >= 512)
sizeString = "" + int((data.fr.size / 1024 / 1024) * 100)/100 + " MB";
else
sizeString = "" + int((data.fr.size / 1024) * 100)/100 + " KB";
this.NameLabel.text = data.name + " \n" + sizeString;
}
]]>
</mx:Script>
</mx:VBox>
</code></pre>
<p>I am trying to get the image:SmoothImage into PictureBox and scaling it down.</p>
<p><b>Note</b> SmoothImage derives from Image.</p>
| <p>you need to make sure you have set</p>
<pre><code>image.scaleContent = true;
image.maintainAspectRatio = false;
</code></pre>
<p>That should scale the content to the size of the swf loader and distortin it so it fills the entire area of the Image component.</p>
<p>Here's a quick version of it working</p>
<pre><code> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
horizontalAlign="center"
width="100" height="100"
verticalGap="0" borderStyle="solid"
initialize="onLoad()"
horizontalScrollPolicy="off"
verticalScrollPolicy="off">
<mx:Canvas width="100%" height="100%" id="PictureBox" horizontalScrollPolicy="off"
verticalScrollPolicy="off" />
<mx:Label id="NameLabel" height="20%" width="100%"/>
<mx:Script>
<![CDATA[
import mx.controls.Image;
private function onLoad():void
{
var image : Image = new Image()
image.source = "http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png";
image.scaleContent = true;
image.maintainAspectRatio =false;
image.percentWidth = 100;
image.percentHeight = 100;
PictureBox.addChild(image);
}
]]>
</mx:Script>
</mx:VBox>
</code></pre>
|
Can optimizations affect the ability to debug a VC++ app using its PDB? <p>In order to be able to properly debug release builds a PDB file is needed. Can the PDB file become less usable when the compiler uses different kinds of optimizations (FPO, PGO, intrinsic functions, inlining etc.)? If so, is the effect of optimization severe or merely cause adjacent lines of code to get mixed up?</p>
<p><em>(I'm using VC2005, and will always choose debugability over optimized performance - but the question is general)</em></p>
| <p>Yes, optimized code is less debuggable. Not only is some information missing, some information will be very misleading.</p>
<p>The biggest issue in my opinion is local variables. The compiler may use the same stack address or register for multiple variables throughout a function. As other posters mentioned, sometimes even figuring out what the "this" pointer is can take a bit of time. When debugging optimized code you may see the current line jumping around as you single step, since the compiler reorganized the generated code. If you use PGO, this jumping around will probably just get worse.</p>
<p>FPO shouldn't affect debuggability too much provided you have a PDB since the PDB contains all the info necessary to unwind the stack for FPO frames. FPO can be a problem when using tools that need to take stack traces without symbols. For many projects, the perf benefit of FPO nowadays doesn't outweigh the hit for diagnosability; for this reason, MS decided not to build Windows Vista with the FPO optimization (<a href="http://blogs.msdn.com/larryosterman/archive/2007/03/12/fpo.aspx">http://blogs.msdn.com/larryosterman/archive/2007/03/12/fpo.aspx</a>).</p>
<p>I prefer to debug unoptimized code but this isn't always possible - some problems only repro with optimized code, customer crash dumps are from the released build, and getting a debug private deployed sometimes isn't possible. Often when debugging optimized code, I use the disassembly view - dissasembly never lies.</p>
<p>This all applies to windbg since I do all native code debugging with it. Visual Studio's debugger might handle some of these cases better.</p>
|
Where can I find a good NHibernate and ASP.NET MVC Reference Application <p>Where can I find a good NHibernate and ASP.NET MVC Reference Application? I downloaded S#arp and this seemed to be a lot more than I needed (IOC and CodeGen via T4). I might work my way up to this later, but I need something smaller at first.</p>
<p>Any simple examples? I just want to pick up how NHibernate Session handling works in ASP.NET MVC. And maybe how some simple query scenarios work. Still trying to grasp how a <a href="http://stackoverflow.com/questions/558974/nhibernate-select-distinct-equivalent-for-a-page-filter-northwind">SELECT DISTINCT</a> would be done in NHibernate and through to the View via the ViewData.</p>
| <p>I would try to tackle them independently. </p>
<p>Before Billy McCafferty wrote sharp-architecture he wrote, what I think is, a must read on <a href="http://www.codeproject.com/KB/architecture/NHibernateBestPractices.aspx">codeproject</a> about best practices with NHibernate. Also, I have just discovered some <a href="http://dimecasts.net/Casts/ByTag/MVC">DimeCasts</a>(by Kyle Baley) under the MVC tag that are very good.</p>
<p><a href="http://blog.wekeroad.com/">Rob Conery</a> created the ASP.NET <a href="http://www.asp.net/learn/mvc-videos/">MVC Storefront</a> video series which he goes over a lot of patterns and practices. The backend written is using Linq to SQL but can be adapted with <a href="http://ayende.com/Blog/archive/2007/03/16/Linq-for-NHibernate.aspx">LinQ to NHibernate</a>. More recently he has also done a video series on <a href="http://tekpub.com/preview/nhibernate">TekPub</a> - NHibernate with <a href="http://ayende.com/blog/">Ayende Rahien</a>. Lastly (for NHibernate) there is the <a href="http://www.summerofnhibernate.com/">Summer of NHibernate</a></p>
<p>The <a href="http://code.google.com/p/sharp-architecture/">S# arch source</a> itself now comes with a sample projects as well. </p>
<p>Finally, there is <a href="http://code.google.com/p/codecampserver/"><strong>Code Camp Server</strong></a> that is built with MVC.Net and NHibernate and uses pretty much every open source tool you can think of... </p>
<p><em>sidenote</em></p>
<p>If your interested in getting rid of those annoying XML files when using NHibernate you might also want to look at <a href="http://nhforge.org/blogs/nhibernate/archive/2008/09/02/a-fluent-interface-to-nhibernate-part-1.aspx">fluent</a>.</p>
|
What is the quickest way from a concept to a site? <p>I've got a bunch of website ideas and I was wondering what is the quickest way to get from a pretty thorough concept definition (idea mind-maps, use-cases, architecture diagrams ) to a working website. The only point is to get to something that's functional, not worrying about performance. The idea is to get something out to showcase a functional site, and after worry about fine-tuning or re-writing parts if necessary. </p>
<p>I am familiar with quite a few web frameworks from open-source and proprietary world, but I could not find so far a swiss-army-knife of web development environments that can get you fast from a concept to a working site. I was kinda wondering if there is such a thing, free or non-free </p>
<p>Looking forward to your suggestions...</p>
<p>UPDATE: The question might get a bit too metaphoric for the kind readers of this site, but I'm at a moment where I feel that implementation details are killing my creativity ... maybe you'll laugh or you'll feel offended, I'm just wondering if anyone can give me a useful hint.. </p>
| <p>First, select a dynamic scripting language. Static types and compilation will slow development. PHP is a good choice since you can download a LAMP package like xampp and start immediately.</p>
<p>Next, use a CMS if at all possible. If you require a flexible front end design, then choose a template focused CMS like Expression Engine. If your site can be relatively generic looking, then use something like Drupal.</p>
<p>If you require the flexibility of a framework, how much time can you spend learning it? You'll get up to speed with CodeIgniter or Kohana quickly. Other frameworks can save time with behind-the-scenes magic, but you can lose flexibility and the learning curve is <strike>steep</strike> expensive.</p>
|
Oracle: What exactly do quotation marks around the table name do? <p>I thought that the quotation mark (") was simply a type of grouping marker but I'm debugging some NHibernate code and notice that while</p>
<pre><code>SELECT * FROM site WHERE site_id = 3;
</code></pre>
<p>Works fine</p>
<pre><code>SELECT * FROM "site" WHERE site_id = 3;
</code></pre>
<p>fails with a table or view does not exist error.</p>
<p>What gives?</p>
| <p>Putting double-quotes around an identifier in Oracle causes Oracle to treat the identifier as case sensitive rather than using the default of case-insensitivity. If you create a table (or a column) with double-quotes around the name, you must always refer to the identifier with double quotes and by correctly specifying the case (with the exception of all upper case identifiers, where double-quotes are meaningless).</p>
<p>Under the covers, Oracle is always doing case-sensitive identifier matching. But it always casts identifiers that are not double-quoted to upper case before doing the matching. If you put double-quotes around an identifier, Oracle skips the casting to upper case.</p>
<p>So if you do something like</p>
<pre><code>CREATE TABLE my_table(
col1 number,
col2 number
)
</code></pre>
<p>you can</p>
<pre><code>SELECT * FROM my_table
SELECT * FROM MY_TABLE
SELECT * FROM My_Table
SELECT * FROM "MY_TABLE"
</code></pre>
<p>but something like</p>
<pre><code>SELECT * FROM "my_table"
</code></pre>
<p>will fail.</p>
<p>On the other hand, if you do something like</p>
<pre><code>CREATE TABLE "my_other_table"(
col1 number,
col2 number
)
</code></pre>
<p>you cannot do</p>
<pre><code>SELECT * FROM my_other_table
SELECT * FROM MY_OTHER_TABLE
SELECT * FROM My_Other_Table
SELECT * FROM "MY_OTHER_TABLE"
</code></pre>
<p>but this</p>
<pre><code>SELECT * FROM "my_other_table"
</code></pre>
<p>will work</p>
|
How can I resolve a "Provider load failure" for WMI requests? <p>I'm using WMI to collect system information. It works fine on every system I've tested it on, but I have one or two users that are reporting problems. The debug logs show the WMI code is throwing a "Provider load failure" exception. I haven't been able to replicate the issue.</p>
<p>The users have verified that the WMI service is running in Automatic mode.</p>
<p>Here's the exception:</p>
<pre><code>System.Management.ManagementException: Provider load failure
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
</code></pre>
<p>Any thoughts on how to troubleshoot and resolve this issue?</p>
| <p>One way to possibly track down the root cause of the issue is to use <a href="http://technet.microsoft.com/en-us/library/cc180684.aspx" rel="nofollow">WBEMTest</a> a tool that the MS Scripting Guys say is one of the easiest ways</p>
<blockquote>
<p>"To find the provider of a WMI class..."</p>
</blockquote>
<p>The Scripting Guys: <a href="http://blogs.technet.com/b/heyscriptingguy/archive/2012/09/12/use-powershell-to-troubleshoot-provider-load-failure.aspx" rel="nofollow">Use PowerShell to Troubleshoot âProvider Load Failureâ</a></p>
<p>The high level steps specific to the Win32_NetworkAdapter are described in this <a href="http://blogs.infosupport.com/win32_network-adapter-provider-load-failure/" rel="nofollow">Win32_network adapter "provider load failure"</a> post by Mark Wolzak at infoSupport.</p>
<ul>
<li>Click start >> run >> wbemtest</li>
<li>click 'Connectâ¦' to connect to a namespace</li>
<li>execute the query 'Select * From MSFT_WmiSelfEvent'</li>
<li>scroll down to the bottom and trace the following WMI events</li>
<li>Look at the details of any Msft_WmiProvider_InitializationOperationFailureEvent or Msft_WmiProvider_LoadOperationFailureEvent for the dll that is causing the issue</li>
</ul>
<p>Thanks to the <a href="http://msmvps.com/blogs/richardsiddaway/archive/2011/03/13/wmi-provider-load-failure.aspx" rel="nofollow">WMIâProvider Load Failure</a> post at Richard Siddaway's Blog for pointing me to this tool and specific methodology.</p>
|
NHibernate Eager loading multi-level child objects <p>I have a hierarchy of objects, Order, Contact, Address:</p>
<pre><code>public class Order {
public virtual Contact BillingContact { get; set; }
}
public class Contact {
public virtual Address Address { get; set; }
}
</code></pre>
<p>I want to query an order by id, and eager load the billingcontact, along with it's address.</p>
<pre><code>var criteria = DetachedCriteria.For<Order>()
.SetFetchMode("BillingContact", FetchMode.Eager)
</code></pre>
<p>This criteria eager loads the BillingContact, but understandably not the address of the BillingContact. If i add:</p>
<pre><code> .SetFetchMode("BillingContact.Address", FetchMode.Eager)
</code></pre>
<p>This does nothing to help.</p>
<p>Also note that these relationships are unidirectional:</p>
<pre><code>public OrderMap()
{
References(x => x.BillingContact)
.Not.Nullable()
.Cascade.All();
}
public ContactMap()
{
HasOne(x => x.Address)
.Cascade.All()
.FetchType.Join();
}
public AddressMap()
{
Map(x => x.Address1);
}
</code></pre>
<p>How can I construct a criteria object that will load the child of the child? Do these relationship mappings seem correct?</p>
| <p>I believe you might need to add an alias to BillingContact to allow you access to it's Address.</p>
<p>Something like:</p>
<pre><code>var criteria = DetachedCriteria.For<Order>()
.CreateAlias("BillingContact", "bc")
.SetFetchMode("BillingContact", FetchMode.Eager)
.SetFetchMode("bc.Address", FetchMode.Eager)
</code></pre>
|
How to start with a PHP website? <p>For a school project I have to produce a website using PHP that allows user to generate there own article or comment on news or others articles. I was wondering how it is best to use the GET function to show the content in an include file and also use the get function for other include files such as the login page and other content the developer (me) has added to website not as articles but as links etc. Anyone got any suggestions or good tutorials they could post up. </p>
| <p>Wheel has been invented, tested, rolled for a million miles: <a href="http://wordpress.org/" rel="nofollow"><strong>WordPress</strong></a></p>
|
What UNIX commands support coloured output? <p>I enjoy using UNIX/bash commands that support coloured output. Consequently, I have a few aliases defined which automatically enable coloured output of the commands that I know support this option. However, I'm sure there are hundreds of commands out there that support coloured output - I'd like to know what they are.</p>
<p>The ones in my <code>~/.bash_aliases</code> file are:</p>
<pre><code>ls --color=auto
grep --color
phpunit --ansi
</code></pre>
<p>What else is there? Is there a list somewhere of all commands that support coloured output? Or better still, some command for grepping my local man pages and plucking out the appropriate command names.</p>
| <p>Why don't you try:</p>
<pre><code>man -K color
</code></pre>
<p>That should search for the word color in all your man pages (content, not just headings).</p>
<p>It asks, for each man page, whether you want to open and view the page:</p>
<pre><code>$ man -K color
/usr/share/man/mann/Widget.n.gz? [ynq] y
/usr/share/man/mann/usual.n.gz? [ynq] y
/usr/share/man/mann/Toplevel.n.gz? [ynq] n
/usr/share/man/mann/itk.n.gz? [ynq] n
/usr/share/man/mann/Archetype.n.gz? [ynq] n
/usr/share/man/man8/squid.8.gz? [ynq] n
/usr/share/man/man7/Xprint.7.gz? [ynq]
/usr/share/man/man7/X.7.gz? [ynq]
/usr/share/man/man7/urxvt.7.gz? [ynq]
/usr/share/man/man7/term.7.gz? [ynq] q
$
</code></pre>
<p>Inside each individual man page, you can use your normal search method (e.g., <code>/color<ENTER></code>) for finding the text. When done with a man page, just exit and it will continue searching.</p>
|
Using GPS to measure area <p>Hey guys, I'm researching something for a friend of mine who's involved in road construction. He needs some sort of a device that he can use to measure distance or area between points. I have done some GPS programming in the past but for mobile devices and i wasn't too impressed with accuracy. That was quite a few years ago and i think the technology has improved, however i am not sure what device i should as the receiver. Since a mobile device would probably be out of the question because i'd need to be able to run my custom application on it, something that hooks up through a USB port would maybe work? I found u-blox PCI hard that works with laptops and PCs. Has anyone on here had any experience with it? Perhaps there are other devices i'd need to look into?</p>
<p>I appreciate any help i can get on this. Thank you.</p>
| <p>You could use a mobile device that has GPS and the ability to run your custom software like the iphone, google phones, and probably a lot of other smart phones.</p>
|
svnsync: PROPFIND request failed <p>I'm desperately trying to backup my google code-repo but since
I'm not too familiar with SVN, I can't get svnsync to work.
I thought that backing up your repo to another repo or dumpfile was an easy
task, but I'm wrong? I would really appreciate tips on how to do this..</p>
<p>What I'm trying to do:</p>
<p><em>@shell:~$ svnsync init <a href="http://www" rel="nofollow">http://www</a>.</em>.org/svn/
http://<em>.gooâglecode.com/svn/trunâk
svnsync: PROPFIND request failed on '/svn'
svnsync: PROPFIND of '/svn': 301 Moved Permanently (<a href="http://www" rel="nofollow">http://www</a>.</em>.org)</p>
<p>What does that mean? And is it possible to fix it?</p>
<p><a href="http://www" rel="nofollow">http://www</a>.*.org/svn/ was created with svnadmin create, ofc.</p>
<p>Thanks in advance! =)</p>
| <p>I would raise this in a comment, but I don't have the points to comment yet. It looks like at least part of your problem is that your URLs may not be correct. The 301 is telling you that the resource you expect to find there is not actually there, so I'd start by checking that URL by doing an svn ls on it.</p>
|
Can I get && to work in Powershell? <p><code>&&</code> is notoriously hard to search for on google, but the best I've found is <a href="http://www.microsoft.com/technet/scriptcenter/webcasts/psweek/day4qanda.mspx">this article</a> which says to use <code>-and</code>.</p>
<p>Unfortunately it doesn't give any more information, and I can't find out what I'm supposed to do with <code>-and</code> (again, a notoriously hard thing to search for)</p>
<p>The context I'm trying to use it in is "execute cmd1, and if successful, execute cmd2", basically this:</p>
<pre><code>csc /t:exe /out:a.exe SomeFile.cs && a.exe
</code></pre>
<p>This should be an easy few rep points to someone who knows, thanks!</p>
<hr>
<p>Edit: If you just want to run multiple commands on a single line and you don't care if the first one fails or not, you can use <code>;</code> For most of my purposes this is fine</p>
<p>For example: <code>kill -n myapp; ./myapp.exe</code>. </p>
| <p>In CMD, '&&' means "execute command 1, and if it succeeds, execute command 2". I have used it for things like:</p>
<pre><code>build && run_tests
</code></pre>
<p>In PowerShell, the closest thing you can do is:</p>
<pre><code>(build) -and (run_tests)
</code></pre>
<p>It has the same logic, but the output text from the commands is lost. Maybe it is good enough for you, though.</p>
<p><strong>EDIT</strong></p>
<p>If you're doing this in a script, you will probably be better off separating the statements, like this:</p>
<pre><code>build
if ($?) {
run_tests
}
</code></pre>
|
A declarative workflow does not start automatically after you install Windows SharePoint Services 3.0 Service Pack 1 <p>That's the title of <a href="http://support.microsoft.com/kb/947284" rel="nofollow">kb947284</a> actually. Recently I was involved in a Sharepoint project. I run into this problem where <strong>my workflow does not start automatically</strong>. If I run the workflow <strong>manually, it's just fine</strong>. I found <a href="http://support.microsoft.com/kb/947284" rel="nofollow">kb947284</a>. Apparently the cause of this problem is the installation of <strong>WSS 3 SP1</strong>. I did what it said in the Resolution section but it didn't work.</p>
<p>The Resolution said <strong>to set the application pool account to use a different user account</strong>. <strong>What kind of different does it mean? What kind of user account will work?</strong> I changed the user account but both old and new account is in the same group of administrator for the server where SP is installed. </p>
<p>Oh! I also found a copy of kb947284 and one comments stated there is already a hotfix (<a href="http://support.microsoft.com/default.aspx/kb/956057" rel="nofollow">kb956057</a>). I've read the issues that are fixed but could not find anywhere about this workflow problem.</p>
<p>Could anyone please tell me how it's supposed to be done? Thanks in advance.</p>
| <p>From the KB:</p>
<p>This behavior occurs because a security fix in Windows SharePoint Services 3.0 SP1 prevents declarative workflows from starting automatically under the system account. After you install Windows SharePoint Services 3.0 SP1, declarative workflows do not start automatically if the following conditions are true:</p>
<ol>
<li>The Windows SharePoint Services Web
application runs under a user's
domain account.</li>
<li>The user logs in by using this
domain account.</li>
<li>The site displays the user name as
System Account. Back to the top</li>
</ol>
<p>My Questions are:
Have you installed WSS SP1?</p>
<p>Are the 3 conditions stated above met?</p>
<p>If so, the application pool identity should be changed to one that isn't used by a person logging into SharePoint.</p>
|
Reading an Excel file in PHP <p>I'm trying to read an Excel file (Office 2003). There is an Excel file that needs to be uploaded and its contents parsed.</p>
<p>Via Google, I can only find answers to these related (and insufficient topics): generating Excel files, reading Excel XML files, reading Excel CSV files, or incomplete abandoned projects. I own Office 2003 so if I need any files from there, they are available. It's installed on my box but isn't and can't be installed on my shared host.</p>
<p><b>Edit:</b> so far all answers point to <a href="http://sourceforge.net/docman/display_doc.php?docid=22092&group_id=99160">PHP-ExcelReader</a> and/or <a href="http://devzone.zend.com/article/3336-Reading-and-Writing-Spreadsheets-with-PHP">this additional article</a> about how to use it.</p>
| <p>You have 2 choice as far as I know:</p>
<ol>
<li><a href="http://sourceforge.net/projects/phpexcelreader/">Spreadsheet_Excel_Reader</a>, which knows the Office 2003 binary format</li>
<li><a href="http://www.codeplex.com/PHPExcel">PHPExcel</a>, which knows both Office 2003 as well as Excel 2007 (XML).</li>
</ol>
<p>PHPExcel uses Spreadsheet_Excel_Reader for the Office 2003 format.</p>
<p>Update: I once had to read some Excel files but I used the Office 2003 XML format in order to read them and told the people that were using the application to save and upload only that type of Excel file.</p>
|
JQuery - How to add a class to every last list item? <p>Got some code here that isn't working:</p>
<pre><code>$("#sidebar ul li:last").each(function(){
$(this).addClass("last");
});
</code></pre>
<p>Basically I have 3 lists and want to add a class (last) to each item appearing last in each unordered list.</p>
<pre><code><ul>
<li>Item 1</li>
<li>Item 2</li>
<li class="last">Item 3</li>
</ul>
</code></pre>
<p>Hope that makes sense,
Cheers!</p>
| <p>Easy mistake to make. Try this:</p>
<pre><code>$("#sidebar ul li:last-child").addClass("last");
</code></pre>
<p>Basically :last doesn't quite do what you think it does. It only matches the very last in the document, not the last in each list. That's what :last-child is for.</p>
|
Why does Thread.Sleep(0) fix my problems, and how to avoid it? <p>I'm working on a client server application. At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock. If I step in to debug the problem, then the program appears to be processing. Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem. The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code. If I don't call it enough, the code seems to be in deadlock. Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread. </p>
<p>Is there a good way to track down exactly what is causing this. It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP. However, it's impossible to debug, because simply stepping into the code causes the problem to go away. I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there. Any pointers would be greatly appreciated.</p>
<p>[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher. I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode. The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.</p>
<p>[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely. Still the problem persists. There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there. And it's not deadlocked. It runs, albeit very slowly, even though it's eating up all the processor resources.</p>
| <p>Thread.Sleep(0) is a yield. I am guessing this rearranges the way you call to avoid some issues. I think if you released code with the yield and ran it on 1000 machines, you would get a lot of bug reports. I am guessing you need some type of lock/critical section to avoid your dead lock because some where your code is not thread safe. That could be in a library you are calling.</p>
<ol>
<li><strong>Add in logging and see if the problems still happens.</strong> Hopefully you can figure out what functions are causing the dead lock</li>
<li><strong>Add some critical sections.</strong> Uses a divide and conquer approach you should be able to narrow down where the problem is happening.</li>
</ol>
|
How can I check the memory usage of objects in iPython? <p>I am using iPython to run my code. I wonder if there is any module or command which would allow me to check the memory usage of an object. For instance:</p>
<pre><code>In [1]: a = range(10000)
In [2]: %memusage a
Out[2]: 1MB
</code></pre>
<p>Something like <code>%memusage <object></code> and return the memory used by the object.</p>
<p><strong>Duplicate</strong></p>
<blockquote>
<p><a href="http://stackoverflow.com/questions/33978/find-out-how-much-memory-is-being-used-by-an-object-in-python">Find out how much memory is being used by an object in Python</a></p>
</blockquote>
| <p>Unfortunately this is not possible, but there are a number of ways of approximating the answer:</p>
<ol>
<li><p>for very simple objects (e.g. ints, strings, floats, doubles) which are represented more or less as simple C-language types you can simply calculate the number of bytes as with <a href="http://stackoverflow.com/a/563921/1922357">John Mulder's solution</a>.</p></li>
<li><p>For more complex objects a good approximation is to serialize the object to a string using cPickle.dumps. The length of the string is a good approximation of the amount of memory required to store an object. </p></li>
</ol>
<p>There is one big snag with solution 2, which is that objects usually contain references to other objects. For example a dict contains string-keys and other objects as values. Those other objects might be shared. Since pickle always tries to do a complete serialization of the object it will always over-estimate the amount of memory required to store an object.</p>
|
How to read CGBitmapContextData? (on iPhone) <p>I'm working on obtaining bitmap data like ARGB from an image. </p>
<p>a). I create a bitmapcontext for the image: </p>
<pre><code>context = CGBitmapContextCreate(void * data, size_t width, size_t height, size_t bitsPerComponent, size_t bytesPerRow, CGColorSpaceRef colorspace, CGBitmapInfo bitmapInfo)</code></pre>
<p>b). I draw the image to the context:</p>
<pre><code>CGContextDrawImage(context, rect, imageRef);</code></pre>
<p>c). Then I get data from the bitmapcontext: </p>
<pre><code>void * data = CGBitmapContextGetData(context);</code></pre>
<p>d). void... not readable?</p>
<p>I find that it only returns a void pointer to the image context data which means the data of the context cannot be obtained(writeOnly). Are there any other ways to return the value from the context data?</p>
<p>PS: If I create an unsigned char pointer * data, it will return 240 for RGB and 255 for alpha which are not the correct color components.</p>
| <p>The pointer can still point to the image data even if its type is void. I posted another related topic at:
<a href="http://stackoverflow.com/questions/561663/how-to-pull-out-the-argb-component-from-bitmapcontext-on-iphone">http://stackoverflow.com/questions/561663/how-to-pull-out-the-argb-component-from-bitmapcontext-on-iphone</a></p>
<p>And the problem had already been solved.</p>
|
Is there a way to simulate a click on an alert in JavaScript? <p>I have a page with an iframe whose source page is in a separate domain. From time to time, the source page generates an alert. When it does so, it stops what it is doing until the user clicks OK to the alert.</p>
<p>What I would like to do is programmatically click OK on this alert so the source page can get back to being useful. Is this possible?</p>
| <p>JavaScript is single-threaded, which means when you call a function, it blocks until it returns. When you call alert(), that passes control to the browser which decides how to handle it. It is not Javascript which is popping the UI dialog, it is the browser. alert() does not return until the browser receives the "OK" event and returns control. The javascript thread is halted until that happens.</p>
<p>So for at least two different reasons stated in the above paragraph, the answer is <strong>no</strong> :)</p>
|
HTML unordered list sucks in IE7 <p>I've created a HTML ordered list which looks fine in FF, but pretty awful in IE.
My specific problems with the way IE displays the list are:</p>
<ol>
<li>List markers are missing</li>
<li>Vertical spacing between list items is very uneven</li>
</ol>
<p>It seems the superscripts are the cause of (2), but I'm not sure how I can fix this problem (without removing the superscripts).</p>
<p><strong>EDIT:</strong> I gave up on my single-list dreams and split the list into 3 separate lists. I've removed the link from the text above to avoid confusing future readers.</p>
<p>Thanks,
Don</p>
| <p>This is a known bug of IE5, IE6, and still in IE 7.</p>
<p>IE 8 Beta 2 and the latest, IE 8 RC1, will display your web page correctly.</p>
<p>But these are a list of list item bug before IE 8:</p>
<p><a href="http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/" rel="nofollow">http://www.gtalbot.org/BrowserBugsSection/MSIE7Bugs/</a></p>
<p><a href="http://gtwebdev.com/workshop/gaps/white-space-bug.php" rel="nofollow">http://gtwebdev.com/workshop/gaps/white-space-bug.php</a></p>
|
How can I extract a subtree from my svn repository into a new one? <p>We have a subversion repository with one directory that is:</p>
<ul>
<li>not really in need of revision control beyond the capabilities of RCS</li>
<li>not versioned in conjunction with anything else in the repository</li>
<li>modified about 6x as often as the rest of the repository</li>
</ul>
<p>Although I know that high rev numbers aren't a problem, nonetheless I'd like to pull this one single directory out of my main repository and into a second, ideally new one.</p>
<p>What is the best process for that? If it makes a difference, the svn repository is hosted on a (... checks... ) FreeBSD machine.</p>
<p>(edit) It's worth noting that while I need to retain the version history in the new repository, there's no need to obliterate the content in the old; it can just sit there, for all I care.</p>
| <p>You could use <em>svnadmin dump</em> and <em>svnadmin load</em> to create a new repository from the original one; then copy the directory that doesn't really fit into your scheme to a better location, then delete everything else. In the original repository you would simply delete the non-fitting directory. This keeps all history intact, and you end up with two repositories.</p>
<p>There is probably a way to subsequently clean both repositories from the then useless parts of the history (<em>svndumpfilter</em>), but since hard disc space is quite cheap I wouldn't think this necessary. Anyway, the <a href="http://svnbook.red-bean.com/en/1.1/ch05s03.html#svn-ch-5-sect-3.5" rel="nofollow">SVN documentation</a> has all the information about it.</p>
|
Program to view what a webpage would look through a mobile phone <p>I know this might off subject but what's a good program let's me view what a website might look like on a iPhone or other mobile device which connects to the Internet. Dreamweaver cs3 might have this but I can't find it anyone know?</p>
| <p>Use the iphone simulator (part of the iphone SDK) and go to the webpage you want to test using safari. </p>
<p>Very simple except you will need a intel mac ( can be done on a ppc mac but installing the SDK requires some tricks on ppc and is not supported).</p>
|
In Sql Server 2005, is there a way to query the total disk space (physical hard drive(s)) available on the server? <p>I found this in googling, but I don't think it's the complete code?</p>
<p><a href="http://www.dba-oracle.com/t_sql_server_2005_windows_script_display_disk_space_usage.htm" rel="nofollow">http://www.dba-oracle.com/t_sql_server_2005_windows_script_display_disk_space_usage.htm</a></p>
<p>I was hoping there was a simple system stored procedure, like for finding the total size of MDF file (exec sp_helpdb DATABASE_NAME).</p>
<p>Any suggestions would be appreciated.</p>
| <p>Does xp_fixeddrives do the trick? </p>
<pre><code>EXEC master.dbo.xp_fixeddrives
</code></pre>
|
Checking the value of a Lua stack item from C++ <p>how do I check the value of the top of the stack in Lua?</p>
<p>I have the following C++ code:</p>
<pre><code>if (luaL_loadfile(L, filename) == NULL) {
return 0;// error..
}
lua_pcall(L,0,0,0); // execute the current script..
lua_getglobal(L,"variable");
if (!lua_isstring(L,-1)){ // fails this check..
lua_pop(L,1);
return 0; // error
}
</code></pre>
<p>The contents of the file in question is</p>
<pre><code>-- A comment
variable = "MyString"
</code></pre>
<p>Any ideas?</p>
| <p>The likely problem is that <a href="http://www.lua.org/manual/5.1/manual.html#luaL_loadfile" rel="nofollow"><code>luaL_loadfile()</code></a> is documented to return the same values as <a href="http://www.lua.org/manual/5.1/manual.html#lua_load" rel="nofollow"><code>lua_load()</code></a> or one additional error code. In either case, the return value is an <code>int</code> where 0 means success and a nonzero value is an error code.</p>
<p>So, the test <code>luaL_loadfile(...) == NULL</code> is <strong>true</strong> if the file was loaded, but the code calls that an error and returns.</p>
<p>The function <code>lua_pcall()</code> also returns a status code, and you may want to verify that as well. </p>
<p>Otherwise, the script as shown does create a global variable, and <code>lua_getglobal()</code> would retrieve that to the stack where it could be tested with <code>lua_isstring()</code>, or probably more usefully let you return its value if it is sufficiently string-like with <a href="http://www.lua.org/manual/5.1/manual.html#lua_tostring" rel="nofollow"><code>lua_tostring()</code></a>. The latter function will return either a <code>const char *</code> pointing at a nul-terminated string, or NULL if the value at the stack index can't be converted to a string. See the Lua reference manual as linked for the rest of the details and a caveat about using <code>lua_tostring()</code> inside a loop.</p>
<p><strong>Edit:</strong> I added better links to the manual in a couple of places.</p>
|
How to figure out what got clicked? <p>In jquery, how can I figure out what object was clicked?</p>
<p>Is there a way to alert(...) the type of tag? like if it was an <code><a href></code> or a <code><img></code> etc?</p>
| <p>The object that was clicked is passed into the click handler as <code>this</code>. You can find out the type of element with <code>nodeName</code>. Like this:</p>
<pre><code>function handle_click() {
var clicked_element = this;
alert(clicked_element.nodeName);
}
$("#mylink").click(handle_click);
</code></pre>
|
Difference between if () { } and if () : endif; <p>Are there any differences between...</p>
<pre><code>if ($value) {
}
</code></pre>
<p>...and...</p>
<pre><code>if ($value):
endif;
</code></pre>
<p>?</p>
| <p>They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my <code>.phtml</code> files (Zend Framework) I will write something like this:</p>
<pre><code><?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>
</code></pre>
|
Reset checkboxes in datalist on click of button that is outside of datalist using c# <p>Reset checkboxes in datalist on click of button that is outside of datalist using c#</p>
| <p>In the eventhandler for the buttons OnClick event you'd loop trough each item in the datalist and find the checkbox and reset it.</p>
|
Should I use a number or an email id to identify a user on website? <p>I have a web app where I register users based on their email id.</p>
<p>From a design/ease of use/flexibility point of view, should I assign a unique number to each user or identify user based on emailid?</p>
<p>Advantage of assigning unique number:</p>
<ol>
<li>I can change the login itself at a later point without losing the data of the user(flexible).</li>
</ol>
<p>Disadvantage:</p>
<ol>
<li>I have to deal with numbers when using the sql command line(error prone).</li>
</ol>
<p>Which is better? Do you see any other issues that need to be considered for either scheme?</p>
| <p>The identity of your users should be unique and immutable. Choosing the email address as identity is not a good idea for several reasons:</p>
<ul>
<li>The email is one facet of the user's identity that can change at any point in time.</li>
<li>You might decide to allow more than one emails.</li>
<li>You might decide to add other facets, like OpenID or Live ID, or even just old plain username.</li>
<li>There's nothing wrong with allowing multiple identityies to share the same email facet. It is a rare scenario, but not unheard of.</li>
<li>Normalizing the email address is hard and error prone, so you might have problems enforcing the uniqueness. (Are email addresses case sensitive? Do you ignore . or + inside emails? How do you compare non-english emails?)</li>
</ul>
<p>Btw, using the email as a public representation of the user identity can be a security and privacy problem. Especially if some of your users are under 13 years. You will need a different public facet for the user identity.</p>
|
Can you store a variable inside a if-clause? <p>I'm kinda waiting for a 'no' answer on this question.</p>
<p>I was interested if you can save a variable at the same time when you checking it in an if-clause. </p>
<p>Let's say I have this code.</p>
<pre><code>if(foo!=null){
if(foo.getBar()!=null){
Bar bar = foo.getBar();
System.out.println("Success: " + bar);
} else {
System.out.println("Failure.");
}
} else {
System.out.println("Failure.");
}
</code></pre>
<p>I handling now to "failure" -states independently, even if the outcome is the same. I could get them together like this:</p>
<pre><code>if(foo!=null && foo.getBar()!=null){
Bar bar = foo.getBar();
System.out.println("Success: " + bar);
} else {
System.out.println("Failure.");
}
</code></pre>
<p>Much neater code already. if foo is null it will stop there and won't try foo.getBar (in the if) so I won't get a NPE. The last thing i would like to enhance, and the main question: Do I really gave to call on foo.getBar() twice? It would be nice to get away from the second identical call if getBar() would be a very heavy operation. So I am wondering if there is somehow possible to do something similiar to this:</p>
<pre><code>if(foo!=null && (Bar bar = foo.getBar())!=null){
Bar bar = foo.getBar();
System.out.println("Success: " + bar);
} else {
System.out.println("Failure.");
}
</code></pre>
<p>I would have to break it up to two different if's again if I would like to do </p>
<pre><code>Bar bar = foo.getBar();
if (bar!=null) ...
</code></pre>
| <p>This is the closest you can get:</p>
<pre><code>Bar bar;
if(foo!=null && (bar = foo.getBar())!=null){
System.out.println("Success: " + bar);
} else {
System.out.println("Failiure.");
}
</code></pre>
|
Subscription based software: Does it work? <p>A while back I worked with a software company that sold a specialized software product. Ever so often they would release a patch for free and a new version that would require an upgrade fee. This is typically how the software industry works.</p>
<p>After some time the company decided on a new strategy, Subscription based software. This turns out to be a way for the software company to charge a small, incremental fee for each "transaction" that is performed on their software. Under this model the patches and upgrades were included in the per/transaction fee and there was a 'true up' in the number of transactions every so often in order to collect their fees.</p>
<p>To me this seems like a better way to develop and sell software. The software company gets continual income stream, the customer doesn't have to worry about upgrade costs and such, and if the customer gets really big then your income stream grows with their growth.</p>
<p>The problem (and reason for this question) is that I don't see anyone doing that anymore. Is it because this model doesn't work? Have I taken an overly simplistic view of developing and selling software without seeing some of the negative sides of this model? </p>
<p><strong>[EDIT]</strong> I am interested in the developers opinion on whether writing Subscription based software is a good way to develop software. </p>
<p>So this question is directed towards the professional developers who have worked on commercial applications: <strong>Can anyone speak with experience on this model and why it does/doesn't work?</strong></p>
| <p>I used to work for a company which moved from product license to subscription based model. Here are some observations about that: </p>
<ol>
<li>Offer both product license and subscription models</li>
<li>In product license: user buys 'n' number of seats for their use. </li>
<li>In subscription models, customer <em>buys your software for 'x' months time and 'y' people.</em> </li>
<li>It will help you a lot if your company also develops 'consultants' who will work with your customers to get the software implementation etc at client site (any required installation, training etc)</li>
</ol>
<p>In fact if you see services like GMail enterprise, Fogbuz etc they give different pricing options:</p>
<ul>
<li>where you want the app hosted: your servers or their servers</li>
<li>you will be charged $x per number of people using the software</li>
</ul>
<p>I think a subscription model (time based) will definitely work in the current times and in fact the cloud model helps towards such freedom in revenue models: for example, you can choose to 'subscribe' to a cloud database rather than purchasing a database server.</p>
|
After moving a UITableView row, then selecting it, it only turns blue at the edges <p>I have a <code>UITableView</code> with reorderable rows and I'm using the standard <code>UITableViewCell.text</code> property to display text. When I tap Edit, move a row, tap Done, then tap the row, the built-in <code>UILabel</code> turns completely white (text and background) and opaque, and the blue shade to the cell doesn't show behind it. What gives? Is there something I should be doing that I'm not? I have a hacky fix, but I want the real McCoy.</p>
<p>Here is how to reproduce it:</p>
<p>Starting with the standard "Navigation-Based Application" template in the iPhone OS 2.2.1 SDK:</p>
<ol>
<li><p>Open RootViewController.m</p></li>
<li><p>Uncomment <code>viewDidLoad</code>, and enable the Edit button:</p>
<pre><code>- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
</code></pre></li>
<li><p>Specify that the table has a few cells:</p>
<pre><code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;
}
</code></pre></li>
<li><p>In <code>tableView:cellForRowAtIndexPath:</code>, add a line to set the text property of a cell, and therefore to use the built-in UILabel subview:</p>
<pre><code>// Set up the cell...
cell.text = @"Test";
</code></pre></li>
<li><p>To enable reordering, uncomment <code>tableView:moveRowAtIndexPath:toIndexPath:</code>. The default implementation is blank, which is fine in this case since the template doesn't include a data model.</p></li>
<li><p>Configure the project for the Simulator, OS 2.2.1, Build and Go. When the app comes up, tap Edit, then slide any row to a new position, tap Done, and then tap each row one at a time. Usually a tap will select a row, turn it blue, and turn its text white. But a tap on the row that you just moved does that <em>and</em> leaves the UILabel's background color as white. The result is a confusing white open space with blue strips on the edges. Oddly enough, after the first bogus tap, another tap appears to correct the problem.</p></li>
</ol>
<p>So far I have found a hack that fixes it, but I'm not happy with it. It works by ensuring that the built-in <code>UILabel</code> is non-opaque and that it has no background color, immediately upon selection.</p>
<pre><code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// hacky bugfix: when a row is reordered and then selected, the UILabel displays all crappy
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews) {
if ([[view class] isSubclassOfClass:[UILabel class]]) {
((UILabel *) view).backgroundColor = nil;
view.opaque = NO;
}
}
// regular stuff: only flash the selection, don't leave it blue forever
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
</code></pre>
<p>This appears to work, but I don't expect it to be a good idea forever. What is the Right Way to fix this?</p>
| <p>This looks like a bug in UITableView's rendering, and you should file a Radar bug report on it. It's like the cells don't get refreshed properly after the move.</p>
<p>One way to work around this for now is to not use the built-in label, but roll your own in the cell:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
CGRect frame = cell.contentView.bounds;
frame.origin.x = frame.origin.x + 10.0f;
UILabel *textLabel = [[UILabel alloc] initWithFrame:frame];
[textLabel setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin];
textLabel.tag = 1;
textLabel.textAlignment = UITextAlignmentLeft;
textLabel.backgroundColor = [UIColor clearColor];
textLabel.textColor = [UIColor blackColor];
textLabel.font = [UIFont boldSystemFontOfSize:20.0];
textLabel.numberOfLines = 1;
textLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:textLabel];
[textLabel release];
}
UILabel *textLabel = (UILabel *)[cell viewWithTag:1];
textLabel.text = @"Test";
return cell;
}
</code></pre>
<p>I tried this, and it doesn't exhibit the same sort of white blank rectangle you see with the built-in label. However, adding another non-opaque view to the table cell might not be the best for overall rendering performance.</p>
<p>I don't know how major of a glitch this is, because Apple doesn't want you to persist a selection highlight on a table row (they've been enforcing this lately during the review process). You're supposed to place a checkmark or move on to the next level in the navigation hierarchy with a selection, at which point this white box would only be on the screen for a fraction of a second.</p>
|
Split rows data to columns <p>I have a table, that has a simple structure:</p>
<blockquote>
<p>user_id, month, balance, balance_type</p>
</blockquote>
<p>I want to display selected balance types per month for each user that is:</p>
<blockquote>
<p>user_id, month, balance_1, balance_2, balance_3, balance_...</p>
</blockquote>
<p>So from data:</p>
<pre><code>ROW user_id month balance balance_type
1 5667 09 20 2068
2 5667 08 23 2068
3 5667 07 21 2068
4 5667 06 19 2068
5 5667 10 22 2068
6 5667 09 20 2069
7 5667 08 23 2069
8 5667 06 19 2069
9 5667 07 21 2069
10 5667 10 22 2069
11 5667 09 4199 2114
12 5667 06 4329 2114
13 5667 08 4365 2114
14 5667 10 4172,88 2114
15 5667 07 4000 2114
16 5667 10 572,1 6062
17 5667 08 598,44 6062
18 5667 07 548,4 6062
19 5667 06 593,51 6062
20 5667 09 575,69 6062
</code></pre>
<p>I would get for example for month 09:</p>
<pre><code>user_id, month, balance_1, balance_2, balance_3, balance_4
5667 09 20 20 4199 575,69
</code></pre>
<p>What is the best solution for this in SQL or/and PL/SQL?</p>
| <p>If this is a one time requirement, I can suggest a hack. Use multiple self joins on user_id and month (you will need as many joins as there are balance types). </p>
<pre><code>select a.user_id, a.month, a.balance balance_1, b.balance balance_2, c.balance balance_3...
from mytable a, mytable b, mytable c....
where
a.month = 9 and
a.balance_type=1 and
a.user_id = b.user_id and
a.month = b.month and
b.balance_type=2 and
b.user_id = c.user_id and
c.user_id = d.user_id and
c.balance_type=3....
</code></pre>
<p>This solution may not be the best but works like a charm as a one time hack.</p>
|
Anybody tried mosso CloudFiles with Google AppEngine? <p>I'm wondering if anybody tried to integrate mosso CloudFiles with an application running on Google AppEngine (mosso does not provide testing sandbox so I cann't check for myself without registering)? Looking at the code it seems that this will not work due to httplib and urllib limitations in AppEngine environment, but maybe somebody has patched cloudfiles?</p>
| <p>It appears to implement a simple RESTful API, so there's no reason you couldn't use it from App Engine. Previously, you'd have had to write your own library to do so, using App Engine's urlfetch API, but with the release of SDK 1.1.9, you can now use urllib and httplib instead.</p>
|
How to get a TextBlock to right-align? <p>How do I get the TextBlock in my status bar below to align to the right?</p>
<p>I've told it to:</p>
<ul>
<li>HorizontalAlignment="Right"</li>
<li>TextAlignment="Right"</li>
</ul>
<p>but the text is still sitting unobediently on the left. What else do I have to say?</p>
<pre><code><Window x:Class="TestEvents124.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300"
MaxWidth="700" Width="700"
>
<DockPanel HorizontalAlignment="Stretch" Margin="0,0,0,0" Width="Auto">
<StatusBar Width="Auto" Height="25" Background="#888" DockPanel.Dock="Bottom" HorizontalAlignment="Stretch">
<TextBlock
Width="Auto"
Height="Auto"
Foreground="#fff"
Text="This is the footer."
HorizontalAlignment="Right"
TextAlignment="Right"
/>
</StatusBar>
<GroupBox DockPanel.Dock="Top" Height="Auto" Header="Main Content">
<WrapPanel Width="Auto" Height="Auto">
<TextBlock Width="Auto" Height="Auto" TextWrapping="Wrap" Padding="10">
This is an example of the content, it will be swapped out here.
</TextBlock>
</WrapPanel>
</GroupBox>
</DockPanel>
</Window>
</code></pre>
| <p>I've had a play with your code and managed to make it look "right" (no pun intended) by using a StatusBarItem rather than a TextBlock:</p>
<pre><code><StatusBar Width="Auto" Height="25"
Background="#888" DockPanel.Dock="Bottom"
HorizontalAlignment="Stretch" >
<StatusBarItem Foreground="#fff"
HorizontalContentAlignment="Right">This is the footer</StatusBarItem>
</StatusBar>
</code></pre>
<p>Not sure what's happening with the TextBlock - all my experience says that some combination of HorizontalContentAlignment and HorizontalAlignment (on both the StatusBar and the TextBlock) should achieve what you want. Anyway - hopefully the StatusBarItem will work for you.</p>
|
Embedding: mono vs lua <p>I am interested in hearing about peoples experience with embedding mono (open source implementation of .NET) in a C/C++ application. How is it to distribute such an application and what are the dependencies? I have tested on OS X and mono comes as a huge framework (hundreds of MB). Do users of my app all need this big framework or can it be stripped down or everything be compiled into the main executable. </p>
<p>I previously have experience with embedding Lua in a C++ app, and that works really well because I can link statically the whole lua interpreter in with my main executable. So I have no external dependencies. Is it possible to do something similar with mono?</p>
<p>Any Lua people here who can comment on how they found mono compared to Lua?</p>
<p>PS: By embedding I mean a C++ application which initializes a mono environment and loads a .NET assembly and executes it and then allows for communication between say C# code in assembly and C++ methods in main executable.</p>
| <p>You should probably also take a look at Mono's <a href="http://www.mono-project.com/Small_footprint">Small Footprint</a> page that describes how you can embed a smaller runtime. Heck, they do it themselves with <a href="http://www.mono-project.com/Moonlight">Moonlight</a>.</p>
<p>I hope that helps.</p>
|
Splitting string into pair of characters in Ruby <p>I have a string (e.g. "AABBCCDDEEFF") and want to split this into an array with each element containing two characters - ["AA", "BB", "CC", "DD", "EE", "FF"].</p>
| <p>Try the String object's <a href="http://www.ruby-doc.org/core/classes/String.html#M000827">scan</a> method:</p>
<pre><code>>> foo = "AABBCCDDEEFF"
=> "AABBCCDDEEFF"
>> foo.scan(/../)
=> ["AA", "BB", "CC", "DD", "EE", "FF"]
</code></pre>
|
Xml vs. Database for application configuration <p>My application configuration is very hierarchical and fits nicely into a single XML.
Soon (YAGNI, Yeh) parts of this information will be consumed by other applications remotely, which calls for a database.</p>
<p>So, I went into designing DB tables and mapping them back to my application's class hierarchy (using EF). however it became a maintenance nightmare.</p>
<p>I'd love to hear from others experience considering this issue, thanks.</p>
| <p>We had very good experience with storing the config in a database for long running applications (like web sites and services). Advantages:</p>
<ul>
<li>You can edit the config remotely and securely (user/password)</li>
<li>It is simple for the application to pick up changes (<code>select max(lmod) from config</code>) automatically or by a signal (ping a web page or create an empty file somewhere)</li>
<li>The application only needs a single item of configuration per environment (dev, test, prod): The DB to use. If you have an application server, your applications are config free for all environments.</li>
</ul>
<p>The main problem is the editing if you have a complex, hierarchical config structure with defaults, lists and inheritance. Our solutions:</p>
<ul>
<li>The config table has these rows: Application varchar(32), Key varchar(512), Value varchar(4096)</li>
<li>One DB per environment (local developer machine, development test, integration test, production)</li>
<li>The key is hierarchical (option.suboption....name)</li>
<li>Defaults use "option.<em>.name" (for example, "jdbc.</em>.driver" since we use only one type of database)</li>
<li>Lists are stored as strings, separated by newline.</li>
<li>Maps are stores as strings, "name=value\n"</li>
<li>There is an implementation which can read the config from a file (for unit tests). Map each hierarchy of the key to an element (......)</li>
</ul>
<p>Config objects hide these details, so the application just works with objects.</p>
<p>A special class is responsible for re-reading the config in case of a change. Usually, we update the config some time during the day and a timed job will reload it after hours. This way, we never need to synchronize the config methods.</p>
<p>Backup and change history were a problem, though. We fixed that by using XML files in the VCS which are then "uploaded" to the DB. This way, we could verify the production config before uploading it (by using it with a special set of unit tests on a developer machine). When it got activated during the night, it usually worked right away and the operator responsible for the app would just have to do a little bit of testing.</p>
|
Easiest way to fetch SSL page via a proxy in Java <p>I would like to fetch a SSL page in Java. The problem is, that I have to authenticate against a http proxy.</p>
<p>So I want a simple way to fetch this page.
I tried the Apache Commons httpclient, but it's too much overhead for my problem.</p>
<p>I tried this piece of code, but it does not contain an authentication action:</p>
<pre><code>import java.io.*;
import java.net.*;
public class ProxyTest {
public static void main(String[] args) throws ClientProtocolException, IOException {
URL url = new URL("https://ssl.site");
Socket s = new Socket("proxy.address", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, s.getLocalSocketAddress());
URLConnection connection = url.openConnection(proxy);
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String tmpLine = "";
while ((tmpLine = br.readLine()) != null) {
System.out.println(tmpLine);
}
}
}
</code></pre>
<p>Can anyone provide some information how to implement it on an easy way?</p>
<p>Thanks in advance</p>
| <p>You need to set a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/net/Authenticator.html" rel="nofollow">java.net.Authenticator</a> before you open your connection:</p>
<pre><code>...
public static void main(String[] args) throws Exception {
// Set the username and password in a manner which doesn't leave it visible.
final String username = Console.readLine("[%s]", "Proxy Username");
final char[] password = Console.readPassword("[%s"], "Proxy Password:");
// Use a anonymous class for our authenticator for brevity
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
URL url = new URL("https://ssl.site");
...
}
</code></pre>
<p>To remove your authenticator after you're finished, call the following code:</p>
<pre><code>Authenticator.setDefault(null);
</code></pre>
<p>The authenticator in Java SE 6 supports <code>HTTP Basic</code>, <code>HTTP Digest</code> <em>and</em> <code>NTLM</code>. For more information, see the <a href="http://java.sun.com/javase/6/docs/technotes/guides/net/http-auth.html" rel="nofollow">Http Authentication</a> documentation at sun.com</p>
|
How do I use p4merge from Xcode? <p>I would like to use the p4merge tool from Xcode in an SVN setup. Asking for trouble?</p>
| <p>Found the solution here:
<a href="http://wiki.changesapp.com/index.php/Application_Integration#XCode_2.5_.26_3" rel="nofollow">http://wiki.changesapp.com/index.php/Application_Integration#XCode_2.5_.26_3</a></p>
<ol>
<li>Go to the "SCM" section in XCode's preferences.</li>
<li>Select the "Options" tab.</li>
<li>Select "Other..." in the pop-up for "View comparisons using:"</li>
<li>In the open panel, hit slash (/). In the field that pops up, type in: /Applications/p4merge.app/Contents/Resources/launchp4merge</li>
</ol>
|
ASP.NET 2.0 Membership: ValidateUser not locking out the user? <p>I am using the default SQLMembershipProvider in my ASP.NET 2.0 website, and expect the Membership.ValidateUser to lock-out the user after entering a number of wrong passwords (5, in my case) but ValidateUser doesn't seem to be caring about keeping count of bad password attempts and locking out the user.</p>
<p>What's wrong?</p>
<p>The Membership configuration in my web.config:</p>
<pre><code><membership defaultProvider="SqlMembershipProvider" >
<providers>
<clear />
<add connectionStringName="ConnectionStringName" enablePasswordRetrieval="true"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="true" passwordFormat="Encrypted" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10" passwordStrengthRegularExpression=""
applicationName="MyApp" name="SqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
</code></pre>
| <p>what is the PasswordAttemptWindow and MaxInvalidPasswordAttempts set to? and is these configuration settings set in the correct web.config? (the one actual in use by the test environment)</p>
|
Convert HTML to PDF in .NET <p>I want to generate a PDF by passing HTML contents to a function. I have made use of iTextSharp for this but it does not perform well when it encounters tables and the layout just gets messy.</p>
<p>Is there a better way?</p>
| <p>Try <a href="http://wkhtmltopdf.org/">wkhtmtopdf</a>. It is the best tool I have found so far.</p>
<p>For .NET, you may use this <a href="https://github.com/codaxy/wkhtmltopdf">small library</a> to easily invoke wkhtmtopdf command line utility.</p>
|
Creating a sub site in SharePoint takes a very long time <p>I am working in a MOSS 2007 project and have customized many parts of it. There is a problem in the production server where it takes a very long time (more than 15 minutes, sometimes fails due to timeouts) to create a sub site (even with the built-in site templates). While in the development server, it only takes 1 to 2 minutes.</p>
<p>Both servers are having same configuration with 8 cores CPU and 8 GIGs RAM. Both are using separate database servers with the same configuration. The content db size is around 100 GB. More than a hundred subsites are there.</p>
<p>What could be the reason why in the other server it will take so much time? Is there any configuration or something else I need to take care?</p>
<h2>Update:</h2>
<p>So today I had the chance to check the environment with my clients. But site creation was so fast though they said they didn't change any configuration in the server.</p>
<p>I also used that chance to examine the database. The disk fragmentation was quite high at 49% so I suggested them to run defrag. And I also asked the database file growth to be increased to 100MB, up from the default 1MB.</p>
<p>So my suspicion is that some processes were running heavily on the server previously, that's why it took that much of time.</p>
<h2>Update 2:</h2>
<p>Yesterday my client reported that the site creation was slow again so I went to check it. When I checked the db, I found that instead of the reported <strong>100GB</strong>, the content db size is only around <strong>30GB</strong>. So it's still far below the recommended size.</p>
<p>One thing that got my attention is, the site collection recycle bin was holding almost <strong>5 millions items</strong>. And whenever I tried to browse the site collection recycle bin, it would take a lot of time to open and the whole site collection is inaccessible.</p>
<p>Since the web application setting is set to the default (30 days before cleaning up, and 50% size for the second stage recycle bin), is this normal or is this a potential problem also?</p>
<p>Actually, there was also another web application using the same database server with 100GB content db and it's always fast. But the one with 30GB is slow. Both are having the same setup, only different data.</p>
<p>What should I check next?</p>
<hr>
<p>So today I had the chance to check the environment with my clients. But site creation was so fast though they said they didn't change any configuration in the server.</p>
<p>I also used that chance to examine the database. The disk fragmentation was quite high at 49% so I suggested them to run defrag. And I also asked the database file growth to be increased to 100MB, up from the default 1MB.</p>
<p>So my suspicion is that some processes were running heavily on the server previously, that's why it took that much of time.</p>
<p>Thanks for the inputs everyone, I really appreciate.</p>
<hr>
<p>Yesterday my client reported that the site creation was slow again so I went to check it. When I checked the db, I found that instead of the reported <strong>100GB</strong>, the content db size is only around <strong>30GB</strong>. So it's still far below the recommended size.</p>
<p>One thing that got my attention is, the site collection recycle bin was holding almost <strong>5 millions items</strong>. And whenever I tried to browse the site collection recycle bin, it would take a lot of time to open and the whole site collection is inaccessible.</p>
<p>Since the web application setting is set to the default (30 days before cleaning up, and 50% size for the second stage recycle bin), is this normal or is this a potential problem also?</p>
<p>Actually, there was also another web application using the same database server with 100GB content db and it's always fast. But the one with 30GB is slow. Both are having the same setup, only different data.</p>
<p>Any idea what should I check next? Thanks a lot.</p>
| <p>Yes, its normal OOB if you haven't turned the Second Stage Recycle bin off or set a site quota. If a site quota has not been set then the growth of the Second Stage Recycle bin is not limited...</p>
<p>the second stage recycle bin is by default limited to 50% size of the site quota, in other words if you have a site quota of 100gb then you would have a Second Stage recycle bin of 50gb. If a site quota has not been set, there are not any growth limitations...</p>
|
How to get MessageBox.Show() to pop up in the middle of my WPF application? <p>I have a 700w x 300h WPF applciation and can drag it anywhere on my large screen.</p>
<p>When my application executes:</p>
<pre><code>MessageBox.Show("Sorry, this function is not yet implemented.");
</code></pre>
<p>the mesage box appears in the middle of my <em>screen</em>, which may or may not even be near the application itself.</p>
<p>How can I get my MessageBox to appear in the middle of my <em>application</em> instead?</p>
| <p>Here's a version of the MessageBoxEx helper class posted in the other thread that uses WPF style message boxes (Note that you still need to reference System.Drawing):</p>
<pre><code>using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Drawing;
public class MessageBoxEx
{
private static IntPtr _owner;
private static HookProc _hookProc;
private static IntPtr _hHook;
public static MessageBoxResult Show(string text)
{
Initialize();
return MessageBox.Show(text);
}
public static MessageBoxResult Show(string text, string caption)
{
Initialize();
return MessageBox.Show(text, caption);
}
public static MessageBoxResult Show(string text, string caption, MessageBoxButton buttons)
{
Initialize();
return MessageBox.Show(text, caption, buttons);
}
public static MessageBoxResult Show(string text, string caption, MessageBoxButton buttons, MessageBoxImage icon)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon);
}
public static MessageBoxResult Show(string text, string caption, MessageBoxButton buttons, MessageBoxImage icon, MessageBoxResult defResult)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defResult);
}
public static MessageBoxResult Show(string text, string caption, MessageBoxButton buttons, MessageBoxImage icon, MessageBoxResult defResult, MessageBoxOptions options)
{
Initialize();
return MessageBox.Show(text, caption, buttons, icon, defResult, options);
}
public static MessageBoxResult Show(Window owner, string text)
{
_owner = new WindowInteropHelper(owner).Handle;
Initialize();
return MessageBox.Show(owner, text);
}
public static MessageBoxResult Show(Window owner, string text, string caption)
{
_owner = new WindowInteropHelper(owner).Handle;
Initialize();
return MessageBox.Show(owner, text, caption);
}
public static MessageBoxResult Show(Window owner, string text, string caption, MessageBoxButton buttons)
{
_owner = new WindowInteropHelper(owner).Handle;
Initialize();
return MessageBox.Show(owner, text, caption, buttons);
}
public static MessageBoxResult Show(Window owner, string text, string caption, MessageBoxButton buttons, MessageBoxImage icon)
{
_owner = new WindowInteropHelper(owner).Handle;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon);
}
public static MessageBoxResult Show(Window owner, string text, string caption, MessageBoxButton buttons, MessageBoxImage icon, MessageBoxResult defResult)
{
_owner = new WindowInteropHelper(owner).Handle;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon, defResult);
}
public static MessageBoxResult Show(Window owner, string text, string caption, MessageBoxButton buttons, MessageBoxImage icon, MessageBoxResult defResult, MessageBoxOptions options)
{
_owner = new WindowInteropHelper(owner).Handle;
Initialize();
return MessageBox.Show(owner, text, caption, buttons, icon,
defResult, options);
}
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
public const int WH_CALLWNDPROCRET = 12;
public enum CbtHookAction : int
{
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
}
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
} ;
static MessageBoxEx()
{
_hookProc = new HookProc(MessageBoxHookProc);
_hHook = IntPtr.Zero;
}
private static void Initialize()
{
if (_hHook != IntPtr.Zero)
{
throw new NotSupportedException("multiple calls are not supported");
}
if (_owner != null)
{
_hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(_hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = _hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(_hHook);
_hHook = IntPtr.Zero;
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(_owner, ref recParent);
System.Drawing.Point ptCenter = new System.Drawing.Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
System.Drawing.Point ptStart = new System.Drawing.Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
height, false);
}
}
</code></pre>
|
Code Freeze when you aren't going to be finished <p>I am working on a project that has been running for a long period of time and we're coming up on a final release of the product.</p>
<p>Current testing efforts have discovered there are about thirty defects left in the system, however we don't have time to fix all of these defects (a very common situation I am sure).</p>
<p>I have had several discussions with different people about whether the code freeze should go ahead. Currently my manager wants to keep the code freeze, however to fix remaining critical defects in the window between freeze and release (about 5 weeks). I am worried that this isn't an actual code freeze, but rather a code "slush" at best. The defects will be triaged by a team of senior engineers to make sure that only critical fixes out of the remaining issues are actually worked on, however from an initial look the critical issues seem to number about two thirds of the total outstanding defects.</p>
<p>I understand that having a code freeze presents certain psychological benefits for developers such as providing a fixed end date for all work. However this seems to be completely negated by my manager openly discussing fixes that will go in "after" the freeze.</p>
<p>I was wondering if anyone else has had a similar experience or could provide me with some advice about what the best way to deal with this situation is. I am starting to think that nobody actually freezes their codebase on the day they say they are going to.</p>
<p>We are planning on branching from the trunk in subversion on code-freeze-day to make sure that the final release version of the product is isolated from the development trunk, so I am not too worried about issues of changes being made affecting the release version of the product.</p>
<p>Thanks,</p>
<p>Aidos</p>
<p>EDIT: I suppose the best way to explain my managers' thinking is that it's not really a code freeze, more of a "functionality freeze", however as all of the functionality has been in the product for some time now I think this is a gross oversimplification.</p>
<p>EDIT2: I'd like to thank everyone for their great answers, unfortunately I can only mark one as helpful, even though all 7 answers so far have been incredibly helpful.</p>
| <p>It's a balancing act. </p>
<p>On one hand it's nice to have a code freeze period, but on the other, it's in nobody's interest for you to ship a product with critical issues large enough to make your customers walk away.</p>
<p>If the issues are serious enough, no code freeze would stop me fixing them if it were my product.</p>
<p>Good luck!</p>
|
SSRS Microsoft Reporting: Conditional grouping <p>Is it possible to make a group and sort conditional? If so, is it possible to somehow do this based on the value of a textbox item?</p>
<p>I thought I could just set the Expression of the group and sort to something like <code>=IIF(ReportItems!TheTextBox.Value = 0, 0, Fields!FieldName.Value)</code>, which would be perfect, but it doesn't allow me to use ReportItems in group or sort expressions =(</p>
<p>Really don't want to make two reports whenever I need that feature... hope someone can shed some light on this!</p>
<p>Using:</p>
<ul>
<li>Microsoft reporting services</li>
<li>Report viewer with local processing</li>
</ul>
| <p><strong>edit</strong></p>
<blockquote>
<p>It is a sub-report, so I can't use
report parameters. </p>
</blockquote>
<p>you can. see <a href="http://msdn.microsoft.com/en-us/library/ms160348.aspx" rel="nofollow">How to: Add a Subreport and Parameters (Reporting Services)</a><br />
<strong>/edit</strong></p>
<p>Try to check this report parameter collection in grouping expression. Something like:</p>
<pre><code>=IIF(Parameters!<ParameterName>.Count = 0, 0, Fields!FieldName.Value)
</code></pre>
<p>See <a href="http://msdn.microsoft.com/en-us/library/aa337293.aspx" rel="nofollow">Using Parameters Collection References in Expressions (Reporting Services)</a></p>
|
What is the difference between NOT(x > y) and (x < y) in an SQL query? <p>What is the difference between the following query:</p>
<pre><code>SELECT * FROM employee WHERE NOT(start_date > '01-JAN-1970');
</code></pre>
<p>and this query:</p>
<pre><code>SELECT * FROM employee WHERE start_date < '01-JAN-1970';
</code></pre>
<p>Is there any difference, and if so, how is <code>NOT(x > y)</code> used differently from <code>(x < y)</code>. Can anyone provide an example?</p>
<p>Thanks.</p>
| <p>In <code>MySQL</code> and <code>PostgreSQL</code></p>
<pre><code>SELECT * FROM employee WHERE not(start_date > '01-JAN-1970')
</code></pre>
<p>will not use an <code>INDEX</code> on <code>start_date</code> if any, their optimizers are not smart enough.</p>
<p>Otherwise, if you correct the condition not be not strict in exaÑtly one of cases (either <code>not(start_date >= '01-JAN-1970')</code> or <code>start_date <= '01-JAN-1970'</code>), the queries are equal.</p>
|
How to temporarily disable the log in SQL2000/2005? <p>Is there a way to stop the log file from growing (or at least from growing as much) in SQL2000/2005?</p>
<p>I am running a very extensive process with loads of inserts and the log is going through the roof.</p>
<p><strong>EDIT</strong>: please note I am talking about an batch-import process not about everyday update of live-data.</p>
| <p>You can't disable the log, but you could perform your inserts in batches and backup/truncate the log in between batches.</p>
<p>If the data originates from outside your database you could also consider using <a href="http://msdn.microsoft.com/en-us/library/aa174646.aspx" rel="nofollow">BCP</a>.</p>
|
Preserve datalist data on load event in c# <p>I have datalist containing radio buttons and check boxes. If I select some of them and then redirect to another aspx page. when I come to previous page the radio buttons and check boxes in datalist must be selected. I have selected data in session variable. How to do this using c#.</p>
| <p>Using the ItemDataBound event I would retrieve the radio button and compare it's value to your Session variable</p>
<p>something like this:</p>
<pre><code>protected void MyDataList_ItemDataBound(object sender, DataListItemEventArgs e)
{
RadioButton myRadioButton = e.Items.FindControl("myRadioButton") as RadioButton;
if (myRadioButton == null) { }
else
{
if (string.IsNullOrEmpty(Session[myRadioButton.Value])) {}
else myRadioButton.Checked = true;
}
}
</code></pre>
|
Javascript - form select element open url in new window and submit form <p><strong>UPDATED</strong> - please read further details below original question</p>
<p>I have a select form element with various urls, that I want to open in a new window when selected - to do this I have the following code in the element's onchange event:</p>
<pre><code>window.open(this.options[this.selectedIndex].value,'_blank');
</code></pre>
<p>This works fine. But I also want to submit the form when changing this select element value - I've tried various things, but I can't seem to get it to work.</p>
<p>I have jquery, so if it's easier to achieve via that then that's fine.</p>
<p><em>Update - I've just realised there is another issue with the above, because some of the urls are actually used to generate and output pdfs, and these do not work - they open and then immediately close (at least in IE7).</em></p>
<p><strong>UPDATE 07/05/09</strong> - I've now opened a bounty for this question as I really need to come up with a working solution. I did originally get around the issue by displaying links instead of a form select element, but this is no longer feasible.</p>
<p>The reason I need the above is that I have a large number of files that might need to be viewed / printed, too many to reasonably display as a list of links. I need to submit the form to record the fact a particular file has been viewed / printed, then display a log of the file history on the form - I'm comfortable with achieving this side of things, so don't require assistance there, but I thought it would help to place the context. </p>
<p>So, to clarify my requirements - I need a form select element and 'View' button that when clicked will not only launch a file download in a new window (note the above issue I faced when these files were PDFs), but also submit the form that contains the select element.</p>
| <p>Here ya go</p>
<pre><code><script type="text/javascript">
$(function() {
$("#selectElement").change(function() {
if ($(this).val()) {
window.open($(this).val(), '_blank');
$("#formElement").submit();
}
});
// just to be sure that it is submitting, remove this code
$("#formElement").submit(function() {
alert('submitting ... ');
});
});
</script>
<form id="formElement" method="get" action="#">
<select id="selectElement">
<option></option>
<option value="http://www.deviantnation.com/">View Site 1</option>
<option value="http://stackoverflow.com/">View Site 2</option>
<option value="http://serverfault.com/">View Site 3</option>
</select>
</form>
</code></pre>
|
Porting a .NET 3.5 application to a portable device <p>I have written a server/client application using sockets in C# for .NET 3.5. I'm interested in porting the client part to some kind of mobile device and am pondering the best way. The client is actually an underlying library and a GUI depending heavily on touch interface capabilities.</p>
<p>As I see it I have a few options:</p>
<ol>
<li>Just get an EEE PC and run it on, that's kind of portable but I loose the touch part</li>
<li>Rebuild the library for mobile platforms and make a new, reduced, GUI app</li>
<li>Start a web server and make some kind of web interface to run on iPhones and what not</li>
</ol>
<p>What would be the best route? What problems can I run into in my alternatives above? I'd really prefer alternative 1 or 2 over 3 because of how the server is currently done and the fact that I know nothing about webservers or ASP.NET. Oh and I'd like to stay with the environment I'm alredy in, that is .NET, so no Ruby on Rails suggestions please. (Not saying Ruby is bad or anything, I just don't know it and don't have the time to learn).</p>
| <p>I'd go for option 2 then. It wont take you too long (hopefully) to port the libraries over to the Compact Framework, and providing it's just sockets, etc, you're dealing with then I'm sure the CF will handle it fine.</p>
<p><strong>EDIT:</strong> The only problems you'll have with option 2 is if you use any .Net functions that are not in the CF. If that is the case, you'll usually be able to find it within OpenNETCF.</p>
<p>You will need to create a new GUI, but providing you've coded your libraries well, it should just be a case of assigning methods/events where applicable on your device.</p>
<p>I'd say though that option 3 is the best option - it expands your customer base dramatically, especially with the growing number of WM and iPhone users.</p>
|
can my programs access more than 4GB of memory? <p>if I run python on a 64bit machine with a 64bit operating system, will my programs be able to access the full range of memory? I.e. Could I build a list with 10billion entries, assuming I had enough RAM? If not, are there other programming languages that would allow this?</p>
| <p>You'll need to be sure that Python has been built as a 64 bit application. For example, on Win64 you'll be able to run the 32bit build of Python.exe but it won't get the benefits of the 64 bit environment as Windows will run it in a 32bit sandbox.</p>
|
sql query to find customers who order too frequently? <p>My database isn't actually customers and orders, it's customers and prescriptions for their eye tests (just in case anyone was wondering why I'd want my customers to make orders less frequently!)</p>
<p>I have a database for a chain of opticians, the prescriptions table has the branch ID number, the patient ID number, and the date they had their eyes tested. Over time, patients will have more than one eye test listed in the database. How can I get a list of patients who have had a prescription entered on the system more than once in six months. In other words, where the date of one prescription is, for example, within three months of the date of the previous prescription for the same patient.</p>
<p>Sample data:</p>
<pre><code>Branch Patient DateOfTest
1 1 2007-08-12
1 1 2008-08-30
1 1 2008-08-31
1 2 2006-04-15
1 2 2007-04-12
</code></pre>
<p>I don't need to know the actual dates in the result set, and it doesn't have to be exactly three months, just a list of patients who have a prescription too close to the previous prescription. In the sample data given, I want the query to return:</p>
<pre><code>Branch Patient
1 1
</code></pre>
<p>This sort of query isn't going to be run very regularly, so I'm not overly bothered about efficiency. On our live database I have a quarter of a million records in the prescriptions table.</p>
| <p>Something like this</p>
<pre><code>select p1.branch, p1.patient
from prescription p1, prescription p2
where p1.patient=p2.patient
and p1.dateoftest > p2.dateoftest
and datediff('day', p2.dateoftest, p1.dateoftest) < 90;
</code></pre>
<p>should do... you might want to add</p>
<pre><code>and p1.dateoftest > getdate()
</code></pre>
<p>to limit to future test prescriptions.</p>
|
Using jep.invoke() method <p>I need to call a function from a python script and pass in parameters into it. I have a test python script which I can call and run from java using Jepp - this then adds the person. </p>
<p>Eg Test.py</p>
<pre><code>import Finding
from Finding import *
f = Finding()
f.addFinding("John", "Doe", 27)
</code></pre>
<p>Within my Finding class I have <code>addFinding(firstname, lastName, age)</code></p>
<p>However, I wish to be able to do this from within java. Should I be using the <code>jep.invoke()</code> method. Does anyone have a hello world example of such a thing being done or forward me to some good examples? </p>
<p>Does anyone have any suggestions please? </p>
<p>Thanks in advance</p>
| <p>Easier way to run python code in java is to use <a href="http://www.jython.org/" rel="nofollow">jython</a>.</p>
<p><strong>EDIT:</strong> Found an <a href="http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1" rel="nofollow">article with examples</a> in the jython website.</p>
|
"BigInt" in C? <p>What is the easiest way to handle huge numbers in C? I need to store values in the Area 1000^900... </p>
<p>Does anybody know of an easy way to do that? Any help would really be appreciated!</p>
| <p>Use <a href="http://gmplib.org/" rel="nofollow">libgmp</a>:</p>
<blockquote>
<p>GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating-point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on...</p>
<p>Since version 6, GMP is distributed under the dual licenses, <a href="https://www.gnu.org/licenses/lgpl.html" rel="nofollow">GNU LGPL v3</a> and <a href="https://www.gnu.org/licenses/gpl-2.0.html" rel="nofollow">GNU GPL v2</a>...</p>
<p>GMP's main target platforms are Unix-type systems, such as GNU/Linux, Solaris, HP-UX, Mac OS X/Darwin, BSD, AIX, etc. It also is known to work on Windows in both 32-bit and 64-bit mode...</p>
</blockquote>
|
Private working set size dependent on application name <p>A colleague has been trying to reduce the memory footprint of a 32 bit app running on vista 64 and has noticed some weird behaviour in the reported size of the private working set.</p>
<p>He made some changes and recompiled the app. Then he ran the app and loaded in a data file. The task manager reports that private working set is 98Mb. He then simply renamed the app to 'fred.exe' now when he runs fred.exe and loads the same data file the private working set is reported to be 125Mb. Rename the file back to its original name, repeat and the private working set is back to 98Mb.</p>
<p>Does anyone know what causes this?</p>
| <p>This usually happens during full moons.</p>
<p>Did he remember to sacrifice a chicken to Ba'al-ze-Bool, the god of memory?</p>
|
Casting NSString to unsigned char * <p>I'm trying to use a function that has the following signature to sign a HTTP request:</p>
<pre><code>extern void hmac_sha1(const unsigned char *inText, int inTextLength, unsigned char* inKey, const unsigned int inKeyLength, unsigned char *outDigest);
</code></pre>
<p>And this is the method I wrote to use it:</p>
<pre><code>- (NSString *)sign: (NSString *)stringToSign {
NSString *secretKey = @"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const unsigned char *inText = (unsigned char *)[stringToSign UTF8String];
int inTextLength = [stringToSign length];
unsigned char *inKey = (unsigned char *)[secretKey UTF8String];
const unsigned int inKeyLength = (unsigned int)[secretKey length];
unsigned char *outDigest;
hmac_sha1(inText, inTextLength, inKey, inKeyLength, outDigest);
NSString *output = [NSString stringWithUTF8String:(const char *)outDigest];
return output;
</code></pre>
<p>}</p>
<p>The problem is I'm sure this is not the way I'm supposed to do this casting, as inside this hmac_sha1 function I get a EXC_BAD_ACCESS exception.</p>
<p>Since I am new to Objective-C and have close to no experience in C (surprise!) I don't really know what to search for. Any tips on how I can start solving this?</p>
<p>Thanks in advance!</p>
<p>Btw, I got the reference for this function <a href="http://stackoverflow.com/questions/476455/is-there-a-library-for-iphone-to-work-with-hmac-sha-1-encoding/476513">here in stackoverflow</a>.</p>
| <p>It looks like the problem is not with the casting, but with <code>outDigest</code>. The fifth argument to <code>hmac_sha1</code> should point to an already allocated buffer of size 20 bytes (I think).</p>
<p>If you change the line that says</p>
<pre><code>unsigned char *outDigest;
</code></pre>
<p>to say</p>
<pre><code>#define HMACSHA1_DIGEST_SIZE 20
void *outDigest = malloc(HMACSHA1_DIGEST_SIZE);
</code></pre>
<p>That should get you past the crash inside <code>hmac_sha1</code>.</p>
<p>Then you've got the problem of converting the data at <code>outDigest</code> into an <code>NSString</code>. It looks like <code>hmac_sha1</code> will put 20 bytes of random-looking data at <code>outDigest</code>, and not a null terminated UTF-8 string, so <code>stringWithUTF8String:</code> won't work. You might want to use something like this instead if you have to return an <code>NSString</code>:</p>
<pre><code>NSString *output = [[NSString alloc] initWithBytesNoCopy:outDigest
length:HMACSHA1_DIGEST_SIZE
encoding:NSASCIIStringEncoding
freeWhenDone:YES];
</code></pre>
<p>I don't think <code>NSString</code> is really the right type for the digest, so it might be worth changing your method to return an <code>NSData</code> if you can.</p>
|
Overloading, strings, and default parameters <p>Refactoring legacy code, I came across this function (pseudocode):</p>
<pre><code>int getMessage( char * buffer, int size = 300 );
</code></pre>
<p>Gee, look at that buffer just waiting to overflow. So I came up with a function using std::string, and thought it would be nice to use function overloading:</p>
<pre><code>int getMessage( std::string & buffer );
</code></pre>
<p>So far, so good. But when I try to <em>call</em> the function with a string:</p>
<pre><code>std::string buffer;
int rc = getMessage( buffer );
</code></pre>
<p>I get this error:</p>
<pre><code>cannot convert 'std::string' to 'char*' for argument '1' to 'int getMessage(char*, int)'
</code></pre>
<p>Obviously, the compiler (GCC 4.1.2) tries hard to convert std::string to char* to satisfy the first function's parameter list (using the default value to satisfy the second parameter), gives up, but doesn't try the second function...</p>
<p>I wouldn't have a problem working around this issue, but I'd like to know why this fails, and whether there would be a way to make it work as intended.</p>
| <p>It works as expected on my GCC 4.3.2, maybe you misspelled the name of the overload? There's no conversion from std::string to char*, so the compiler shouldn't have any problems choosing the correct overload.</p>
<pre><code>$ cat test.cpp
#include <string>
#include <stdio.h>
int getMessage( char * buffer, int size = 300 )
{
printf("1\n");
return 1;
}
int getMessage( std::string & buffer )
{
printf("2\n");
return 2;
}
int main()
{
std::string buffer;
buffer = "Hello";
int rc = getMessage( buffer );
}
$ g++ test.cpp -Wall -pedantic
test.cpp: In function âint main()â:
test.cpp:20: warning: unused variable ârcâ
$ ./a.out
2
$ $ g++ -v 2>&1|tail -n1
gcc version 4.3.2 (Ubuntu 4.3.2-1ubuntu12)
$
</code></pre>
|
(Deep) copying an array using jQuery <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object">What is the most efficient way to clone a JavaScript object?</a> </p>
</blockquote>
<p>I need to copy an (ordered, not associative) array of objects. I'm using jQuery. I initially tried </p>
<pre><code>jquery.extend({}, myArray)
</code></pre>
<p>but, naturally, this gives me back an object, where I need an array (really love jquery.extend, by the way).</p>
<p>So, what's the best way to copy an array? </p>
| <p>Since Array.slice() does not do deep copying, it is not suitable for multidimensional arrays:</p>
<pre><code>var a =[[1], [2], [3]];
var b = a.slice();
b.shift().shift();
// a is now [[], [2], [3]]
</code></pre>
<p>Note that although I've used <code>shift().shift()</code> above, the point is just that <em><code>b[0][0]</code> contains a pointer to <code>a[0][0]</code></em> rather than a value. </p>
<p>Likewise <code>delete(b[0][0])</code> also causes <code>a[0][0]</code> to be deleted and <code>b[0][0]=99</code> also changes the value of <code>a[0][0]</code> to 99.</p>
<p>jQuery's <code>extend</code> method <em>does</em> perform a deep copy when a true value is passed as the initial argument:</p>
<pre><code>var a =[[1], [2], [3]];
var b = $.extend(true, [], a);
b.shift().shift();
// a is still [[1], [2], [3]]
</code></pre>
|
Generate a number of ranges for a random set of values <p>Given a set of random numeric values in a database, how do I generate a limited list of ranges where each range contains at least one value? The ranges should not overlap and ideally have a similar amount of values in them. Ideally their boundaries should also be multiples of 10, 100, 1000 etc...</p>
<p>For example:</p>
<pre>Values: 100,150,180,300,400,500,600,650,700
results in
4 ranges: 100-180(2), 180-300(1), 300-600(3), 600-800(3)</pre>
<p>How could this be done in C# or T-SQL?</p>
| <p>In <code>MS SQL 2005+</code>:</p>
<pre><code>SELECT range, (MIN(getprev) + MIN(value)) / 2 as range_start, (MAX(getnext) + MAX(value)) / 2 AS range_end, COUNT(*) as range_values
FROM (
SELECT value,
NTILE(4) OVER (ORDER BY value ) AS range,
(
SELECT TOP 1 value
FROM values li
WHERE li.value < lo.value
ORDER BY
li.value DESC
) AS getprev,
(
SELECT TOP 1 value
FROM values li
WHERE li.value > lo.value
ORDER BY
li.value
) AS getnext
FROM values lo
) vo
GROUP BY range
ORDER BY range
</code></pre>
<p>In your case:</p>
<pre>
1 100 240 3
2 240 450 2
3 450 625 2
4 625 700 2
</pre>
|
ASP.NET MVC - Form Submission, Retrieve Database ID, and Redirect <p>I currently learning ASP.NET MVC . I wondered if it is possible when a form is submitted to the get the id of the new record and then redirect to a new page with the new record id?</p>
<p>The information is entered into the database correctly, but Iâm not sure how to get the id?</p>
<p>For example, complete a new customer details form and then redirect the page to an orders form where new orders can be added for the customer.</p>
| <p>How are you accessing the database? If you are using an ORM (such as NHibernate or LINQ to SQL) then the object should have it's ID property updated after you insert it into the database.</p>
<p>If you are hand rolling the SQL then you need to do a select in the same statement as the insert of:</p>
<pre><code>insert into ...
select scope_identity()
</code></pre>
<p>This will return the ID of the row you have just created.</p>
<p>Then you can do this within your action:</p>
<pre><code>return RedirectToAction("YourActionName", new {id});
</code></pre>
<p>With the ID retrieved either from the saved object or the return value of the SQL. Whichever fits your scenario.</p>
<p><strong>Edit</strong></p>
<p>As you've mentioned you are using NHibernate then you can do this:</p>
<pre><code>var myNewObject = // some way of creating the object
// some way of saving the object
// at this point NHibernate will have set the ID of the object for you
return RedirectToAction("YourActionName", new { id = myNewObject.Id });
</code></pre>
|
XPath Node element indexing based on attribute <p>I am trying to build an Infopath form which populates fields with data back from a Sharepoint list. I set up a drop-down list box who's values get populated from a Sharepoint data source. That part works fine. Now I want other string fields to get automatically populated once the user selects one of the items from the list.
<br/>
So I set up a rule to do this. I wrote an XPath formula to grab the attribute from the Sharepoint list</p>
<pre><code>xdXDocument:GetDOM("Base Printers")
/dfs:myFields/dfs:dataFields/dfs:Base_Printers/@PNP_String
</code></pre>
<p>The problem is that this always grabs the attribute (PNP_String) from the first item in the list. I want to populate it with the proper printer (Base_Printers) based on the user's selection. So I have to index into Base_Printers, and then pick the PNP_String. So I tried this</p>
<pre><code>.../dfs:Base_Printers[2]/@PNP_String
</code></pre>
<p>It will index into the 2nd item and return that PNP string, which is great!<br/>
But I need to index to the element the user picked, so I tried this:</p>
<pre><code>.../dfs:Base_Printers[@Printer=my:basePrinter]/@PNP_String
</code></pre>
<p>Where @Printer is the attribute in the sharepoint list, and my:basePrinter is the local infopath variable of the Drop down list. And that does nothing for me. When I tried a literal value:</p>
<pre><code>.../dfs:Base_Printers[@Printer='XYZ']/@PNP_String
</code></pre>
<p>It picked the right pnp string.
<br/>
So my question is, how can I index into that array of printers based on the user's selection?</p>
<p>Thanks</p>
| <p>I think I figured it out.</p>
<pre><code>xdXDocument:GetDOM("Base Printers")/dfs:myFields/dfs:dataFields
/dfs:Base_Printers[@Printer = current()]/@PNP_String
</code></pre>
<p>For some strange reason, it works when you use:</p>
<pre><code>@Printer = current()
</code></pre>
<p>But not when you use:</p>
<pre><code>@Printer = my:basePrinter
</code></pre>
<p>Even though both current() and my:basePrinter return the same string.</p>
<p>Weirdness...</p>
|
Difference between JOIN and INNER JOIN <p>Both these joins will give me the same results:</p>
<pre><code>SELECT * FROM table JOIN otherTable ON table.ID = otherTable.FK
</code></pre>
<p>vs</p>
<pre><code>SELECT * FROM table INNER JOIN otherTable ON table.ID = otherTable.FK
</code></pre>
<p>Is there any difference between the statements in performance or otherwise? </p>
<p>Does it differ between different SQL implementations? </p>
| <p>They are functionally equivalent, but <code>INNER JOIN</code> can be a bit clearer to read, especially if the query has other join types (i.e. <code>LEFT</code> or <code>RIGHT</code> or <code>CROSS</code>) included in it.</p>
|
Are there cross-platform precompiled header frameworks/methods in C++? <p>I'm wondering what others have experienced implementing cross-platform (linux and windows) precompiled headers in C++. I'm thinking of what Visual Studio lets you do with stdafx.h files that can drastically improve compile times for large amounts of C++ code by precompiling the common headers used across the board (std/boost/etc headers). Is there a way to make this happen cross platform with some kind of framework or something?</p>
<p>What kind of experience have you had trying to do this? </p>
<h3>Edit</h3>
<p>I don't really mean sharing the actual resulting pch, I'm more interested in frameworks that can generate pch and whatever the equivelant would be for, say, gcc, when compiled on that specific platform.</p>
| <p><code>gcc</code> will automatically precompile headers if you pass a header file instead of an implementation file. Simply add the <code>-x</code> switch if it tries to produce object code. GCC will always look for the <code>.gch</code> file before the header, so it's simple enough to use. <a href="http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html" rel="nofollow">This page</a> has more info. Add it to your <code>Makefile</code> to automate the process.</p>
|
Why could VirtualBox not find a registered machine named Windows_7?n <p>I'm trying to change TCP/UDP of a virtual machine using VBoxManage setextradata.</p>
<p>Whenever I type the command:</p>
<pre>sudo VBoxManage setextradata Windows_7 "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guestEmule_TCP/Protocol" TCP</pre>
<p>I get the following error:</p>
<pre>VirtualBox Command Line Management Interface Version 2.1.4
(C) 2005-2009 Sun Microsystems, Inc.
All rights reserved.
[!] FAILED calling a->virtualBox->FindMachine(Bstr(a->argv[0]), machine.asOutParam()) at line 3688!
[!] Primary RC = VBOX_E_OBJECT_NOT_FOUND (0x80BB0001) - Object corresponding to the supplied arguments does not exist
[!] Full error info present: true , basic error info present: true
[!] Result Code = VBOX_E_OBJECT_NOT_FOUND (0x80BB0001) - Object corresponding to the supplied arguments does not exist
[!] Text = Could not find a registered machine named 'Windows_7'
[!] Component = VirtualBox, Interface: IVirtualBox, {339abca2-f47a-4302-87f5-7bc324e6bbde}
[!] Callee = IVirtualBox, {339abca2-f47a-4302-87f5-7bc324e6bbde}</pre>
<p>The virtual-machine has been created using GUI. Any idea?</p>
<pre>$ cd /Users/marco/Library/VirtualBox/Machines/Windows_7
$ ls
Logs Windows_7.xml
Windows 7.xml.1.5-macosx.bak
$ sudo vboxmanage registervm Windows_7.xml
VirtualBox Command Line Management Interface Version 2.1.4
(C) 2005-2009 Sun Microsystems, Inc.
All rights reserved.
[!] FAILED calling a->virtualBox->OpenMachine(Bstr(a->argv[0]), machine.asOutParam()) at line 762!
[!] Primary RC = NS_ERROR_FAILURE (0x80004005) - Operation failed
[!] Full error info present: true , basic error info present: true
[!] Result Code = NS_ERROR_FAILURE (0x80004005) - Operation failed
[!] Text = Could not lock the settings file '/var/root/Library/VirtualBox/Windows_7.xml' (VERR_FILE_NOT_FOUND)
[!] Component = Machine, Interface: IMachine, {ea6fb7ea-1993-4642-b113-f29eb39e0df0}
[!] Callee = IVirtualBox, {339abca2-f47a-4302-87f5-7bc324e6bbde}</pre>
| <p>It fails because you are using sudo. VirtualBox is designed to be run by any user (in the <code>vboxusers</code> group), and sudo runs the command as the root user whose VirtualBox configuration is empty.</p>
<p>You can check that by typing:</p>
<pre><code>sudo VBoxManage -nologo list vms # Should print only a newline
VBoxManage -nologo list vms # Detailled information about all your VMs
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.