input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
Custom view transition in OpenGL ES <p>I'm trying to create a custom transition, to serve as a replacement for a default transition you would get here, for example:</p>
<pre><code>[self.navigationController pushViewController:someController animated:YES];
</code></pre>
<p>I have prepared an OpenGL-based view that performs an effect on some static texture mapped to a plane (let's say it's a copy of the flip effect in Core Animation). What I don't know how to do is:</p>
<ul>
<li>grab current view content and make a texture out of it (I remember seeing a function that does just that, but can't find it)</li>
<li>how to do the same for the view that is currently offscreen and is going to replace current view </li>
<li>are there some APIs I can hook to in order to make my transition class as native as possible (make it a kind of Core Animation effect)?</li>
</ul>
<p>Any thoughts or links are greatly appreciated!</p>
<p><strong>UPDATE</strong></p>
<p>Jeffrey Forbes's answer works great as a solution to capture the content of a view. </p>
<p>What I haven't figured out yet is how to capture the content of the view I want to transition to, which should be invisible until the transition is done.</p>
<p>Also, which method should I use to present the OpenGL view?
For demonstration purposes I used pushViewController. That affects the navbar, though, which I actually want to go one item back, with animation, check this vid for explanation:</p>
<p><a href="http://vimeo.com/4649397">http://vimeo.com/4649397</a>.</p>
<p>Another option would be to go with presentViewController, but that shows fullscreen.
Do you think maybe creating another window (or view?) could be useful?</p>
|
<p>While I cannot completely answer your question without doing some more research of my own, I can help a bit:</p>
<p>-In order to get the view of a UINavigationController, you need to take a screenshot. The easiest way to do this is by grabbing it into a UIImage:</p>
<pre><code>UIGraphicsBeginImageContext(self.view.frame.size);
[[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
UIImage* test = UIGraphicsGetImageFromCurrentImageContext();
UIImageView* view = [[UIImageView alloc] initWithImage:test];
UIGraphicsEndImageContext();
</code></pre>
<p>I am not sure if you can render a GLContext (not familiar on the phone) into a CGImage, but I would do something like that (and init a UIImage from that). I would prerender every frame of the animation you are trying to do and slap it into an UIImageView using the animation stuff provided within. That is, if your animation is simple enough. Otherwise, it might come down to writing your own animation function :-/</p>
|
SELECT with ORs including table joins <p>I've got a database with three tables: Books (with book details, PK is CopyID), Keywords (list of keywords, PK is ID) and KeywordsLink which is the many-many link table between Books and Keywords with the fields ID, BookID and KeywordID.</p>
<p>I'm trying to make an advanced search form in my app where you can search on various criteria. At the moment I have it working with Title, Author and Publisher (all from the Book table). It produces SQL like:</p>
<pre><code>SELECT * FROM Books WHERE Title Like '%Software%' OR Author LIKE '%Spolsky%';
</code></pre>
<p>I want to extend this search to also search using tags - basically to add another OR clause to search the tags. I've tried to do this by doing the following</p>
<pre><code>SELECT *
FROM Books, Keywords, Keywordslink
WHERE Title LIKE '%Joel%'
OR (Name LIKE '%good%' AND BookID=Books.CopyID AND KeywordID=Keywords.ID)
</code></pre>
<p>I thought using the brackets might separate the 2nd part into its own kinda clause, so the join was only evaluated in that part - but it doesn't seem to be so. All it gives me is a long list of multiple copies of the one book that satisfies the <code>Title LIKE '%Joel%'</code> bit.</p>
<p>Is there a way of doing this using pure SQL, or would I have to use two SQL statements and combine them in my app (removing duplicates in the process).</p>
<p>I'm using MySQL at the moment if that matters, but the app uses ODBC and I'm hoping to make it DB agnostic (might even use SQLite eventually or have it so the user can choose what DB to use).</p>
|
<p>You need to join the 3 tables together, which gives you a tablular resultset. You can then check any columns you like, and make sure you get <em>distinct</em> results (i.e. no duplicates).</p>
<p>Like this:</p>
<pre><code>select distinct b.*
from books b
left join keywordslink kl on kl.bookid = b.bookid
left join keywords k on kl.keywordid = k.keywordid
where b.title like '%assd%'
or k.keyword like '%asdsad%'
</code></pre>
<p>You should also try to avoid starting your LIKE values with a percent sign (%), as this means SQL Server can't use an index on that column and has to perform a full (and slow) table scan. This starts to make your query into a "starts with" query.</p>
<p>Maybe consider the full-text search options in SQL Server, also.</p>
|
cfront for C++ <p>Is a cfront tool available for the new C++? For any other modern languages?</p>
|
<p><a href="http://comeaucomputing.com/" rel="nofollow">Comeau C/C++</a> is a C-generating C++ compiler, like cfront.</p>
|
Are there specific "technical debts" that are not worth incurring? <p>There are (at least) two ways that technical debts make their way into projects. The first is by conscious decision. Some problems just are not worth tackling up front, so they are consciously allowed to accumulate as technical debt. The second is by ignorance. The people working on the project don't know or don't realize that they are incurring a technical debt. This question deals with the second. Are there technical debts that you let into your project that would have been trivial to keep out ("If I had only known...") but once they were embedded in the project, they became dramatically more costly? </p>
|
<p>Ignoring security problems entirely. </p>
<p>Cross-site scripting is one such example. It's considered harmless until you get <code>alert('hello there!')</code> popping up in the admin interface (if you're lucky - script may as well silently copy all data admins have access to, or serve malware to your customers).</p>
<p>And then you need 500 templates fixed <em>yesterday</em>. Hasty fixing will cause data to be double-escaped, and won't plug all vulnerabilities.</p>
|
In Django, Problem with {{ block.super }}, How do I avoid duplicating a `block` in multiple template files? <p>For 2 child template files inheriting a block, the <code>{{ block.super }}</code> does not resolve</p>
<p>Python 2.5.2, Django 1.0, Windows XP SP3</p>
<p>Sample skeleton code for files involved:</p>
<ol>
<li><code>base.html</code></li>
<li><code>item_base.html</code></li>
<li><code>show_info_for_all_items.html</code></li>
<li><code>show_info_for_single_item.html</code></li>
</ol>
<p>FILE : <code>base.html</code></p>
<pre><code>{% block content %}
{% endblock %}
</code></pre>
<p>FILE : <code>item_base.html</code></p>
<pre><code>{% extends "base.html" %}
{% block item_info %}
Item : {{ item.name }}<br/>
Price : {{ item.price }}<br/>
{% endblock %}
</code></pre>
<p>FILE : <code>show_info_for_all_items.html</code></p>
<pre><code>{% extends "item_base.html" %}
{% block content %}
<h1>info on all items</h1>
<hr/>
{% for item in items %}
{% block item_info %}
{{ block.super }}
{% endblock %}
<hr/>
{% endfor %}
{% endblock %}
</code></pre>
<p>FILE : <code>show_info_for_single_item.html</code></p>
<pre><code>{% extends "item_base.html" %}
{% block content %}
<h1>info on single item</h1>
{% block item_info %}
{{ block.super }}
{% endblock %}
{% endblock %}
</code></pre>
<p><code>show_info_for_all_items.html</code> shows a list of items along with each item's info.</p>
<p><code>show_info_for_single_item.html</code> shows a single item with the item's info.</p>
<p><code>show_info_for_all_items.html</code> and <code>show_info_for_single_item.html</code> share same code for showing item info, so I moved it to <code>item_base.html</code> into <code>block item_info</code></p>
<p>but the <code>{{ block.super }}</code> in <code>show_info_for_all_items.html</code> and <code>show_info_for_single_item.html</code> does not work. <code>{{ block.super }}</code> resolves as blank.</p>
<p>If I move the code back from <code>block item_info</code> in <code>item_base.html</code> into <code>show_info_for_all_items.html</code> and <code>show_info_for_single_item.html</code> it works but then I have to duplicate same <code>block item_info</code> code in 2 files.</p>
<p>If the block.super issue can not be solved, does Django offer something like INCLUDE => <code>{% INCLUDE "item_base.html" %}</code> so blocks from a template file can be included ( instead of <code>extends</code> )</p>
<p>How do I avoid duplicating <code>block item_info</code> in both html files?</p>
|
<blockquote>
<p>Does Django offer something like
INCLUDE (...)</p>
</blockquote>
<p>Yes!, just take a look at the documentation: <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/#include" rel="nofollow">include</a></p>
<p>Put the common code block in <em>foo.html</em>, and then, in each template:</p>
<pre><code>{% include 'foo.html' %}
</code></pre>
|
Is your employer comfortable with a hosted bug tracking solution, or it has to be inhouse? <p>Was your employer comfortable with a hosted bug tracking solution, or it just had to be in house for security/paranoia reasons?</p>
<p>I can see small teams of remote developers benefiting from it, but most bosses (i would think) would be to paranoid to let someone else know of their internals.</p>
|
<p>In-house due to security concerns of having data off-premises.</p>
|
Passing Interface in a WCF Service? <p>I'm experimenting with WCF Services, and have come across a problem with passing Interfaces.</p>
<p>This works:</p>
<pre><code>[ServiceContract]
public interface IHomeService
{
[OperationContract]
string GetString();
}
</code></pre>
<p>but this doesn't:</p>
<pre><code>[ServiceContract]
public interface IHomeService
{
[OperationContract]
IDevice GetInterface();
}
</code></pre>
<p>When I try to compile the client it fails on the GetInterface method. I get an Exception saying that it can't convert Object to IDevice.</p>
<p>On the clientside the IHomeService class correctly implements GetString with a string as it's returntype, but the GetInterface has a returntype of object. Why isn't it IDevice?</p>
|
<p>You need to tell the WCF serializer which class to use to serialize the interface</p>
<pre><code>[ServiceKnownType(typeof(ConcreteDeviceType)]
</code></pre>
|
How is FlexBuilder compiling my app? <p>I'd like to see the command-line arguments that FlexBuilder is using to compile my application. This is so that I can build them into the ANT script I'm working on. Is there any way to view the command line compilation step?</p>
<p>The reason I'm asking for this is that when I compile my app using Ant/Flex SDK vs. FlexBuilder my app behaves differently.</p>
|
<p>So I figured out the answer.</p>
<p>First of all, you can get a better idea of how FlexBuilder compiles your app by adding a -dump-config=C:\myConfig.xml to the compile arguments in FlexBuilder. This outputs an xml file containing configuration settings used in the compilation step. You can also use this file as an argument to compc or mxmlc if you'd like. Read more about it
<a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=kb404341" rel="nofollow">here</a>...</p>
<p>But, here's what actually solved my problem. I was using the regular old Flex SDK installed on our integration server to compile my apps using Ant. This is the free SDK you can download from Adobe's site. I then took the FlexBuilder directory from my local machine and copied it up to the integration server and pointed my build script to use that version of the SDK (and changed my path env variable). </p>
<p>When I compiled using the FlexBuilder version of the SDK, all was well and the strange bugs I was seeing in my app disappeared.</p>
<p>Moral of the story, make sure you are using the same version of the SDK for your automated builds as you use to build locally.</p>
|
Iterate over HashMap.values() in JSF+Facelets <p>I'm using JSF/Facelets, and I'm trying to iterate over some Document objects (custom object) that I'm keeping in a HashMap. When the page is loaded, I'm getting the error "Property 'name' not found on type java.util.HashMap$Values". Here's what's in my backing bean:</p>
<pre><code>private Map<String, Document> documents = new HashMap<String, Document>();
public Collection<Document> getDocuments(){
return documents.values();
}
</code></pre>
<p>And in my xhtml page:</p>
<pre><code><h:dataTable id="documentTable"
value="#{DocumentManager.allDocuments}"
var="doc" rowClasses="list-row-odd, list-row-even"
headerClass="table-header" styleClass="bordered">
<h:column id="col_name">
<f:facet name="header">Name</f:facet>
${doc.name}
</h:column>
</h:dataTable>
</code></pre>
<p>If I change the getDocuments function to the following, it works (meaning the table is displayed without error), but I'm not sure why I need to put the values in the list for the JSF/Facelets page to display properly.</p>
<pre><code>public List<Document> getDocuments(){
List<Document> rtrn = new ArrayList<Document>();
for(Document doc : documents.values())
rtrn.add(doc);
return rtrn;
}
</code></pre>
<p>Shouldn't I be able to iterate over the Collection?</p>
|
<p>Well, as it turns out, you can't just use any kind of collection type with dataTable, and for good reason. From the <a href="http://myfaces.apache.org/core12/myfaces-impl/tlddoc/h/dataTable.html">MyFaces 1.2 Spec</a>, the value attribute must be:</p>
<blockquote>
<p>An EL expression that specifies the
data model that backs this table.</p>
<p>The value referenced by the EL
expression can be of any type.</p>
<ul>
<li>A value of type DataModel is used directly.</li>
<li>Array-like parameters of type <code>Object[]</code>, <code>java.util.List</code>, <code>java.sql.ResultSet</code> or <code>javax.servlet.jsp.jstl.sql.Result</code> are wrapped in a corresponding DataModelthat knows how to iterate over the elements.</li>
<li>Other values are wrapped in a DataModel as a single row.</li>
</ul>
<p>Note in particular that unordered collections, eg <code>Set</code> are not supported. Therefore if the value expression references such an object then the table will be considered to contain just one element - the collection itself.</p>
</blockquote>
<p>The Collection returned from HashSet.values() is not ordered and, therefore is not supported. If it was, you'd have no idea what order the rows in your table would be output, and refreshes of the page could re-order them randomly. Not good.</p>
<p>The error you're getting is, from the last paragraph, it says that the datatable is treating your Collection as the row object, and Collection doesn't have a "name" property.</p>
|
JMS/DDS Integration <p>I have a legacy C++ application that uses <a href="http://portals.omg.org/dds" rel="nofollow">DDS</a> for asynchronous communication/messaging. I need to integrate this application into a JavaEE environment that uses JMS for messaging. Other than building a standalone JMS/DDS bridge module, are there any other options that I might have?</p>
|
<p>If you want to continue to use your existing DDS product, your best bet will almost certainly turn out to be a custom bridge. Current DDS implementations are generally not interoperable at the message level and not even close at the QoS level.</p>
<p>To use something like the RTI Message Service, you will have to use RTI DDS. If you happen to already be using that particular product, this may be an option for you. Otherwise, I would recommend writing a bridge that explicitly publishes and subscribes your topics of interest.</p>
<p>Keep in mind that JMS doesn't have the rich set of QoS that DDS has. In all but the simplest cases there will be a need to figure out what behavior you really expect from your topics and explicitly determine how to implement it using JMS.</p>
|
Best practices for storing postal addresses in a database (RDBMS)? <p>Are there any good references for best practices for storing postal addresses in an RDBMS? It seems there are lots of tradeoffs that can be made and lots of pros and cons to each to be evaluated -- surely this has been done time and time again? Maybe someone has at least written done some lessons learned somewhere?</p>
<p>Examples of the tradeoffs I am talking about are storing the zipcode as an integer vs a char field, should house number be stored as a separate field or part of address line 1, should suite/apartment/etc numbers be normalized or just stored as a chunk of text in address line 2, how do you handle zip +4 (separate fields or one big field, integer vs text)? etc. </p>
<p>I'm primarily concerned with U.S. addresses at this point but I imagine there are some best practices in regards to preparing yourself for the eventuality of going global as well (e.g. naming fields appropriately like region instead of state or postal code instead of zip code, etc.</p>
|
<p>As an 'international' user, there is nothing more frustrating than dealing with a website that is oriented around only US-format addresses. It's a little rude at first, but becomes a serious problem when the validation is also over-zealous.</p>
<p>If you are concerned with going global, the only advice I have is to keep things free-form. Different countries have different conventions - in some, the house number comes before the street name, in some it comes after. Some have states, some regions, some counties, some combinations of those. Here in the UK, the zipcode is not a zipcode, it's a postcode containing both letters and numbers.</p>
<p>I'd advise simply ~10 lines of variable-length strings, together with a separate field for a postcode (and be careful how you describe that to cope with national sensibilities). Let the user/customer decide how to write their addresses.</p>
|
How can i make a catch all route to handle '404 page not found' queries for ASP.NET MVC? <p>Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?</p>
<p>NOTE: I don't want to set this up in my IIS settings.</p>
|
<p>Found the answer myself.</p>
<p><a href="http://richarddingwall.name/2008/08/17/strategies-for-resource-based-404-errors-in-aspnet-mvc/">Richard Dingwall</a> has an excellent post going through various strategies. I particularly like the FilterAttribute solution. I'm not a fan of throwing exceptions around willy nilly, so i'll see if i can improve on that :)</p>
<p>For the global.asax, just add this code as your last route to register:</p>
<pre><code>routes.MapRoute(
"404-PageNotFound",
"{*url}",
new { controller = "StaticContent", action = "PageNotFound" }
);
</code></pre>
|
Decode gzipped web page retrieved via cURL in PHP <p>I'm retrieving a gzipped web page via curl, but when I output the retrieved content to the browser I just get the raw gzipped data. How can I decode the data in PHP?</p>
<p>One method I found was to write the content to a tmp file and then ...</p>
<pre><code>$f = gzopen($filename,"r");
$content = gzread($filename,250000);
gzclose($f);
</code></pre>
<p>.... but man, there's got to be a better way.</p>
<p>Edit: This isn't a file, but a gzipped html page returned by a web server.</p>
|
<p>I use curl and:</p>
<pre><code>curl_setopt($ch,CURLOPT_ENCODING , "gzip");
</code></pre>
|
Batch Updates using DataAdapter <p>I have a situation where I have a bunch of SQL Update commands that all need to be executed. I know that DataSets can do batch updates, but the only way I've been able to accomplish it is to load the whole table into a dataset first. What if I want to only update a subset of the records in a table?</p>
|
<p>The easiest way out here is load table with the required rows (rows you wan to update). Double check that the RowState is "Inserted".
Assign the InsertCommand property of the adapter with your stored procedure (wrapped in an SqlCommand) that does the "update", this tweak will ensure that all the rows present in the table gets updated.</p>
<p>The fundamental here being: The DataAdapter runs the UpdateCommand on rows for which state is Updated, runs InsertCommand for rows which state is Inserted and finally DeleteCommand for the rows for which state is Deleted.</p>
|
Meaning of exception in C# app: "Not a legal OleAut date"? <p>Does anyone know what this means. Getting this in C# winforms applications:</p>
<blockquote>
<p>Not a legal OleAut date</p>
</blockquote>
|
<p>It means that somewhere in the program is attempting to convert to or from an OLE Automation Date outside the valid range 1-January-4713 BC to 31-December-9999 AD. It might have slipped through because OLE Automation Dates are represented as a <strong>double</strong>.</p>
<p>Start by looking for any uses of the methods:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.datetime.fromoadate.aspx">DateTime.FromOADate</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.datetime.tooadate.aspx">DateTime.ToOADate</a></p>
|
Get source jar files attached to Eclipse for Maven-managed dependencies <p>I am using Maven (and the Maven Eclipse Integration) to manage the dependencies for my Java projects in Eclipse. The automatic download feature for JAR files from the Maven repositories is a real time saver. Unfortunately, it does not include API documentation and source code.</p>
<p>How can I set up Maven to automatically also get the source and javadoc attachments and register them properly with Eclipse?</p>
|
<p>I am sure m2eclipse Maven plugin for Eclipse - the other way around - can do that. You can configure it to download both the source files and javadoc automatically for you.</p>
<p>This is achieved by going into Window > Preferences > Maven and checking the "Download Artifact Sources" and "Download Artifact JavaDoc" options.</p>
<p><img src="http://i.stack.imgur.com/CNUBh.png" alt="Screenshot of Maven Preferences" title="Maven Preferences"></p>
|
Algorithm: array of arrays in Cocoa Touch (perhaps using NSCountedSet) <p>This one is a bit tedious in as far as explaining, so here goes. I'm essentially populating a tableView on the iPhone with multiple sections, and potentially multiple rows per section. To my understanding, it's best to have an array of arrays so that you can simply determine how many sections one has by sending a message to the top level array of count, then for rows per section, doing the same for the inner array(s). My data is in the form of a dictionary. One of the key/value pairs in the dictionary determines where it will be displayed on the tableView. An example is the following:</p>
<pre><code>{
name: "bob",
location: 3
}
{
name: "jane",
location: 50
}
{
name: "chris",
location: 3
}
</code></pre>
<p>In this case I'd have an array with two subarrays. The first subarray would have two dictionaries containing bob and chris since they're both part of location 3. The second subarray would contain jane, since she is in location 50. What's my best bet in Cocoa populate this data structure? A hash table in C would probably do the trick, but I'd rather use the classes available in Cocoa.</p>
<p>Thanks and please let me know if I need to further clarify.</p>
|
<p>The following code works: (<b>edit:</b> added my initialization code)</p>
<pre><code>NSArray * arrayOfRecords = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"bob", @"name",
[NSNumber numberWithInt:3], @"location", nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"jane", @"name",
[NSNumber numberWithInt:50], @"location", nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"chris", @"name",
[NSNumber numberWithInt:3], @"location", nil],
nil];
NSMutableDictionary * sections = [NSMutableDictionary dictionary];
for (NSDictionary * record in arrayOfRecords)
{
id key = [record valueForKey:@"location"];
NSMutableArray * rows = [sections objectForKey:key];
if (rows == nil)
{
[sections setObject:[NSMutableArray arrayWithObject:record] forKey:key];
}
else
{
[rows addObject:record];
}
}
NSArray * sortedKeys = [[sections allKeys] sortedArrayUsingSelector:@selector(compare:)];
NSArray * sortedSections = [sections objectsForKeys:sortedKeys notFoundMarker:@""];
NSLog(@"%@", sortedSections);</code></pre>
|
How to check if two objects are of the same type in Actionscript? <p>I want to do this in Actionscript:</p>
<pre><code>typeof(control1) != typeof(control2)
</code></pre>
<p>to test if two objects are of the same type. This would work just fine in C#, but in Actionscript it doesnt. In fact it returns <code>'object'</code> for both <code>typeof()</code> expressions because thats the way Actionscript works.</p>
<p>I couldn't seem to find an alternative by looking in the debugger, or on pages that describe <code>typeof()</code> in Actionscript.</p>
<p>Is there a way to get the actual runtime type?</p>
|
<p>The best way is to use <code>flash.utils.getQualifiedClassName()</code>. Additionally, you can use <code>flash.utils.describeType()</code> to get an XML document the describes more about the class.</p>
|
Use of 'prototype' vs. 'this' in JavaScript? <p>What's the difference between</p>
<pre><code>var A = function () {
this.x = function () {
//do something
};
};
</code></pre>
<p>and</p>
<pre><code>var A = function () { };
A.prototype.x = function () {
//do something
};
</code></pre>
|
<p>The examples have very different outcomes.</p>
<p>Before looking at the differences, the following should be noted:</p>
<ul>
<li>A constructor's <em>prototype</em> provides a way to share methods and values among instances via the instance's private <code>[[Prototype]]</code> property.</li>
<li>A function's <em>this</em> is set by how the function is called or by the use of <em>bind</em> (not discussed here). Where a function is called on an object (e.g. <code>myObj.method()</code>) then <em>this</em> within the method references the object. Where <em>this</em> is not set by the call or by the use of <em>bind</em>, it defaults to the global object (window in a browser) or in strict mode, remains undefined.</li>
<li>JavaScript is a object oriented language, i.e. everything is an Object, including functions.</li>
</ul>
<p>So here are the snippets in question:</p>
<pre><code>var A = function () {
this.x = function () {
//do something
};
};
</code></pre>
<p>In this case, variable <code>A</code> is assigned a value that is a reference to a function. When that function is called using <code>A()</code>, the function's <em>this</em> isn't set by the call so it defaults to the global object and the expression <code>this.x</code> is effectively <code>window.x</code>. The result is that a reference to the function expression on the right hand side is assigned to <code>window.x</code>.</p>
<p>In the case of:</p>
<pre><code>var A = function () { };
A.prototype.x = function () {
//do something
};
</code></pre>
<p>something very different occurs. In the first line, variable <code>A</code> is assigned a reference to a function. In JavaScript, all functions objects have a <em>prototype</em> property by default so there is no separate code to create an <em>A.prototype</em> object.</p>
<p>In the second line, <em>A.prototype.x</em> is assigned a reference to a function. This will create an <em>x</em> property if it doesn't exist, or assign a new value if it does. So the difference with the first example is which object's <em>x</em> property is involved in the expression.</p>
<p>Another example is below. It's similar to the first one (and may be what you meant to ask about):</p>
<pre><code>var A = new function () {
this.x = function () {
//do something
};
};
</code></pre>
<p>In this example, the <code>new</code> operator has been added before the function expression so that the function is called as a constructor. When called with <code>new</code>, the function's <em>this</em> is set to reference a new Object whose private <code>[[Prototype]]</code> property is set to reference the constructor's public <em>prototype</em>. So in the assignment statement, the <code>x</code> property will be created on this new object. When called as a constructor, a function returns its <em>this</em> object by default, so there is no need for a separate <code>return this;</code> statement.</p>
<p>To check that <em>A</em> has an <em>x</em> property:</p>
<pre><code>console.log(A.x) // function () {
// //do something
// };
</code></pre>
<p>This is an uncommon use of <em>new</em>, since the only way to reference the constructor is via <em>A.constructor</em>. It would be much more common to do:</p>
<pre><code>var A = function () {
this.x = function () {
//do something
};
};
var a = new A();
</code></pre>
<p>Another way of achieving a similar result is to use an immediately invoked function expression:</p>
<pre><code>var A = (function () {
this.x = function () {
//do something
};
}());
</code></pre>
<p>In this case, <code>A</code> assigned the return value of calling the function on the right hand side. Here again, since <em>this</em> is not set in the call, it will reference the global object and <code>this.x</code> is effectively <code>window.x</code>. Since the function doesn't return anything, <code>A</code> will have a value of <code>undefined</code>.</p>
<p>These differences between the two approaches also manifest if you're serializing and de-serializing your Javascript objects to/from JSON. Methods defined on an object's prototype are not serialized when you serialize the object, which can be convenient when for example you want to serialize just the data portions of an object, but not it's methods:</p>
<pre><code>var A = function () {
this.objectsOwnProperties = "are serialized";
};
A.prototype.prototypeProperties = "are NOT serialized";
var instance = new A();
console.log(instance.prototypeProperties); // "are NOT serialized"
console.log(JSON.stringify(instance));
// {"objectsOwnProperties":"are serialized"}
</code></pre>
<p><strong>Related questions</strong>:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/186244/what-does-it-mean-that-javascript-is-a-prototype-based-language"><strong>What does it mean that JavaScript is a prototypal language?</strong></a></li>
<li><a href="http://stackoverflow.com/questions/235360/what-is-the-scope-of-a-function-in-javascriptecmascript"><strong>What is the scope of a function in JavaScript?</strong></a></li>
<li><strong><a href="http://stackoverflow.com/questions/3127429/javascript-this-keyword">How does the "this" keyword work?</a></strong></li>
</ul>
<p><strong>Sidenote:</strong> There may not be any significant memory savings between the two approaches, however using the prototype to share methods and properties will likely use less memory than each instance having its own copy.</p>
<p>JavaScript isn't a low-level language. It may not be very valuable to think of prototyping or other inheritance patterns as a way to explicitly change the way memory is allocated.</p>
|
Any DAL/ORM on GAE? <p>Is there any Database Abstraction Layer (DAL) or Object Relational Mapper (ORM) that works on Google App Engine (GAE), and on normal relational databases (RDBS), other than <a href="http://www.web2py.com" rel="nofollow">web2py</a>'s?</p>
<p>If not, is anybody working on porting one of the existing DAL/ORM to GAE?</p>
|
<p>There is an ORM for Google App Engine. There are some differences between it and SQLAlchemy, but looks like it works. Check this page: <a href="http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html" rel="nofollow">http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html</a></p>
|
Remote Name could not be resolved <p>While accessing a webservice which is availbale at <a href="http://recpushdata.cyndigo.com/jobs.asmx" rel="nofollow">http://recpushdata.cyndigo.com/jobs.asmx</a>, I am getting this Exception. "Remote name could not be resolved"</p>
<p>Any Suggesytion..what to do..</p>
|
<p>The server error you got in the previous comment is good - it means your original problem, being unable to resolve the remote host, is solved. </p>
<p>As to your HTTP 500 error, check the event log for that time on the remote host. If you don't have access to it, contact its administrator. </p>
|
Some keys not working with a Dojo Widget <p>I tried to follow <a href="http://mindtrove.info/articles/creating-an-accessible-internationalized-dojo-rating-widget/" rel="nofollow">the widget example by mindtrove's blog</a>. Here is <a href="http://mindtrove.info/html/rating-tutorial.html" rel="nofollow">the example demo page</a>.</p>
<p>There are some problems with this widget: left & right arrow keys, and home & end keys are not working in Firefox(I am using a Mac), and none of any keys are working if I load the example page in Safari. I am not sure if this is only my Mac's problem or not working on Mac at all.</p>
<p>Here are some codes in the widget Rating.js:</p>
<pre>
_onKeyDown: function(event) {
switch(event.keyCode) {
case dojo.keys.UP_ARROW:
case dojo.keys.RIGHT_ARROW:
this.currentValue += 1
this.currentValue = Math.min(this.currentValue, this.maximumValue);
dojo.stopEvent(event);
break;
case dojo.keys.DOWN_ARROW:
case dojo.keys.LEFT_ARROW:
this.currentValue -= 1
this.currentValue = Math.max(this.currentValue, this.minimumValue);
dojo.stopEvent(event);
break;
case dojo.keys.HOME:
this.currentValue = this.minimumValue;
dojo.stopEvent(event);
break;
case dojo.keys.END:
this.currentValue = this.maximumValue;
dojo.stopEvent(event);
break;
}
// refresh the display
this._update();
}
</pre>
<p>As far as I can see, all the keys cought in this function event should work. I am not sure why some are not working. By the way, I find out one thing interesting: for those keys (left, right, home & end) keys in Firefox, they works if I hold my shift key.</p>
<p>I am not sure if the problem is a bug in the widget's codes or Dojo's bug in case of Mac?</p>
|
<p>Typical Dojo behaviour. What "class" does this one extend? You can check if it's "base class" exhibits the same bugs. But in the case of Dojo you can never be sure where bugs come from, you can only be sure there are tons of them.</p>
|
apply CSS dynamically in asp.net 2.0 <p>I have a scrolling div with Three linkbuttons and three differents divs. I need to apply CSS to active linkbutton as soon as button is clicked.The codes used by me are:</p>
<pre><code>protected void btnNetwork_Click(object sender, EventArgs e)
{
this.btnForecast.CssClass = "li_1";
this.btnBlog.CssClass = "li_2";
this.btnNetwork.CssClass = "li_3_active";
this.btnNetwork.ForeColor = System.Drawing.Color.White;
lblMsg.Visible = false;
BindGW("-----------------------------------");
Forecast.Visible = false;
Blog.Visible = false;
Network.Visible = true;
}
</code></pre>
<p>Thanks & Regards,</p>
<p>Khushi</p>
|
<p>Instead of using server side event use client side javascript event. Try:</p>
<pre><code>$get('btnId').setAttribute("class", "some_class_name");
</code></pre>
|
DataGridView Filtering OnClick Event (C# WinForm) <p>How to filter my datagridview by the value of my label.text on click event? That value is from my linq query:</p>
<pre><code>dataSet.Tables[0].AsEnumerable().Where(c => c.Field<int>("ageColumn") > 3 &&
c.Field<int>("ageColumn") < 5).Count();
</code></pre>
<p>Let's just say the above query gives me 12 (label.text = 12), now when I click "12", I want my datagridview to ONLY show those 12 rows that meet my above query.</p>
|
<p>Do you need it to be dynamic? Perhaps store the query itself as a lambda in the Tag property of your label:</p>
<pre><code>Predicate<DataColumn> clause = c => c.Field<int>("ageColumn") > 3
&& c.Field<int>("ageColumn") < 5;
label1.Tag = clause;
</code></pre>
<p>... then re-evaluate your query when the label is clicked:</p>
<pre><code>var clause = (sender as Label).Tag as Predicate<DataColumn>;
myDataSource = dataSet.Tables[0].AsEnumerable().Where(clause);
</code></pre>
<p>I don't know if this would work, but at least it would let you "attach" a where-clause to various lables.</p>
<p>I'd also recommend taking a look at <a href="http://www.codeplex.com/bindablelinq" rel="nofollow">Bindable LINQ</a> so the results of your queries can be bound to. Very cool stuff.</p>
|
Which RDBMS do you use with Django and why? <p>I recently switched a project from MySQL InnoDB to PostgreSQL, and I feel bigger lags when inserting and updating data with ajax. This may be subjective. I know the Django devs recommend postgres and I know psycopg2 is supposed to be faster than MysqlDB. Personaly I like the way postgres enforces database integrity, but am mostly worried about performance for this project. Want to hear other people's opinion on this.</p>
|
<p>Why don't you measure? That's the only way to be sure about the performance. Hand waving about how slow or not is something without hard data is like trying to catch water with your hands.</p>
<p>Measure transactions per second or even better, requests per second with a web server stress tool like The Grinder (which can be scripted in Jython) with both MySQL backend and PostgreSQL and afterwards see if that makes a difference. If it does, ask around here, or, more specifically, ask on the pgsql-general or pgsql-performance mailing lists. There are many expert people there which know loads about it, even the main devs. There are tons of knobs on PostgreSQL configuration related to performance.</p>
|
Any tool that can upgrade .NET 1.1 WinForm code to .NET 2.0 "style"? <p>I mean a tool that can extract certain contents from old .NET 1.1 WinForm code and put it in .designer file (make it looks like .net 2.0 WinForm code). This also involves an update to the project file (.csproj/.vbproj)..</p>
<p>If no existing tool yet, any tip or pointer on how to do this by programming?</p>
|
<p>It is possible to do using a macro, have a look at <a href="http://www.dotnetjunkies.com/WebLog/jamesnies/archive/2006/11/27/VS2005DesignerClassMacroForCSharp.aspx" rel="nofollow">this article</a> for the macro code.</p>
<p>If anyone else is looking to do this for VB.net (as I did) the only example I could find was this one in c# but it gave me a basis and we got it to work with a vb project.</p>
|
DropDownList.SelectedValue changes (as a child control in a FormView) aren't sticking <p>Okay, I have a FormView with a couple of child controls in an InsertItemTemplate. One of them is a DropDownList, called DdlAssigned. I reference it in the Page's OnLoad method like so:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
((DropDownList)FrmAdd.FindControl("DdlAssigned")).SelectedValue =
((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
</code></pre>
<p>Basically I'm just setting the default value of the DropDownList to the user currently logged in.</p>
<p>Anyway, when the page finishes loading the SelectedValue change isn't reflected on the page. I stepped through OnLoad and I can see the change reflected in my Watch list, but when all is said and done nothing's different on the page.</p>
|
<p>I figured it out. I'm still missing exactly why it doesn't work just on FormLoad, but performing the change in the FormView's DataBound event does the trick.</p>
<pre><code>protected void FrmAdd_DataBound(object sender, EventArgs e)
{
// This is the same code as before, but done in the FormView's DataBound event.
((DropDownList)FrmAdd.Row.FindControl("DdlAssigned")).SelectedValue =
((Guid)Membership.GetUser().ProviderUserKey).ToString();
}
</code></pre>
<p>So, I guess the general rule of thumb is that if you are having problems making changes to controls when working with databinding, try to make them immediately after it has been bound.</p>
|
Admin generic inlines for multi-table subclassed models broken --- any alternatives? <p>Here's what I'm trying to do, and failing...</p>
<p>I have a File model which has a generic-relation to other objects:</p>
<pre><code>class File(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
file = models.FileField(upload_to='files/%Y/%m/%d')
# etc....
</code></pre>
<p>I also want to have a sub-class of File to deal with the specific case of images to be displayed in-page, rather than downloaded:</p>
<pre><code>class Image(File):
file = models.ImageField(upload_to='files/%Y/%m/%d')
</code></pre>
<p>All of the above works fine, including generic inlines of the File model, until I want to use a generic-inline of the Image model --- the save process fails to create the base class instance and so raises an error stating that the Image.file_ptr (the 'secret' foreign key to the base class) cannot be None.</p>
<p>So, basically, generic inlines do not properly support multi-table inheritance at the moment.</p>
<p>It's quite likely that I'm making this more complicated than it need be, so can anyone suggest either a fix for this problem, or a better way of achieving the same end?</p>
<p>Please let me know if you need further clarification.</p>
|
<p>Inheritance can be implemented two ways in a relational model.</p>
<p>A subclass can be a new table with all the same columns as the superclass repeated. This works well when you have an abstract superclass or subclass features that override the superclass.</p>
<p>A subclass can be just the unique columns with a join to the superclass table. This works well when you have a concrete superclass.</p>
<p>In your case, it looks you might have the following.</p>
<pre><code>class FileFacts( models.Model ):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
class DownloadFile( models.Model ):
facts = models.ForeignKey( FileFacts )
file = models.FileField(upload_to='files/%Y/%m/%d')
class InlineImage( models.Model ):
facts = models.ForeignKey( FileFacts )
file = models.ImageField(upload_to='files/%Y/%m/%d')
</code></pre>
<p>This is my preference for handling a subclass-like model.</p>
|
MySQL A Search, A Select of multiple rows, Joining and all in one query <p>I am first doing a search on the table tags which results in all the rows returned together with their additional data from the table links (on which i do a join). The table tags works such that for an auto _id there can be multiple rows (1 tag per row so multiple tags is multiple rows). </p>
<p>What I want to do is that instead of just getting multiple rows back which match the auto _id and query. I want to get each tag back for each auto_id that is found, in 1 row (some form of distinct but that puts all the tags comma seperated in 1 field), hence the group_concat (which obviously is not working at the moment - i've added it as pseudo).</p>
<pre><code>SELECT ta.auto_id, li.address, li.title, GROUP_CONCAT(SELECT tag FROM tags WHERE auto_id = ta.auto_id)
FROM `tags` AS ta
JOIN
links AS li
ON ta.auto_id = li.auto_id
GROUP BY ta.tag
WHERE ta.user_id = 1
AND (ta.tag LIKE '%query%')
</code></pre>
<p>I hope I've made my case clear.</p>
<p>Thank you very much,</p>
<p>Ice</p>
|
<p>If I understand what you're asking, something like this should do the trick:</p>
<pre><code>SELECT ta.auto_id, li.address, li.title, GROUP_CONCAT(ta.tag) -- Get a comma separated list of all the tags
FROM tags AS ta
INNER JOIN links AS li ON ta.auto_id = li.auto_id
WHERE ta.user_id = 1
AND ta.tag LIKE '%query%'
GROUP BY li.id -- Group by links id, so you get one row for each link, which contians a list of tags
</code></pre>
|
Content Delivery Network algorithms, examples, code <p>What design considerations must be taken when writing software for content-distribution systems, such as managing the synchronisation and distribution of data, redirecting downloads to the nearest servers and so on?</p>
<p>I am also looking for examples of open source CDN (content delivery network) software. I can think of two projects, <a href="http://www.coralcdn.org/">CoralCDN</a> and <a href="http://labtel.ing.uniroma1.it/opencdn/">OpenCDN</a></p>
<p>Please note that there is more to a CDN than just hardware bandwidth. A CDN is a combination of software <em>and</em> hardware. </p>
<p>What I would like to go for, is software for streaming media as well as static assets. I'm having trouble figuring out how to properly synch streaming media across servers (since the file access can be fairly random), while static assets seem a little bit easier, as it's a one time request.</p>
|
<p>You realize that the value a content delivery network has is purely in the number of servers they own and the proximity of the servers to end users?</p>
<p>Are you sure you're going down the right path?</p>
|
problem with PHP reading CSV files <p>I'm trying to read data from a.csv file to ouput it on a webpage as text.</p>
<p>It's the first time I'm doing this and I've run into a nasty little problem.</p>
<p>My .csv file(which gets openened by Excel by default), has multiple rows and I read the entire thing as one long string.</p>
<p>like this:</p>
<pre><code>$contents = file_get_contents("files/data.csv");
</code></pre>
<p>In this example file I made, there are 2 lines.</p>
<blockquote>
<p>Paul Blueberryroad
85 us Flashlight,Bag November 20,
2008, 4:39 pm</p>
<p>Hellen Blueberryroad
85 us lens13mm,Flashlight,Bag,ExtraBatteries November
20, 2008, 16:41:32</p>
</blockquote>
<p>But the string read by PHP is this:</p>
<p>Paul;Blueberryroad 85;us;Flashlight,Bag;November 20, 2008, 4:39 pmHellen;Blueberryroad 85;us;lens13mm,Flashlight,Bag,ExtraBatteries;November 20, 2008, 16:41:32</p>
<p>I'm splitting this with:</p>
<pre><code>list($name[], $street[], $country[], $accessories[], $orderdate[]) = split(";",$contents);
</code></pre>
<p>What I want is for $name[] to contain "Paul" and "Hellen" as its contents. And the other arrays to receive the values of their respective columns.</p>
<p>Instead I get only Paul and the content of $orderdate[] is</p>
<blockquote>
<p>November 20, 2008, 4:39 pmHellen</p>
</blockquote>
<p>So all the rows are concatenated. Can someone show me how i can achieve what I need?</p>
<p>EDIT: solution found, just one werid thing remaining:</p>
<p>I've solved it now by using this piece of code:</p>
<pre><code>$fo = fopen("files/users.csv", "rb+");
while(!feof($fo)) {
$contents[] = fgetcsv($fo,0,';');
}
fclose($fo);
</code></pre>
<p>For some reason, allthough my CSV file only has 2 rows, it returns 2 arrays and 1 boolean. The first 2 are my data arrays and the boolean is 0.</p>
|
<p>You are better off using <a href="http://www.php.net/fgetcsv" rel="nofollow">fgetcsv()</a> which is aware of CSV file structure and has designated options for handling CSV files. Alternatively, you can use <a href="http://www.php.net/manual/en/function.str-getcsv.php" rel="nofollow">str_getcsv()</a> on the contents of the file instead.</p>
|
Flex Help: Repeaters not repeating in an Accordian control <p>I am having a issue with databinding child repeaters inside an accordion control, hopefully you can help...</p>
<p>I have an accordion in a ViewStack (of which,that ViewStack is also in another top-level ViewStack). I have a repeater in each child of the accordion control. The component looks like such:</p>
<pre>
<code>
<mx:Box
xmlns:mx="http://www.adobe.com/2006/mxml"
creationComplete="init()"
>
<mx:ViewStack>
...
<mx:Accordion creationComplete="accordianInit()">
<mx:Box label="Groups" width="100%">
<mx:Repeater id="rpGroups" width="100%">
<mx:CheckBox id="chkGroups"
label="{rpGroups.currentItem.name}" />
</mx:Repeater>
</mx:Box>
<mx:Box label="Contacts">
<mx:Repeater id="rpContacts">
<mx:CheckBox id="chkContacts"
label=quot;{rpContacts.currentItem.full_name}" />
</mx:Repeater>
</mx:Box>
</mx:Accordion>
...
</mx:ViewStack>
<mx:Box>
</code>
</pre>
<p>The problem is that if I bind the 2 repeaters in the <strong>init</strong> function, then both repeaters don't show any data. If I bind the repeaters in the <strong>accordianInit</strong> function, then only the first repeater (rpGroups) gets databound...</p>
<p>Where should I be data binding the repeaters so that both repeaters repeat properly?</p>
<p>Hopefully this makes sense, if not I can elaborate more, any help is appreciated.</p>
|
<p>Bind the dataProvider of the repeater to the source in MXML itself:</p>
<pre><code><mx:Repeater dataProvider="{the_data}" ... />
</code></pre>
<p>The reason you're seeing the behavior you are is because the Accordion (and ViewStack) does not create all of it's children right away. It only creates the child that is visible (so, the first Box, and the first ViewStack child initially). </p>
<p>Because of this behavior, when you try to assign data to the repeaters in the first init() event handler the repeaters have no instantiated container to repeat children into. When you assign data to the repeaters in accordionInit() then only the first Box has been created, which is why only the first repeater works.</p>
<p>If you don't want to bind to the data via the dataProvider attribute of the Repeater tag (as I've shown above), then you can use a change handler on the Accordion to set the repeater data as the user changes panes (because as the user clicks into the panes, they get created by the Flex framework).</p>
<p>All of this comes about from the <em>creationPolicy</em> property: <a href="http://livedocs.adobe.com/flex/3/html/layoutperformance_05.html" rel="nofollow">http://livedocs.adobe.com/flex/3/html/layoutperformance_05.html</a></p>
|
What should be in a 'technical work plan'? <p>I'm applying for grant to fund part of the development of a web app, one question I'm stuck on says to describe the: </p>
<p><strong>Tasks and full technical details and risks relating to your project, including detailed technical work plan</strong></p>
<p>Any guidance on what specific topics should be covered would be very gratefully received</p>
<p>There is a separate question regarding the proposed methodology - but I have this covered</p>
<p>Background info. - It's a rails projects and we've been using BDD (user stories) and XP</p>
|
<p>Well that's a pretty open-ended question, but as regards the work plan, you should probably focus on the specific tasks you're actually going to need to complete to get to the end goal of having a working system. I'm thinking of things like:</p>
<ul>
<li>Install the environment.</li>
<li>Define the database schema and what drivers are needed to interact with it.</li>
<li>Develop the XYZ front-end.</li>
<li>Develop the ABC back-end.</li>
</ul>
<p>Depending on what's expected, I would say there's a good chance you'll need to attach man-day sizings to these.</p>
<p>These are just examples - not only will you need to be more complete, you'll also want to put a lot more detail in there. Obviously I can't do that, not knowing the details of your project.</p>
|
How to deal with a Many-To-Many Relation in my API <p>I have two entities Foo and Bar with a Many to Many relationship between them.</p>
<p>Let's say there is no semantic argument for why Foo might be "responsible" for the many to many relationship, but we arbitrarily decide that Foo is responsible for the relation (I.e., in NHibernate we would mark Bar as Inverse)</p>
<p>That's all well and good from a DB perspective, but my entity APIs reveal a problem.</p>
<pre><code> // Responsible for the relation
public class Foo
{
List<Bar> Bars = new List<Bar>();
public void AddBar(Bar bar)
{
Bars.Add(bar);
bar.AddFoo(this);
}
}
public class Bar
{
List<Foo> Foos = new List<Foo>();
// This shouldn't exist.
public void AddFoo(Foo foo)
{
Foos.Add(foo);
foo.AddBar(this); // Inf Recursion
}
}
</code></pre>
<p>If we've decided that Foo is responsible for this relationship, how do I update the associated collection in Bar without creating a public Bar.AddFoo() method which shouldn't even exist?</p>
<p>I feel like I should be able to maintain the integrity of my domain model without resorting to having to reload these entities from the DB after an operation such as this.</p>
<p>UPDATE: Code tweak inspired by commenter. </p>
|
<p>You might be missing a domain concept there. Have you tried creating a third entity: FooBarRelationship?</p>
|
How do I sum a list<> of arrays <p>I have a List< int[] > myList, where I know that all the int[] arrays are the same length - for the sake of argument, let us say I have 500 arrays, each is 2048 elements long. I'd like to sum all 500 of these arrays, to give me a single array, 2048 elements long, where each element is the sum of all the same positions in all the other arrays.</p>
<p>Obviously this is trivial in imperative code:</p>
<pre><code>int[] sums = new int[myList[0].Length];
foreach(int[] array in myList)
{
for(int i = 0; i < sums.Length; i++)
{
sums[i] += array[i];
}
}
</code></pre>
<p>But I was wondering if there was a nice Linq or Enumerable.xxx technique?</p>
|
<p>Edit: Ouch...This became a bit harder while I wasn't looking. Changing requirements can be a real PITA.</p>
<p>Okay, so take each position in the array, and sum it:</p>
<pre><code>var sums = Enumerable.Range(0, myList[0].Length)
.Select(i => myList.Select(
nums => nums[i]
).Sum()
);
</code></pre>
<p>That's kind of ugly...but I think the statement version would be even worse.</p>
|
What language would people recommend as simple GUI that can be used as input to a script runing on Cygwin? <p>I need a simple window with three input boxes and three labels (login name, password, and server node) and a button to execute the script. I do not want any third party programs that need to be installed on Windows. If it can be installed on Cygwin that would be great.</p>
|
<p>You might want to look at Tcl/Tk and the notion of starkits and starpacks. With the latter you can create a single-file windows executable so your end users wouldn't have to install anything other than this program.</p>
<p>By using tk 8.5 you'll also get the benefit of native windows widgets so the GUI can look very professional. </p>
<p>The code would look something like this:</p>
<pre><code>package require Tk 8.5
proc main {} {
ttk::frame .f
ttk::label .l1 -text "Username:" -anchor e
ttk::label .l2 -text "Password:" -anchor e
ttk::label .l3 -text "Server:" -anchor e
ttk::entry .e1 -textvariable data(username)
ttk::entry .e2 -textvariable data(password) -show *
ttk::entry .e3 -textvariable data(server)
ttk::button .b1 -text "Submit" -command run
grid .l1 .e1 -sticky ew -in .f -padx 4
grid .l2 .e2 -sticky ew -in .f -padx 4
grid .l3 .e3 -sticky ew -in .f -padx 4
grid x .b1 -sticky e -row 4 -in .f -padx 4 -pady 4
grid rowconfigure .f 3 -weight 1
grid columnconfigure .f 1 -weight 1
pack .f -side top -fill both -expand true
focus .e1
}
proc run {} {
global data
puts "username: $data(username)"
puts "password: $data(password)"
puts "server: $data(server)"
}
main
</code></pre>
|
Viewing swf files in magazine format <p>I have a set of swf files and can view them one at a time. However what I would like to is to view them in magazine format, as below:
First view is: swf file1 (magazine front cover)
Next view: swf file2 (magazine page 1) on left + swf file3 (magazine page 2) on right
Next view: swf file4 (magazine page 3) on left + swf file5 (magazine page 4) on right
Next view: swf file6 (magazine page 5) on left + swf file7 (magazine page 6) on right
etc
etc
Last view: swf filex (magazine back cover)</p>
<p>So it's like flipping through a amagzine. This is what one can see on issuu.com
I'd like to get the software that will do this. Preferably free! </p>
|
<p>Check out Megazine, it's an open source page flip engine that will do exactly what you need written in AS3, source code is available.</p>
<p><a href="http://megazine.mightypirates.de/" rel="nofollow">http://megazine.mightypirates.de/</a> </p>
|
Exit Edit Mode <p>I have an array of objects which populate a UITableView. When a user removes the last object from the array, I automatically create a new "default" object. However, in the TableView, when the user gets there, the list is still in "Edit" mode. Is there a way for me to programatically set the TableView back to "normal" mode again?</p>
|
<p>Set the table's <code>editing</code> property to <code>NO</code>. <a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006943-CH3-SW59" rel="nofollow">UITableView Reference</a></p>
|
Tool to trace local function calls in Linux <p>I am looking for a tool like <a href="http://linux.die.net/man/1/ltrace">ltrace</a> or <a href="http://linux.die.net/man/1/strace">strace</a> that can trace locally defined functions in an executable. ltrace only traces dynamic library calls and strace only traces system calls. For example, given the following C program:</p>
<pre><code>#include <stdio.h>
int triple ( int x )
{
return 3 * x;
}
int main (void)
{
printf("%d\n", triple(10));
return 0;
}
</code></pre>
<p>Running the program with <code>ltrace</code> will show the call to <code>printf</code> since that is a standard library function (which is a dynamic library on my system) and <code>strace</code> will show all the system calls from the startup code, the system calls used to implement printf, and the shutdown code, but I want something that will show me that the function <code>triple</code> was called. Assuming that the local functions have not been inlined by an optimizing compiler and that the binary has not been stripped (symbols removed), is there a tool that can do this?</p>
<p><strong>Edit</strong></p>
<p>A couple of clarifications:</p>
<ul>
<li>It is okay if the tool also provides trace information for non-local functions.</li>
<li>I don't want to have to recompile the program(s) with support for specific tools, the symbol information in the executable should be enough.</li>
<li>I would be really nice if I could use the tool to attach to existing processes like I can with ltrace/strace.</li>
</ul>
|
<p>Assuming you only want to be notified for specific functions, you can do it like this:</p>
<p>compile with debug informations (as you already have symbol informations, you probably also have enough debugs in)</p>
<p>given</p>
<pre><code>#include <iostream>
int fac(int n) {
if(n == 0)
return 1;
return n * fac(n-1);
}
int main()
{
for(int i=0;i<4;i++)
std::cout << fac(i) << std::endl;
}
</code></pre>
<p>Use gdb to trace:</p>
<pre><code>[js@HOST2 cpp]$ g++ -g3 test.cpp
[js@HOST2 cpp]$ gdb ./a.out
(gdb) b fac
Breakpoint 1 at 0x804866a: file test.cpp, line 4.
(gdb) commands 1
Type commands for when breakpoint 1 is hit, one per line.
End with a line saying just "end".
>silent
>bt 1
>c
>end
(gdb) run
Starting program: /home/js/cpp/a.out
#0 fac (n=0) at test.cpp:4
1
#0 fac (n=1) at test.cpp:4
#0 fac (n=0) at test.cpp:4
1
#0 fac (n=2) at test.cpp:4
#0 fac (n=1) at test.cpp:4
#0 fac (n=0) at test.cpp:4
2
#0 fac (n=3) at test.cpp:4
#0 fac (n=2) at test.cpp:4
#0 fac (n=1) at test.cpp:4
#0 fac (n=0) at test.cpp:4
6
Program exited normally.
(gdb)
</code></pre>
<p>Here is what i do to collect all function's addresses:</p>
<pre><code>tmp=$(mktemp)
readelf -s ./a.out | gawk '
{
if($4 == "FUNC" && $2 != 0) {
print "# code for " $NF;
print "b *0x" $2;
print "commands";
print "silent";
print "bt 1";
print "c";
print "end";
print "";
}
}' > $tmp;
gdb --command=$tmp ./a.out;
rm -f $tmp
</code></pre>
<p>Note that instead of just printing the current frame(<code>bt 1</code>), you can do anything you like, printing the value of some global, executing some shell command or mailing something if it hits the <code>fatal_bomb_exploded</code> function :) Sadly, gcc outputs some "Current Language changed" messages in between. But that's easily grepped out. No big deal.</p>
|
Resharper update namespace on all files in project <p>I know i can update my current files namespace to match the directory structure. Can i do this all at once for all files in a project.</p>
|
<p>AFAIK, there is no way to do this OOB. </p>
<p>But, you can update them fairly quickly through the Class View window. Open class view window, click on the namespace you want to rename, hit CTRL + R + R and then rename. </p>
<p><a href="http://rickardnilsson.net/post/2008/08/26/ReSharper-User-tip-2-Refactor-rename-namespace.aspx" rel="nofollow">This blog post outlines it very well</a></p>
|
Custom accordion - using each <p>I am trying to create a custom accordion for my page to that display my posts. I have it in list format using HTML and I am trying to create an effect when you click each header to expand to show more information.</p>
<p>But I don't want to have say six blocks of code for six of the <code><li></code> elements I have on the page.</p>
<p>Is there a way to run it through .each(); perhaps? Instead of creating each section? Try a more dynamic approach.</p>
|
<p>Did you take a look at <a href="http://roshanbh.com.np/2008/03/expandable-collapsible-toggle-pane-jquery.html" rel="nofollow">this tutorial</a> ?</p>
<p>Because, as this <a href="http://roshanbh.com.np/examples/exapandable-panel/" rel="nofollow">example illustrates</a>, one does not need multiple conditions to achieve this.</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
//hide the all of the element with class msg_body
$(".msg_body").hide();
//toggle the componenet with class msg_body
$(".msg_head").click(function()
{
$(this).next(".msg_body").slideToggle(600);
});
});
</script>
</code></pre>
<blockquote>
<p>All the element with the class name âmsg_bodyâ is collapsed when the page is loaded.</p>
<p>The âslideToggle()â function of jQuery is used to expand and collapse the âdivâ with class âmsg_bodyâ. </p>
<p>When user clicks on the element with the class â.msg_headâ, then div with class âmsg_bodyâ next to it, gets toggled with sliding effect, making toggle panel using jQuery.</p>
</blockquote>
|
How do I get a div to float to the bottom of its container? <p>I have floated images and inset boxes at the top of a container using float:right (or left) many times. Recently I hit a need to float a div at the bottom right corner of another div with the normal text wrap that you get with float (text wrapped above and to the left only).</p>
<p>I thought this must be relatively easy even though float has no bottom value but I haven't been able to do it using a number of techniques and searching the web hasn't come up with anything other than using absolute positioning but this doesn't give the correct word wrap behaviour.</p>
<p>I had thought this would be a very common design but apparently it isn't. If nobody has a suggestion I'll have to break my text up into separate boxes and align the div manually but that is rather precarious and I'd hate to have to do it on every page that needs it.</p>
|
<p>Set the parent div to <code>position: relative</code>, then the inner div to... </p>
<pre><code>position: absolute;
bottom: 0;
</code></pre>
<p>...and there you go :)</p>
|
Entity Framework pipeline: Expression trees to ESQL to SQL? <p>What is the Entity Framework pipeline like?
What gets translated to SQL, Expression Trees or ESQL, or both?
Is ESQL something an Entity Framework provider needs to implement or translate, or that the framework takes care of?</p>
|
<p>Both Entity SQL and LINQ expressions are parsed into a common cannonical query tree which is then parsed to generate the provider specific SQL.</p>
<p>Jim Wooley</p>
<p><a href="http://www.ThinqLinq.com" rel="nofollow">www.ThinqLinq.com</a></p>
|
MultiMap implementation <p>I'm writing a simple IDictionary abstraction in C# that wraps a
Dictionary<K, ICollection<V>>. Basically, it maps multiple values to one key. I can't decide whether to remove a key and its empty list when the last item in a values list is removed, or leave it (to avoid instantiating a new collection if the key is reused) and do checks on a key's values' Count when determining whether a key exists.</p>
|
<p>I would remove the collections so that your MultiMap has consistent behavior. If I used your MultiMap I would be very surprised (and unhappy) to find that a missing key behaves differently depending on whether a key was previously in the MultiMap or not.</p>
<p>Does Clear() remove the the Collections?</p>
<p>You may also create an unintended memory leak if you do not remove the collections. A developer may add many items, then remove them. Memory usage (after GC) should return to the same amount as before those items were added.</p>
<p>I would not worry about the cost of creating Collections. I would worry about the contract you create for your MultiMap. If after profiling your application you find that to be a concerned, you could modify or create a special MultiMap for that behavior. Don't fall into the trap of premature optimization.</p>
|
Where should a script block with jquery code be placed on an ASP.NET MVC Master Page? <p>Getting started with jquery and having trouble getting hello world type example going for asp.net mvc. I get a runtime error "object expected" when trying to load a page with this script. </p>
<p>A. Where should script tags be placed in a master page?
B. What might I be doing wrong? There are definitely "a" elements in my page?</p>
<pre><code><script src="../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.corner.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function(event) {
alert("Thanks for visiting!");
});
});
</script>
</code></pre>
|
<p>Hmmm ... </p>
<p>To answer your first question: They should be put in the <code><head></code> element.</p>
<p>Also, usually I use the <a href="http://docs.jquery.com/Events/bind#typedatafn">'bind' method</a> when sinking events in the DOM (like it looks like you're trying to do).</p>
<p>So, code would look like:</p>
<pre><code>$(document).ready(function()
{
// Bind each link to a handler:
$("a").bind('click dblclick', function(event)
{
alert('click');
})
});
</code></pre>
<p>Also, a few design tips (since you're working with something close to my heart (ASP.NET MVC with jQuery):</p>
<p>Add an extra 'ContentPlaceHolder' at the bottom of your master page's <code><head></code> element. This will allow you to have page specific javascript run in it's proper location: in the 'head' section of the page, and it'll allow you to make page-specific javascript includes. </p>
<p>It'll look something like this:</p>
<pre><code> <asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
</code></pre>
<p><strong>Why is this useful?</strong> I'll tell you: That jQuery rounded corners plugin you're using might only be used on a few pages -- why include it on every page?</p>
|
Is VARCHAR like totally 1990s? <ol>
<li>VARCHAR does not store Unicode characters.</li>
<li>NVARCHAR does store Unicode characters.</li>
<li>Today's applications should always be Unicode compatible.</li>
<li>NVARCHAR takes twice the amount of space to store it.</li>
<li>Point 4 doesn't matter because storage space is extremely inexpensive.</li>
</ol>
<p>Ergo: When designing SQL Server databases today, one should always use NVARCHAR.</p>
<p>Is this sound reasoning? Does anyone disagree with any of the premises?
Are there any reasons to choose VARCHAR over NVARCHAR today?</p>
|
<p>You match the datatype with the data that will be stored in the column. By a similar argument you could say why not store all data in NVARCHAR columns, because numbers and dates can be represented as strings of digits.</p>
<p>If the best match for the data that will be stored in the column is VARCHAR, then use it.</p>
|
Proper MIME media type for PDF files <p>When working with PDFs, I've run across the MIME types <code>application/pdf</code> and <code>application/x-pdf</code> among others. </p>
<p>Is there a difference between these two types, and if so what is it? Is one preferred over the other?</p>
<p>I'm working on a web app which must deliver huge amounts of PDFs and I want to do it the correct way, if there is one.</p>
|
<p>The standard MIME type is <code>application/pdf</code>. The assignment is defined in <a href="http://www.rfc-editor.org/rfc/rfc3778.txt">RFC 3778, The application/pdf Media Type</a>, referenced from the <a href="http://www.iana.org/assignments/media-types/">MIME Media Types registry</a>.</p>
<p>MIME types are controlled by a standards body, The <a href="http://www.iana.org/">Internet Assigned Numbers Authority</a> (IANA). This is the same organization that manages the root name servers and the IP address space.</p>
<p>The use of <code>x-pdf</code> predates the standardization of the MIME type for PDF. MIME types in the <code>x-</code> namespace are considered experimental, just as those in the <code>vnd.</code> namespace are considered vendor-specific. <code>x-pdf</code> might be used for compatibility with old software.</p>
|
Catch "The program stopped working" on Vista <p>On Vista, I got a problem with the application crash handler. Basically, if something unexpected occurs which cannot be captured by SEH, I get this pop-up window with "The application stopped working", blablabla, "Close program/Debug program" -- that is, after I disable the error reporting using the system control panel. With error reporting enabled, you would get a task dialog with search for solution online, close, debug.</p>
<p>This is not so funny if it happens in automated tools, and I wonder whether there is a way to get rid of it <em>totally</em>, read, if my app crashes, it just crashes to the command line or disappears but does not bring up a dialog.</p>
|
<p>Use</p>
<pre><code>SetErrorMode(SetErrorMode(0)|SEM_NOGPFAULTERRORBOX);
</code></pre>
<p>But I would suggest to install an exceptions handler which creates a dump so you can verify what happened. For example <a href="http://code.google.com/p/crashrpt/" rel="nofollow">crashrpt</a> (or <a href="http://www.codeproject.com/KB/debug/crash_report.aspx" rel="nofollow">here</a>).</p>
<p>See also</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx</a></li>
</ul>
|
Differences between SVN and SVN+SSH on a Windows SVN server? <p>I'm trying to understand the differences in terms of subversion repository security between a regular svn:// and svn+ssh:// access.</p>
<p>I've setup my subversion repository in a custom port and ip address and opened that same port on the firewall, and configured the repository with access only to authenticated users.</p>
<p>From what I could understand, subversion svn:// access connects through the subversion port while svn+ssh:// connects to the ssh port to create a tunnel to the server (much like using PuTTY).</p>
<p>I assume that the use for svn+ssh is the extra added security of not having the svn port open to the world or am I missing something else?</p>
<p><b>EDIT:</b>
How is the svn+ssh:// command different than opening a PuTTY tunnel to my server and using svn://localhost/repository instead? I've read several articles on how to get subversion to get svn+ssh to work in windows but I can't make much sense of all. Opening a tunnel with PuTTY works just fine but I do have to remember to first open it before calling svn://localhost/repository.</p>
|
<p>That is right, according to the <a href="http://svnbook.red-bean.com/en/1.0/ch06s03.html" rel="nofollow">documentation</a> what the SSH version does is to create a tunnel so instead of using the svn "socket" you would be using a more secured version using the SSH protocol to comunicate between ends.</p>
<p>The difference between svn+ssh:// and creating your own tunnel with PuTTY iss the convenience of the first.</p>
|
Joins and where conditions <p>I have the following (shortened query):</p>
<pre><code>SELECT
`Statistics`.`StatisticID`,
COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`
FROM `Statistics`
LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`
WHERE `FlagCount` = 0
GROUP BY `Statistics`.`StatisticID`
ORDER BY `SubmittedTime` DESC
LIMIT 0, 10
</code></pre>
<p>Now, neither <code>FlagCount = 0</code> or <code>COUNT(Flags.FlagType)</code> work in the <code>WHERE</code> clause. I thought about using a <code>SET</code> but I'm not sure how I'd add that to the query. Any ideas?</p>
<p>Thanks,</p>
|
<p>Use <a href="http://dev.mysql.com/doc/refman/5.0/en/select.html" rel="nofollow"><code>HAVING COUNT(DISTINCT Flags.FlagType) = 0</code></a>.</p>
|
Script to add MSIUSEREALADMINDETECTION to MSI <p>Anyone have a script (JScript, VBScript or similar) in the spirit of <a href="http://blogs.msdn.com/astebner/archive/2007/05/28/2958062.aspx">this handy script</a> but adding the <a href="http://msdn.microsoft.com/en-us/library/aa816403(VS.85).aspx">MSIUSEREALADMINDETECTION</a> property</p>
<p>I know I could use Orca manually or with its transform feature, but would rather not go there.</p>
|
<p>Some refs</p>
<ul>
<li><p><a href="http://msdn.microsoft.com/en-us/library/aa368568(VS.85).aspx">Windows Installer SDK - Execute SQL Statements</a> </p></li>
<li><p><a href="http://www.koders.com/noncode/fid9C9C2D7366257C7CD2F39E21D97397EB035201BE.aspx">wirunsql.vbs</a> </p></li>
</ul>
<p>Modifying the CustomAction_NoImpersonate.js referenced in the question gives this script which can add/set any value in the Properties table.</p>
<p>Call with "cscript.exe MSI_SetProperty.js your.msi property value"</p>
<pre><code>// MSI_SetProperty.js <msi-file> <property> <value>
// Performs a post-build fixup of an msi to set the specified property (and add it if it doesn't already exist)
// Constant values from Windows Installer SDK
var msiOpenDatabaseModeTransact = 1;
var msiViewModifyInsert = 1;
var msiViewModifyUpdate = 2;
if (WScript.Arguments.Length != 3)
{
WScript.StdErr.WriteLine("Usage: " + WScript.ScriptName + "file property value");
WScript.Quit(1);
}
var filespec = WScript.Arguments(0);
var property = WScript.Arguments(1);
var value = parseInt(WScript.Arguments(2));
var installer = WScript.CreateObject("WindowsInstaller.Installer");
var database = installer.OpenDatabase(filespec, msiOpenDatabaseModeTransact);
WScript.StdOut.WriteLine("Looking for property:" + property);
try
{
var sql = "SELECT Property, Value FROM Property WHERE Property = '" + property + "'";
var view = database.OpenView(sql);
view.Execute();
var record = view.Fetch();
if (record)
{
while (record)
{
WScript.StdOut.Write("Found: " + record.StringData(0) + ", " + record.StringData(1) + ", " + record.StringData(2));
if (record.IntegerData(2) != value)
{
WScript.StdOut.WriteLine(" - changing to " + value);
record.IntegerData(2) = value;
view.Modify(msiViewModifyUpdate,record);
}
else
WScript.StdOut.WriteLine(" - OK");
record = view.Fetch();
}
}
else
{
WScript.StdOut.WriteLine("Not found, so adding");
// There may be a better way to do this?
sql = "INSERT INTO Property (Property,Value) VALUES ('" + property + "','" + value + "')";
view = database.OpenView(sql);
view.Execute();
}
view.Close();
database.Commit();
}
catch(e)
{
WScript.StdErr.WriteLine(e);
WScript.Quit(1);
}
</code></pre>
|
What are some of the drawbacks to using C-style strings? <p>I know that <a href="http://en.wikipedia.org/wiki/Buffer_overflow" rel="nofollow">buffer overruns</a> are one potential hazard to using C-style strings (char arrays). If I know my data will fit in my buffer, is it okay to use them anyway? Are there other drawbacks inherent to C-style strings that I need to be aware of?</p>
<p><strong>EDIT:</strong> Here's an example close to what I'm working on:</p>
<pre><code>char buffer[1024];
char * line = NULL;
while ((line = fgets(fp)) != NULL) { // this won't compile, but that's not the issue
// parse one line of command output here.
}
</code></pre>
<p>This code is taking data from a FILE pointer that was created using a <code>popen("df")</code> command. I'm trying to run Linux commands and parse their output to get information about the operating system. Is there anything wrong (or dangerous) with setting the buffer to some arbitrary size this way?</p>
|
<p>There are a few disadvantages to C strings:</p>
<ol>
<li>Getting the length is a relatively expensive operation.</li>
<li>No embedded nul characters are allowed.</li>
<li>The signed-ness of chars is implementation defined.</li>
<li>The character set is implementation defined.</li>
<li>The size of the char type is implementation defined.</li>
<li>Have to keep track separately of how each string is allocated and so how it must be free'd, or even if it needs to be free'd at all.</li>
<li>No way to refer to a slice of the string as another string.</li>
<li>Strings are not immutable, meaning they must be synchronized separately.</li>
<li>Strings cannot be manipulated at compile time.</li>
<li>Switch cases cannot be strings.</li>
<li>The C preprocessor does not recognize strings in expressions.</li>
<li>Cannot pass strings as template arguments (C++).</li>
</ol>
|
Must I use all tables in an Entity Framework model? <p>I am building an Entity Framework model for a subset of the Pubs database from microsoft. I am only interested and publishers and books, not publishers and employees, but there is a foreign key constraint between the publishers and emoloyees tables. When I remove the employees entity from my model, the model won't validate because of the foreign key constraint.</p>
<p>How do I create a model for a subset of a database when that subset links to other tabes with foreign key constraints?</p>
<p>Because this is for a demo, I deleted the offending tables and constraints from the database, but this won't work in production.</p>
|
<p>You could create views of the pertinent data and bind your model to that. I am not a database expert, but a DBA that I formerly worked with recommended this approach because she said that the view is less intensive on the database server to begin with.</p>
<p>Prior to the release of 3.5 SP1, we built a DAL on top of LINQ to SQL (without DBML mappings, but that is another story) that mapped all of the domain objects to either stored procedures or views. That way, the DBA was happy about the calls following a more set execution plan, as well as being able to encapsulate the database logic outside of the codebase.</p>
|
Actionscript3 to JavaScript communication: best practices <p>On a more abstract level then <a href="http://stackoverflow.com/questions/299729/javascript-to-flash-communication">a previous question</a>, in my experience there are 3 ways to call a javascript function on an html page from an embedded .swf using AS3: ExternalInterface, fscommand, and navigateToURL.</p>
<p>Let's compare and contrast these methods (and maybe others I haven't listed) and talk about the pros and cons of each - right now, ExternalInterface <em>seems</em> like the way to go in terms of flexibility, but is it right for all situations? Are there concrete benefits in terms of execution speed or anything like that? I'm curious - what do we think?</p>
|
<p>ExternalInferface was created to make communication between JS and Flash easier, so it doens't really make sense to use anything else. Common practice is to check if its available first by evaluating the value of the ExternalInterface.available property before making a call to some JS. This property tells you if the SWF in which you want to call some JS from is inside a container that offers an external interface. In otherwords, if using ExternalInterface will work. If its not available then just use flash.net.sendToUrl. Never use fscommand() as it uses VBScript and can cause conflicts with other VBScript on a page. Additionally, you can only send one argument string with fscommand and have to split it on the JS side.</p>
|
UI Useability - Reordering and merging columns <p>I'm writing a little web-based utility for my brother who needs to merge columns in a CSV file. I know things like this surely exist somewhere, but a large part of this is that is a fun little exercise.</p>
<p>Anyways, I'm trying to figure out the best/neatest way to present the part of the UI where he reorders the columns and chooses which columns get merged.</p>
<p>The jQuery UI "selectable" interaction provides about 85% of what I need - the simple reordering of the columns - but I'm having a bit of a rough time with the merging. What I'm trying to do is make it so that "merged" columns become a nested list under a single item.</p>
<p>For example:</p>
<pre><code><ul id="columns">
<li>Column 1</li>
<li>Column 2</li>
</ul>
</code></pre>
<p>would become:</p>
<pre><code><ul id="columns">
<li>Column 1<ul class="merge"><li>Column 2</li></ul></li>
</ul>
</code></pre>
<p>This is proving to be a bit more of a pain than I anticipated, so I was wondering if anyone had any ideas for a better way to present the overall UI. I'm fairly comfortable in jQuery, so bonus points if it can be done in jQuery :D</p>
<p>@dylanfm: This <em>isn't</em> tabular data - it's just a list of column <em>names</em>, but no actual data. Besides, the specific HTML element I use is hardly at the heart of what I'm asking.</p>
<p>@smo: I like the simplicity of your idea, but the problem is that there are several <em>dozen</em> different columns, so listing every column once per column would unfortunately be out of the question.</p>
<p>@strager: That's pretty much exactly what I've been trying to do, it's just that particulars of making UI respond the way I want have been giving me problems. I'll give you the answer for now, and I guess it's back to the salt mines for me.</p>
|
<p>Basic steps:</p>
<ol>
<li>Grab the list of columns to be merged as an array of <li>'s.
<ul>
<li>If you're merging two already-merged columns (or one of the colums is already merged), extract each column in the group. In your structure, you'd want to make "Column 1" have its own <li> without the child <ul>.</li>
<li>You'd probably want to clone these, as you'll be deleting the original nodes in (6).</li>
</ul></li>
<li>Create a new <ul> node, adding the proper "merged" className.</li>
<li>Add all the <li>'s you gathered in (1), except the first one, and insert them as children to the <ul>.</li>
<li>Insert the <ul> as the last child of the first <li> you gathered in (1).</li>
<li>Insert the <li> (parent in (4)) as a child of the column list ($('#columns')).</li>
<li>Delete the original columns which you were going to merge.</li>
</ol>
|
Rhino Mocks: How to return conditonal result from a mock object method <p>I would like to do something like the following but can't seem to get the syntax for the Do method quite right.</p>
<pre><code>var sqr = new _mocks.CreateRenderer<ShapeRenderer>();
Expect.Call(sqr.CanRender(null)).IgnoreArguments().Do(x =>x.GetType() == typeof(Square)).Repeat.Any();
</code></pre>
<p>So basically, I would like to set up the sqr.CanRender() method to return true if the input is of type Square and false otherwise.</p>
<p>Can someone help me out?</p>
|
<p>Are you looking for this?</p>
<pre><code>Expect.Call(sqr.CanRender(null)).IgnoreArguments()
.Do((Func<Shape, bool>) delegate(Agent x){return x.GetType() == typeof(Square);})
.Repeat.Any();
</code></pre>
<p>EDIT: The answer was correct in spirit bu the original syntax did not quite work. </p>
|
PNG Transparency with PHP <p>Hey having some trouble trying to maintain transparency on a png when i create a thumbnail from it, anyone any experience with this? any help would be great, here's what i am currently doing:</p>
<pre><code>$fileName= "../js/ajaxupload/tees/".$fileName;
list($width, $height) = getimagesize($fileName);
$newwidth = 257;
$newheight = 197;
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, true);
$source = imagecreatefrompng($fileName);
imagealphablending($source, true);
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagesavealpha($thumb, true);
imagepng($thumb,$newFilename);
</code></pre>
|
<p>I have had success doing it like this in the past:</p>
<pre><code>$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, false);
imagesavealpha($thumb, true);
$source = imagecreatefrompng($fileName);
imagealphablending($source, true);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagepng($thumb,$newFilename);
</code></pre>
<p>I found the output image quality much better using <code>imagecopyresampled()</code> than <code>imagecopyresized()</code></p>
|
asp.net CMS solution: best mechanism for storing the data in SQL <p>I've worked on a number of CMS systems using the .NET platform (the CMS management system is in ASP.NET, and the site which renders the content is both ASP.NET and PHP).</p>
<p>I've traditionally stored the generated content in classes that serialize to XML, which is stored in MSSQL 2005/2008 in a varchar(max) field. This has made it convenient structuarally for different consumers of the content to work with, and it can be bound to classes (for re-opening the CMS record and editing it, or for the consuming website).</p>
<p>However, I've been wondering what type of storage mechanism is popular with other CMS shops, and if anyone likes or has serious issue with the approach I'm most familiar with.</p>
<p>Good, bad, ugly? What would you do?</p>
|
<p>I personally treat the data as any other data that would be stored in the system, for example I have a module built for DNN that stores collection of text data, I have the following collection of columns in a table for it.</p>
<ul>
<li>EntryId</li>
<li>UpdatedBy</li>
<li>UpdatedDate</li>
<li>CreatedBy</li>
<li>CreatedDate</li>
<li>SortOrder</li>
<li>Content (NTEXT)</li>
<li>Hidden (Bit)</li>
</ul>
<p>I find that this keeps the data easy to find, and it is easy to manipulate regardless of the caller.</p>
|
Serving contextual based ads on sites built entirely in Flash? <p>What's the status of adsense (or equivalent) being able to serve contextual based ads on sites built entirely in Flash?</p>
|
<p>Check out <a href="https://www.mochiads.com/" rel="nofollow">Mochiads</a>. Adsense ish type of service for embedding into Flash applications.</p>
<p>(they're behind <a href="http://code.google.com/p/mochiweb/" rel="nofollow">mochiweb</a>, the erlang web server, which is way cool)</p>
|
How to make Eclipse prompt me for command line arguments <p>I know I can configure command line arguments in the Run configuration but I want to run a java file multiple times with different command line arguments. It's a pain to change the Run Configuration every time.</p>
<p>Is there a way I can make Eclipse prompt me for command line arguments every time I run the program?</p>
|
<p>Add <code>string_prompt</code> as a <code>Program Argument</code> in the <code>Run</code> configuration.</p>
<pre><code> ${string_prompt}
</code></pre>
<p>There are also a <code>file_prompt</code> and a <code>folder_prompt</code> if you want specifically files\folders.</p>
<p>These are available through the <code>Variables</code> button on the <code>(x)= Arguments</code> tab of the Run Configuration dialog.</p>
|
NSInvocation for Dummies? <p>How exactly does <code>NSInvocation</code> work? Is there a good introduction?</p>
<p>Iâm specifically having issues understanding how the following code (from <em>Cocoa Programming for Mac OS X, 3rd Edition</em>) works, but then also be able to apply the concepts independently of the tutorial sample. The code:</p>
<pre><code>- (void)insertObject:(Person *)p inEmployeesAtIndex:(int)index
{
NSLog(@"adding %@ to %@", p, employees);
// Add inverse of this operation to undo stack
NSUndoManager *undo = [self undoManager];
[[undo prepareWithInvocationTarget:self] removeObjectFromEmployeesAtIndex:index];
if (![undo isUndoing])
[undo setActionName:@"Insert Person"];
// Finally, add person to the array
[employees insertObject:p atIndex:index];
}
- (void)removeObjectFromEmployeesAtIndex:(int)index
{
Person *p = [employees objectAtIndex:index];
NSLog(@"removing %@ from %@", p, employees);
// Add inverse of this operation to undo stack
NSUndoManager *undo = [self undoManager];
[[undo prepareWithInvocationTarget:self] insertObject:p
inEmployeesAtIndex:index];
if (![undo isUndoing])
[undo setActionName:@"Delete Person"];
// Finally, remove person from array
[employees removeObjectAtIndex:index];
}
</code></pre>
<p>I get what itâs trying to do. (BTW, <code>employees</code> is an <code>NSArray</code> of a custom <code>Person</code> class.)</p>
<p>Being a .NET guy, I try to associate unfamiliar Obj-C and Cocoa concepts to roughly analogous .NET concepts. Is this similar to .NETâs delegate concept, but untyped? </p>
<p>This isnât 100% clear from the book, so Iâm looking for something supplemental from real Cocoa/Obj-C experts, again with the goal that I understand the fundamental concept beneath the simple(-ish) example. I'm really looking to be able to independently apply the knowledge -- up until chapter 9, I was having no difficulty doing that. But now ... </p>
<p>Thanks in advance!</p>
|
<p>According to <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSInvocation%5FClass/Reference/Reference.html">Apple's NSInvocation class reference</a>:</p>
<blockquote>
<p>An <code>NSInvocation</code> is an Objective-C message rendered static, that is, it is an action turned into an object.</p>
</blockquote>
<p>And, in a <em>little</em> more detail:</p>
<p>The concept of messages is central to the objective-c philosophy. Any time you call a method, or access a variable of some object, you are sending it a message. <code>NSInvocation</code> comes in handy when you want to send a message to an object at a different point in time, or send the same message several times. <code>NSInvocation</code> allows you to <em>describe</em> the message you are going to send, and then <em>invoke</em> it (actually send it to the target object) later on.</p>
<p><hr /></p>
<p>For example, let's say you want to add a string to an array. You would normally send the <code>addObject:</code> message as follows:</p>
<pre><code>[myArray addObject:myString];
</code></pre>
<p><hr /></p>
<p>Now, let's say you want to use <code>NSInvocation</code> to send this message at some other point in time:</p>
<p>First, you would prepare an <code>NSInvocation</code> object for use with <code>NSMutableArray</code>'s <code>addObject:</code> selector:</p>
<pre><code>NSMethodSignature * mySignature = [NSMutableArray
instanceMethodSignatureForSelector:@selector(addObject:)];
NSInvocation * myInvocation = [NSInvocation
invocationWithMethodSignature:mySignature];
</code></pre>
<p>Next, you would specify which object to send the message to:</p>
<pre><code>[myInvocation setTarget:myArray];
</code></pre>
<p>Specify the message you wish to send to that object:</p>
<pre><code>[myInvocation setSelector:@selector(addObject:)];
</code></pre>
<p>And fill in any arguments for that method:</p>
<pre><code>[myInvocation setArgument:&myString atIndex:2];
</code></pre>
<p>Note that object arguments must be passed by pointer. Thank you to <a href="http://stackoverflow.com/users/53790/ryan-mccuaig">Ryan McCuaig</a> for pointing that out, and please see <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSInvocation%5FClass/Reference/Reference.html#//apple%5Fref/occ/instm/NSInvocation/setArgument%3AatIndex%3A">Apple's documentation</a> for more details.</p>
<p>At this point, <code>myInvocation</code> is a complete object, describing a message that can be sent. To actually send the message, you would call:</p>
<pre><code>[myInvocation invoke];
</code></pre>
<p>This final step will cause the message to be sent, essentially executing <code>[myArray addObject:myString];</code>.</p>
<p>Think of it like sending an email. You open up a new email (<code>NSInvocation</code> object), fill in the address of the person (object) who you want to send it to, type in a message for the recipient (specify a <code>selector</code> and arguments), and then click "send" (call <code>invoke</code>).</p>
<p>See <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/DistrObjects/Tasks/invocations.html">Using NSInvocation</a> for more information.</p>
<p><hr /></p>
<p><code>NSUndoManager</code> uses <code>NSInvocation</code> objects so that it can <em>reverse</em> commands. Essentially, what you are doing is creating an <code>NSInvocation</code> object to say: "Hey, if you want to undo what I just did, send this message to that object, with these arguments". You give the <code>NSInvocation</code> object to the <code>NSUndoManager</code>, and it adds that object to an array of undoable actions. If the user calls "Undo", <code>NSUndoManager</code> simply looks up the most recent action in the array, and invokes the stored <code>NSInvocation</code> object to perform the necessary action.</p>
<p>See <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/UndoArchitecture/Tasks/RegisteringUndo.html">Registering Undo Operations</a> for more details.</p>
|
IE 7 not displaying a simple JS Alert? <p>Try clicking on the "Print" button on the following page:
(link removed - consensus is that everything was working fine and the problem was my setup)
For debugging purposes, I've replaced a chunk of javascript with a simple alert("test"), and even that isn't showing up in IE7 for me. It works totally fine in Safari, FF (Mac and PC) and IE6, but for some reason it's not working in IE7. For your reference, the code in the button is this:</p>
<pre><code><a onclick="makeNewWindow()" href="#"><img src="/print.gif"/></a>
</code></pre>
<p>And the JS inside /newsletter/print.js is this:</p>
<pre><code>function makeNewWindow() {
alert("test");
}
</code></pre>
<p>Can anyone help me understand if there's a way around this, or if this has something to do with the fact that I'm running "IE7 Standalone" via Parallels on my Mac? Any help is greatly appreciated.</p>
<p>Thanks,
Mike</p>
|
<p>Just tested it on IE7 Vista and it worked fine... Your code looks sound as well, so I think it might be an issue with your setup?</p>
|
Hierarchical table column in Java <p>Is there any Java library that supports hierarchical column?</p>
<p>For example (the first three row are columns) :</p>
<pre><code>------------------------------------------------
2008 |
------------------------------------------------
January | February |
------------------------------------------------
Week1 | Week2 | Week3 | Week 1 | Week2 | Week3 |
------------------------------------------------
10 | 20 | 14 | 12 | 15 | 3 |
------------------------------------------------
</code></pre>
|
<p>May be a <a href="http://javadesktop.org/swinglabs/build/weekly/latest/swingx-HEAD/javadoc/org/jdesktop/swingx/JXTree.html" rel="nofollow">JXTree</a> from <a href="https://swinglabs.dev.java.net/" rel="nofollow">SwingLab</a> could approach what you are looking for.</p>
<p>Illustration <a href="http://avatar21.superihost.com/index.php?entry=entry060514-170809" rel="nofollow">here</a>, from the <a href="https://swingx.dev.java.net/" rel="nofollow">Swingx</a> project</p>
<p><img src="http://avatar21.superihost.com/images/JXTableJXTreeTable.png" /></p>
|
Is a good idea to enable jmx (lambda probe) on a production server? <p>We are experiencing some slowdowns on our web-app deployed on a Tomcat 5.5.17 running on a Sun VM 1.5.0_06-b05 and our hosting company doesn't gives enough data to find the problem.</p>
<p>We are considering installing <a href="http://www.lambdaprobe.org">lambda probe</a> on the production server but it requires to enable jmx (com.sun.management.jmxremote) in order to obtain memory and cpu statistics.</p>
<p>Does enabling jmx incur a serious performance penalty?</p>
<p>If we enable jmx, are we opening any security flaw? Do i need to setup secure authentication if we are only enabling local acces to jmx?</p>
<p>Is anyone using the same (tomcat + lambda probe) without problems on production?</p>
<h1>UPDATE</h1>
<p>Looking at the answers it seems that enabling JMX alone doesn't incur significant overhead to the VM. The extra work may come if the monitoring application attached to the VM, be it <em>jConsole</em>, <em>lambda probe</em> or any other, is polling with excessive dedication.</p>
|
<p>You can cross out security flaws by using secure authentication. Just keeping the JMX service ready does not incur any significant overhead and is generally a good idea. There's a benchmark <a href="http://weblogs.java.net/blog/emcmanus/archive/2006/07/how_much_does_i.html">here</a> about this.</p>
|
Bad request when client call a webservice that also calls another webservice <p>I have a client application that calls a function1 on webservice1 on server1 in the local network. The webservice1 then calls another webservice2 on an remote server2.</p>
<p>If open Internet Explorer on server1 and point it to the function1 on webservice1 and run the function, everything goes fine.</p>
<p>But if I run it from the client computer I got "bad request", "protocolerror". All other webservice functions works fine from the client, only the function that itself call another function on another server got this error.</p>
<p>Is there any security context I must handle that I dont know about or anything else you can guess from what I described?</p>
<p>Client is winXP and win2003, server1 is a virtual 2003 server on a physical win2008 server.</p>
<p>Google could not help me here, I could se other with same problems but no solution.</p>
<p>When Im running in my developement setup (webservice1 and client on my computer, there are no problem)</p>
|
<p>Make sure that the anonymous access account (IUSR_blahblahblah) for your first web service is a member of a network group that has access to the second web server.</p>
|
What is your favorite Delphi open source functional testing tool? <p>I'm aware of <a href="http://selenium.openqa.org/">Selenium</a> which is a very good open source automated website testing tool.</p>
<p>Is there any equivalent open source tool to provide functional testing for Win32 GUI Delphi Applications?</p>
<p>After a quick Google I've found this one : <a href="http://code.google.com/p/eft/">EFT</a></p>
<p>So my question is what is your favourite functional testing tool and why?</p>
|
<p>I use <a href="http://dunit.sourceforge.net/" rel="nofollow">DUnit</a> for testing the internals of Delphi code. Like other xUnit tools, it is good for testing libraries and routines, but has no web functionality or GUI test support. </p>
<p>You don't say what you mean by "functional testing".</p>
<p>It looks from the question as if you are testing Desktop not web applications. With appropriate program design and reasonable amount of custom code, you could get DUNit to cover most of the code with tests - this will be easier with desktop app than with a web application, since you can use Delphi code to create a form and click buttons upon it. </p>
<p>Just remember that putting all the code in the form's button click event is not a good way to organise code. It does not separate concerns and it is harder to test.</p>
|
SRV record lookup with PHP <p>If you type</p>
<pre><code>nslookup -type=SRV _xmpp-server._tcp.gmail.com
</code></pre>
<p>(or use the dig command in OSX) you get some SRV records relating to google chat</p>
<p>I would like to replicate this functionality in PHP, does anyone have any good ideas how to do this?</p>
<p>I would like to avoid using exec() as this does not return 100% standard responses across OSX/*NIX/WINDOWS</p>
<p>Thanks!</p>
|
<p>You could use <a href="http://pear.php.net/package/Net_DNS" rel="nofollow">Pear Net_DNS</a>. I managed to get this to work on Linux, but haven't tested it on Windows or any others:</p>
<pre><code>require_once('Net/DNS.php');
$resolver = new Net_DNS_Resolver();
$response = $resolver->query('_xmpp-server._tcp.gmail.com', 'SRV');
if ($response) {
foreach ($response->answer as $rr) {
$rr->display();
}
}
</code></pre>
<p>I modified the example from their documentation. hope this helps</p>
|
Why does regex "[^<]*<\\?" exhibit exponential time when the text doesn't have a "<"? <p>Using ICU 4.0 regex library, I find that the following regex is exhibiting exponential time:</p>
<pre><code>actual: "[^<]*<\?"
C code: "[^<]*<\\?"
</code></pre>
<p>Aim: find "<?" where there is no other "<" before it</p>
<p>When running this regex on plain text with no "<" characters at all it appears to take exponential time. If the text has at least a single "<" then it is quick. I don't understand why. </p>
<p>Shouldn't the required match on "<?" prevent this from needing to backtrack? I would have thought that it would try to find the first "<" and then test the rest of the expression. If it can't find a "<" then it would give up because the pattern obviously can't match.</p>
<p>Is this a bug in the ICU regex or is it expected?</p>
|
<p>You will find an explanation at <a href="http://swtch.com/~rsc/regexp/regexp1.html" rel="nofollow" title="Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby, ...)">Regular Expression Matching Can Be Simple And Fast</a>.<br />
As MizardX said, if the match fails at position 0, the engine will try again at position 1, 2, etc. If the text is long, be ready to wait for quite some time...</p>
<p>The solution is to anchor your expression: <code>"^[^<]*<\?"</code></p>
|
Can I add an attribute to a function to prevent reentry? <p>At the moment, I have some functions which look like this:</p>
<pre><code>private bool inFunction1 = false;
public void function1()
{
if (inFunction1) return;
inFunction1 = true;
// do stuff which might cause function1 to get called
...
inFunction1 = false;
}
</code></pre>
<p>I'd like to be able to declare them like this:</p>
<pre><code>[NoReEntry]
public void function1()
{
// do stuff which might cause function1 to get called
...
}
</code></pre>
<p>Is there an attribute I can add to a function to prevent reentry? If not, how would I go about making one? I've heard about AOP attributes that can be used to add code before and after function calls; would they be suitable?</p>
|
<p>Instead of using a bool and setting it directly, try using a long and the Interlocked class:</p>
<pre><code>long m_InFunction=0;
if(Interlocked.CompareExchange(ref m_InFunction,1,0)==0)
{
// We're not in the function
try
{
}
finally
{
m_InFunction=0;
}
}
else
{
// We're already in the function
}
</code></pre>
<p>This will make the check thread safe.</p>
|
How to convert std::string to lower case? <p>I want to convert a <code>std::string</code> to lowercase. I am aware of the function <code>tolower()</code>, however in the past I have had issues with this function and it is hardly ideal anyway as use with a string would require iterating over each character.</p>
<p>Is there an alternative which works 100% of the time?</p>
|
<p>From <a href="http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/">http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/</a>:</p>
<pre><code>#include <algorithm>
#include <string>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
</code></pre>
<p>You're really not going to get away with not iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.</p>
<p>If you really hate tolower(), here's a non-portable alternative that I don't recommend you use:</p>
<pre><code>char easytolower(char in){
if(in<='Z' && in>='A')
return in-('Z'-'z');
return in;
}
std::transform(data.begin(), data.end(), data.begin(), easytolower);
</code></pre>
<p>Be aware that <code>::tolower()</code> can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.</p>
|
.NET/IIS friendly in-memory antivirus scanning <p>I'm looking for a solution that would let me scan files on the fly. It would need to integrate nicely with either with IIS(6.0 or 7.0) or ASP.NET. I spent some time trying to find something on the Internet but unfortunately all I've found is a COM based solution that still forces me to save files on disk (<a href="http://www.opswat.com/metascan.shtml" rel="nofollow">http://www.opswat.com/metascan.shtml</a>)
Update:
The solution needs to be hosted internally. </p>
<p>Thanks</p>
<p>Pawel</p>
|
<p>We use <a href="http://www.sophos.com/products/enterprise/email/security-and-control/integration/" rel="nofollow">Sophos Anti-Virus Interface</a> (SAVI), an in-process COM-based solution which you can access using COM interop, which does support in-memory scanning.</p>
|
Something better than .ToArray() to force enumeration of LINQ output <p>I'm working with LINQ to objects and have a function where in some cases I need to modify the underlying collection before calling <code>Aggregate(...)</code> and then return it to its original state before the funciton returns the results of <code>Aggregate(...)</code>. My current code looks something like this:</p>
<pre><code>bool collectionModified = false;
if(collectionNeedsModification)
{
modifyCollection();
collectionModified = true;
}
var aggregationResult = from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue;
if(collectionModified)
modifyCollection();
return aggregationResult;
</code></pre>
<p>However, as written, if I modify the collection, I will get the wrong result because I'm putting the collection back in its original state before <code>aggregationResult</code> is enumerated and LINQ results are lazy-evaluated. My current solution is to use <code>.ToArray()</code> on my LINQ query like this:</p>
<pre><code>var aggregationResult = (from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue).ToArray();
</code></pre>
<p>The size of the resulting array will always be small (< 100 items) so memory / processing time is not a concern. Is this the best way to handle my problem, or is there a better way to force the evaluation of a LINQ query?</p>
|
<p>Just to check I understand you - you basically want to iterate through all of the results, just to force any side effects to take place?</p>
<p>Side effects are generally a bad idea precisely because things are harder to understand with this kind of logic. Having said that, the easiest way to do it and force full evaluation is probably to just iterate through it:</p>
<pre><code>foreach (var result in aggregationResult)
{
// Deliberately empty; simply forcing evaluation of the sequence.
}
</code></pre>
<p>Alternatively you could use <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.lastordefault.aspx" rel="nofollow">LastOrDefault()</a> to avoid all the copying involved in ToArray(). <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.count.aspx" rel="nofollow">Count()</a> will be okay so long as the result doesn't implement <code>IList<T></code> (which involves a short-cut).</p>
|
How do you internationalise text in the database? <p>Having a fully internationalised application is a necessity if you want to sell worldwide.
In Java we're using resource bundles and that solves things for static text codeside.</p>
<p>But what do you do about text that is stored in the database? Starting with static definitions, to user modifiable objects, ending with user entered data.</p>
<p>Assuming you have a database used by users with different Locales - how do you handle this? How far do you internationalise? Where do you draw the line?
What workaround can keep users from receiving text in a language they don't understand?</p>
|
<p>Don't store system generated text in the database. Instead, store a code (like a message number) and then internationalize it at the GUI level. Make sure that the only text that comes directly out of the database is text that the user put in themselves. Make sure your database is set to accept unicode text.</p>
|
How can I set the program name for sybase connections in jdbc? <p>I can do it in C, and I can do it in perl, but I don't see how to set the program name on sybase connections using jdbc?</p>
|
<p>I eventually found it here: <a href="http://www.sybase.com/detail?id=1009812" rel="nofollow">http://www.sybase.com/detail?id=1009812</a>
"APPLICATIONNAME" is a property you can pass in the list of properties to the connect() function.</p>
|
Best practices for maintaining shared hosting websites with ASP.NET and SQL Server? <p>I've been doing PHP/MySQL websites with shared hosting providers for the last couple years. The day-to-day process is basically:</p>
<ul>
<li>develop in Eclipse, one website per folder</li>
<li>upload via FileZilla, one website per folder</li>
<li>use PHPMyAdmin to create and manage your local and online databases and transfer data from one to another</li>
<li>to backup the online database I do dump of the database tables into script and copy them locally</li>
</ul>
<p><strong>I now want to build websites with ASP.NET with SQL Server 2008</strong> on shared hosting providers, and am trying to get into this new paradigm, hopefully some of you can give me some pointers based on your experience and tell me what I am not doing optimally:</p>
<ul>
<li>I've installed both the Visual Web Developer 2008 Express as well as the full version of Visual Studio 2008, both seem to be full-featured tools for developing ASP.NET sites. <strong>In terms of websites at shared hosting providers, what can you do with the full version that you can't do with the express version?</strong></li>
<li>I use FileZilla to upload my sites, which seems to work fine. <strong>Do you use an external FTP program to upload your sites or do you use the "Publish" or "FTP Website" in the above IDEs?</strong></li>
<li>I installed SQL Server 2008 Management Studio and can now issue SQL commands to my online SQL Server database (although I strangely can't see my database in the list on the left, I can still access it, I assume this is some rights issue with my provider, www.domainbox.de, but this provider told me to use their online manager instead, which is called "ASP.NET Enterprise Manager" which is extremely simple but at least has a "Query Box" which allows me to send queries to my database.) <strong>Is this "ASP.NET Enterprise Manager" standard with ASP.NET hosters or is there something else that is better, e.g. where you could edit your data in the grid, etc.?</strong> And I assume that with most providers you are able to manage your online SQL Server database with SQL Server Management Studio, is that correct? (I remember back in 2001 managing online SQL Server 2000 database at a shared hosting provider with Enterprise Manager and it would take literally 10 minutes for me to see my database on the left because it listed out the other 800 customer databases as well -- hopefully this has been solved by now).</li>
<li><strong>How do you backup your data in your online database to local storage?</strong> (currently I would have to write code that output my data to some other format, e.g. XML or SQL Script)</li>
<li>And after you make a number of structural and data changes to your local database, <strong>how do you transfer those changes and the new data to your online database?</strong> (I had to install SSMS Tools [<a href="http://www.ssmstoolspack.com" rel="nofollow">http://www.ssmstoolspack.com</a>] to be able to dump my data into a script so that I could get it back into my online database).</li>
</ul>
<p>So, although I've gotten most things to work, I feel like there must be better ways to go about this, better providers, better tools, etc. <strong>Would like to hear some "best practices" advice from anyone who works with ASP.NET, SQL Server and shared hosting.</strong></p>
|
<p>For the most part, what you're doing now will work with an asp.net website.</p>
<p>For your development environment, I don't think you will be limited by using Visual Web Developer 2008 express for what you want to do. Here is a microsoft page that compares every version of visual studio 2008, including Visual Web Developer 2008 Express: <a href="http://msdn.microsoft.com/en-us/vstudio/products/cc149003.aspx" rel="nofollow">Visual Studio 2008 Product Comparison</a></p>
<p>For deploying your website over the net, I would generall stick to deploying manually. You can use some of the automated stuff in visual studio, but your deployment will tend to be a little slower. After compiling your application, it will then delete every file in your destination website, and upload everying from scratch (uncompressed I think). Your whole site will be down while this happens. When you deploy manually you can upload just the changed files, or everything in a compressed format.</p>
<p>Regarding the SQL server, many shared hosting services will let you connect with some sort of local SQL management tool. However, connecting this way generally uses a lot of bandwidth so they throttle the allowed bandwidth for this way down. This is probably the performance issues you previously saw. If you can get by with it, I would use their hosted SQL tools for most of your work, but then use the management studio for anything it can't handle.</p>
<p>For backing up your SQL server, if your host doesn't have a way for you to perform an automatic backup then you will have to do something yourself. I would first check to see if they will allow you to at least run a SQL backup command. This will generate a .bak file of your database, but on the local database server. Most places will work with you on this, since many customers need this.</p>
<p>For applying changes to your database, your best bet is to script all of the changes into one sql script and run it using the remote SQL management tool. These aren't hard to write, and there are a few tools out there that will help you with it. I personally like to use Visio. It lets me compare two databases (local and remote) then generate a script to apply to the remote one with all the changes.</p>
<p>Good luck</p>
|
how to (simply) generate POST http request from java to do the file upload <p>I would like to upload files from java application/applet using POST http event. I would like to avoid to use any library not included in SE, unless there is no other (feasible) option. <br>
So far I come up only with very simple solution. <br>
- Create String (Buffer) and fill it with compatible header (<a href="http://www.ietf.org/rfc/rfc1867.txt" rel="nofollow">http://www.ietf.org/rfc/rfc1867.txt</a>)<br>
- Open connection to server URL.openConnection() and write content of this file to OutputStream. <br>
I also need to manually convert binary file into POST event. <br><br>
I hope there is some better, simpler way to do this?</p>
|
<p>You need to use the <code>java.net.URL</code> and <code>java.net.URLConnection</code> classes.</p>
<p>There are some good examples at <a href="http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html" rel="nofollow">http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html</a></p>
<p>Here's some quick and nasty code:</p>
<pre><code>public void post(String url) throws Exception {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.setDoOutput(true);
if (c instanceof HttpURLConnection) {
((HttpURLConnection)c).setRequestMethod("POST");
}
OutputStreamWriter out = new OutputStreamWriter(
c.getOutputStream());
// output your data here
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
c.getInputStream()));
String s = null;
while ((s = in.readLine()) != null) {
System.out.println(s);
}
in.close();
}
</code></pre>
<p>Note that you may still need to urlencode() your POST data before writing it to the connection.</p>
|
When are API methods marked "deprecated" actually going to go away? <p>I'm code reviewing a change one of my co-workers just did, and he added a bunch of calls to Date.toMonth(), Date.toYear() and other deprecated Date methods. All these methods were deprecated in JDK 1.1, but he insists that it's ok to use them because they haven't gone away yet (we're using JDK 1.5) and I'm saying they might go away any day now and he should use Calendar methods. Has Sun actually said when these things are going away, or does "@deprecated" just mean you lose style points?</p>
|
<p>Regarding the APIs, ... it is not specified they will be removed anytime soon.</p>
<p><a href="http://java.sun.com/j2se/1.5.0/compatibility.html">Incompatibilities in J2SE 5.0 (since 1.4.2)</a>:</p>
<p>Source Compatibility</p>
<blockquote>
<p>[...]<br />
In general, the policy is as follows, except for any incompatibilities listed further below: </p>
<p>Deprecated APIs are interfaces that are supported only for backwards compatibility. The javac compiler generates a warning message whenever one of these is used, unless the -nowarn command-line option is used. It is recommended that programs be modified to eliminate the use of deprecated APIs, <strong>though there are no current plans to remove such APIs</strong> â with the exception of JVMDI and JVMPI â entirely from the system.</p>
</blockquote>
<p>Even in its <a href="http://java.sun.com/javase/6/docs/technotes/guides/javadoc/deprecation/deprecation.html">How and When To Deprecate APIs</a>, nothing is being said about a policy regarding actually <em>removing</em> the deprected APIs...</p>
|
Windows domain changed cause sql2005 login fail <p>My company change the domain from abc to xyz and now i can't log into my local sql2005 via Windows login nor sql login.</p>
<p>both login gave me this error: An error has occured while establishing a connection to the server. blah blah blah...Sql server does not allow remote connection. Error:26 - Error locating Server/Instance specified.</p>
<p>i check the server instance is running. i can understand the windows login fail but how can sql login fail as well? does anyone know how to fix this?</p>
|
<p>It's weird but i find the solution. I select the database that i want to connect to which is the same instance on the login screen then using the sql authentication. i was able to login in. It turn out the my work station was renamed. that's why it can't find the server instance.</p>
|
How do I perform a Unit Test using threads? <p><b>Executive Summary:</b> When assertion errors are thrown in the threads, the unit test doesn't die. This makes sense, since one thread shouldn't be allowed to crash another thread. The question is how do I either 1) make the whole test fail when the first of the helper threads crashes or 2) loop through and determine the state of each thread after they have all completed (see code below). One way of doing the latter is by having a per thread status variable, e.g., "boolean[] statuses" and have "statuses[i] == false" mean that the thread failed (this could be extended to capture more information). However, that is not what I want: I want it to fail just like any other unit test when the assertion errors are thrown. Is this even possible? Is it desirable?</p>
<p>I got bored and I decided to spawn a bunch of threads in my unit test and then have them call a service method, just for the heck of it. The code looks approximately like:</p>
<pre><code>Thread[] threads = new Thread[MAX_THREADS];
for( int i = 0; i < threads.length; i++ ) {
threads[i] = new Thread( new Runnable() {
private final int ID = threadIdSequenceNumber++;
public void run() {
try {
resultRefs[ID] = runTest( Integer.toString( ID ) ); // returns an object
}
catch( Throwable t ) {
// this code is EVIL - it catches even
// Errors - don't copy it - more on this below
final String message = "error testing thread with id => "
+ ID;
logger.debug( message, t );
throw new IllegalStateException( message, t );
// need to wrap throwable in a
// run time exception so it will compile
}
}
} );
}
</code></pre>
<p>After this, we will loop through the array of threads and start each one. After that we will wait for them all to finish. Finally, we will perform some checks on the result references.</p>
<pre><code>for( Thread thread : threads )
thread.start();
logger.debug( "waiting for threads to finish ..." );
boolean done = false;
while( !done ) {
done = true;
for( Thread thread : threads )
if( thread.isAlive() )
done = false;
}
for( int i = 0; i < resultRefs.length; i++ ) {
assertTrue( "you've got the world messed, dawg!",
myCondition(resultRefs[i]) );
</code></pre>
<p>Here's the problem. Did you notice that nasty try-catch-throwable block? I just added that as a temporary hack so I could see what was going on. In runTest( String ) a few assertions are made, e.g., assertNotNull( null ), but since it is in a different thread, it doesn't cause the unit test to fail!!!!</p>
<p>My guess is that we will need to somehow iterate over the threads array, check the status of each, and manually cause an assertion error if the thread terminated in a nasty way. What's the name of the method that gives this information (the stack trace of the dead thread).</p>
|
<p>Concurrency is one of those things that are very difficult to unit test. If you are just trying to test that the code inside each thread is doing what it is supposed to test, may be you should just test this code isolated of the context.
If in this example the threads collaborate to reach a result, may be you can test that collaboration without using threads. That would be done by executing all the collaborative parts sequentially.
If you want to test for race conditions and these kind of things, unit testing is not the best way. You will get tests that sometimes fail and sometimes don´t fail.
To summarize, I think that may be your problem is that you are unit testing in a level too high.
Hope this helps</p>
|
Why doesn't this generic interface stack work? <p>I have a bunch of generic interfaces and classes</p>
<pre><code>public interface IElement {
// omited
}
class Element implements IElement {
// omited
}
public interface IElementList<E extends IElement> extends Iterable {
public Iterator<E> iterator();
}
class ElementList implements IElementList<Element> {
public Iterator<Element> iterator() {
// omited
}
}
public interface IElementListGroup<E extends IElementList<? extends IElement>> {
public E getChosenElementList();
}
class ElementListGroup implements IElementListGroup<ElementList> {
public ElementList getChosenElementList() {
// omited
}
}
</code></pre>
<p>And then a simple code</p>
<pre><code>ElementListGroup group;
for(Element e : group.getChosenElementList())
{
// omited
}
</code></pre>
<p>And the line with for keyword throwe a "cannot convert from element type Object to Element" compiler error.</p>
<p>Thanks in advance.</p>
|
<p><code>IElementList</code> needs to implement <code>Iterable<E></code>. Otherwise, the interface specifies <code>Iterator iterator()</code>, not <code>Iterator<E> iterator()</code>. This makes the compiler think that you're iterating over <code>Object</code>s.</p>
<p>I made this change, and it compiled fine (after adding some null returns).</p>
|
Flash Media Server/PHP Application <p>I need help finding resources that would help me or at least point me in the right direction in building a Flash media server/PHP application. I basically want to improve my current application by instead of progressive download using flash media server so that the videos will not only stream well but they can't be downloaded by the end user.</p>
<p>What the current application does is show a login form on the homepage and then when logged in the user can then navigate the site by choosing videos from a particular video category or video uploaded by a specific user. All this is done with PHP. The video page uses progressive download to display the video after the video ID has been passed using PHP.</p>
<p>I need to know how PHP and flash media server work together. Are there any resources out there where I can find a good application example (really simple) that demonstrates how PHP and flash media server can be used to stream videos dynamically such that PHP checks for the login, video ID, video channels, and video category information while the flash media server streams the video.</p>
|
<p>Really, PHP and FMS shouldn't be talking at all. It can be done within FMS, but a much easier approach is to let your Flash Player (which you'll have to have anyway) do the talking to FMS. Flash to FMS communication is well documented and very easy. Just have the PHP call forth a Flash video player with whatever info you need. It would probably be eaiser to have PHP authenticate and give the Flash some sort of authentication token if you're really worried about security.</p>
<p>Just so you know though, just because your media is streaming doesn't mean someone can't download it. There's several tools to rip streamed media out there. It is of course <em>more</em> secure, but it's not full-proof.</p>
|
Is there a way to expand the code window in VS.NET to maximum size? <p>In Eclipse you can double-click on the tab of the code window and expand it to full size, e.g. if you will be working on just the code awhile and want maximum size on a smaller monitor, etc.</p>
<p>Is there a way to expand the code window in Visual Studio.NET in one click (otherwise I have to collapse Toolbox, Solution Explorer, Properties, etc.)</p>
|
<p>Shift+Alt+Enter takes you to full screen mode, which hides most panes. The only two I had were a close window history and my pending check-ins, but for the most part this works well.</p>
|
Best way to define true, false, unset state <p>If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.</p>
<p>What's the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?</p>
|
<pre><code>Boolean a = true;
Boolean b = false;
Boolean c = null;
</code></pre>
<p>I would use that. It's the most straight-forward.</p>
<p>Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:</p>
<pre><code>public enum ThreeState {
TRUE,
FALSE,
TRALSE
};
</code></pre>
<p>There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass <code>true</code> and <code>false</code>. If you don't like the <code>null</code>, since it's telling rather little about its meaning here, you can still make a <code>public static final Boolean tralse = null;</code> in your class.</p>
|
Do all WPF render transforms run in double-precision? <p>WPF stores all its data in double precision. I just want to confirm that all transforms, etc., run in double precision. </p>
<p>I'm working on a WPF canvas, which is very large (40,000,000 x 40,000,000), translating and scaling to zoom into it - placing tiles on to it that contain satellite imagery. To scale and translate I'm using a TransformGroup, containing a ScaleTransform and TranslateTransform.</p>
<p>When zoomed in close, the tiles seem to wobble about as you slightly adjust the scaletransform, as if their location on the canvas is slightly changing, even though all I'm changing is the scaletransform. I'm worried that the transforms aren't being done in double-precision, but are being shipped to the hardware and done in single-precision.</p>
<p>Is there any way to control the precision of render transforms? Or at least confirm that it's using double-precision and not single-precision? </p>
<p>Thanks.</p>
|
<p>some time ago, I noticed the exact same thing: rendered bitmaps will be severely distorted when using extreme transforms. Some tests I did back then convinced me that WPF does indeed forward transforms to the GPU, which then uses single-precision processing instead of double-precision.</p>
<p>The only workaround I found is to simplify the transforms. For instance, rather than giving an image a size of 100,000 by 100,000 units and a scale factor of 0.0001, give it a size of 1 unit and a scale factor of 10. The same thing goes for translation.</p>
<p>Depending on your design, this may mean that your layout logic will become a good deal more complex, as you will have to do some calculations manually that WPF will otherwise do for you. For an application allowing for a large range of zoom levels (such as from a view of the entire earth down to a single building), there just seems to be no other way.</p>
|
How to study design patterns? <p>I have read around 4-5 books on design patterns, but still I dont feel I have come closer to intermediate level in design patterns?</p>
<p>How should I go studying design patterns?</p>
<p>Is there any best book for design pattern?</p>
<p>I know this will come only with experience but there must be some way to master these?</p>
|
<p>I read three books and still did not understand patterns very well until I read <a href="http://oreilly.com/catalog/9780596007126/">Head First Design Patterns</a> by OReilly. This book opened my eyes and really explained well.</p>
<p><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR9ohzNKE8bWdqrgYAeEwkdvJp1AKc8OpX3WazG-jDQ6bdbC9i_" alt="alt text"></p>
|
Is it possible to use BindingSource.find on multple columns? <p>Is it possible to use BindingSource.find on multple columns?</p>
<p>I have a treeview and a combobox. The combobox provides the ID that is used to build the treeview. When I select a node in the tree view I want to display the details/child information for the ID from the combobox and the tag/ID value from the tree Node. </p>
<p>What is the best way to do this? I was trying to use controls bound to a binding source. I want to change the position of the binding source, but I need to search the binding source for the value from the combo as well as the tree node I just selected?????</p>
|
<p>I don't know if it is the best way to do what I was trying to accomplish, but BindingSource.Filter method works great for my scenario.</p>
|
Model-View-Presenter and Modal Dialog boxes.... How to? <p>I am implementing MVP/M-V-VM in WPF and I'm having good luck with it so far. However, I don't see how this model supports implementing Modal dialog boxes. I've derived my work from Crack.NET (<a href="http://www.codeplex.com/cracknetproject" rel="nofollow">http://www.codeplex.com/cracknetproject</a>) to learn how this stuff works.</p>
<p>I have a ShellView view (which is just XAML) that has a menu on it. The menu binds to a command in the ShellModelView that says "EditPreferences".</p>
<p>The ShellModelView implements the ICommand for EditPreferences and here we want to put up a dialog box to let the user edit preferences for the application. </p>
<p>Several problems here:
1. The ShellModelView doesn't have a reference to the ShellView to properly parent the dialog. The ShellModelView is the DataContext of the ShellView but I don't see a backreference that's setup.
2. The ShellModelView shouldn't be loading explicit UI anyway. So what's the proper interaction model here?
3. How do I build up my PreferencesDialog so that it's properly separated between logic and view as well? PreferencesDialog itself needs to be a Window so you can call ShowDialog on it, but that means you need a reference to the Window (e.g. View) in order to instantiate it. Ideally I should be able to unit test the code/validation within PreferencesDialog without instantiating the view (using a Mock view perhaps?).</p>
|
<p>Perhaps this is not the appropriate way to look at it, but this is the approach I take with M-V-VM in WPF. Opening windows and dialog boxes or an "EditPreferences" view are UI specific functions. If I were to rewrite the your entire UI replacing all of the views, I may wind up combining the "EditPreferences" view with another view, and therefore never want to open it in another screen. If this were tied to the ViewModel, it would be difficult to get around. In this particular situation, I would have a button or menu item in my "ShellView" that creates a new instance of my "EditPreferences" view, and then passes in the "EditPreferences" ViewModel which may either come from a property in my "ShellViewModel", or perhaps my "EditPreferences" view instantiates the ViewModel itself.</p>
<p>Here is a similar question on SO that basically says the same thing: <a href="http://stackoverflow.com/questions/303006/m-v-vm-design-question-calling-view-from-viewmodel#306902">M-V-VM Design Question. Calling View from ViewModel</a></p>
|
Unable to debug WCF service message <p>I've got a Visual Studio 2008 solution with a WCF service, and a client.</p>
<p>When I run my client, and call a method from my service I get a message saying "Unable to automatically debug 'Home.Service'. The remote procedure could not be debugged. This usually indicates that debugging has not been enabled on the server."</p>
<p>I've googled around, and have tried the following.</p>
<pre><code><system.web>
<compilation debug="true" />
</system.web>
</code></pre>
<p>has been added in app.config on both the client and the server.</p>
<p>I have also made sure that the project is being compiled in Debug mode.</p>
<p>What else could be causing this message?</p>
<p>Edit: Added more info based on feedback questions</p>
<ul>
<li>It is using wsHttpBinding</li>
<li><p>I have set</p>
<pre><code><serviceDebug includeExceptionDetailInFaults="true"/>
</code></pre></li>
<li><p>I am using</p>
<pre><code>var service = new HomeReference.HomeServiceClient();
service.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
</code></pre></li>
</ul>
<p>Unfortunately the error shows up the first time I call a method on my Service. I can dismiss the messagebox, and the application continues working. Any Exceptions thrown on the server at not propagated back to the client though (I assume it should?)</p>
|
<p>I was fighting with this exact same error for over an hour and low and behold I restarted VS2008 and it magically fixed itself. Give it a try as it might save you some time.</p>
|
Multi-lingual projects in Visual Studio <p>Would anyone know if there are plans or extensions to Visual Studio to allow for multi-lingual projects?</p>
<p>While the .NET platform is truly polyglot, Visual Studio project are stubbornly monoglot which means that all the work that goes into tooling C# and VB is unusable from newer languages like F# and IronPython.</p>
<p>PEX is an example of a great extension to Visual Studio that simply doesn't work in F#.</p>
<p>Wasn't there a module system built into .NET specifically to enable ployglot compilation?</p>
<p>regards,</p>
<p>Danny</p>
|
<p>I work at Microsoft on the F# team and .NET Libraries like PEX should be fully interoperable with F# modulo bugs, so if you are blocked by something please send the issue to fsbugs@microsoft.com.</p>
<p>It is possible to produce multi-language assemblies in .NET, using a concept called netmodules: <a href="http://blogs.msdn.com/junfeng/archive/2005/02/12/371683.aspx" rel="nofollow">http://blogs.msdn.com/junfeng/archive/2005/02/12/371683.aspx</a>. Unfortunately I don't know if F# supports this (I doubt it.)</p>
<p>As for getting tooling support for polyglot development, there are currently no plans to enable that within Visual Studio. However, please consider providing mentioning this on <a href="http://connect.microsoft.com/VisualStudio" rel="nofollow">http://connect.microsoft.com/VisualStudio</a>. The people who drive features for future releases take feedback on that site into consideration, especially if it gets a lot of traction in the .NET community.</p>
<p>But for the time being I recommend you use F# for what it is good at - algorithmic development, exploring data, etc. And use C#/VB for the presentation layer.</p>
|
Audit trails and implementing SOX/HIPAA/etc, best practices for sensitive data <p>I consider myself to be relatively proficient in terms of application design, but I've never had to work with sensitive data. I've been wondering about what the best practices were for audit trails and how exactly one should implement them. I don't have to do it right now, but it'd be nice to be able to confidently talk with a medical company if they ask me to do some work for them.</p>
<p>Let's say we have a "school" database, with 'teachers', 'classes', 'students' all normalized in a many-to-many 'grades' table. What would you log? Every insert/update on the 'grades table'? Only updates (say, a kid breaks in and wants to change grades, this should send up redflags)? Does this vary entirely based on how paranoid one wants to be? Is there a best practice?</p>
<p>Is this something that should be done in the database? (A trigger on each sensitive SELECT which inserts a row to an 'audit' table logging each query?) What should be logged? Is there functionality automatically built into Oracle/DB2 that do it for you? Should this be application side logic?</p>
<p>If anyone has any formal documentation/books on how to deal with sensitive data (not quite DoD "Trusted Computing" spec, but something along the lines of that :P), I'd appreciate it. I'm sorry if this question is terribly vague. I realize that this varies from application to application. I just want to hear your detailed experiences with dealing with sensitive data.</p>
|
<p>The first thing to understand is the native auditing capabilities of your chosen DBMS. These vary in detail, but generally provide a way to configure which operations are audited, and provide secure storage for the audit records that they generate.</p>
<p>The next thing to understand is what you want to audit. In the case of HIPAA and SOX, for example, you are probably looking at PII - Personal Identifying Information. Remember the fuss made about people accessing Obama's phone records, or various celebrities medical records, or ... Those were caught because the system audited who read those records, and the audit analysis officer (AAO) spotted that the celebrity records were accessed by people who were not specifically authorized to do so. So, those systems must be logging who accesses each record, and spotting when the user who does so does not have an authentic business reason to do so. In these cases, it appears that the users had read authority for the records, so if their ordinary duties required them to look at the records, they could do so. But, when they were not required to do so, then they were abusing their power and appropriately sanctioned (up to and including losing jobs over it).</p>
<p>What this means is that you probably don't want to track who accesses the table of States which records the state code and full name (and assorted other bits of information about the state). There is nothing confidential about that list - it doesn't matter who reads it. Of course, almost no-one should write to it; the list of states does not change very often - but that can probably be handled by revoking update and delete permission on the table from everyone.</p>
<p>OTOH, you probably do want to record who accesses the records in medical histories (HIPAA), or who modifies the data in the accounting systems (SOX). You might or might not need to worry about who reads the accounting data; a lot of that can be dealt with by basic permissions (accounting staff have permission; IT staff do not). However, auditing is always an extra line of defense.</p>
<p>Bear in mind that audit records are no help whatsoever if they are never looked at. In general, auditing slows a system down (simply because it is doing more work when it writes audit records); it is important to understand how much it slows down before deciding to implement your auditing strategy. However, there are some things that are more important than application speeed, and one of those is keeping yourself and other staff members out of jail. Auditing can be necessary to ensure that happens.</p>
|
Practical non-Turing-complete languages? <p>Nearly all programming languages used are <a href="http://en.wikipedia.org/wiki/Turing_Complete">Turing Complete</a>, and while this affords the language to represent any <a href="http://en.wikipedia.org/wiki/Computability_theory_(computer_science)">computable</a> algorithm, it also comes with its own set of <a href="http://en.wikipedia.org/wiki/Halting_problem">problems</a>. Seeing as all the algorithms I write are intended to halt, I would like to be able to represent them in a language that guarantees they will halt.</p>
<p><a href="http://en.wikipedia.org/wiki/Regular_Expression">Regular expressions</a> used for matching strings and <a href="http://en.wikipedia.org/wiki/Finite_state_machine">finite state machines</a> are used when <a href="http://en.wikipedia.org/wiki/Lexing">lexing</a>, but I'm wondering if there's a more general, broadly language that's not Turing complete?</p>
<p><strong>edit:</strong> I should clarify, by 'general purpose' I don't necessarily want to be able to write all halting algorithms in the language (I don't think that such a language would exist) but I suspect that there are common threads in halting proofs that can be generalized to produce a language in which all algorithms are guaranteed to halt.</p>
<p>There's also another way to tackle this problem - eliminate the need for theoretically infinite memory. Once you limit the amount of memory the machine is allowed, the number of states the machine is in is finite and countable, and therefore you can determine if the algorithm will halt (by not allowing the machine to move into a state it's been in before).</p>
|
<p>Don't listen to the naysayers. There are very good reasons one might prefer a non-Turing complete language in some contexts, if you want to guarantee termination, or simplify code, for example by removing the possibility of runtime errors. Sometimes, just ignoring things may not be sufficient. </p>
<p>The paper <a href="http://www.jucs.org/jucs_10_7/total_functional_programming/jucs_10_07_0751_0768_turner.pdf">Total Functional Programming</a> argues more or less persuasively that in fact we should almost always prefer such a restricted language because the compiler's guarantees are so much stronger. Being able to prove a program halts can be significant in and of itself, but really this is the product of the much easier reasoning that the simpler languages afford. As one component in a hierarchy of languages of varying capability, the range of utility of non-universal languages is quite broad.</p>
<p>Another system that addresses this layering concept much more fully is <a href="http://www-fp.cs.st-andrews.ac.uk/hume/index.shtml">Hume</a>. The <a href="http://www-fp.cs.st-andrews.ac.uk/hume/report/hume-report.pdf">Hume Report</a> gives a full description of the system and its five layers of progressively more complete, and progressively less safe, languages.</p>
<p>And finally, don't forget <a href="http://pll.cpsc.ucalgary.ca/charity1/www/home.html">Charity</a>. It's a bit abstract, but it is also a very interesting approach to a useful but not universal programming language, which is based very directly on concepts from category theory.</p>
|
Is it advisable to use arrays in Javascript using tens of thousands of indexes? <p>Is it advisable to use arrays in Javascript using tens of thousands of indexes?</p>
<p>I have a database which contains a table of static data, meaning that it will never change. In this case would it be advisable to convert this table to a javascript array and look the info up in there when needed? Is this bad practice?</p>
<p>The table in question contains roughly 40,000 key/value pair entries.</p>
|
<p>No.</p>
<p>I'd keep the table, as its a single point of maintenance.</p>
<p>You'll find that doing a XmlHTTPRequest to return a key/value pair based on a server side query, would actually perform faster, and have significantly less memory footprint than a huge JavaScript array.</p>
|
WPF: Adding a Trigger to a Button <p>I am currently coding a program with a WPF UI and I have a button which is either close or cancel, depending on if there were any changes made on the page. To achieve this I want to use a trigger (wrapped in a style) on the button so that when the dependency property HasChanges is true the button will change from "Close" to "Cancel". So far my program displays "Close" as the button's text, but nothing happens when my dependency property HasChanges becomes true. The WPF page is being written in VB.Net and not XAML.</p>
<p>So far I have:</p>
<pre><code>Private Sub SetUpMyButton()
Me.MyButton.Style = Me.GetMyButtonStyle()
End Sub
Private Function GetMyButtonStyle() As Style
Dim hasChangesTrigger as New Trigger
hasChangesTrigger.Property = CustomControl.HasChangesProperty
hasChangesTrigger.Value = True
hasChangesTrigger.Setters.Add(New Setter(Button.ContentProperty, "Cancel"))
Dim hasChangesStyle as New Style
hasChangesStyle.TargetType = GetType(Button)
hasChangesStyle.Setters.Add(New Setter(Button.ContentProperty, "Close"))
hasChangesStyle.Triggers.Add(hasChangesTrigger)
hasChangesStyle.Seal()
Return hasChangesStyle
End Function
</code></pre>
<p>Any help is greatly appreciated.</p>
|
<p>I'm at a loss as to why you'd do this in code and not XAML, but I think it's just that your trigger doesn't know where to look for the custom dependency property. With your code as is, it will look for the HasChanges property on the button itself. Is that intended? Maybe you need to set the <code>Trigger</code>'s <code>SourceName</code> property. Or perhaps using a different trigger type altogether (eg. a <code>DataTrigger</code>) would be easier.</p>
|
What are some good techniques for performance testing SharePoint web parts and controls? <p>This is a question about performance testing specific to SharePoint web parts and controls (although standard ASP.NET methods would be applicable as well). I'm wondering what are some good techniques, considering factors such as:</p>
<ul>
<li>caching (what and when should you cache?)</li>
<li>load balanced servers (storing state)</li>
<li>interaction with other parts of the page (e.g. multiple JavaScript execution)</li>
<li>measuring CPU usage for a particular control</li>
<li>rendered page size</li>
</ul>
|
<p>I recommend Visual Studio Test Suite 2008 with SP1. We have used a test agent on our indexing server with the test controller running on the developers desktop with Visual Studio installed.</p>
<p>It is possible to simulate browser caching and we have found errors with our own server caching where the caching was not actually working.</p>
<p>Load balanced servers are easy to work with as you can simulate a range of ip addresses. You do need to be able to assign a range of ip addresses to the machine running the tests and only the last octet of the ip address is able to be adjusted. The stats on each web front end can be added to the perfmon stats generated by the test.</p>
<p>You can simulate clicks on different parts of the page if required, but the more complex the scenario the harder it is to get perfect.</p>
<p>The CPU and other stats measuring is great. All the test results can be added to a database and the charting of the tests during and after the load test is really good.</p>
<p>Comments can be added to each test run so you can identify them easily when you need to view the results of tests that have been run before.</p>
<p>Be warned that the results can quickly add up in size over time.</p>
|
How do I get images located in my recourse folder into an array? <p>I want to load 52 images (deck of cards) in gif format from my recourse folder into an Image[] in c#. Any ideas?</p>
<p>Thanks,
Jon</p>
|
<p>You can read a Bitmap from a file like this;</p>
<pre><code> public static Bitmap GetBitmap( string filename )
{
Bitmap retBitmap = null;
string path = String.Concat( BitmapDir, filename );
if ( File.Exists( path ) )
{
try
{
retBitmap = new Bitmap( path, true );
}
catch { }
}
return retBitmap;
}
</code></pre>
<p>You can get a list of files in a resource directory like this;</p>
<pre><code>string[] files = Directory.GetFiles( BitmapDir, "*.gif" );
</code></pre>
<p>Just iterate through files calling GetBitmap( file ) and populate your array. BitmapDir is obviously the directory where your GIF files live.</p>
|
What is the best way to determine the number of days in a month with javascript? <p>I've been using this function but I'd like to know what's the most efficient and accurate way to get it.</p>
<pre><code>function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
</code></pre>
|
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
console.log(daysInMonth(2, 1999)); // February in a non-leap year
console.log(daysInMonth(2, 2000)); // February in a leap year</code></pre>
</div>
</div>
</p>
<p>Day 0 is the last day in the previous month. Because the month constructor is 0-based, this works nicely. A bit of a hack, but that's basically what you're doing by subtracting 32.</p>
|
Is it possible to have different members in a class document have different colours? <p>I am using visual studio 2008 professional and was wondering, how can I have different colours for method calls within class methods, and for properties/fields? This would be good as it would give me a quick visual overview of what my class has too much of (e.g. 20 fields and 2 methods - which will give me some interesting information on my design - not that I do this, anyway).</p>
<p>Ideally, I'd like to have these members highlighted, as when you step through.</p>
<p>Thanks</p>
|
<p>Out of the box, I do not believe it is possible in Visual Studio 2008. You might need an aftermarket addon to implement this specific functionality. You could always look into <a href="http://www.wholetomato.com/tour.asp?syntax" rel="nofollow">Visual Assist X</a>, although it is a commercial product.</p>
|
ASP.NET theme not rendering correctly <p>I have a small web application which uses themes. The themes work on host, so on preinit, if the host = a, load x theme, if the host = b, load y theme. </p>
<p>In my code this looks like: </p>
<p>If request.url.host.contains("a") Then
Page.Theme = x
Else
request.url.host.contains("b") Then
Page.Theme = y </p>
<p>I have a url which is a.abc.com and another which is b.abc.com (well it is this structure, but the letters are meaningful/company names). Problem is (and I have done host == ""), when I debug my site on localhost (another clause in the above if block where host = localhost), the style renders perfectly. Alignment of elements are perfect as I expect with the numerical values I have provided for width, margins, etc in the css. But when I use the publish tool of VS2008 (with updatable ticked), and upload to a.abc.com, which has the same stylesheet as localhost (a copy in its own folder), there are all sorts of alignment issues as if I have done no work. Why do my styles render incorrectly @ runtime? If it helps, I am using VS2008 Pro Edition, IIS6 and Windows Server 2003.</p>
<p>What is frustrating is that the page source indicates the theme is loading ok, as it is referenced in HTML head. So when I publish, the theme for a.abc.com is loaded and referenced. Other than all this information, there is no obvious sign of what the problem is. I haven't tried to conventionally reference a single CSS file in the ASPX markup, but if I did and this worked, then it doesn't explain the problem either, anyway.</p>
<p>Thanks</p>
|
<p>Are you setting the Theme early enough in your code? A Theme must be applied to a page very early in the request lifecycle, in the PreInit event, if you do it in code-behind.</p>
|
Rails model without database <p>I want to create a Rails (2.1 and 2.2) model with ActiveRecord validations, but without a database table. What is the most widely used approach? I've found some plugins that claim to offer this functionality, but many of them don't appear to be widely used or maintained. What does the community recommend I do? Right now I am leaning toward coming up with my own solution based on <a href="http://www.prestonlee.com/2007/12/29/rails-20-validations-without-extending-activerecordbase/">this blog post</a>.</p>
|
<p>There is a better way to do this in Rails 3: <a href="http://railscasts.com/episodes/219-active-model">http://railscasts.com/episodes/219-active-model</a></p>
|
LDAP: why would the following use of DirectoryEntry return no members for a large global security group? <p>The following code works for 90+ % of global security groups, but for one very large global security group, it returns an enumerator, but no member objects of the group, even though the group has many thousands.</p>
<pre><code>DirectoryEntry group = groupResult.GetDirectoryEntry();
filter = "member;range=0-20";
group.RefreshCache(new[] { filter });
PropertyValueCollection groupMembers = group.Properties["member"];
IEnumerator iEnum = groupMembers.GetEnumerator();
//On one large global security group, this returns a valid iEnum,
//but no member entries. The group has thousands.
//This code works for every other group I've encountered.
</code></pre>
|
<p>The problem may not be with your code, but with access security in your directory - you may not have rights to enumerate the members of that group.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.