input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
jQuery: selecting checked checkbox <p>Suppose I have the following HTML:</p>
<pre><code><form id="myform">
<input type='checkbox' name='foo[]'/> Check 1<br/>
<input type='checkbox' name='foo[]' checked='true'/> Check 2<br/>
<input type='checkbox' name='foo[]'/> Check 3<br/>
</form>
</code></pre>
<p>Now, how do I select the checked input fields with name 'foo[]'?</p>
<p>This is my try, but it doesn't work:</p>
<pre><code>$('#myform input[name='foo']:checked:enabled');
</code></pre>
| <p>The name of the field isn't <code>foo</code>, it is <code>foo[]</code>. You could use the <a href="http://docs.jquery.com/Selectors/attributeStartsWith#attributevalue">attributeStartsWith</a> selector:</p>
<pre><code>$("input[name^='foo']:checked:enabled",'#myform');
</code></pre>
<p>Ideally, you'd be able to do this:</p>
<pre><code>$("input[name='foo[]']:checked:enabled",'#myform');
</code></pre>
<p>But as <a href="http://stackoverflow.com/questions/739695/jquery-selector-value-escaping/740168#740168">this answer</a> explains, jQuery uses this to parse the <code>value</code> part of the <code>attr=value</code> condition:</p>
<pre><code>(['"]*)(.*?)\3|)\s*\]
</code></pre>
<blockquote>
<p>\3 being the group containing the opening quotes, which weirdly are allowed to be multiple opening quotes, or no opening quotes at all. The .*? then can parse any character, including quotes until it hits the first â]â character, ending the match. There is no provision for backslash-escaping CSS special characters, so you can't match an arbitrary string value in jQuery.</p>
</blockquote>
<p>In other words, as soon as jQuery hits the first <code>]</code> it thinks the value is over. So you are stuck with startsWith or using pure DOM elements, as that answer also explains.</p>
<p><strong>SUPER DUPER IMPORTANT EDIT</strong>:<br />
This bug is fixed, apparently. You should be able to use the code I described as "ideal", above.</p>
|
Populate 2 or more tables in ASP MVC <p>I'm looking for a way to populate more than 1 table in MVC, because the method only allows me to return One ModelView or I don't know how to return more. Do I have to build the table in the controller and store into a ViewData and display the viewData in the page?</p>
<p>Edit: Sorry, I think I didn't express the idea. The point is that I want to populate 2 or more datatables in the page.</p>
<p>For example, if I have a Customer and that Customer has 5 Contacts and 5 Addresses, I want to display the Customer Information and 2 Tables with Contacts and Addresses.</p>
<pre><code>for each p in modelview
{
"<td>" + p.Name + "</td>"
}
for each p2 in modelview2
{
"<td>" + p2.Product + "</td>"
}
</code></pre>
| <p>ViewData is a dictionary; you can store multiple items in there, simply via:</p>
<pre><code>ViewData["foo"] -= ...
ViewData["bar"] -= ...
</code></pre>
<p>You can then get these (separately) in the view. The other approach is to declare a type that <em>encapsulates</em> both properties, and use an instance of that type as the model (and a typed view). Personally, I prefer the simple key/cast approach.</p>
|
MSSQL - Presenting data when column names dynamic <p>I am presenting to a final authority evaluation scores for employees. Each row is an employeeâs data and since the categories to be evaluated can change from period to period the column names cannot be hardcoded in the Stored Procedures. I have already devised the following solution. <br/> <br/>
1 Create a temp table<br/>
2 Dynamically use the Alter Table command to add all applicable columns (Stored in @ColumnNames)<br/>
3 Use Dynamic SQL inside a cursor to write an insert for each employee that gets the correct scores (IE N employees means N inserts) <br/> </p>
<pre><code>(SELECT @ECMScores = COALESCE(@ECMScores + ',', '') + CAST(EIS.ECMScore AS NVARCHAR(1000)) (FROM...))
SET @SQLString = ''
SET @SQLString = @SQLString + 'INSERT INTO #ResultSet ('
SET @SQLString = @SQLString + 'EvaluationScoreID,'
SET @SQLString = @SQLString + 'EmployeeID,'
SET @SQLString = @SQLString + 'EmployeeName,'
SET @SQLString = @SQLString + @ColumnNames
SET @SQLString = @SQLString + ') '
SET @SQLString = @SQLString + 'VALUES ('
SET @SQLString = @SQLString + ''+CAST(@EvaluationScoreID AS NVARCHAR(MAX))+','
SET @SQLString = @SQLString + ''+CAST(@EmployeeID AS NVARCHAR(MAX))+','
SET @SQLString = @SQLString + '"'+@EmployeeName+'",'
SET @SQLString = @SQLString + @ECMScores
SET @SQLString = @SQLString + ')'
EXECUTE sp_executesql @SQLString
</code></pre>
<p>The problem is it takes approx 1 second for every 100 employees. This quickly becomes unacceptableâ¦</p>
<p>Does anyone have any better ideas on how to proceed? Removing the cursor (obviously), and using one insert (Perhaps Select into) is my first idea perhaps reading from a dynamically created XML variableâ¦</p>
<p>Thanks,</p>
| <p>don't store data in the schema</p>
<p>create tables like this:</p>
<pre><code>Assignment
AssignmentID int not null primary key identity(1,1)
AssignmentName varchar(50) not null
AssignmentDate datetime not null
etc..
Score
ScoreID int not null primary key identity(1,1)
EmployeeID int not null
AssignmentID int not null
ScoreValue int not null
Employee
EmployeeID int not null primary key identity(1,1)
EmployeeName varhar(100) not null
etc..
</code></pre>
<p>you can now create "assignments" and insert "scores" without building dynamic queries because your columns always change. your columns will now stay the same and the data will change.</p>
|
Quick way to insert interface methods to a class in Visual Studio 2005 <p>I know that in Eclipse, if your class implements an interface or extends an abstract class, there is a quick way to add the method definitions to your class. Can this be done with VS2005? How?</p>
| <p>This is language specific but </p>
<p>For C#: Right click on the interface, navigate to Implement Inteface and choose the explicit or implict option. The same menu is available for abstract classes (slightly different name)</p>
<p>There is also a smart tag that will show up on a C# interface / abstract base with the same options. The hot key to get this to popup is "CTRL+."</p>
<p>For VB.Net: Simply hit Enter after the interface name and the methods will be auto-populated.</p>
|
Photo application <p>I'm developing an application just for fun that consists of capturing images from a webcam.</p>
<p>What I would like to know is how can I apply some filters to the image that I capture? Ideally I would like to develop something like Apple iPhoto; something that defaces the image.</p>
<p>The programming language I am using is C#.</p>
| <p>if you wnat to implement the filter algorithms, first of all you have to find all operations involved in the algorithm (also a simple low-pass can involve a bit of work) and then you need to access every single pixels of the image (you can do this using Image or Bitmap classes, using the Set/GetPixel method.</p>
|
Java Transactions API and .NET System.Transactions <p>I'm analyzing the different behaviors between the JTA (Java Transactions API) and the .NET counterpart System.Transactions: the approach is quite different between the two of them.
In fact, Java's version of Transactions seems more a specification, leaving to developers the obligation to implement either the <code>Transactions</code>, <code>TransactionManager</code> and other interfaces defined.
.NET has a more concrete implementation, which doesn't allow developers to define their own <code>Transaction</code> object, but providing interfaces to handle resources managed during the transactions's lifetime (while Java provides some XTA* interfaces for the same purpose)</p>
<ul>
<li><p>I'm wondering if any out there has ever had the occasion to port some Java code making use of JTA to .NET and which main differences has he/she noticed.</p></li>
<li><p>Furthermore, could anyone clarify me the behavior of <code>TransactionManager.setRollbackOnly</code> against <code>TransactionManager.rollback</code> (in JTA)? .NET version has just the <code>Transaction.Rollback</code> method which is more imperative.</p></li>
</ul>
| <p>rollback() sends an actual rollback command to the underlying resources. setRollbackOnly() puts a marker on the current transaction which is read when it's time to decide whether to commit or rollback. Once setRollbackOnly() has been called the only possible outcome is rollback but the rollback call is not actually made when setRollbackOnly() is being called.</p>
<p>That's the idea behind both methods. I'm not sure in how far different implementations make this distinction, and even if setRollbackOnly() would actually do a rollback when called it wouldn't make any practical difference.</p>
|
How do I add syntactic sugar in my Javascript library? <p>Right now the library can translate this operation </p>
<pre><code>Select * from List where name = k% order by desc
</code></pre>
<p>to</p>
<pre><code>List.filter(function(x) { return x.first_char() == 'k' }).sort().reverse());
</code></pre>
<p>Whats the best hack to remove the () so that the developer can write statements like:</p>
<pre><code>List.filter(fn(x) { return x.first_char == 'k' }).sort.reverse;
</code></pre>
<p>Naive approach:</p>
<pre><code>maxfn = function() {this[0]..}; Array.prototype.max = maxfn();
</code></pre>
<p>But with this approach I can't access 'this'.</p>
<p>I wanted to add a syntactic sugar for </p>
<pre><code>new Array("1","2","3")
</code></pre>
<p>to something like :)(suggestions needed) </p>
<pre><code>_("1","2" ,"3")
</code></pre>
<p>like we have in scheme where list -> '</p>
<p>I tried to clone the arguments but failed.</p>
<p>Thanks.</p>
| <p>For lists you can use <a href="http://json.org" rel="nofollow">JSON</a> notation:</p>
<pre><code>["1", "2", "3"]
</code></pre>
|
How to display simple HTML in a Silverlight textblock? <p>I've got a source of data that has HTML tags in it (B, I, A) and need to display this in a Silverlight ListBox. </p>
<p>Searching around it seems to be an issue but most of the posts are old and have to do with Silverlight 1 it seems.</p>
<p>What is currently the best way to display simple HTML with Silverlight, if nothing else, just the B, I and A tags for bold, italic and hyperlinks?</p>
| <p>There's no native support in Silverlight 2.0. However, someone has gone and created a <code>HtmlTextBlock</code> control which should be suitable for your purposes. Check out the author's <a href="http://blogs.msdn.com/delay/archive/2008/03/17/continuing-support-for-simple-html-display-in-silverlight-htmltextblock-sample-updated-for-silverlight-2-beta-1.aspx" rel="nofollow">block post</a> on the subject. There's also a demo page <a href="http://cesso.org/Samples/SilverlightHtmlTextBlock/" rel="nofollow">here</a>.</p>
|
Passing multiple Eval() to a JavaScript function from ASPX <p>I am trying to pass multiple <code>Eval()</code> arguments to a JavaScript function from an <code>.aspx</code> file, but I keep getting compiler errors. I am new to JavaScript and have never really used <code>Eval()</code> before. Where am I going wrong?</p>
<p><strong>NB</strong>: The line shown below is actually all on one line, but is wrapped here for clarity:</p>
<pre><code><asp:LinkButton runat="server" Text='<%#Eval("Title")%>'
OnClick='javascript:ShowEventDetails'
CommandArgument='<%#
Eval("EventID").ToString() & Eval("Title").ToString() &
Eval("Location").ToString() & Eval("StartTime").ToString() &
Eval("Description").ToString() & Eval("Link").ToString() &
Eval("ContactFirstName").ToString() & Eval("ContactLastName").ToString() &
Eval("ContactEmail").ToString() & Eval("InsertionTime").ToString() &
Eval("EventAdmin").ToString()%>); ' />
</code></pre>
<p>Are there better ways of doing this? If so, what are they?</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.onclick.aspx" rel="nofollow">OnClick</a> is a property on the control which expects a reference to an event handler method. Putting JavaScript in the OnClick property will not work.</p>
<p>If you want to execute arbitrary JavaScript when the button is clicked, use <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linkbutton.onclientclick.aspx" rel="nofollow">OnClientClick</a>. I presume you want to pass the evals into ShowEventDetails as arguments (formatted for readability):</p>
<pre><code><asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Eval("Title")%>'
OnClientClick='ShowEventDetails("<%# Eval("EventID").ToString() %>",
"<%# Eval("Title").ToString() %>",
"<%# Eval("Location").ToString() %>",
"<%# Eval("StartTime").ToString() %>",
"<%# Eval("Description").ToString() %>",
"<%# Eval("Link").ToString() %>",
"<%# Eval("ContactFirstName").ToString() %>",
"<%# Eval("ContactLastName").ToString() %>",
"<%# Eval("ContactEmail").ToString() %>",
"<%# Eval("InsertionTime").ToString() %>",
"<%# Eval("EventAdmin").ToString() %>");' />
</code></pre>
<p>Essentially you are constructing one long string:</p>
<pre><code>ShowEventDetails('123','Event Title','New York' ... etc ...
</code></pre>
<p>Which is executed in JS when the LinkButton is clicked.</p>
|
benchmarking django apps <p>I'm interested in testing the performance of my django apps as I go, what is the best way to get line by line performance data?</p>
<p><strong>note</strong>: Googling this returns lots of people benchmarking django itself. I'm not looking for a benchmarks of django, I'm trying to test the performance of the django apps that I'm writing :)</p>
<p>Thanks!</p>
<p><strong>edit</strong>: By "line by line" I just mean timing individual functions, db calls, etc to find out where the bottlenecks are on a very granular level</p>
| <p>There's two layers to this. We have most of #1 in place for our testing. We're about to start on #2.</p>
<ol>
<li><p>Django in isolation. The ordinary Django unit tests works well here. Create some tests that cycle through a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data. This isn't real web performance, but it's an easy-to-work with test scenario that you can use for tuning.</p></li>
<li><p>Your whole web stack. In this case, you need a regular server running Squid, Apache, Django, MySQL, whatever. You need a second computer(s) to act a client exercise your web site through urllib2, doing a few (less than 6) "typical" use cases. Get this, post that, etc. Collect timing data. This still isn't "real" web performance, because it isn't through the internet, but it's as close as you're going to get without a really elaborate setup.</p></li>
</ol>
<p>Note that the #2 (end-to-end) includes a great deal of caching for performance. If your client scripts are doing similar work, caching will be really beneficial. if your client scripts do unique things each time, caching will be less beneficial.</p>
<p>The hardest part is determining what the "typical" workload is. This isn't functional testing, so the workload doesn't have to include everything. Also, the more concurrent sessions your client is running, the slower it becomes. Don't struggle trying to optimize your server when your test client is the slowest part of the processing.</p>
<hr>
<p><strong>Edit</strong></p>
<p>If "line-by-line" means "profiling", well, you've got to get a Python profiler running.</p>
<p><a href="https://docs.python.org/library/profile.html" rel="nofollow">https://docs.python.org/library/profile.html</a></p>
<p>Note that there's plenty of caching in the Django ORM layer. So running a view function a half-dozen times to get a meaningful set of measurements isn't sensible. You have to run a "typical" set of operations and then find hot-spots in the profile. </p>
<p>Generally, your application is easy to optimize -- you shouldn't be doing much. Your view functions should be short and have no processing to speak of. Your form and model method functions, similarly, should be very short.</p>
|
How do I catch the click event of a button who has a TDBGrid as its parent? <p>I have a small button I want to add to the top left corner of a Delphi TDBGrid component (in the header/title cells). I am able to place the button easily, but now the click event is not handled. I'm guessing the event is being caught by the grid. Any way I can force this specific event to go to the button instead? Note I still need the grid to handle click events for its title buttons like it currently does.</p>
<pre><code>procedure TForm38.FormCreate(Sender: TObject);
begin
button1.Parent := grid;
button1.Top := 0;
button1.Left := 0;
button1.Width := 12;
button1.Height := 18;
button1.OnClick := Button1Click;
end;
</code></pre>
<p><strong>Update:</strong>I've found I was able to use the button's MouseDown event which seems to work well, but I couldn't use the click event.</p>
<pre><code>procedure TForm38.Button1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if ( Button = mbLeft ) then
TButton(Sender).Click;
end;
</code></pre>
| <p>Wow, this is a toughie. TDBGrid doesn't have a generic "OnClick" event handler, and the position of your button makes it difficult to fake it. The only thing I can think of is to create your own component. This isn't as difficult as it might sound at first. Descend from TDBGrid and override the MouseUp method. Take a look at the way TCustomDBGrid.MouseUp is implemented. I haven't tested this, but you could probably try something like this: After the if statement that tests for</p>
<pre><code>(cell.x >= FIndicatorOffset)
</code></pre>
<p>and fires off click events, have it fire TitleClick(nil) or something if cell.x < FIndicatorOffset. Then attach an event handler to your grid's OnTitleClick event that calls Button1.Click if Column = nil. (Yeah, sort of a hack, but I can't think of an easier way to do it. If I were you I'd report this one to QC as a bug.)</p>
|
Is this LINQable? <p>I have a string which denotes a filter path (eg. "Plant Filters\Equipment\Equipment List")
The leaf node is of type Filter and rest are FilterFolders. </p>
<p>I need to:</p>
<ol>
<li>Go thru each node (not leaf) and get it's -> Folders</li>
<li>Check the next entry in the path and see if it matches a folder from above</li>
<li>If it matches, it's the last-1, then it gets its Filters</li>
<li>Then check its Filters and see if it matches the last string entry, if not, then get its folder and basically go back to step 2.</li>
</ol>
<p>What's the best way to do this?</p>
| <p>This is a recursive structure and cannot be handled with the LINQ standard query operators. Here you can find an <a href="http://www.pluralsight.com/community/blogs/jeffsch/archive/2006/08/18/33631.aspx" rel="nofollow">implementation of the Y-combinator</a> that allows to write recursive lambda expression. I am not sure if you should use it because under the hood it is quite a complex solution to a simple problem. This <a href="http://work.j832.com/2008/01/flattening-recursive-algorithms-with.html" rel="nofollow">implementation of a recursive query operator</a> (Note that the linked blog entry is not the correct final solution - read the later entries to get it right) is much simpler but does not solve the general problem of defining recursive lambda expressions.</p>
|
passing a jquery object into a function <p>How would you do something like this:</p>
<pre><code>somemethod($("#buttonelement"));
function(ele) {
ele.click(function(event) { alert("hi"); });
}
</code></pre>
<p>in other words how do you pass in an element as a jquery object and register the click event.</p>
| <p>Just like that...?</p>
<pre><code>function someMethod(ele) {
ele.click(function(event) {
alert("hi");
});
}
someMethod($("#buttonelement"));
</code></pre>
<p>The jQuery object is just like any other object in Javascript and can be passed to functions as normal.</p>
|
AspNetSqlMembershipProvider and PasswordRecovery Control <p>My scenario is I have a asp.net 2.0 application web application which had the AspNetSqlMembershipProvider properties as:</p>
<blockquote>
<p>enablePasswordRetrieval="false" and passwordFormat="Hashed"</p>
</blockquote>
<p>But now the need has risen to store user's passwords unencrypted as clear text and display them to Superusers. I have done this by changing the AspNetSqlMembershipProvider properties to:</p>
<blockquote>
<p>enablePasswordRetrieval="true" and passwordFormat="Clear"</p>
</blockquote>
<p>The problem is the way the PasswordRecovery control behaves. From what I have read it checks the properties of the AspNetSqlMembershipProvider tag if enablePasswordRetrieval="true" and passwordFormat="Clear" it will attempt to retrieve the password this is causing a problem when the password is effectively still stored as a hashed one. Is there any way of forcing the PasswordRecovery control to reset not retrieve the password when AspNetSqlMembershipProvider properties are enablePasswordRetrieval="true" and passwordFormat="Clear"?</p>
<p>Sorry for the long winded explanation, all help / pointers very much appreciated as always. Thank you.</p>
| <p>I don't think you'll have any luck trying to use two methods for storing passwords in the database.</p>
<p>My advice is to change the passwords on the accounts that have hashed passwords so they get stored as plain text and move on from there.</p>
<p>Alternatively, if you <em>must</em> store some hashed and some clear-text passwords, you'll have to look at extending the membership provider to support this. In my experience, this is often more trouble than it's worth.</p>
|
Why do I get a 404 error when I try to access my rails site using https? <p>My server is currently hosting a php site. This site uses ssl for certain pages already. Now I am transitioning over to rails, and all my new rails apps go into a subfolder. Passenger is setup and and my app works great. One problem, If i try to go to these pages using ssl, I get a 404 error. Apparently apache is looking for the literal folder instead of handing it off to Passenger as it normally does. What am I missing?</p>
| <p>Apache for the SSL (port 443) site is probably not set up for Passenger in the same way as for the "normal" (port 80) site.</p>
|
scaleable cloud computing services <p>I'm looking for a cloud computing service with the following requirements:</p>
<ul>
<li>no need to manage servers</li>
<li>instant availability</li>
<li>automatic scaling</li>
<li>ability to run tasks for at least a couple of minutes</li>
</ul>
<p>Google App Engine seems to meet all of these requirements with the exception that processes can only run for 30 seconds.</p>
<p>My application is a website that performs some heavy-duty calculations for the users when requested. I expect the load to be near zero for half the time, and at a maximum of hundreds of simultaneous tasks being run.</p>
<p>Does something like this exist?</p>
<p>Edit:
These are the services I've already looked at, and why they won't work for me:</p>
<ul>
<li>Amazon EC2 - requires server management, and I can't go from 0 to 1 servers in a matter of seconds</li>
<li>Amazon MapReduce - it takes a couple minutes to start up. If it was available in a matter of seconds, this would be what I'd use</li>
<li>Microsoft Azure - as Alan said, it still requires server management</li>
<li>Google App Engine - tasks can only last 30 seconds</li>
</ul>
| <p>I believe Amazon's EC2 fits your requirements.</p>
<p><a href="http://aws.amazon.com/ec2/" rel="nofollow">Amazon EC2</a></p>
|
How do you remove an advertised shortcut programmatically? <p>So I botched an msi installer and deployed it after only testing installation, not uninstall (bad I know, added running of an exe after install, but forgot to specify that it should only occur on install not uninstall). </p>
<p>I found the <a href="http://support.microsoft.com/kb/290301" rel="nofollow">Windows Installer Cleanup</a> util, and the related msizap that I'll use to automate the process. The problem now is that when a newer version is installed on top afterwards, the advertised shortcut still tries to do a repair (or whatever it's actually doing trying to load the old version) and fails. Running the program directly from the file works fine, but I need to remove the advertised shortcuts in an automated way. It doesn't need to be incredibly robust, fairly small private beta install-base right now, so can assume that shortcuts are in the originally installed locations of desktop and start menu.</p>
<p>Are there any special concerns I need to take into account for an advertised shortcut or can I just treat it as any other file and just remove it?</p>
| <p>As far as the shortcut is concerned, it's just a normal file that can be deleted. </p>
<p>However I'll caution you about using MSIZAP - it is really a <em>last resort</em> and leaves a lot of information behind, shared DLL counts, registry entries, files, etc. Once removing the Windows Installer information you then need to remove any information related to your program from the registry. SharedDLL ref counts are the worst thing as they'll screw up when you try to reinstall/uninstall with the new MSI.</p>
<p>Rob has a good post up detailing some of <a href="http://robmensching.com/blog/posts/2009/3/6/More-on-Haacks-Troubleshooting-Windows-MSI-Installers" rel="nofollow">the pitfalls of using MSIZAP</a>. It's not something you want to use unless you're prepared to manually hunt down all the registry information it leaves behind. </p>
|
Updating display order of multiple MySQL rows in one or very few queries <p>I have a table with say 20 rows each with a number for display order (1-20).</p>
<pre><code>SELECT * FROM `mytable` ORDER BY `display_order` DESC;
</code></pre>
<p>From an admin area you can drag the rows around or type a new number manually for each row.</p>
<p>Surely it's not good to loop over an UPDATE query for every row, what's an alternative in one or very few queries suitable for updating one cell in 20 rows or even more, 50-200+?</p>
<p><hr /></p>
<p><strong>Edit:</strong> A lot of good responses and ideas. I might expand on the ideas I've considered so far:</p>
<p><strong>One array string</strong>: I could have the order in a string listing the unique row IDs in the order I want - eg rows 1,9,2,6,23. When the order is updated, a hidden field updates with JavaScript and adds that to the database or a text file when complete:</p>
<pre><code>UPDATE `my_dispaly_order_table` SET `display_order`='1,9,2,6,23';
</code></pre>
<p><strong>Update each row individually</strong>: This is what I was trying to avoid but it would only be changed very infrequently so 20-30 calls in one hit once a week or month might not be a problem so simply calling UPDATE on each row is what I usually do:</p>
<pre><code>UPDATE `mytable` SET `display_order`='1' WHERE `rowId` = 1;
UPDATE `mytable` SET `display_order`='2' WHERE `rowId` = 9;
UPDATE `mytable` SET `display_order`='3' WHERE `rowId` = 2;
UPDATE `mytable` SET `display_order`='4' WHERE `rowId` = 6;
UPDATE `mytable` SET `display_order`='5' WHERE `rowId` = 23;
</code></pre>
| <p>You should first ensure that the column has no UNIQUE index, otherwise mysql will tell you that the constraint is broken during the query. After that you can do things like:</p>
<pre><code>-- Move #10 down (i.e. swap #10 and #11)
UPDATE mytable SET display_order =
CASE display_order
WHEN 10 THEN 11
WHEN 11 THEN 10
END CASE
WHERE display_order BETWEEN 10 AND 11;
-- Move #4 to #10
UPDATE mytable SET display_order
CASE display_order
WHEN 4 THEN 10
ELSE display_order - 1
END CASE
WHERE display_order BETWEEN 4 AND 10;
</code></pre>
<p>But you should actually ensure that you do things in single steps. swapping in two steps will result in broken numbering if not using ids. i.e.:</p>
<pre><code>-- Swap in two steps will not work as demostrated here:
UPDATE mytable SET display_order = 10 WHERE display_order = 11;
-- Now you have two entries with display_order = 10
UPDATE mytable SET display_order = 11 WHERE display_order = 10;
-- Now you have two entries with display_order = 11 (both have been changed)
</code></pre>
<p>And here is a reference to the <a href="http://dev.mysql.com/doc/refman/5.1/de/case-statement.html">CASE statement of mysql</a>.</p>
|
Best way to obfuscate an e-mail address on a website? <p>I've spent the past few days working on updating my personal website. The URL of my personal website is (my first name).(my last name).com, as my last name is rather unusual, and I was lucky enough to pick up the domain name. My e-mail address is (my first name)@(my last name).com. So really, when it comes down to guessing it, it's not very hard.</p>
<p>Anyways, I want to integrate a mailto: link into my website, so people can contact me. And, despite my e-mail address not being very hard to guess, I'd rather not have it harvested by spam bots that just crawl websites for e-mail address patterns and add them to their database.</p>
<p>What is the best way for me to obfuscate my e-mail address, preferably in link form? The methods I know of are:</p>
<pre><code><a href="mailto:x@y.com">e-mail me</a>
</code></pre>
<p>It works, but it also means that as soon as my website hits Google, I'll be wading through spam as spam bots easily pick out my e-mail address.</p>
<pre><code><img src="images/e-mail.png" />
</code></pre>
<p>This is less desirable, because not only will visitors be unable to click on it to send me an e-mail, but smarter spam bots will probably be able to detect the characters that the image contains.</p>
<p>I know that there is probably no perfect solution, but I was just wondering what everyone thought was best. I'm definitely willing to use JavaScript if necessary, as my website already makes use of tons of it.</p>
| <p>I encode the characters as HTML entities (<a href="http://www.wbwip.com/wbw/emailencoder.html">something like this</a>). It doesn't require JS to be enabled and seems to have stopped most of the spam. I suppose a smart bot might still harvest it, but I haven't had any problems.</p>
|
Optimizing Telerik ASP.NET AJAX Controls <p>Any good sources(links) about optimizing Telerik Web controls? I imagine that there are features that are turned on by default. These features require resources (javascript, css, images) to be downloaded on request. It would be nice to know what these feature are and to turn them off if not used. </p>
<p>Do you know of such features? I'm primarily interested in Telerik AJAX components.</p>
| <p>Does this help?</p>
<p><a href="http://www.telerik.com/help/aspnet-ajax/optimizing_output_and_page_load_time_by_using_radscriptmanager_and_radstylesheetmanager.html" rel="nofollow">Optimizing output, page load time and the overall performance of RadControls for ASP.NET AJAX</a></p>
<p><a href="http://www.telerikwatch.com/2009/02/optimization-tips-radinput-vs.html" rel="nofollow">RadInput vs. RadInputManager</a></p>
<p><a href="http://telerikwatch.com/2008/05/optimization-tips-using.html" rel="nofollow">Using RadAjaxManagerProxy Controls</a> </p>
<p>Did you even try searching anything?</p>
|
BindAsEventListener equivalent in jQuery? <p>I am trying to bind a click event to some element using jQuery.
Using prototype I know I can do this using <code>BindAsEventListener()</code>.</p>
<p>Example: </p>
<pre><code>var myObject = {
init: function(txtOneId, txtTwoId, lblResultId, ancAddId) {
this.txtOneId = txtOneId;
this.txtTwoId = txtTwoId;
this.lblResultId = lblResultId;
this.ancAddId = ancAddId;
var addListener = this.addResult.bindAsEventListener(this);
Event.observe(this.txtOneId, 'keyup', addListener);
Event.observe(this.txtTwoId, 'keyup', addListener);
},
addResult: function() {
var valueOne = $(this.txtOneId).value;
var valueTwo = $(this.txtTwoId).value;
if (isNaN(valueOne) || valueOne == "")
valueOne = 0;
else
valueOne = parseInt(valueOne);
if (isNaN(valueTwo) || valueTwo == "")
valueTwo = 0;
else
valueTwo = parseInt(valueTwo);
var result = valueOne + valueTwo;
$(this.lblResultId).innerHTML = result;
return false;
}};
</code></pre>
| <p>I assume that you are still using prototype, and have added the jQuery no conflict so that <strong>$()</strong> is a prototype method and <strong>$j()</strong> is a jQuery method.</p>
<p><strong>Quick Answer</strong></p>
<p>You only need to make a change on your init method.</p>
<pre><code> init: function(txtOneId, txtTwoId, lblResultId, ancAddId) {
this.txtOneId = txtOneId;
this.txtTwoId = txtTwoId;
this.lblResultId = lblResultId;
this.ancAddId = ancAddId;
var handler = function(event){ event.data.addResult(event) };
$j(this.txtOneId).bind('keyup', this, handler);
$j(this.txtTwoId).bind('keyup', this, handler);
}
</code></pre>
<p><strong>Explanation</strong></p>
<p>With Prototype you used the bindAsEventListener function so that the this reference will be available when the event is received. </p>
<p>For jQuery you can pass this event data with the bind method using the following syntax (from <a href="http://api.jquery.com/bind/" rel="nofollow">jquery api</a>):</p>
<pre><code>.bind( eventType [, eventData], handler(eventObject) );
</code></pre>
<p>Applied to your code, with the use of an anonymous function, this resolves to:</p>
<pre><code>$j(this.txtOneId).bind('keyup', this, function(event){ event.data.addResult(event) });
</code></pre>
<p>In this case we bind the 'keyup' event to the text elements, pass the this reference as eventData and then in the handler function we reference the eventData (this) with event.data to execute the this.addResult(event) method.</p>
|
Does the Sun JVM slow down when more memory is allocated via -Xmx? <p>Does the Sun JVM slow down when more memory is available and used via -Xmx? (Assumption: The machine has enough physical memory so that virtual memory swapping is not a problem.)</p>
<p>I ask because my production servers are to receive a memory upgrade. I'd like to bump up the -Xmx value to something <em>decadent</em>. The idea is to prevent any heap space exhaustion failures due to my own programming errors that occur from time to time. Rare events, but they could be avoided with my rapidly evolving webapp if I had an obscene -Xmx value, like 2048mb or higher. The application is heavily monitored, so unusual spikes in JVM memory consumption would be noticed and any flaws fixed.</p>
<p>Possible important details:</p>
<ul>
<li>Java 6 (runnign in 64-bit mode)</li>
<li>4-core Xeon</li>
<li>RHEL4 64-bit</li>
<li>Spring, Hibernate</li>
<li>High disk and network IO</li>
</ul>
<p><strong><em>EDIT</strong>: I tried to avoid posting the configuration of my JVM, but clearly that makes the question ridiculously open ended. So, here we go with relevant configuration parameters:</em></p>
<pre><code>-Xms256m
-Xmx1024m
-XX:+UseConcMarkSweepGC
-XX:+AlwaysActAsServerClassMachine
-XX:MaxGCPauseMillis=1000
-XX:MaxGCMinorPauseMillis=1000
-XX:+PrintGCTimeStamps
-XX:+HeapDumpOnOutOfMemoryError
</code></pre>
| <p>By adding more memory, it will take longer for the heap to fill up. Consequently, it will reduce the frequency of garbage collections. However, depending on how mortal your objects are, you may find that how long it takes to do any single GC increases.</p>
<p>The primary factor for how long a GC takes is how many <em>live</em> objects there are. Thus, if virtually all of your objects die young and once you get established, none of them escape the young heap, you may not notice much of a change in how long it takes to do a GC. However, whenever you have to cycle the tenured heap, you may find everything halting for an unreasonable amount of time since most of these objects will still be around. Tune the sizes accordingly.</p>
|
Where to go to browse for open source projects to work on? <p>I've decided to have a look around for open source projects that need a hand and lend a bit of time to one or two. One question though, is there a site(s) that lists current open source projects that are looking for developers and is there anywhere I could for example filter open source projects by language/technology/etc.</p>
<p>What I'm after is a way of getting an overview of many open source projects so I can make a decision whether they interest me or not.</p>
<p>Ideas where to find such information?</p>
| <p>The three major ones:</p>
<p><a href="http://sourceforge.net/" rel="nofollow"><strong>SourceForge</strong></a></p>
<p><a href="http://www.codeplex.com" rel="nofollow"><strong>CodePlex</strong></a></p>
<p><a href="http://code.google.com" rel="nofollow"><strong>Google Code</strong></a></p>
|
Django: How to use stored model instances as form choices? <p>I have a model which is essentially just a string (django.db.models.CharField). There will only be several instances of this model stored. How could I use those values as choices in a form?</p>
<p>To illustrate, the model could be <code>BlogTopic</code>. I'd like to offer users the ability to choose one or several topics to subscribe to.</p>
<p>I started writing something like:</p>
<pre><code>from mysite.blog.models import BlogTopic
choices = [(topic.id, topic.name) for topic in BlogTopic.objects.all()]
class SubscribeForm(forms.Form):
topics = forms.ChoiceField(choices=choices)
</code></pre>
<p>But I'm not sure when <code>choices</code> would be defined. I assume only when the module is first imported (i.e. when starting Django). Obviously that is not a very good approach.</p>
<p>This seems like it would be a common requirement, but I can't seem to find any examples. I suspect I may be missing something obvious here. Anyway, thanks in advance for your answers.</p>
| <pre><code>topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())
</code></pre>
|
Keep a http connection alive in C#? <p>How do i keep a connection alive in C#? I'm not doing it right. Am i suppose to create an HttpWebRequest obj and use it to go to any URLs i need? i dont see a way to visit a url other then the HttpWebRequest.Create static method.</p>
<p>How do i create a connection, keep it alive, browse multiple pages/media on the page and support proxys? (i hear proxy are easy and support is almost standard?)
-edit- good answers. How do i request a 2nd url? </p>
<pre><code>{
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("http://google.com");
WebRequestObject.KeepAlive = true;
//do stuff
WebRequestObject.Something("http://www.google.com/intl/en_ALL/images/logo.gif");
}
</code></pre>
| <p>Have you tried the <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive.aspx">HttpWebRequest.KeepAlive</a> property? It sets the appropriate Keep-Alive HTTP header and does persist the connections. (Of course this must also be supported and enabled by the remote web server).</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.keepalive.aspx">HttpWebRequest.KeepAlive</a> documentation on MSDN states that it is set to <strong>true</strong> by default for HTTP1.1 connections, so I suspect the server you're trying to contact does not allow connection persistence.</p>
<p>Proxy is used automatically and its settings are taken from your system (read Internet Explorer) settings. It is also possible to override the proxy settings via <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.proxy.aspx">HttpWebRequest.Proxy</a> property or by tweaking the application configuration file (see <a href="http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx">http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx</a>).</p>
|
Partial list unpack in Python <p>In Python, the assignment operator can unpack list or tuple into variables, like this:</p>
<pre><code>l = (1, 2)
a, b = l # Here goes auto unpack
</code></pre>
<p>But I need to specify exactly the same amount of names to the left as an items count in the list to the right. But sometimes I don't know a size of the list to the right, for example if I use split(). Example:</p>
<pre><code>a, b = "length=25".split("=") # This will result in a="length" and b=25
</code></pre>
<p>But the following code will lead to an error:</p>
<pre><code>a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item
</code></pre>
<p>Is it possible to somehow unpack list in the example above so I get a = "DEFAULT_LENGTH" and b equals to 'None' or not set? A straightforward way looks kind of long:</p>
<pre><code>a = b = None
if "=" in string :
a, b = string.split("=")
else :
a = string
</code></pre>
| <p>This may be of no use to you unless you're using Python 3. However, for completeness, it's worth noting that the <a href="http://www.python.org/dev/peps/pep-3132/" rel="nofollow">extended tuple unpacking</a> introduced there allows you to do things like:</p>
<pre><code>>>> a, *b = "length=25".split("=")
>>> a,b
("length", ['25'])
>>> a, *b = "DEFAULT_LENGTH".split("=")
>>> a,b
("DEFAULT_LENGTH", [])
</code></pre>
<p>I.e. tuple unpacking now works similarly to how it does in argument unpacking, so you can denote "the rest of the items" with <code>*</code>, and get them as a (possibly empty) list.</p>
<p>Partition is probably the best solution for what you're doing however.</p>
|
force breaking a string in a fixed width Gridview cell <p>I have a Gridview control on an ASP.Net page with fixed width cells. The data coming from the database occasionally comes over as a contiguous string of characters. When there are dashes in the string, it will break so as not to upset the width of the layout. If there are no dashes (specifically, I'm dealing with underscores), the string will not break and forces the cell to widen out, thus upsetting the layout of the page. Is there a way to tell the cell to keep its width and break the string? As it stands, I don't have access to the field's data directly, as the GridView bind its datasource to a dataset object coming from the database. Thanks for any feedback.</p>
| <p>If you handle the <a href="http://msdn.microsoft.com/en-us/library/aa479342.aspx" rel="nofollow">RowDataBound event</a> you'll be able to break the string "manually". Otherwise it'll only break based on "HTML rules".</p>
|
How to detect a hung thread? <p>Is it possible to detect a hung thread? This thread is not part of any thread pool, its just a system thread. Since thread is hung, it may not process any events.</p>
<p>Thanks,</p>
| <p>In theory, it is <a href="http://en.wikipedia.org/wiki/Halting%5FProblem" rel="nofollow">impossible</a>. If you are on Windows and suspect that the thread might be deadlocked, I guess you could use GetThreadContext a few times and check if it is always the same, but I don't know how reliable it will be.</p>
|
<cite> as part of semantic markup <p>One of the sites I develop has lots of information linked between each other; we have companies, we have products for those companies. The company page links to the page listing the products for that company, and vice versa.</p>
<p>From the <a href="http://www.w3.org/TR/html401/struct/text.html#edef-CITE" rel="nofollow">HTML spec</a>:</p>
<blockquote>
<p>CITE:
Contains a citation or a reference to other sources.</p>
</blockquote>
<p>Does this imply that I could (semantically) use a <code><cite></code> for a company link? What about on the company page to a product?</p>
<p>If not, could someone tell me what might be the "correct" semantic tag for this?</p>
| <p>If you're just linking to other pages then semantically you should just use <code><a href=...></code>. If you're quoting a small piece of information, like the information from the HTML spec in your question, and providing a link to the original source, you might use <code><cite></code>. Think of it as a citation in a book or research paper.</p>
|
How to generate examples of a gettext plural forms expression? In Python? <p>Given a gettext Plural-Forms line, general a few example values for each <code>n</code>. I'd like this feature for the web interface for my site's translators, so that they know which plural form to put where. For example, given:</p>
<p><code>"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%"</code>
<code>"10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"</code></p>
<p>... I want the first text field to be labeled "1, 21..", then "2, 3, 4...", then "5, 6..." (not sure if this is exactly right, but you get the idea.)</p>
<p>Right now the best thing I can come up with is to parse the expression somehow, then iterate x from 0 to 100 and see what n it produces. This isn't guaranteed to work (what if the lowest x is over 100 for some language?) but it's probably good enough. Any better ideas or existing Python code?</p>
| <p>Given that it's late, I'll bite.</p>
<p>The following solution is hacky, and relies on converting your plural form to python code that can be evaluated (basically converting the x ? y : z statements to the python x and y or z equivalent, and changing &&/|| to and/or)</p>
<p>I'm not sure if your plural form rule is a contrived example, and I don't understand what you mean with your first text field, but I'm sure you'll get where I'm going with my example solution:</p>
<pre><code># -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
p = "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
# extract rule
import re
matcher = re.compile('plural=(.*);')
match = matcher.search(p)
rule = match.expand("\\1")
# convert rule to python syntax
oldrule = None
while oldrule != rule:
oldrule = rule
rule = re.sub('(.*)\?(.*):(.*)', r'(\1) and (\2) or (\3)', oldrule)
rule = re.sub('&&', 'and', rule)
rule = re.sub('\|\|', 'or', rule)
for n in range(40):
code = "n = %d" % n
print n, eval(rule)
</code></pre>
|
Default values in a C Struct <p>I have a data structure like this:</p>
<pre>
struct foo {
int id;
int route;
int backup_route;
int current_route;
}
</pre>
<p>and a function called update() that is used to request changes in it. </p>
<pre>
update(42, dont_care, dont_care, new_route);
</pre>
<p>this is really long and if I add something to the structure I have to add a 'dont_care' to EVERY call to update( ... ).
<p>
I am thinking about passing it a struct instead but filling in the struct with 'dont_care' beforehand is even more tedious than just spelling it out in the function call. Can I create the struct somewhere with default values of dont care and just set the fields I care about after I declare it as a local variable?</p>
<pre>
struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);
</pre>
<p>What is the most elegant way to pass just the information I wish to express to the update function? </p>
<p>and I want everything else to default to -1 (the secret code for 'dont care')</p>
| <p>While macros and/or functions (as already suggested) will work (and might have other positive effects (i.e. debug hooks)) they are more complex than needed; the simplest and possibly most elegant solution is to just define a constant that you use for variable initialisation:</p>
<pre><code>const struct foo FOO_DONT_CARE = { // or maybe FOO_DEFAULT or something
dont_care, dont_care, dont_care, dont_care
};
...
struct foo bar = FOO_DONT_CARE;
bar.id = 42;
bar.current_route = new_route;
update(&bar);
</code></pre>
<p>This code has virtually no mentally overhead of understanding the indirection and it is very clear what fields in bar you explicit set while (safely) ignoring those you do not set.</p>
|
Refactoring method that binds controls to LINQ <p>I have a function that binds LINQ results to the controls on my form. The below code works but I just can't get over the feeling I should be slapped for the copy/paste aspect. Can someone help me with what i need to do to deodorize this?</p>
<p>Thank You!</p>
<pre><code>private void BindDataToForm()
{
// Bind data to form
CaseNotesDataContext db = new CaseNotesDataContext();
Table<CN_MaintItem> caseNotesItems = db.GetTable<CN_MaintItem>();
// For each object
var contactType = from cType in caseNotesItems
where cType.CategoryID == 2
select cType.ItemDescription;
chkContactType.DataSource = contactType;
var contactLocation = from cLocation in caseNotesItems
where cLocation.CategoryID == 3
select cLocation.ItemDescription;
lkuContactLocation.Properties.DataSource = contactLocation;
var contactMethod = from cMethod in caseNotesItems
where cMethod.CategoryID == 4
select cMethod.ItemDescription;
lkuContactMethod.Properties.DataSource = contactMethod;
var contactWith = from cWith in caseNotesItems
where cWith.CategoryID == 5
select cWith.ItemDescription;
chkContactWith.DataSource = contactWith;
var domains = from d in caseNotesItems
where d.CategoryID == 6
select d.ItemDescription;
chkDomains.DataSource = domains;
}
</code></pre>
| <p>I don't know if this really solves anything but try:</p>
<pre><code>public static class MyExtentsions {
public IQueryable<string> GetItemDescriptions(this Table<CN_MaintItem> table, int cat)
{
return from x in table
where x.CategoryID == cat
select x.ItemDescription;
}
}
</code></pre>
<p>So you can pull the information like this:</p>
<pre><code>using (CaseNotesDataContext db = new CaseNotesDataContext()) {
Table<CN_MaintItem> caseNotesItems = db.GetTable<CN_MaintItem>();
chkContactType.DataSource = caseNotesItems.GetItemDescriptions(2);
lkuContactLocation.Properties.DataSource = caseNotesItems.GetItemDescriptions(3);
// etc...
}
</code></pre>
|
Delimiter in one string <p>Here is an example of a file that i use to create a mysql db. The delimiter is "," but in the description for a single column exist ",".</p>
<pre><code>Header: City State Zip Description
Los Angeles, California , 98005, "welcome to california, were are living the dream","Please stay, a while."
</code></pre>
<p>The problem is that the description in "quotes" contains a delimiter which causes the file to have additional columns.</p>
<p>Someone told me that regex or preg_match functions my be able to solve my problem. Can someone tell me how.</p>
| <p>No need to reinvent any wheels, PHP already has what you need in <a href="http://www.php.net/manual/en/function.fgetcsv.php" rel="nofollow">fgetcsv</a></p>
|
jgoodies bindings + indirect changes <p>I'm having a brain cramp trying to understand the appropriate way to use JGoodies bindings in my application.</p>
<p>I have a class Article which is a bean that has read-only properties. <code>Article</code> is a "plain" bean, and doesn't manage property listeners, since the properties don't ever change. I have a Swing JPanel which I would like to use to display certain properties of an article. Different Article objects may be viewed at different times.</p>
<p>I'm looking for something (X) which does the following through one or more objects:</p>
<ol>
<li>X contains the currently viewed Article. I can call <code>X.setArticle()</code> and <code>X.getArticle()</code> to change to a different Article. There is no other way to change the currently viewed Article, I have to go through X so it knows I'm changing it.</li>
<li>When I set up my JPanel, I want to use X to create read-only JTextFields that are bound to various properties of the currently viewed Article (title, authors, etc.)</li>
<li>(this follows from #1 and #2) Anytime X.setArticle() is called, the contents of the text fields will automatically update.</li>
</ol>
<p>I have tried using BeanAdapter to extract the property models from an Article contained in a ValueHolder, and BasicComponentFactory.createTextField() to create the text fields, and it all seems to work <em>except</em> that I get a <code>com.jgoodies.binding.beans.PropertyUnboundException</code> complaining that my Article class has unbound properties. Duh! I know that, I just can't figure out how to get the right "plumbing" to deal with it. Each <code>Article</code> is unmodifiable, but the currently viewed Article may point to a different one.</p>
<p>any suggestions?</p>
| <p>I figured it out.</p>
<p>I do something like this:</p>
<pre><code> // on setup:
BeanAdapter<Article> adapter = new BeanAdapter<Article>((Article)null,
false);
// the "false" in the constructor means don't try to observe property
// changes within the Article, but we still can observe changes
// if the Article itself is replaced with a new one.
JTextField tfAuthors = BasicComponentFactory.createTextField(
adapter.getValueModel("authors"));
JTextField tfTitle = BasicComponentFactory.createTextField(
adapter.getValueModel("title"));
</code></pre>
<p>Later, when I change the Article object, I just do this:</p>
<pre><code> public void showArticle(Article article)
{
adapter.setBean(article);
}
</code></pre>
<p>and everything updates on screen very nicely.</p>
|
Is there a way to find out what's referencing my object in .NET? <p>Basically, I have an object that I think should be garbage-collected but it's not.
I am pretty certain all references to it are gone from what I can see in the code but for some reason, it is not getting destroyed.</p>
<p>Is there some way to find out what's holding my object hostage?
There doesn't seem to be a way to do that in Visual Studio 2005.
WinDbg perhaps?</p>
| <p>Yes, you can use WinDbg + SOS to trace your managed heap. <a href="http://blogs.msdn.com/ricom/archive/2004/12/10/279612.aspx" rel="nofollow">This link</a> should get you started.</p>
<p>Note - you don't have to use VADump (steps 1 to 3) to get a dump file, the Visual Studio debugger has this feature built in for an attached process.</p>
|
How to write my own wrapper in C#? <p>In my other question, I've been trying to find someone who knows where to find free open source OCR library for C#. However, it seems there is only C++ library and obviously, C++ is not C#.</p>
<p>One of the responds suggested to write my own wrapper in C#. I have pretty much no idea how to do it, where to learn to do it, or what it actually is - except I believe it's calling C++ methods in dll by changed method calls, .. that's just assumption, indeed.</p>
<p>Please, help out one more newbie. Thank you</p>
| <p>You can get a good start here:</p>
<p><a href="http://www.csharphelp.com/2006/01/call-unmanaged-code-part-1-simple-dllimport/" rel="nofollow">Call Unmanaged Code. Part 1 - Simple DLLImport</a></p>
|
Using TwitPic API from ObjectiveC/iPhone <p>There's a similar question on here about this which I've read and I've tried to follow the advice given there... and I think I'm 95% complete but the remaining 5%... well you know ;-)</p>
<p>So I'm trying to call the twitPic API to upload an image and I've got the image contained in a UIImageView which I'm displaying on the screen (I can see it so it's definitely there). My code to form the API call looks like this:</p>
<pre><code> NSURL *url = [NSURL URLWithString:@"http://twitpic.com/api/upload"];
NSString *username = @"myUsername";
NSString *password = @"myPassword";
NSData *twitpicImage = UIImagePNGRepresentation(imageView.image);
// Now, set up the post data:
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:twitpicImage forKey:@"media"];
[request setPostValue:username forKey:@"username"];
[request setPostValue:password forKey:@"password"];
// Initiate the WebService request
[request start];
</code></pre>
<p>I get an error back from it stating 'image not found'.</p>
<p>Is it obvious what I'm doing wrong? Any hints at all? I'm only a week deep in ObjectiveC so it's quite likely it's a real newbie error.</p>
<p>On the same track - it's not clear to me how I can capture a success or failure properly in code here - I'm currently dumping the 'request responseString' to an alert which isn't the best thing - how can I check the result properly?</p>
<p>I've also seen the use of 'NSLog' - which I suspect is a debugging/console logging tool - but I can't see the output from this anywhere in XCode - it doesn't SEEM to be shown in the debugger - any clues at all?!</p>
<p>Sorry if the above is really dumb - I can take a little ridicule - but I'm kind of isolated with my iPhone adventures - no one to bounce anything off etc - so I'm venting it all off here ;-)</p>
<p>Cheers,</p>
<p>Jamie.</p>
| <p>You need to use the setData method to copy the image data into the post, like this:</p>
<pre><code>[request setData:twitPicImage forKey:@"media"];
</code></pre>
<p>You're making a synchronous call, which is going to stall your app while you upload all that image data - you might want to switch to using an NSOperationQueue, or the ASINetworkQueue subclass that allows you to show a progress bar.</p>
<p>You should be able to see NSLog output in the debugger window of XCode. Make sure you've switched to this (control top left with a spray can on). You can also launch the console. </p>
|
Close MS Office C# Console <p>I'm writing an automated test to determine whether or not rtf files are successfully opened by MS Word. So far I looping through all the rtfs within a given directory and opening them. Later I will have to catch exceptions to generate a report (log the file name that crashed word).</p>
<p>I am processing a large number of files. My application is currently opening a new instance of Word for each file. Can someone tell me how to close Word? </p>
<pre><code>public class LoadRTFDoc
{
private object FileName;
private object ReadOnly;
private object isVisible;
private object Missing;
private ApplicationClass WordApp;
private object Save;
private object OrigFormat;
private object RouteDoc;
public LoadRTFDoc(object filename)
{
this.WordApp = new ApplicationClass();
this.FileName = filename;
ReadOnly = false;
isVisible = true;
Missing = System.Reflection.Missing.Value;
Save = System.Reflection.Missing.Value;
OrigFormat = System.Reflection.Missing.Value;
RouteDoc = System.Reflection.Missing.Value;
}
public void OpenDocument()
{
WordApp.Visible = true;
WordApp.Documents.Open(ref FileName, ref Missing, ref ReadOnly, ref Missing, ref Missing,
ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref Missing,
ref isVisible, ref Missing, ref Missing, ref Missing, ref Missing);
WordApp.Activate();
}
public void CloseDocument()
{
WordApp.Documents.Close(ref Save, ref OrigFormat, ref RouteDoc);
}
}
</code></pre>
<p>I am executing the CloseDocument() method after each document is opened. Anyone have some insight for me on this?</p>
<p>Thanks!</p>
| <pre><code>WordApp.Quit()
</code></pre>
<p>will exit the application. </p>
<p>However, the safest way is to get a handle to the process and kill the winword process. In C# the following code would do that:</p>
<pre><code>foreach (Process p in Process.GetProcessesByName("winword"))
{
if (!p.HasExited)
{
p.Kill();
}
}
</code></pre>
<p>The reason is that it will happen frequently (I assume, especially since you are testing documents created not by Word) that Word will hang with an open message box, e.g. a repair dialog. In that case killing the process is the easiest way to close the application.</p>
<p>I would suggest that you first try to close Word using <code>Application.Quit</code>. If this does not work it indicates a problem with your input file (most likely because a repair dialog is blocking Word). You should record this as an error in your log and then proceed killing the winword process.</p>
<p>Another problem you might face is Word's document recovery feature blocking the application on startup (and thus preventing a document from being opened until the recovery dialog box is clicked away). Document recovery can be disabled by deleting the following registry key under both HKCU and HKLM prior to starting Word (replace 12.0 with 11.0 for Word 2003 and 10.0 for Word XP):</p>
<pre><code>Software\Microsoft\Office\12.0\Word\Resiliency
</code></pre>
<p>It goes without saying that killing Word is a rather rude approach, however, it is simple and rather robust. The code above will just kill any instance of Word for a user. If you want to kill only a specific instance things get more difficult. You would have to retrieve the process id of a specific Word instance. Typically this can be done by searching for the window title of the instance, e.g. using WinAPI functions like <code>FindWindowByCaption</code> and <code>GetWindowThreadProcessId</code>.</p>
|
Actionscript 3.0: Scope <p>Tutorials usually don't deal with scope in Actionscript. Can you point me to some documentation and/or explain what should I know about it. I want to avoid problems arising from certain classes are not visible at certain places.</p>
| <p>These should help.</p>
<p>Function scope:</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_21.html" rel="nofollow">http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_21.html</a></p>
<p>Packaging and namespace:</p>
<p><a href="http://livedocs.adobe.com/flex/3/html/03_Language_and_Syntax_04.html#119303" rel="nofollow">http://livedocs.adobe.com/flex/3/html/03_Language_and_Syntax_04.html#119303</a></p>
|
Unable to show only one drawer by jQuery at startup <p>I want only one drawer to be open at startup. At the moment, all drawers are open.</p>
<p><strong>The <a href="http://jqueryfordesigners.com/slide-out-and-drawer-effect/" rel="nofollow">jQuery code</a></strong></p>
<pre><code>$(document).ready(function () {
// hide all ULs inside LI.drawer except the first one
$('LI.drawer UL:not(:first)').hide();
// apply the open class
$('li.drawer:first ul').addClass('open');
$('h2.drawer-handle').click(function () {
// hide the currently visible drawer contents
$('li.drawer ul:visible').hide();
// remove the open class from the currently open drawer
$('h2.open').removeClass('open');
// show the associated drawer content to 'this' (this is the current H2 element)
// since the drawer content is the next element after the clicked H2, we find
// it and show it using this:
$(this).next().show();
// set a class indicating on the H2 that the drawer is open
$(this).addClass('open');
});
});
</code></pre>
<p><strong>The HTML in the body</strong></p>
<pre><code><ul class="drawers">
<li class="drawer">
<h2 class="drawer-handle open">Contact</h2>
<ul>
<li>A</li>
<li>B</li>
</ul>
</li>
<li class="drawer">
<h2 class="drawer-handle">papers</h2>
<ul>
<li>A</li>
<li>B</li>
</ul>
</li>
</ul>
</code></pre>
<p><strong>How can you show one drawer and hide the rest at the startup?</strong></p>
| <p>You've got the right idea, just the wrong placement of your :first clause.</p>
<pre><code>$('li.drawer:first ul').addClass('open');
</code></pre>
|
How to shell execute a file in C#? <p>I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.</p>
<p>Is it possible?</p>
<p>EDIT:</p>
<p>Sample code:</p>
<pre><code>string pythonScript = @"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ( );
proc.StartInfo.WorkingDirectory = workDir;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.FileName = pythonScript;
proc.StartInfo.Arguments = "1, 2, 3";
</code></pre>
<p>I don't get any error, but the script isn't run. When I run the script manually, I see the result.</p>
| <p>Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.</p>
<pre><code> private static string CallPython(string script, string pyArgs, string workingDirectory, string[] standardInput)
{
ProcessStartInfo startInfo;
Process process;
string ret = "";
try
{
startInfo = new ProcessStartInfo(@"c:\python25\python.exe");
startInfo.WorkingDirectory = workingDirectory;
if (pyArgs.Length != 0)
startInfo.Arguments = script + " " + pyArgs;
else
startInfo.Arguments = script;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardInput = true;
process = new Process();
process.StartInfo = startInfo;
process.Start();
// write to standard input
foreach (string si in standardInput)
{
process.StandardInput.WriteLine(si);
}
string s;
while ((s = process.StandardError.ReadLine()) != null)
{
ret += s;
throw new System.Exception(ret);
}
while ((s = process.StandardOutput.ReadLine()) != null)
{
ret += s;
}
return ret;
}
catch (System.Exception ex)
{
string problem = ex.Message;
return problem;
}
}
</code></pre>
|
Silverlight Toolkit Treeview: Getting the parent of a selected item <p>I'm using the TreeView component from the Silverlight toolkit and I'm trying to get the parent of a selected node. The TreeView is bound to a series of objects, so directly working with a TreeViewItem appears to be out of the question. </p>
<pre><code><toolkit:TreeView SelectedItemChanged="DoStuff" DisplayMemberPath="Name" ItemsSource="{Binding MyCollection}">
<toolkit:TreeView.ItemTemplate>
<common:HierarchicalDataTemplate ItemsSource="{Binding MySubCollection}">
<StackPanel>
<TextBlock Text="{Binding Name}" />
</StackPanel>
</common:HierarchicalDataTemplate>
</toolkit:TreeView.ItemTemplate>
</toolkit:TreeView>
</code></pre>
<p>Is there a way to fetch the parent of an item selected in the DoStuff event?</p>
| <p>As long as you've downloaded the latest Silverlight Toolkit then this is easy using the TreeViewExtensions that are included.</p>
<ol>
<li>Download the <a href="http://www.codeplex.com/Silverlight" rel="nofollow">Silverlight Toolkit</a> and install.</li>
<li>Add a reference to System.Windows.Controls.Toolkit (from the Silverlight Toolkit)</li>
<li><p>Use the GetParentItem() extension method, like so:</p>
<pre><code>private void DoStuff(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (e.NewValue != null)
{
var parent = ((TreeView)sender).GetParentItem(e.NewValue);
//
// Do stuff with parent, this snippet updates
// a TextBlock showing the name of the current parent
if (parent != null)
{
Status.Text = parent.ToString();
}
}
}
</code></pre></li>
</ol>
|
Display slideshow of Private Photosets from Flickr <p>I have a number of photo sets that are marked as private on Flickr. I have a website and I would like to display all of them as Flash Sideshow.</p>
<p>I am currently using Flickr.NET open source library and I have created a web application to retrieve the list of all the photo sets. I can use other methods to display photos but I really like the embed slideshow feature of Flickr.</p>
<p>Hence my question - How should I code the Embed to display private photosets without making my photos as public ?</p>
| <p>You can't do it using the standard Flickr embed: <a href="http://www.flickr.com/help/blogging/#2937" rel="nofollow">http://www.flickr.com/help/blogging/#2937</a></p>
<p>All the embed parameters outlined here: <a href="http://paulstamatiou.com/2005/11/19/how-to-quickie-embedded-flickr-slideshows" rel="nofollow">http://paulstamatiou.com/2005/11/19/how-to-quickie-embedded-flickr-slideshows</a></p>
<p>I think the only way you can do this is to build it yourself using the Flickr.Net library. You'll need to authenticate with the Flickr API to access your private photos.</p>
<p>I assume from your question that the slideshow containign private photos must be going on a secured private website, otherwise you would just make the photos public?</p>
|
Structuremap 2.0 documentation <p>I'm just starting to learn DI/IOC methods and like what I see so far from Structuremap. The problem is that my current project is limited to .NET 2.0 so I cannot use the new version (2.5) of Structuremap. That being said, can someone point me towards some documentation for v2.0? Most articles and tutorials use v2.5 and only a small few use previous versions. The ones I can find are VERY basic in nature and I'd like to see all the features Structuremap has to offer. Thanks</p>
| <p>Your best bet would be to download the Docs folder from the <code>Release_2.0</code> tag of StructureMap's subversion repository:</p>
<p><a href="http://structuremap.svn.sourceforge.net/viewvc/structuremap/tags/Release%5F2.0/Docs/" rel="nofollow">http://structuremap.svn.sourceforge.net/viewvc/structuremap/tags/Release%5F2.0/Docs/</a></p>
<p>If you do not have subversion installed, there is a link at the bottom to download a GNU tarball, which you should be able to open with 7zip.</p>
|
MSChart and ASP.NET MVC Partial View <p>I'm currently trying to add an MSChart to a partial view in ASP.NET MVC RTM. I have reviewed the following blog <a href="http://code-inside.de/blog-in/2008/11/27/howto-use-the-new-aspnet-chart-controls-with-aspnet-mvc/" rel="nofollow">entry</a>, and I'm currently investigating Option B. If I take my code an place it inside a View (ASPX) Page and it works fine, but when I copy the exact code into a Partial View (ASCX) I get the following excpetion: "CS1502: The best overloaded method match for 'System.IO.TextWriter.Write(char)' has some invalid arguments
". Has anyone else run into this and solved the issue or do they know why it's impossible to use this strategy with MSChart and MVC?</p>
<p>My code is exactly what's in option B on the linked article.</p>
| <p>I'm not exactly sure what the problem is, but the most common cause of that error is that you've used a statement inside a "<%= %>" block rather than an expression. Since the code within a "<%= %>" block is placed within a call to <code>System.IO.TextWriter.Write</code>, it must be an expression. Statements must be enclosed within "<% %>" blocks, rather than "<%= %>".</p>
<p>The code you referenced should be working just fine on a partial view, if it runs on a "regular" view. Make sure that the call to <code>RenderPartial</code> is in a "<% %>" block because <code>RenderPartial</code> does not actually return anything, it does the rendering directly in place.</p>
|
jQuery Execution? <p>My jQuery script has a glitch animating a div position. The bug seems to occur when I click the link right as the page is loading.</p>
| <blockquote>
<p>The bug seems to occur when I click
the link right as the page is loading</p>
</blockquote>
<p>This is because you are using the <code>ready</code> function and that executes as soon as the <strong>page has finished loading.</strong></p>
<p>Thus, if you click on something whilst the page is still loading keep in mind that the JavaScript in that <code>ready</code> function has not been executed yet.</p>
<p><hr /></p>
<p>The reason why you can't always reproduce it most probably because the page will be cached the second time round and you wouldn't have time to click anything before the page has finished loading (since it's cached) and thus the js code would have been executed already when you click.</p>
|
is there statically typed language with nice lambda support for the JVM? <p>I'd quite like to write some Google App Engine apps, but I'm a c# developer by trade, and as such I like static typing and Linq (or at least extensions + lambdas + predicates, if not query syntax). Is there a language I can use on the JVM that offers these features?</p>
| <p>Scala: <a href="http://www.scala-lang.org/" rel="nofollow">http://www.scala-lang.org/</a></p>
<p>Actually, Groovy also has optional static typing, so I'll include it as well, but most static-type, uh, types seem to prefer Scala. Groovy can be found at: <a href="http://groovy.codehaus.org/" rel="nofollow">http://groovy.codehaus.org/</a></p>
|
Javascript document.all and document.getSelection - Firefox alternative <p>The script below will replace selected word in a textarea. But it only works on IE. Any idea how to make it work on Firefox? (The problem seems to lie in (document.all)? document.selection.createRange() : document.getSelection();)</p>
<pre><code><SCRIPT LANGUAGE="JavaScript">
<!--//
var seltext = null;
var repltext = null;
function replaceit()
{
seltext = (document.all)? document.selection.createRange() : document.getSelection();
var selit = (document.all)? document.selection.createRange().text : document.getSelection();
if (selit.length>=1){
if (seltext) {
repltext= prompt('Please enter the word to replace:', ' ');
if ((repltext==' ')||(repltext==null)) repltext=seltext.text;
seltext.text = repltext;
window.focus()
}
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<form name="f">
<textarea cols='40' rows='10' name='msg'></textarea>
<input type="button" name="b" value="Replace" onClick="replaceit();">
</form>
</BODY>
</code></pre>
| <p>The document.all bit is being used as a test to see if it's IE or not. The way it's written document.getSelection() is what would be used in Firefox and document.selection.createRange() in IE</p>
<p>See
<a href="http://www.hscripts.com/tutorials/javascript/ternary.php" rel="nofollow">http://www.hscripts.com/tutorials/javascript/ternary.php</a></p>
<p>So the problem isn't document.all, but rather that the getSelection() isn't working. Not sure why exactly as that's not a construct I've used recently, but try window.getSelection() as per this: (and google for others if this doesn't do the trick)
<a href="http://www.webdeveloper.com/forum/archive/index.php/t-138944.html" rel="nofollow">http://www.webdeveloper.com/forum/archive/index.php/t-138944.html</a></p>
|
I'm looking for an application/text editor that <p>can best help me systematically modify the "replace" field of a regex search as it encounters each match.</p>
<p>For example, I have an xml file that needs the phrase "id = $number" inserted at regular points in the text, and basically, $number++ each time the regex matches (id = 1, id = 2, etc) until the end of the file.</p>
<p>I know I could just write a bash/perl/python script or some such, but I'd like it to be at least moderately user-friendly so I could teach my intelligent (but less technically-inclined) workers how to use it and make their own modifications. Regexing is not a problem for them.</p>
<p>The closest I've come so far is Notepad++'s Column Editor and 'increase [number] by' function, but with this I have to write a separate regex to align everything, add the increments, and then write another to put it back. Unfortunately, I need to use this function on too many different types of files and 'replace's to make macros feasible.</p>
<p>Ideally, the program would also be available for both Windows & Linux (WINE is acceptable but native is much preferred), and have a 'VI/VIM input' option (if it's a text editor), but these are of secondary importance.</p>
<p>Of course, it'd be nice if there is an OSS solution, and I'd be glad to donate $20-$50 to the developer(s) if it provides the solution I'm looking for.<br /><br /><br />
Apologies for the length, and thanks so much for your help!</p>
| <p>emacs (version 22 and later) can do what you're looking for. See <a href="http://steve-yegge.blogspot.com/2006/06/shiny-and-new-emacs-22.html" rel="nofollow">Steve Yegge's blog</a> for a really interesting read about it. I think this should work:</p>
<pre>
M-x replace-regexp
Replace regexp: <i>insert pattern regexp here</i>
Replace regexp with: id = \#
</pre>
<p><code>\#</code> is a special metacharacter that gets replaced by the total number of replacements that have occurred so far, starting from 0. If you want the list to start from 1 instead of 0, use the following replacement string:</p>
<pre>id = \,(1+ \#)</pre>
|
Is there an alternative way to free dynamically allocated memory in C - not using the free() function? <p>I am studying for a test, and I was wondering if any of these are equivalent to free(ptr):</p>
<pre><code> malloc(NULL);
calloc(ptr);
realloc(NULL, ptr);
calloc(ptr, 0);
realloc(ptr, 0);
</code></pre>
<p>From what I understand, none of these will work because the free() function actually tells C that the memory after ptr is available again for it to use. Sorry that this is kind of a noob question, but help would be appreciated. </p>
| <p>Actually, the last of those is equivalent to a call to <code>free()</code>. Read the specification of <code>realloc()</code> very carefully, and you will find it can allocate data anew, or change the size of an allocation (which, especially if the new size is larger than the old, might move the data around), and it can release memory too. In fact, you don't need the other functions; they can all be written in terms of <code>realloc()</code>. Not that anyone in their right mind would do so...but it could be done.</p>
<p>See Steve Maguire's "<a href="http://rads.stackoverflow.com/amzn/click/1556155514" rel="nofollow">Writing Solid Code</a>" for a complete dissection of the perils of the <code>malloc()</code> family of functions. See the <a href="http://accu.org/" rel="nofollow">ACCU</a> web site for a complete dissection of the perils of reading "Writing Solid Code". I'm not convinced it is as bad as the reviews make it out to be - though its complete lack of a treatment of <code>const</code> does date it (back to the early 90s, when C89 was still new and not widely implemented in full).</p>
<hr>
<p>D McKee's notes about MacOS X 10.5 (BSD) are interesting...</p>
<p>The C99 standard says:</p>
<h3>7.20.3.3 The malloc function</h3>
<blockquote>
<p>Synopsis</p>
</blockquote>
<pre><code>#include <stdlib.h>
void *malloc(size_t size);
</code></pre>
<blockquote>
<p>Description</p>
<p>The malloc function allocates space for an object whose size is specified by size and
whose value is indeterminate.</p>
<p>Returns</p>
<p>The malloc function returns either a null pointer or a pointer to the allocated space.</p>
</blockquote>
<h3>7.20.3.4 The realloc function</h3>
<blockquote>
<p>Synopsis</p>
</blockquote>
<pre><code>#include <stdlib.h>
void *realloc(void *ptr, size_t size);
</code></pre>
<blockquote>
<p>Description</p>
<p>The realloc function deallocates the old object pointed to by ptr and returns a
pointer to a new object that has the size specified by size. The contents of the new
object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values.</p>
<p>If ptr is a null pointer, the realloc function behaves like the malloc function for the
specified size. Otherwise, if ptr does not match a pointer earlier returned by the
calloc, malloc, or realloc function, or if the space has been deallocated by a call
to the free or realloc function, the behavior is undefined. If memory for the new
object cannot be allocated, the old object is not deallocated and its value is unchanged.</p>
<p>Returns</p>
<p>The realloc function returns a pointer to the new object (which may have the same
value as a pointer to the old object), or a null pointer if the new object could not be
allocated.</p>
</blockquote>
<hr>
<p>Apart from editorial changes because of extra headers and functions, the ISO/IEC 9899:2011 standard says the same as C99, but in section 7.22.3 instead of 7.20.3.</p>
<hr>
<p>The Solaris 10 (SPARC) man page for realloc says:</p>
<blockquote>
<p>The realloc() function changes the size of the block pointer to by ptr to size bytes and returns a pointer to the (possibly moved) block. The contents will be unchanged up to the lesser of the new and old sizes. If the new size of the block requires movement of the block, the space for the previous instantiation of the block is freed. If the new size is larger, the contents of the newly allocated portion of the block are unspecified. If ptr is NULL, realloc() behaves like malloc() for the specified size. If size is 0 and ptr is not a null pointer, the space pointed to is freed.</p>
</blockquote>
<p>That's a pretty explicit 'it works like free()' statement.</p>
<p>However, that MacOS X 10.5 or BSD says anything different reaffirms the "No-one in their right mind" part of my first paragraph. </p>
<hr>
<p>There is, of course, the <a href="http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf" rel="nofollow">C99 Rationale</a>...It says:</p>
<h3>7.20.3 Memory management functions</h3>
<blockquote>
<p>The treatment of null pointers and zero-length allocation requests in the definition of these
functions was in part guided by a desire to support this paradigm:</p>
</blockquote>
<pre><code>OBJ * p; // pointer to a variable list of OBJs
/* initial allocation */
p = (OBJ *) calloc(0, sizeof(OBJ));
/* ... */
/* reallocations until size settles */
while(1) {
p = (OBJ *) realloc((void *)p, c * sizeof(OBJ));
/* change value of c or break out of loop */
}
</code></pre>
<blockquote>
<p>This coding style, not necessarily endorsed by the Committee, is reported to be in widespread
use.</p>
<p>Some implementations have returned non-null values for allocation requests of zero bytes.
Although this strategy has the theoretical advantage of distinguishing between ânothingâ and âzeroâ (an unallocated pointer vs. a pointer to zero-length space), it has the more compelling
theoretical disadvantage of requiring the concept of a zero-length object. Since such objects
cannot be declared, the only way they could come into existence would be through such
allocation requests.</p>
<p>The C89 Committee decided not to accept the idea of zero-length objects. The allocation
functions may therefore return a null pointer for an allocation request of zero bytes. Note that this treatment does not preclude the paradigm outlined above.</p>
<p>QUIET CHANGE IN C89</p>
<p>A program which relies on size-zero allocation requests returning a non-null pointer
will behave differently.</p>
</blockquote>
<p>[...]</p>
<h3>7.20.3.4 The realloc function</h3>
<blockquote>
<p>A null first argument is permissible. If the first argument is not null, and the second argument is 0, then the call frees the memory pointed to by the first argument, and a null argument may be
returned; C99 is consistent with the policy of not allowing zero-sized objects.</p>
<p><em>A new feature of C99:</em> the realloc function was changed to make it clear that the pointed-to
object is deallocated, a new object is allocated, and the content of the new object is the same as
that of the old object up to the lesser of the two sizes. C89 attempted to specify that the new object was the same object as the old object but might have a different address. This conflicts
with other parts of the Standard that assume that the address of an object is constant during its
lifetime. Also, implementations that support an actual allocation when the size is zero do not
necessarily return a null pointer for this case. C89 appeared to require a null return value, and
the Committee felt that this was too restrictive.</p>
</blockquote>
<hr>
<p><a href="http://stackoverflow.com/users/15727/thomas-padron-mccarthy">Thomas Padron-McCarthy</a> <a href="http://stackoverflow.com/questions/750060/is-there-an-alternative-way-to-free-dynamically-allocated-memory-in-c-not-usin/750075?noredirect=1#comment561534_750075">observed</a>:</p>
<blockquote>
<p>C89 explicitly says: "If size is zero and ptr is not a null pointer, the object it points to is freed." So they seem to have removed that sentence in C99?</p>
</blockquote>
<p>Yes, they have removed that sentence because it is subsumed by the opening sentence:</p>
<blockquote>
<p>The realloc function deallocates the old object pointed to by ptr</p>
</blockquote>
<p>There's no wriggle room there; the old object is deallocated. If the requested size is zero, then you get back whatever <code>malloc(0)</code> might return, which is often (usually) a null pointer but might be a non-null pointer that can also be returned to <code>free()</code> but which cannot legitimately be dereferenced.</p>
|
RA layer request failed while git-svn fetch <p>I use git svn to sync with the subversion repos:</p>
<pre><code>$ mkdir prj && cd prj
$ git svn init http://url/to/repos/branches/experimental
$ git svn fetch
</code></pre>
<p>and got the error message:</p>
<pre><code>RA layer request failed: OPTIONS of 'http://url/to/repos/branches/experimental':
Could not read status line: connection was closed by proxy server
(http://url/to/repos) at /usr/bin/git-svn line 1352
</code></pre>
<p>Why and how can I fix this?</p>
| <p>I had the same issue when accessing a SVN repo <strong>through a proxy</strong>.</p>
<p>The solution for me was to edit <code>~/.subversion/servers</code> and add the needed proxy to the <code>[globals]</code> section. Uncomment the relevant lines (<code>http-proxy-host</code>, <code>http-proxy-port</code>, optionally <code>http-proxy-username</code> and <code>http-proxy-password</code>) and enter the needed information there.</p>
<p>This is needed because <code>git svn</code> uses the settings stored in <code>~/.subversion/servers</code> to access SVN repositories.</p>
|
shadow mapping multitexture <p>There is this tutorial about shadow mapping:
<a href="http://www.paulsprojects.net/tutorials/smt/smt.html" rel="nofollow">http://www.paulsprojects.net/tutorials/smt/smt.html</a></p>
<p>Ok, but I did not realize how to make a scene with multitexture.</p>
<p>If in the third pass of shadow mapping It is need to bind the shadow mapping projected texture to perform depth comparison, HOW can I bind another textures if I need to bind the shadow mapping texture?</p>
<p>Must I set shadow mapping as a separate texture to be bind? Something like this:</p>
<ol>
<li>Active shadow mapping texture</li>
<li>Active texture 1</li>
<li>Active texture 2</li>
</ol>
<p>I tried that but it did not work (maybe I've done something wrong).</p>
| <p>Just to clarify, you have a pre-existing multi-textured scene you want to shadowmap?</p>
<p>If so, activating all your texture units should work (<strong>if</strong> you have enough, I think the OpenGL 1.4/1.5 spec only calls for a minimum of two; check GL_MAX_TEXTURE_UNITS_ARB via glGetIntegerv()). If you don't have enough texture units you'll have to use multi-pass rendering/blending.</p>
|
tabbed html application <p>I am writing a complex tab based web application where each tab is unrelated to each other in the sense that there is no interaction. So for ease of development i want I want each tab to be a separate html page viewable on its own and at later stage I can assemble them via tabs or may be menus or trees
so question or questions are:</p>
<ol>
<li>I am planning to use iframes, does all major browser support them?</li>
<li>Are iframes going to be deprecated, so what are alternatives e.g. is object tag supported by all major browsers?</li>
<li>May be i can use some better strategy instead of iframe/object?</li>
</ol>
<p>but what i love about iframes is that it can be totally modular, so each page doesn't know about other.<img src="http://img4.imageshack.us/img4/4327/mytabs.png" alt="alt text" /></p>
<p>Note: i selected the answer which explain well but still i am not sure why not iframes
question <a href="http://stackoverflow.com/questions/768222/iframes-vs-ajax">http://stackoverflow.com/questions/768222/iframes-vs-ajax</a> may answer that</p>
| <ol>
<li><p>Yes, all major desktop browsers support iframes. So do many mobile browsers, including IEMobile, Opera Mobile, and Safari on the iPhone. The only major browser I know of that <i>doesn't</i> support iframes is the BlackBerry Browser.</p></li>
<li><p>The object tag is supported by most browsers, but the implementation is extremely inconsistent across the various browsers.</p></li>
<li><p>What's wrong with just having a flat page with an ordinary navigation menu? If you are only displaying one page at a time, and the only interface element being placed outside of the iframe is a tab menu, then why not just integrate the tabs into the page layout and do away with the frames?</p>
<p>Frames of any sort tend to break the familiar browser behaviors that people are used--like the forward and back navigation buttons. And they completely disable the use of bookmarks. When building a website, you should try not to restrict or dictate to visitors how they're allowed to browse your site. If the user wants to open a link a new tab, they should not be left without a navigation menu. If they make their browser window a particular size, the page content should fill that area, not a predetermined area specified by the dimensions of the iframe.</p>
<p>Frames are inherently user-unfriendly, which, unsurprisingly, makes them search-engine-unfriendly; which is why so few professional websites use frames/iframes. Cheap broadband is widespread enough these days that reloading a few extra kilobytes of navigational data makes no difference to the overall user experience.</p></li>
</ol>
|
How do I set or clear the first 3 bits using bitwise operations? <p>Lets say I have a number like <code>0x448</code>. In binary this is <code>0100 0100 1000</code>.</p>
<p>How do I set the bits 1, 2 and 3 to either all 0's or all 1's using bit-wise operations? When I say the first three, I'm counting the rightmost bit as the zero bit.</p>
<p>So, for example</p>
<p>Bits as 1's:</p>
<pre><code>b12 b0
0100 0100 1110
^^^
</code></pre>
<p>Bits as 0's:</p>
<pre><code>b12 b0
0100 0100 0000
^^^
</code></pre>
<p>I'm guessing that to set them to 1's I use bit-wise OR with a mask of 14 (0x000e)? But if that is the case, how do I do something similar for clearing the bits?</p>
<p><hr /></p>
<p>Related:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c/">How do you set, clear and toggle a single bit in C?</a> (syntax varies, but the operations are the same)</li>
</ul>
| <p>You have the bit setting correct: <code>OR</code> with the mask of the bits you want to set.</p>
<p>Bit clearing bits is very similar: <code>AND</code> with the ones-complement of the bits you want cleared. </p>
<p>Example: Word of <code>0x0448</code>.</p>
<p>Settings bits 1, 2 and 3 would be <code>Word OR 0x000e</code>:</p>
<pre><code> 0000 0100 0100 1000 = 0x0448
OR 0000 0000 0000 1110 = 0x000e
---- ---- ---- ----
= 0000 0100 0100 1110 = 0x044e
</code></pre>
<p>Clearing bits 1, 2 and 3 would be <code>Word AND 0xfff1</code>:</p>
<pre><code> 0000 0100 0100 1000 = 0x0448
AND 1111 1111 1111 0001 = 0xfff1
---- ---- ---- ----
= 0000 0100 0100 0000 = 0x0440
</code></pre>
<p>Elaborating on the ones-complement, the AND pattern for clearing is the logical NOT of the OR pattern for setting (each bit reveresed):</p>
<pre><code> OR 0000 0000 0000 1110 = 0x000e
AND 1111 1111 1111 0001 = 0xfff1
</code></pre>
<p>so you can use your favorite language NOT operation instead of having to figure out both values.</p>
|
How can I print a single JPanel's contents? <p>I have a <code>JPanel</code> with two labels with pictures. I need to print these content of the <code>JPanel</code>. Please help me out. How can I print only this <code>JPanel</code>'s contents, as I also have different components on my <code>JFrame</code> but I just need to print <strong>this</strong> <code>JPanel</code>.</p>
<p>Thanks.</p>
| <p>Here is the sample to print any Swing component.</p>
<pre><code>public void printComponenet(){
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
pj.setPrintable (new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum){
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
componenet_name.paint(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false)
return;
try {
pj.print();
} catch (PrinterException ex) {
// handle exception
}
}
</code></pre>
<p>Hope this can help others.</p>
|
Does the order of headers in an HTTP response ever matter? <p>Is it ever meaningful whether the order of headers is</p>
<pre><code>A: 1
B: 2
</code></pre>
<p>vs</p>
<pre><code>B:2
A:1
</code></pre>
<p>I'm trying to figure out if I can use a dictionary to store a list of headers or if it needs to be some kind of list or ordered dictionary.</p>
| <p>No, it does not matter for headers with different names. See <a href="http://tools.ietf.org/html/rfc2616">RFC 2616</a>, section 4.2:</p>
<blockquote>
<p>The order in which header fields with differing field names are
received is not significant. However, it is "good practice" to send
general-header fields first, followed by request-header or response-
header fields, and ending with the entity-header fields.</p>
</blockquote>
<p>It DOES matter, however, for multiple headers with the same name:</p>
<blockquote>
<p>Multiple message-header fields with the same field-name MAY be
present in a message if and only if the entire field-value for that
header field is defined as a comma-separated list [i.e., #(values)].
It MUST be possible to combine the multiple header fields into one
"field-name: field-value" pair, without changing the semantics of the
message, by appending each subsequent field-value to the first, each
separated by a comma. The order in which header fields with the same
field-name are received is therefore significant to the
interpretation of the combined field value, and thus a proxy MUST NOT
change the order of these field values when a message is forwarded.</p>
</blockquote>
|
Java XML APIs <p>I've dealt with a few XML APIs in Java, but I don't have a good understanding of all the frameworks available in Java for dealing with XML for whatever purpose (e.g. JAXB, JAXP, Xerces, StAX, Castor, etc.). Can anyone highlight the most popular Java XML APIs and give a quick description of what they're intended to be used for? I'd also be interested in which APIs are used nowadays, and which might be considered deprecated.</p>
| <ul>
<li><p><a href="http://en.wikipedia.org/wiki/Java%5FAPI%5Ffor%5FXML%5FProcessing">JAXP</a> is a "pluggable API", a set of interfaces and abstract classes with a "reference implementation" by Sun, but it uses the factory approach to allow you to swap out to a different implementation (e.g. one that might be faster in certain types of uses) without having to change any of your code, just by <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/SAXParserFactory.html#newInstance%28%29">changing a system property</a>. It includes DOM, SAX, StAX, and XSLT. Sun has a good <a href="http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP2.html">comparison page</a> for DOM/SAX/StAX. I'd recommend the <a href="http://rads.stackoverflow.com/amzn/click/059610149X">O'Reilly book on Java XML</a>, you can find it used at a decent price but just make sure you have the latest (3rd) edition.</p></li>
<li><p><a href="http://en.wikipedia.org/wiki/JAXB">JAXB</a> is a way of binding Java classes to XML files, using an XML schema. (You can autogenerate the java classes using a schema, or you can autogenerate the schema using java classes. I've used the former but not the latter.) It can be useful if your XML files have a well-known schema, and you want to treat the data in an XML file as if it were objects in a Java class. You do very little API calls at all, just one or two to marshal the data from Java to XML, or unmarshal the data from XML to Java. If your XML files are more freeform and/or you want to use XPATH to find things, you're probably better off using one of the JAXP API's.</p></li>
<li><p>Castor is an alternative to JAXB; I haven't used it but there's a <a href="http://www.ibm.com/developerworks/xml/library/x-databdopt2/">comparison page on IBM's website</a>.</p></li>
<li><p><a href="http://xerces.apache.org/">Xerces</a> is Apache's family of XML-handling packages. It includes one for Java, most of which can be used through JAXP as an alternate implementation for Sun's reference implementation. It also includes libraries for C++ and Perl.</p></li>
</ul>
|
Convert string value into html format in php <p>Any one know how to convert string value into html format in php?
For Example:</p>
<pre><code>$string = "Hello World!!
How are you?"
</code></pre>
<p>If I echo $string, it will display like this:</p>
<pre><code>Hello World!!How are you?
</code></pre>
<p>Instead of:</p>
<pre><code>Hello World!!
How are you?
</code></pre>
<p>Any way php can conver the $string into html format? If I input:</p>
<pre><code>$string = "Hello World!!
How are you?"
</code></pre>
<p>Php will convert it to become:</p>
<pre><code>$string = "Hello World!!<br>How are you?"
</code></pre>
| <p>Youâre looking for the <a href="http://docs.php.net/nl2br" rel="nofollow"><code>nl2br</code> function</a> that adds an HTML line break tag <code><br /></code> to every physical line break sequence (<code>\n</code>, <code>\r</code> or <code>\r\n</code>):</p>
<pre><code>\n â <br />\n
\r â <br />\r
\r\n â <br />\r\n
</code></pre>
|
WatiN Compatibility with Windows <p>I am running tests successfully on Windows XP but not even got a single successful build while running through Windows 2003.</p>
<p>Any one knows whether it is compatible or not as I read on some site that WatiN is fully tested on XP and not on other Windows editions.</p>
| <p>I'd ordinarily post this as a comment on Sam's answer, but I'm trying to make a stack trace searchable, so here goes...</p>
<pre><code>WatiN.Core.Exceptions.IENotFoundException : Could not find an IE window matching constraint: Timeout while waiting to attach to newly created instance of IE.. Search expired after '30' seconds.
at WatiN.Core.IE.CreateIEPartiallyInitializedInNewProcess()
at WatiN.Core.IE.CreateNewIEAndGoToUri(Uri uri, IDialogHandler logonDialogHandler, Boolean createInNewProcess)
at WatiN.Core.IE..ctor(String url, Boolean createInNewProcess)
c:\...\WithVendorSite.cs(42,0): at WithVendorSite.VerifyCanLogIn(TargetSite target)
</code></pre>
<p>I developed my test on Windows 7 against WatiN 2.0.10.928 but the test was continually getting stuck with a blank browser with <code>about:blank</code> in the address bar when run on Windows Server 2008 with latest WUs, and Enhanced Security Configuration turned off and running the tests elevated (Run as Administrator).</p>
<p>The problem in my case (thanks Sam) was the absence of <code>Microsoft.mshtml.dll</code> in the bin directory (I had figured out <code>Interop.shdocvw.dll</code> was necessary from error messages I'd encountered on the Windows 7 side).</p>
<p>After adding <code>Microsoft.mshtml.dll</code>, things run happily with ESC turned back [but the test process needs to run elevated].</p>
|
how to write java program get pid <p>how to write java program get pid?</p>
| <p><a href="http://blog.igorminar.com/2007/03/how-java-application-can-discover-its.html" rel="nofollow">How a Java Application Can Discover its Process ID (PID)</a></p>
<p>Not very straightforward, but apparently there is no "official" way.</p>
|
Bypass all cacheing on jQuery.autocomplete(1.02) <p>I am using <strong>jQuery.autocomplete(1.02)</strong> on my search box and I want <strong>exact</strong> string and substring matching. I don't care (yet!) about the database load, I'm happy for it to fire off a query every keystroke and bypass the caching entirely - I just don't want anything missed.</p>
<p>To this end I have tried setting <em>cacheLength=1</em>, the minimum permitted, but the autocomplete function refuses to fire off a GET request for each key up.</p>
<pre><code>searchbox GET_request
'a' -> http://localhost/service_search_request?q=a
'ar' -> http://localhost/service_search_request?q=ar
'ars' -> http://localhost/service_search_request?q=ars
</code></pre>
<p>Instead, it sends the first and the third and misses the second, giving me the wrong results for 'ar' :-/ I've cleared my cache and sessions but it looks like some sort of caching is still going on. AFAIK I have no proxying going on and I'm shift-refreshing each time. It looks likely then that this behavior is from jQuery.autocomplete itself.</p>
<p><strong>So my questions are...</strong></p>
<p><strong>A)</strong> Does this seem likely? i.e. is it a feature, or maybe a bug?</p>
<p><strong>B)</strong> If so is there a clean way around it?...</p>
<p><strong>C)</strong> If not, what autocomplete would you use instead?</p>
<p>Naturally <em>D) No you're just using it incorrectly you douche!</em> is always a possibility, and indeed the one I'd prefer having spent time going down this road - assuming it comes with a link to the docs I've failed to find / read!</p>
<p>Cheers,</p>
<p>Roger :)</p>
| <p>I wonder why <strong>cacheLength</strong> doesn't work, but had trouble with autocomplete too. IMHO, there are errors in it. However, in the <a href="http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url%5For%5Fdataoptions" rel="nofollow">list of options</a>, there is a <strong>matchSubset</strong> you could set to false.</p>
<p><strong>EDIT:</strong>
somewhere around line 335 is a function called "request". You could add some debug messages to it, to see what happens: (note: you need <a href="http://getfirebug.com/" rel="nofollow">firebug</a> installed or "console" will be unknown)</p>
<pre><code>function request(term, success, failure) {
console.debug("ac request...");
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
console.debug("ac request 1, loaded data from cache: " + data + " term: " + term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){
console.debug("ac request 2, data is not in the cache, request it");
</code></pre>
<p>"flushCache" can easily be used in the function you can attach / set as options. I used this, to clear the Cache, if there could be more data in the backend:</p>
<pre><code>formatItem: function (data,i,n,value){
if(i === (this.max -1)){
console.debug("flushCache");
jQuery(this).flushCache();
}
return data[1] + " (" + data[0] + ")";
}
</code></pre>
|
Eclipse class designer and design<--> java source bindings <p>I'm tutoring a subject on rapid prototyping at university for 2nd/3rd year students.</p>
<p>Can anyone recommend a (free) way to design class hierarchies in a GUI design surface within Eclipse? </p>
<p>The UML design surfaces in Eclipse Modelling Tools are almost perfect, but I can't find any documentation about how to bind these to java source files.</p>
<p><em>Leaving aside your personal ideology about how software should be designed, it's very important we have a visual tool.</em> </p>
<p>I've been spoiled in visual studio with bi-directional designer to source mapping. I was hoping to provide a similar tool for my students, but I need some advice in making this happen.</p>
<p>Any help is greatly appreciated.</p>
<p><strong>UPDATE:</strong> I'm actually not tutoring on OOD next semester, but on rapid prototyping and software architecture. The aim of this subject is to teach some rapid design techniques leveraging design patterns, using servelets to deliver web pages, etc. Students <em>learning</em> OOD currently use BlueJ. This subject aims to step it up and push them in the deep end with a real IDE.</p>
<p><strong>UPDATE</strong> I'm playing with NetBeans w/ UML addon and it's very very good. The only problem with it is that it requires manual "generate code" and "reverse engineer code" button clicks. Way way better than Eclipse. Netbeans is winning the war so far.</p>
| <p><a href="http://www.bluej.org/about/what.html" rel="nofollow">BlueJ</a> is a GUI Java IDE that allows students to go from UML diagrams to code. It's free and recently open source.</p>
<p>It also supports extensions similar to popular Eclipse extensions: PMD, checkstyle, etc.</p>
<p>It's specifically designed for teaching:</p>
<blockquote>
<p>The BlueJ environment was developed as part of a university research project about teaching object-orientation to beginners.</p>
<p>The aim of BlueJ is to provide an easy-to-use teaching environment for the Java language that facilitates the teaching of Java to first year students. Special emphasis has been placed on visualisation and interaction techniques to create a highly interactive environment that encourages experimentation and exploration.</p>
</blockquote>
<p>It includes several <a href="http://www.bluej.org/doc/documentation.html" rel="nofollow">tutorials</a>.</p>
|
Most common docblock for Delphi and/or FreePascal code <p>I'm quite familiar with PHP dockblocks since it's been my job for the last 15+ years.</p>
<pre><code>/**
* Description
*
* @tag bla bla
* @tag more bla bla
*/
</code></pre>
<p>What I'm trying to understand is if there is a standard like that for Delphi and/or FreePascal.</p>
<p>From my analysis on an awful lot of code I never seen any, but I could be dead wrong.</p>
| <h1>Delphi documentation tools</h1>
<p>Using the XMLDoc tool for API documentation and HelpInsight with Delphi 2005
<a href="http://edn.embarcadero.com/article/32770" rel="nofollow">http://edn.embarcadero.com/article/32770</a></p>
<p>XML Documentation in Delphi 2006
<a href="http://tondrej.blogspot.com/2006/03/xml-documentation-in-delphi-2006.html" rel="nofollow">http://tondrej.blogspot.com/2006/03/xml-documentation-in-delphi-2006.html</a></p>
<p>DelphiCodeToDoc
<a href="http://dephicodetodoc.sourceforge.net/" rel="nofollow">http://dephicodetodoc.sourceforge.net/</a></p>
<p>Doc-O-Matic
<a href="http://www.doc-o-matic.com/examplesourcecode.html" rel="nofollow">http://www.doc-o-matic.com/examplesourcecode.html</a></p>
<p>PasDoc
<a href="http://pasdoc.sipsolutions.net/" rel="nofollow">http://pasdoc.sipsolutions.net/</a></p>
<p>Pascal Browser
<a href="http://www.peganza.com/" rel="nofollow">http://www.peganza.com/</a></p>
<p>Doxygen
<a href="http://www.stack.nl/~dimitri/doxygen/" rel="nofollow">http://www.stack.nl/~dimitri/doxygen/</a></p>
<p>Pas2Dox
<a href="http://sourceforge.net/projects/pas2dox/" rel="nofollow">http://sourceforge.net/projects/pas2dox/</a></p>
<p>JADD - Just Another DelphiDoc
<a href="http://delphidoc.sourceforge.net/" rel="nofollow">http://delphidoc.sourceforge.net/</a></p>
<h2>Stackoverflow discussion</h2>
<p>Is there a Delphi code documentor that supports current Delphi syntax?
<a href="http://stackoverflow.com/questions/673248/is-there-a-delphi-code-documentor-that-supports-current-delphi-syntax">http://stackoverflow.com/questions/673248/is-there-a-delphi-code-documentor-that-supports-current-delphi-syntax</a></p>
<p>Code documentation for delphi similar to javadoc or c# xml doc
<a href="http://stackoverflow.com/questions/236047/code-documentation-for-delphi-similar-to-javadoc-or-c-xml-doc">http://stackoverflow.com/questions/236047/code-documentation-for-delphi-similar-to-javadoc-or-c-xml-doc</a></p>
<p>Documenting Delphi
<a href="http://stackoverflow.com/questions/33336/documenting-delphi">http://stackoverflow.com/questions/33336/documenting-delphi</a></p>
|
How can I change annotations/Hibernate validation rules at runtime? <p>If have a Java class with some fields I want to validate using Hibernate Validator.
Now I want my users to be able to configure at runtime which validations take place.</p>
<p>For example:</p>
<pre><code>public class MyPojo {
...
@NotEmpty
String void getMyField() {
...
}
...
}
</code></pre>
<p>Let's say I want to remove the <code>NotEmpty</code> check or replace it with <code>Email</code> or <code>CreditCardNumber</code>, how can I do it? Is it even possible? I guess it comes down to changing annotations at runtime...</p>
| <p>You can't do it normally.</p>
<p>Here's what I've done to get more dynamic validations working via Hibernate Validator.</p>
<ol>
<li>Extend the <code>ClassValidator</code> class.</li>
<li>Override the <code>getInvalidVaues(Object myObj)</code> method. First, call <code>super.getInvalidValues(myObj)</code>, then add the hook to your customized validation.</li>
<li>Instantiate your custom validator and call <code>getInvalidValues</code> to validate. Any hibernate annotated validations will kick off at this point, and your custom dynamic validations (anything not supported by annotations) will kick off as well.</li>
</ol>
<p>Example:</p>
<pre><code>public class MyObjectValidator extends ClassValidator<MyObject>
{
public MyObjectValidator()
{
super(MyObject.class);
}
public InvalidValue[] getInvalidValues(MyObject myObj)
{
List<InvalidValue> invalids = new ArrayList<InvalidValue>();
invalids.addAll(Arrays.asList(super.getInvalidValues(myObj)));
// add custom validations here
invalids.addAll(validateDynamicStuff(myObj));
InvalidValue[] results = new InvalidValue[invalids.size()];
return invalids.toArray(results);
}
private List<InvalidValue> validateDynamicStuff(MyObject myObj)
{
// ... whatever validations you want ...
}
}
</code></pre>
<p>So your custom validation code can contain logic like "Do this validation, if the user configured it, otherwise do that one", etc. You may or may not be able to leverage the same code that powers the hibernate validations, but either way, what you are doing is more involved that the 'normal' use case for hibernate validator.</p>
|
How much code in a rails view is ok? <p>I know that it is best to keep code out of the presentation layer. But, I am wondering how much is considered "acceptable". For example I populate an html select box with this line of code. </p>
<pre><code>CodesecureProject.find(:all,:order => 'name').collect {|project| [project.name, project.id] }
</code></pre>
<p>Right now I have this line of code embedded in the form. What I am wondering if the community thinks if this is to much code and it should be first stored in an instance variable on the controller then the variable used in the form.</p>
| <p>I'm not going to say I'd never do it (I'd be lying) but the code example given would make me nervous. I think I'd be more inclined to deliver the data to the select box from my controller. A helper method is another option if I notice I'm doing something more than once. I'm more likely to see the duplication in the controller than across distinct views.</p>
<p>If I'm using the same HTML component across multiple views, then I might find myself reaching for partials or wrapping the whole thing in a custom helper: project_select() or some such.</p>
<p>The more I work in the MVC world the more I find myself avoiding code in views. I have a feeling that some kind of Zen mastery will be achieved if I reach the zero code state, although the value of that in anything but philosophical terms is highly debatable.</p>
|
How to install program shortcuts for all users? <p>I'm creating an installer msi file using the Windows Installer XML toolkit. When installing the created msi file, a shortcut placed under the ProgramMenuFolder folder results in a shortcut for the Administrator user only. How do I let the installer create a shortcut under the All Users profile, so that everyone on the machine has the shortcut?</p>
| <p>In the <a href="http://wix.sourceforge.net/manual-wix3/wix%5Fxsd%5Fpackage.htm">Package element</a>, add an InstallScope attribute like this:</p>
<pre><code>InstallScope='perMachine'
</code></pre>
|
NHibernate requires events to be virtual? <p>I'm attempting to map an entity hierarchy using NHibernate almost all of which have events. When attempting to build a session factory however, I get error messages similar to the following:</p>
<blockquote>
<p>Core.Domain.Entities.Delivery: method
remove_Scheduled should be virtual</p>
</blockquote>
<p><strong>Delivery</strong> is an entity in my domain model with an event called <strong>Scheduled</strong>. Since events cannot be declared virtual I'm at a loss as to how to proceed here. Why would NHibernate need events to be virtual?</p>
| <p>Public members must be declared virtual if you use lazy loading because NHibernate will create proxy objects for your entities at runtime. So do not use lazy loading or just declare the event as virtual - that is not so common, but it is possible.</p>
<p>NHibernate creates proxy classes for all lazy loaded entities and uses them where an entity is referenced but not yet loaded. Accessing this proxy triggers loading the real entity from the database. This approach requires to inherit from your entity class at runtime and override the public members hence this members to be virtual.</p>
<p>And there is another solution. You can add <code>proxy="ISomeInterface"</code> to the class declaration. Then you do not need virtual members while proxys just implement the given interface.</p>
|
Checking if a particular device driver is loaded <p>I'm trying to work out if I can check if a particular video card device driver is loaded in Windows Server 2003 using C++. Can anyone give me pointers on how I might achieve this?</p>
<p>Thanks</p>
| <p>Use <strong>EnumDeviceDrivers</strong> - there's an example <a href="http://msdn.microsoft.com/en-us/library/ms682619%28VS.85%29.aspx" rel="nofollow">here</a>.</p>
|
Are source-code comments good practice or problematic? <p>I talk about source-code-comments, that explains what happens on the next lines of code, not Javadoc/Doxygen-comments (that comment on the interface).</p>
<p>Comments can make your intention for the code clearer, but on the other hand they could be redundant or even worse outdated (code was changed without changing comment).</p>
| <p>Add comments where you need them to explain to another <strong>why</strong> you did something, the code itself should show clearly enough <strong>what</strong> you did. When Adding comments detailing what the code is doing is when you run the risk of redundant or outdated comments confusing readers of your code.</p>
|
MySQL and SQLite differences in SQL <p>I'm writing java application that is using both <strong>SQLite</strong> and <strong>MySQL</strong> using <strong>JDBC.</strong></p>
<p>Are there any differences in <strong>SQL</strong> for those databases? Can I use same queries for both <strong>SQLite</strong> and <strong>MySQL</strong>, or is there any db specific stuff, that doesn't work on the other one?</p>
<p>As far I've worked only with <strong>MySQL</strong>, so I don't really know much about <strong>SQLite</strong>.</p>
| <p>If you stick to <a href="http://en.wikipedia.org/wiki/SQL-92">ANSI SQL92</a>, you'll should be fine. </p>
<p>There are some SQL92 features missing from both MySQL and SQLite (e.g. FULL OUTER JOIN).
MySQL has both RIGHT JOIN, and LEFT JOIN, SQLite only the LEFT JOIN. SQLite doesn't support FOREIGN KEY constraints, neither does MySQL with MyISAM tables.
SQLite of course doesn't have GRANT/REVOKE, as permission system is based on underlying OS's file permissions.</p>
|
Best way to get the next id number without "identity" <p>I have to insert some records in a table in a legacy database and, since it's used by other ancient systems, changing the table is not a solution.</p>
<p>The problem is that the target table has a int primary key but no identity specification. So I have to find the next available ID and use that:</p>
<pre><code>select @id=ISNULL(max(recid)+1,1) from subscriber
</code></pre>
<p>However, I want to prevent other applications from inserting into the table when I'm doing this so that we don't have any problems. I tried this:</p>
<pre><code>begin transaction
declare @id as int
select @id=ISNULL(max(recid)+1,1) from subscriber WITH (HOLDLOCK, TABLOCK)
select @id
WAITFOR DELAY '00:00:01'
insert into subscriber (recid) values (@id)
commit transaction
select * from subscriber
</code></pre>
<p>in two different windows in SQL Management Studio and the one transaction is always killed as a deadlock victim. </p>
<p>I also tried <code>SET TRANSACTION ISOLATION LEVEL SERIALIZABLE</code> first with the same result...</p>
<p>Any good suggestions to how I can ensure that I get the next id and use that without risking that someone else (or me!) is getting hosed?</p>
<p>Sorry for not mentioning this earlier, but this is a SQL 2000 server so I can't use things like FOR UPDATE and OUTPUT </p>
<h2><strong>UPDATE</strong>: This is the solution that worked for me:</h2>
<pre><code>BEGIN TRANSACTION
DECLARE @id int
SELECT @id=recid
FROM identities WITH (UPDLOCK, ROWLOCK)
WHERE table_name = 'subscriber'
waitfor delay '00:00:06'
INSERT INTO subscriber (recid) values (@id)
UPDATE identities SET recid=recid+1
WHERE table_name = 'subscriber'
COMMIT transaction
select * from subscriber
</code></pre>
<p>The WAITFOR is so that I can have multiple connections and start the query several times to provoke concurrency. </p>
<p>Thanks to Quassnoi for the answer and to all you other guys that contributed! Awesome!</p>
| <p>Create another table:</p>
<pre><code>t_identity (id INT NOT NULL PRIMARY KEY CHECK (id = 1), value INT NOT NULL)
</code></pre>
<p>with a single row, lock this row, and increment <code>value</code> by one each time you need an <code>IDENTITY</code>.</p>
<p>To lock, increment, and return the new value in a single statement, use:</p>
<pre><code>UPDATE t_identity
SET value = value + 1
OUTPUT INSERTED.value
</code></pre>
<p>If you don't want to update, just lock, then issue:</p>
<pre><code>SELECT value
FROM t_identity WITH (UPDLOCK, ROWLOCK)
</code></pre>
<p>This will lock the table until the end of the transaction.</p>
<p>If you always first lock <code>t_identity</code> before messing with <code>ancient_table</code>, you will never get a deadlock.</p>
|
Howto access data held in widget options when inside a widget event handler <p>I have data held in the options variable, but in an event (OnChange) of a select list
this refers to the DOMElement and therefore this.options refers to the list of objects.</p>
<p>everywhere else I can have </p>
<pre><code>var o = this.options;
</code></pre>
<p>but this is no use in this context.</p>
<p>How to get/set the widget information ?</p>
| <p>Use the <a href="http://api.jqueryui.com/jQuery.widget/#method-_on" rel="nofollow"><code>this._on()</code> method</a> to bind the handler. This method is provided by the jQuery UI widget factory and will make sure that within the handler function, <code>this</code> always refers to the widget instance.</p>
<pre class="lang-js prettyprint-override"><code>_create: function () {
...
this._on(this.selectElement, {
change: "_onChange" // Note: function name must be passed as a string!
});
},
_onChange: function (event) {
// 'this' is now the widget instance.
},
</code></pre>
|
How can i get List items to stay together using CSS? <p>The skeleton of the HTML is this</p>
<pre><code><div class="TwoCol">
<img src="imgurl"/>
<h1>A headline</h1>
<p>Some exciting text</p>
<ul>
<li>Item A</li>
<li>Item B</li>
<li>Item C</li>
</ul>
<p>More riveting text </p>
</div>
</code></pre>
<p>The CSS is </p>
<pre><code>.TwoCol img{
float:left;
padding-right:5px;
border:none;
}
.TwoCol ul{
list-style-type:none;
}
</code></pre>
<p>The effect I am after is an image top left within my div with text to the right, if the text is longer than the image it wraps around under the image.</p>
<p>HOWEVER if the list starts to the right of the image, I want all the items to be aligned vertically below each other, not for list items below the image to appear under the image and break the list into two sections.</p>
<p>I need an image sketching utility :)</p>
<p>This </p>
<pre><code>IMG Headline
IMG Para1
IMG Item A
Item B
Item C
Para2
</code></pre>
<p>not This</p>
<pre><code>IMG Headline
IMG Para1
IMG Item A
Item B
Item C
Para2
</code></pre>
<p>Thanks!</p>
| <p>You could set the <code><ul></code> to </p>
<pre><code>display: inline-block;
</code></pre>
<p>You might also want to <code>clear: left;</code> your images, since it's possible that they could start stacking up next to each other depending on the other content.</p>
|
Suggestions For String and DateTime utility functions' Library using Extension Methods <p>I'm writing a library of Extension Methods for String and DateTime utility functions in C#. Can you please help me out by suggesting the useful utlity functions for String and DateTime you may want to be part of it ? With your suggestions I can make it more cohesive and Collective.</p>
<p>Thanks!</p>
| <pre><code>public static bool IsNullOrEmpty(this string value){
return string.IsNullOrEmpty(value);
}
public static string Reverse(this string value) {
if (!string.IsNullOrEmpty(value)) {
char[] chars = value.ToCharArray();
Array.Reverse(chars);
value = new string(chars);
}
return value;
}
public static string ToTitleCase(this string value) {
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
}
public static string ToTitleCaseInvariant(this string value) {
return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(value);
}
</code></pre>
<p>Trivial, but slighty nicer to call.</p>
|
How to XML configure Spring bean for constructor injection when bean has varargs constructor <p>Is there a way to write a Spring bean in XML so that it uses constructor injection when that constructor has a varargs parameter type? IE, is there a way to specify an array the way you can specify a list? </p>
<p>For instance:</p>
<pre><code>class MyClass {
MyClass(String... args) {
// rest omitted
}
}
</code></pre>
| <p>since <code>args</code> is an array of <code>String</code> you can use <code><list></code>:</p>
<pre><code> <bean name="myBean" class="MyClass">
<constructor-arg>
<list>
<value>111</value>
<value>222</value>
<value>333</value>
<value>444</value>
</list>
</constructor-arg>
</bean>
</code></pre>
|
PostgreSQL concatenation <p>I got this function to concat fields in my pgSQL-server:</p>
<pre>
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSE
RETURN acc || ';' || instr;
END IF;
END;
</pre>
<p>It works great, but now I want this function to distinct equal entries. How can I do this?</p>
| <pre><code>CREATE TYPE tp_concat AS (data TEXT[], delimiter TEXT);
CREATE OR REPLACE FUNCTION group_concat_iterate(_state tp_concat, _value TEXT, delimiter TEXT, is_distinct boolean)
RETURNS tp_concat AS
$BODY$
SELECT
CASE
WHEN $1 IS NULL THEN ARRAY[$2]
WHEN $4 AND $1.data @> ARRAY[$2] THEN $1.data
ELSE $1.data || $2
END,
$3
$BODY$
LANGUAGE 'sql' VOLATILE;
CREATE OR REPLACE FUNCTION group_concat_finish(_state tp_concat)
RETURNS text AS
$BODY$
SELECT array_to_string($1.data, $1.delimiter)
$BODY$
LANGUAGE 'sql' VOLATILE;
CREATE AGGREGATE group_concat(text, text, boolean) (SFUNC = group_concat_iterate, STYPE = tp_concat, FINALFUNC = group_concat_finish);
</code></pre>
<p>Use it like this:</p>
<pre><code>SELECT GROUP_CONCAT(textfield, ';', TRUE)
FROM mytable
</code></pre>
<p>if you don't want duplicates, and</p>
<pre><code>SELECT GROUP_CONCAT(textfield, ';', FALSE)
FROM mytable
</code></pre>
<p>if you do.</p>
|
SQL CLR Stored Procedure and Web Service <p>I am current working on a task in which I am needing to call a method in a web service from a CLR stored procedure.</p>
<p>A bit of background:</p>
<p>Basically, I have a task that requires ALOT of crunching. If done strictly in SQL, it takes somewhere around 30-45 mins to process. If I pull the same process into code, I can get it complete in seconds due to being able to optimize the processing so much more efficiently. The only problem is that I have to have this process set as an automated task in SQL Server.</p>
<p>In that vein, I have exposed the process as a web service (I use it for other things as well) and want the SQL CLR sproc to consume the service and execute the code. This allows me to have my automated task.</p>
<p>The problem:</p>
<p>I have read quite a few different topics regarding how to consume a web service in a CLR Sproc and have done so effectivly. Here is an example of what I have followed.</p>
<p><a href="http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/" rel="nofollow">http://blog.hoegaerden.be/2008/11/11/calling-a-web-service-from-sql-server-2005/</a></p>
<p>I can get this example working without any issues. However, whenever I pair this process w/ a Web Service method that involves a database call, I get the following exceptions (depending upon whether or not I wrap in a try / catch):</p>
<p>Msg 10312, Level 16, State 49, Procedure usp_CLRRunDirectSimulationAndWriteResults, Line 0
.NET Framework execution was aborted. The UDP/UDF/UDT did not revert thread token.</p>
<p>or</p>
<blockquote>
<p>Msg 6522, Level 16, State 1, Procedure MyStoredProc , Line 0</p>
<p>A .NET Framework error occurred during execution of user defined
routine or aggregate 'MyStoredProc': </p>
<p>System.Security.SecurityException: Request for the permission of type
'System.Security.Permissions.EnvironmentPermission, mscorlib,
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
failed.</p>
<p>System.Security.SecurityException: </p>
<p>at System.Security.CodeAccessSecurityEngine.Check(Object demand,
StackCrawlMark& stackMark, Boolean isPermSet)</p>
<p>at System.Security.CodeAccessPermission.Demand()</p>
<p>at System.Net.CredentialCache.get_DefaultCredentials()</p>
<p>at
System.Web.Services.Protocols.WebClientProtocol.set_UseDefaultCredentials(Boolean
value)</p>
<p>at
MyStoredProc.localhost.MPWebService.set_UseDefaultCredentials(Boolean
Value)</p>
<p>at MyStoredProclocalhost.MPWebService..ctor()</p>
<p>at MyStoredProc.StoredProcedures.MyStoredProc(String FromPostCode,
String ToPostCode)</p>
</blockquote>
<p>I am sure this is a permission issue, but I can't, for the life of me get it working. I have attempted using impersonation in the CLR sproc and a few other things. Any suggestions? What am I missing?</p>
| <p>I am just figuring this out, but this is what I got:</p>
<p>You need to set the permission_set when you create the assembly in SQL to UNSAFE.</p>
<pre><code>CREATE ASSEMBLY [<assemblyname>] FROM '<path>/<assemblyname>.dll'
WITH PERMISSION_SET = UNSAFE
GO
</code></pre>
<p>If you are using a VS SQL Database Project to do your deployment, this can also be done by setting the Permission to UNSAFE on the Database Tab of Properties for the Database Project.</p>
|
Accessing sqlite3 database <p>I have created database and table through sqlite3 using terminal on macbook, then deploy it with my iPhone application. Its working fine in simulator inserting & retrieving the values from table.</p>
<p>But when i install it on real iPhone it is not working, why? I think it can not get the path of database, then how can i do that?</p>
| <p>Are you leaving the database in the base app path?<br />
Because if you are, the actual hardware won't allow you to write to files in that directory, just read. To write to the database, you will first have to copy it to an accessible directory.</p>
<p>I'm doing something similar to this (where filename is an NSString containing the name of the database file):</p>
<pre><code>NSArray *docPaths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docPath = [docPaths objectAtIndex:0];
NSString *fullName = [docPath stringByAppendingPathComponent:fileName];
NSFileManager *fm = [NSFileManager defaultManager];
if (![fm fileExistsAtPath:fullName])
{
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *defaultName = [path stringByAppendingPathComponent:fileName];
[fm copyItemAtPath:defaultName toPath:fullName error:NULL];
}
</code></pre>
<p>Basically, check if the file already exists and copy it from the base bundlePath if it doesn't.</p>
|
Which validation framework to choose: Spring Validation or Validation Application Block (Enterprise LIbrary 4.0)? <p>I am trying to choose one of the validation frameworks for a major application, and while both options seem enticing, I was wondering whether there are any specific pros and cons I should be aware of before committing to one or the other.</p>
| <p>Validation with attributes is not best solution in my view. Firstly you have to reference infrastructure in domain model. Secondly you don't have any chance to add validation to compiled classes. Lastly you can't validate complex logic with attributes and you have to make Validate method to entity and that just seems awkward.</p>
<p>In my opinion validation should be separated to different object. For example IValidator where you could define validation as rules. Using framework like <a href="http://xval.codeplex.com/" rel="nofollow">xVal</a> helps to do validation in presentation layer with JavaScript.</p>
<p>You may want to look for <a href="http://xval.codeplex.com/" rel="nofollow">xVal</a> and <a href="http://fluentvalidation.codeplex.com/" rel="nofollow">FluentValidation for .NET</a>. <a href="http://nhforge.org/media/p/7.aspx" rel="nofollow">NHibernate Validator</a> 1.2 alpha has fluent syntax as well and it is integrated with xVal (not sure about alpha, but 1.0 should be).</p>
<p>Enterprise Validation Block has few negative sides as well. My entity's properties ended up having 3 rows of attributes and made readability worse. Trying to add validation with AND or OR operators is quite painful too.</p>
|
How to find out size of ASP.NET session, when there are non-serializable objects in it? <p>I have a feeling that I'm putting rather much data in my ASP.NET session, but I've no idea how much and if I should be concerned. I found a <a href="http://stackoverflow.com/questions/198082/how-to-find-out-size-of-session-in-aspnet-from-web-application">similar question</a>, but that relies on serializing objects and checking their serialized size. In my case the majority of data in the session is in objects from another library which doesn't have its classes marked as "Serializable". (I know that this restricts me to using InProc session state provider, but that's another issue). Does anyone have an idea on how to traverse the object graph and find out its size?</p>
<p><strong>Added:</strong> OK, one way would be a manual traversal of the object graph and usage of Marshal.SizeOf() method. But that's a lot of writing to get that working. Is there perhaps a simpler way of achieving the same effect? I'm not aiming for byte precision, I'm interested in the order of magnitude (kilobytes, megabytes, tens of megabytes...)</p>
| <p>For testing, you could put together a stub Custom Session provider, implementing the SessionStateStoreProviderBase abstract class. I would write backing fields that stash everything in WebCache (so that you have session data managed), and eventually generate a statistic using the Marshal.SizeOf() method when the SetAndReleaseItemExclusive method is called.</p>
<pre><code> public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
{
double MemSize = 0;
foreach (object sessObj in item.Items)
{
MemSize += Marshal.SizeOf(sessObj);
}
}
</code></pre>
<p>Consult this question for more information on getting field size:
<a href="http://stackoverflow.com/questions/207592/getting-the-size-of-a-field-in-bytes-with-c">http://stackoverflow.com/questions/207592/getting-the-size-of-a-field-in-bytes-with-c</a></p>
|
How do I make textures transparent in OpenGL? <p>I've tried to research this on Google but there doesn't appear to me to be any coherent simple answers. Is this because it's not simple, or because I'm not using the correct keywords?</p>
<p>Nevertheless, this is the progress I've made so far.</p>
<ol>
<li>Created 8 vertices to form 2 squares.</li>
<li>Created a texture with a 200 bit alpha value (so, about 80% transparent).</li>
<li>Assigned the same texture to each square, which shows correctly.</li>
<li>Noticed that when I use a texture with 255 alpha, it appears brighter.</li>
</ol>
<p>The init is something like the following:</p>
<pre><code>glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, textureIds);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
int i, j;
GLubyte pixel;
for (i = 0; i < TEXTURE_HEIGHT; i++)
{
for (j = 0; j < TEXTURE_WIDTH; j++)
{
pixel = ((((i & 0x8) == 0) ^ ((j & 0x8) == 0)) * 255);
texture[i][j][0] = pixel;
texture[i][j][1] = pixel;
texture[i][j][2] = pixel;
texture[i][j][3] = 200;
}
}
glBindTexture(GL_TEXTURE_2D, textureIds[0]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
TEXTURE_WIDTH, TEXTURE_HEIGHT,
0, GL_RGBA, GL_UNSIGNED_BYTE, texture);
</code></pre>
<p>This is somewhat similar to the code snippet from page 417 in the book, <em>OpenGL Programming Guide</em>, and creates a check pattern.</p>
<p>And then, the display function contains...</p>
<pre><code>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
// Use model view so that rotation value is literal, not added.
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
// ... translation, etc ...
glBindTexture(GL_TEXTURE_2D, textureIds[0]);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, +1.0, 0.0); // top left
glTexCoord2f(0.0, 1.0); glVertex3f(-1.0, -1.0, 0.0); // bottom left
glTexCoord2f(1.0, 1.0); glVertex3f(+1.0, -1.0, 0.0); // bottom right
glTexCoord2f(1.0, 0.0); glVertex3f(+1.0, +1.0, 0.0); // top right
glEnd();
// not neccecary to repeat, just good practice
glBindTexture(GL_TEXTURE_2D, textureIds[0]);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0); glVertex3f(-0.5, +1.0, -1.0); // top left
glTexCoord2f(0.0, 1.0); glVertex3f(-0.5, -1.0, -1.0); // bottom left
glTexCoord2f(1.0, 1.0); glVertex3f(+1.5, -1.0, -1.0); // bottom right
glTexCoord2f(1.0, 0.0); glVertex3f(+1.5, +1.0, -1.0); // top right
glEnd();
glFlush();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
SwapBuffers();
</code></pre>
<p>So, this renders a 2nd square in the background; I can see this but it looks like they're being blended with the background (I assume this because they are darker with 200 bit alpha than 255 bit) instead of the texture behind...</p>
<p><img src="http://i.stack.imgur.com/ducoN.png" alt="Transparent textures not working"></p>
<p>As you can see, no transparency... How can I fix this?</p>
| <p>So the other answer which was here but was deleted mentioned this - Generally, for alpha blending to work correctly you need to sort the objects from far to near in the coordinate system of the camera.<br />
This is why your polygons are blended with the background. You can confirm that this is indeed the problem by disabling the depth test. Without depth test all the fragments are displayed and you'll be able to see the alpha blending.</p>
<p>More on this in <a href="http://www.opengl.org/resources/faq/technical/transparency.htm">this page.</a></p>
|
Temporary table resource limit <p>i have two applications (server and client), that uses TQuery connected with TClientDataSet through TDCOMConnection,
and in some cases clientdataset opens about 300000 records and than application throws exception "Temporary table resource limit".</p>
<p>Is there any workaround how to fix this? (except "do not open such huge dataset"?)</p>
<p>update: oops i'm sorry there is 300K records, not 3 millions..</p>
| <p>The error might be from the TQuery rather than the TClientDataSet. When using a TQuery it creates a temporary table and it might be this limit that you are hitting. However in saying this, loading 3,000,000 records into a TClientDataSet is a bad idea also as it will try to load every record into memory - which maybe possible if they are only a few bytes each but it is probably still going to kill your machine (obviously at 1kb each you are going to need 3GB of RAM minimum).</p>
<p>You should try to break your data into smaller chunks. If it is the TQuery failing this will mean adjusting the SQL (fewer fields / fewer records) or moving to a better database (the BDE is getting a little tired after all).</p>
|
Multiple Footer Rows in a JSF dataTable <p>I am wanting to know if there is any way to have multiple footer rows in a h:dataTable (or t:datatable) I want to do somthing like this (which does not compile) </p>
<pre><code><h:dataTable ... var="row">
<h:column>
<f:facet name="header">
Header
</f:facet>
<h:outputText value="#{row.value}"/>
<f:facet name="footer">
FirstFooter
</f:facet>
<f:facet name="footer">
Second Footer in a new tr
</f:facet>
</h:column>
</h:dataTable>
</code></pre>
<p>With the result being somthing like this</p>
<pre><code><table border=1 style="border:1px solid">
<thead><tr><th>Header</th></tr></thead>
<tbody><tr><td>Data Value 1</td></tr>
<tr><td>Data Value 2</td></tr>
<tr><td>Data Value ...</td></tr>
<tr><td>Data Value n</td></tr>
</tbody>
<tfoot>
<tr><td>FirstFooter</td></tr>
<tr><td>Second Footer in a new tr</td></tr>
</tfoot>
</table>
</code></pre>
<p>Any ideas how best to accomplish this?
Thanks.</p>
<p>EDIT:
It would be great if I could avoid using a custom control/custom renderer</p>
| <p>The solution I ended up using was a custom renderer associated with t:datatable (the tomahawk extension to datatable) </p>
<pre><code>public class HtmlMultiHeadTableRenderer extends HtmlTableRenderer
</code></pre>
<p>I only had to override one method </p>
<pre><code>protected void renderFacet(FacesContext facesContext,
ResponseWriter writer, UIComponent component, boolean header)
</code></pre>
<p>with in which I looked for facets with names header, header2, header3 ... headerN (I stop looking as soon as there is one missing) and the same with footer. This has allowed me do do code like</p>
<pre><code><h:dataTable ... var="row">
<h:column>
<f:facet name="header">
Header
</f:facet>
<f:facet name="header2">
A second Tr with th's
</f:facet>
<h:outputText value="#{row.value}"/>
<f:facet name="footer">
FirstFooter
</f:facet>
<f:facet name="footer2">
Second Footer in a new tr
</f:facet>
</h:column>
</h:dataTable>
</code></pre>
<p>This took about one day(with some other extensions like allowing colspans based on groups) to code and document, </p>
|
problem with containers: *** glibc detected *** free(): invalid pointer: 0x41e0ce94 *** <p>I have a C++ program on Linux that crashes after some time with the message:</p>
<pre><code>*** glibc detected *** free(): invalid pointer: 0x41e0ce94 ***
</code></pre>
<p>Inside the program I make extensive use of containers. They have to store objects of a simple class.</p>
<p><strong>EDIT</strong> 2009-4-17:</p>
<p>In the meantime it seems clear that the error has nothing to do with the simple class. The error still occurs if I change the containers to hold other datatypes. The problem must be somewhere else in my code, I'm trying to figure it out at the moment...</p>
<p>Thanks to everybody who contributed to my question so far, it was helpful and instructive anyway.</p>
| <p>Consider using a std::string to hold the string value instead of a raw char pointer. Then you won't have to worry about managing the string data in your assignment, copy, and destruction methods. Most likely your problem lies there.</p>
<p>Edit: There's no issue with the newer class you posted, and no problem with the first version if you're only using the char * to point to string constants. The problem lies elsewhere in the program or with the way you're using the class. You'll have to spend more time digging in the debugger and/or valgrind to track down the problem. I would figure out what is pointed to at the specified address and try determine why it's being freed twice.</p>
|
Initializing a Generic.List in C# <p>In C#, I can initialize a list using the following syntax.</p>
<pre><code>List<int> intList= new List<int>() { 1, 2, 3 };
</code></pre>
<p>I would like to know how that <code>{}</code> syntax works, and if it has a name. There is a constructor that takes an <code>IEnumerable</code>, you could call that.</p>
<pre><code>List<int> intList= new List<int>(new int[]{ 1, 2, 3 });
</code></pre>
<p>That seems more "standard". When I deconstruct the default constructor for the List I only see </p>
<pre><code>this._items = Array.Empty;
</code></pre>
<p>I would like to be able to do this.</p>
<pre><code>CustomClass abc = new CustomClass() {1, 2, 3};
</code></pre>
<p>And be able to use the <code>1, 2, 3</code> list. How does this work?</p>
<p><strong>Update</strong> </p>
<p>Jon Skeet answered</p>
<blockquote>
<p>It's calling the parameterless
constructor, and then calling Add:</p>
</blockquote>
<pre><code>> List<int> tmp = new List<int>();
> tmp.Add(1); tmp.Add(2); tmp.Add(3);
> List<int> intList = tmp;
</code></pre>
<p>I understand what is does. I want to know how. How does that syntax know to call the Add method? </p>
<p><strong>Update</strong></p>
<p>I know, how cliche to accept a Jon Skeet answer. But, the example with the strings and ints is awesome. Also a very helpful MSDN page is:</p>
<ul>
<li><em><a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx">Object and Collection Initializers (C# Programming Guide)</a></em></li>
</ul>
| <p>This is called a <em>collection initializer</em>. It's calling the parameterless constructor, and then calling Add:</p>
<pre><code>List<int> tmp = new List<int>();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
List<int> intList = tmp;
</code></pre>
<p>The requirements for the type are:</p>
<ul>
<li>It implements <code>IEnumerable</code></li>
<li>It has overloads of <code>Add</code> which are appropriate for the argument types you supply. You can supply multiple arguments in braces, in which case the compiler looks for an <code>Add</code> method with multiple parameters.</li>
</ul>
<p>For example:</p>
<pre><code>public class DummyCollection : IEnumerable
{
IEnumerator IEnumerable.GetEnumerator()
{
throw new InvalidOperationException("Not a real collection!");
}
public void Add(string x)
{
Console.WriteLine("Called Add(string)");
}
public void Add(int x, int y)
{
Console.WriteLine("Called Add(int, int)");
}
}
</code></pre>
<p>You can then use:</p>
<pre><code>DummyCollection foo = new DummyCollection
{
"Hi",
"There",
{ 1, 2 }
};
</code></pre>
<p>(Of course, normally you'd want your collection to implement <code>IEnumerable</code> properly...)</p>
|
Suggest class names for an Event Booking system <p>I'm writing an Event Booking system in C#, which is vexing me greatly because "event" and "delegate" are reserved words. "Delegate" I've changed to "Attendee", but I can't think of an alternative name for the Event class (and instances thereof). The best I've come up with is "Happening", which is a little bit 1970s for my liking. Plus, the classes will be exposed via a customer API so I have to use professional terminology.</p>
<p>Any suggestions would be most gratefully received.</p>
<p>Edit: it is mainly the naming of instances and parameters that is bothering me:</p>
<pre><code>public Booking CreateBooking(Event event, Person person);
</code></pre>
| <p>If you really want to use a C# reserved word, you can prefix it with '@'.</p>
<p>E.g.</p>
<pre><code>public class @class
{
...
}
</code></pre>
<p>Use with caution...</p>
|
Is it possible to get the favorites list from the browser? <p>Is it possible to read a user's favorites list using asp.net?</p>
| <p>This would violate the visitors privacy. You would need a browser component that they installed locally to do such a thing.</p>
|
SSIS - lookup surrogate key for parent <p>I have a table in my source DB that is self referencing</p>
<p>|BusinessID|...|ParentID|</p>
<p>This table is modeled in the DW as
|SurrogateID|BusinessID|ParentID|</p>
<p>First question is, should the ParentID in the DW reference the surrogate id or the business id. My idea is that it should reference the surrogate id.</p>
<p>Then my problem occurs, in my dataflow task of SSIS, how can I lookup the surrogate key of the parent?</p>
<p>If I insert all rows where ParentID is null first and then the ones that are not null I solve part of the problem. </p>
<p>But I still have to lookup the rows that may reference a parent that is also a child.</p>
<p>I.e. I do have to make sure that the parents are loaded first into the DB to be able to use the lookup transformation.</p>
<p>Do I have to resolve to a for-each with sorted input?</p>
| <p>One trick I've used in this situation is to load the rows without the ParentID. I then used another data flow to create an update script based on the source data and the loaded data, then used a SQL task to run the created update script. It won't win prizes for elegance, but it does work.</p>
|
Techniques for storing/retrieving historical data in Rails <p>I'm looking for some ideas about saving a snapshot of some (different) records at the time of an event, for example user getting a document from my application, so that this document can be regenerated later. What strategies do you reccomend? Should I use the same table as the table with current values or use a historical table? Do you know of any plugins that could help me with the task? Please share your thoughts and solutions.</p>
| <p>There are several plugins for this. </p>
<pre><code>Acts_audited
</code></pre>
<p>acts as audited creates a single table for all of the auditable objects and requires no changes to your existing tables. You get on entry per change with the changes stored as a hash in a memo field, the type of change (CRUD). It is very easy to setup with just a single statement in the application controller specifying which models you want audited.
Rolling back is up to you but the information is there. Because the information stored is just the changes building the whole object may be difficult due to subsequent changes.</p>
<pre><code>Acts_as_versioned
</code></pre>
<p>A bit more complicated to setup- you need a separate table for each object you want to version and you have to add a version id to your existing table. Rollback is a very easy. There are forks on github that provide a hash of changes since last version so you can easily highlight the differences (it's what I use). My guess is that this is the most popular solution.</p>
<p>Ones I have no experience with: acts_as_revisable. I'll probably give this one a go next time I need versioning as it looks much more sophisticated.</p>
|
PHP Query Fail <pre><code><?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$dbhost = 'localhost';
$dbuser = 'zuk1_boo';
$dbpass = 'lols';
$dbname = 'zuk1_boo';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$name = $_POST['name'];
$iq = $_POST['iq'];
$nuname = str_replace(" ", "-", $name);
$nuname = $nuname.".gif";
$path = "img/$nuname";
move_uploaded_file($_FILES['userfile']['tmp_name'],$path);
$query = "INSERT INTO celebs (celeb,path1,iqq) VALUES ('$name','$path','$iq')";
mysql_query($query) or die('q fail');
mysql_close($conn);
echo "<br>File $fileName uploaded<br>";
}
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<tr><td><input name="name" type="text" value="name"></td></tr>
<tr><td><input name="iq" type="text" value="iq"></td></tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</code></pre>
<p>Bare in mind there is an ID row with auto increment but even if I add that to the query it still won't work.</p>
<p>No matter what I do with this query it just WILL not work, I've triple checked the sql details and they are fine, even though it appears to be connecting fine anyway. I've played with the field names in the query and they should be fine but it just won't work! $5 Paypal to anyone who can help me, I honestly am so frustrated it's untrue.</p>
| <pre><code>mysql_query($query) or die('q fail');
</code></pre>
<p>Replace this with</p>
<pre><code>mysql_query($query) or die(mysql_error());
</code></pre>
<p>And tell us what you get.</p>
|
Downsides to immutable objects in Java? <p>The advantages of immutable objects in Java seem clear:</p>
<ul>
<li>consistent state</li>
<li>automatic thread safety</li>
<li>simplicity</li>
</ul>
<p>You can favour immutability by using private final fields and constructor injection.</p>
<p>But, what are the downsides to favouring immutable objects in Java?</p>
<p>i.e.</p>
<ul>
<li>incompatibility with ORM or web presentation tools?</li>
<li>Inflexible design?</li>
<li>Implementation complexities?</li>
</ul>
<p>Is it possible to design a large-scale system (deep object graph) that predominately uses immutable objects?</p>
| <blockquote>
<p>But, what are the downsides to
favouring immutable objects in Java?
incompatibility with ORM or web
presentation tools?</p>
</blockquote>
<p>Reflection based frameworks are complicated by immutable objects since they <strong>requires</strong> constructor injection: </p>
<ul>
<li>there are no default arguments in Java, which forces us to ALWAYS provide all of the necessary dependencies </li>
<li>constructor overriding can be messy</li>
<li>constructor argument names are not usually available through reflection, which forces us to depend on argument order for dependency resolution</li>
</ul>
<blockquote>
<p>Implementation complexities?</p>
</blockquote>
<p>Creating immutable objects is still a boring task; the compiler should take care of the implementation details, as in <a href="http://groovy.codehaus.org/Immutable+AST+Macro" rel="nofollow">groovy</a></p>
<blockquote>
<p>Is it possible to design a large-scale system (deep object graph) that predominately uses immutable objects?</p>
</blockquote>
<p>definitely yes; immutable objects makes great building blocks for other objects (they favor composition) since it's much easier to maintain the invariant of a complex object when you can rely on its immutable components. The only true downside to me is about creating many temporary objects (e.g. <a href="https://web.archive.org/web/20080324114426/http://java.sun.com/developer/JDCTechTips/2002/tt0305.html" rel="nofollow">String concat was a problem in the past</a>). </p>
|
JQuery animate <p>I have some JQuery code in the click event handler for a checkbox that updates the value of a span control on the page, then animates the background color of the span tag to yellow and then fade back to white in about a second to draw attention to the user that the value of the span has changed. The problem is that if a user clicks repeatedly on the checkbox, then the animation occurs over and over for how ever many times the user clicked. Any one know how to prevent the JQuery animation from occuring if an animation is already in progress.</p>
| <p>Simply call stop() on the object before animating it:</p>
<pre><code> $('#button').click( function() {
$('#animatedSpan').stop().animate( { } );
});
</code></pre>
|
Compare text of two methods <p>Is there a tool that can do a diff of two methods? I'm working on some legacy code that has several 100-200 line methods that contain a lot of duplication and I would like to abstract the duplication out. Being able to diff the two methods would be a huge help. In case it matters, I'm working with .NET and Visual Studio 2008.</p>
| <p>I use <a href="http://winmerge.org/" rel="nofollow">WinMerge</a> in conjunction with <a href="http://visualstudiogallery.msdn.microsoft.com/a7519ab0-6029-49f3-9243-a74d1718a5bb" rel="nofollow">ClipboardDiff</a>. You can then do the comparison between clipboard contents and highlighted contents, with no need to save any files.</p>
|
Socket programmimg in C, need sample codes and tutorials <p>I want to do socket programming in C. Where client and server are exchanging messages. I have the sample codes with me, but i wanted some elaborate links and tutorials for socket programming C, so that i can write effective and error free code. I will be working with WinSock library and not on Linux. Any help?</p>
| <p>I think the standard response to this question is:</p>
<p><a href="http://beej.us/guide/bgnet/" rel="nofollow">http://beej.us/guide/bgnet/</a></p>
|
Security risks of an un-encrypted connection across an international WAN? <p>The organisation for which I work has an international WAN that connects several of its regional LANs. One of my team members is working on a service that receives un-encrypted messages directly from a FIX gateway in Tokyo to an app server in London, via our WAN. The London end always initiates the authenticated connection, and at no point do these messages leave our WAN. </p>
<p>But our local security guru suggests that we should be encrypting these messages as a <a href="http://www.darkreading.com/story/showArticle.jhtml?articleID=216403220" rel="nofollow">WAN apparently has significantly more security risk than a LAN</a>. How much easier is it really to break into a WAN than a LAN? And what other security risks does a WAN pose in this context?</p>
<p><strong>UPDATE:</strong> Many thanks for your answers. I've decided to encrypt the connection, mainly because it's clear that the WAN does introduce extra security vulnerabilities due to the hardware being outside of our physical control. </p>
| <p>You should protect traffic even on a LAN. Haven't you heard of Heartland Payment Systems and the breach of their system that processes credit cards for hundreds of thousands of merchants? Thieves were sniffing unprotected traffic on Heartland's internal network.</p>
<p>Do this right is cheap and easy, so the value of the data doesn't have to be that great to justify it.</p>
|
Visual Studio code formatter <p>I'm using Visual Studio 2008 for doing work in C# and JavaScript (AJAXy stuff).</p>
<p>Here's my issue -- I love Eclipse and especially the code formatted (Ctrl-Shift-F).
Visual Studio's Ctrl-k, Ctrl-d, really sucks in comparison, especially for javascript.</p>
<p>Is there a way to get VS to behave like the IDE that I miss?</p>
| <p>Go into Tools | Options | Text Editor and edit the language specific settings to you're liking. Ctrl-K, Ctrl-D honors these settings, so you can make the code formatter working the way you want. There are a ton of options you can change (bracket positioning, spacing, indenting, etc.).</p>
|
Anything like DPAPI available for .NET Compact Framework or Windows Mobile? <p>I need a way to protect a private key on a mobile device.</p>
<p>I know in "Writing Secure Code" chapter "Protecting Secret Data" says "Windows CE" cannot be used in secure environments. But the book is many years old now, 2003.</p>
<p>Is this still the case? Tell me it ain't so. There has to be a way to secure a private key today.</p>
| <p>The DPAPI is embodied in a set of Win32 functions, <a href="http://msdn.microsoft.com/en-us/library/aa922939.aspx" rel="nofollow">CryptProtectData</a> and <a href="http://msdn.microsoft.com/en-us/library/aa925037.aspx" rel="nofollow">CryptUnprotectData</a>. These functions are available on Windows CE and Windows Mobile platforms (see links), although I don't know at what version they added support.</p>
<p>The .NET wrapper for the DPAPI is the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx" rel="nofollow">ProtectedData</a> class in System.Security.Cryptography namespace (assembly System.Security.dll). However, I don't think .NET Compact Framework implements this yet, so you'll have to use P/Invoke if using .NET.</p>
|
Trouble porting OpenGL code to iPhone's OpenGL ES <p>Here, is the sample code which I am using. This code is in OpenGL. I want to port it to OpenGL ES. <code>glArrayElement()</code> is not supported in OpenGL ES. Instead, it was recommended to use <code>glDrawElements()</code>, <code>glDrawArrays()</code>. I am not able to convert this. Can you please help me out to convert the code.</p>
<pre><code>glTexCoordPointer(2,GL_FLOAT,sizeof(struct texcoord),tex);
glColorPointer(4,GL_UNSIGNED_BYTE,4,col);
glNormalPointer(GL_FLOAT,sizeof(vector),wet->n);
glVertexPointer(2,GL_FLOAT,sizeof(struct vertexcoord),vert);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glLockArraysEXT(0,wet->w*wet->h);
i=0;
for(int y=0;y<wet->h-1;y++)
{
glBegin(GL_TRIANGLE_STRIP);
for(int x=0;x<wet->w;x++)
{
glArrayElement(i);
glArrayElement(i+wet->w);
i++;
}
glEnd();
}
glUnlockArraysEXT();
</code></pre>
<p>And one more question is do we have any replacement for <code>glEnable(GL_TEXTURE_RECTANGLE_EXT)</code> in OpenGL ES.</p>
| <p>everything from glLockArrays down you can get rid of. just replace all that with glDrawArrays and youre done.</p>
|
Javascript to handle manipulating url anchor for bookmarking <p>I'd like to use the anchor part of the url (after the #) so that my page can have ajax/dhtml but still be able to have bookmarks work properly. I'm wondering is someone can help me get started on writing some javascript code for this. I'm using jQuery, but if the solution's a generic one, that's fine too.</p>
<p>For my page, I could have settings like:
"a" could be a number from 10-50
"b" is a 0 or 1
"c" is a 0 or 1
etc...</p>
<p>I'd like some tips on writing optimized javascript code which could both parse and set something like #a=23&b=0&c=1</p>
<p>Also, I'd like to keep my url as short as possible, so if the default of "a" was 23, in the example above, the a=23 would be omitted.</p>
<p>Is there a library that does all this stuff already?</p>
| <p>Have a look at the <strong>jQuery history plugin</strong>: <a href="http://www.mikage.to/jquery/jquery_history.html" rel="nofollow">http://www.mikage.to/jquery/jquery_history.html</a></p>
|
Is there anything as good as TOAD for Postgres (Windows)? <p>I'm just looking for a management tool like TOAD for Postgres. Anyone used a good one?</p>
<p>Edit - I work mostly within the data itself and the database already has a mature model/design. I use the edit windows the most (well, in TOAD for Oracle anyway.)</p>
<p>As far as I know, Toad only exists naturally for: Oracle, MS SQL, DB2 and MySQL...</p>
<p>--JS</p>
| <p>Doesn't TOAD exist for several plattforms?</p>
<p>I'm using pgAdmin III which fills my needs so far.</p>
<p><a href="http://www.pgadmin.org/">http://www.pgadmin.org/</a></p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.