input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
What is the best way to program against powershell's x64 vs. x86 variability <p>We have several scripts we use to install and configure the dependencies backing the systems we maintain. We run these anytime we establish a dev, test, demo, train, prod, etc. environment. We often find that we have to deal with x64 vs. x86 architecture, especially where the powershell scripts are concerned.</p>
<p>For example, I have a script that uses the <a href="http://www.codeplex.com/psmsi">Windows Installer PowerShell Extensions</a> to determine if a program/patch has been installed. The script doesn't work in an x64 environment without explicitly invoking PowerShell (x86), which, isn't in the path by default. As we port these scripts to the x64 platform it would be great to maintain a single set of scripts that work in powershell on both architectures and only invoke x86 code when needed.</p>
<p>Does anyone know of a strategy for doing this?</p>
| <p>I run into this issue a lot with my configuration scripts. The basic approach I take is to </p>
<ol>
<li>Use several functions to test if I'm in a 64 bit environment (<a href="http://blogs.msdn.com/jaredpar/archive/2008/10/16/powershell-and-64-bit-windows-helper-functions.aspx">http://blogs.msdn.com/jaredpar/archive/2008/10/16/powershell-and-64-bit-windows-helper-functions.aspx</a>)</li>
<li>Invoke x86/x64 PowerShell based on the needs of a particular script</li>
</ol>
<p>Unfortunately a lot of this is done in a brute force manner. Each particular configuration entry that is x86/x64 dependent essentially has 2 code paths (one for each architecture). </p>
<p>The only real exception I've been able to make is to test for the existince of certain programs on disk. I have a handy function (Get-ProgramFiles32) which makes it easy to test for programs.</p>
<pre><code>if ( test-path (join-path Get-ProgramFiles32 "subversion") ) { ...
</code></pre>
<p>Here are all of the helper functions that I have in my common library that deal with 32/64 bit differences. </p>
<pre><code># Get the path where powershell resides. If the caller passes -use32 then
# make sure we are returning back a 32 bit version of powershell regardless
# of the current machine architecture
function Get-PowerShellPath() {
param ( [switch]$use32=$false,
[string]$version="1.0" )
if ( $use32 -and (test-win64machine) ) {
return (join-path $env:windir "syswow64\WindowsPowerShell\v$version\powershell.exe")
}
return (join-path $env:windir "System32\WindowsPowerShell\v$version\powershell.exe")
}
# Is this a Win64 machine regardless of whether or not we are currently
# running in a 64 bit mode
function Test-Win64Machine() {
return test-path (join-path $env:WinDir "SysWow64")
}
# Is this a Wow64 powershell host
function Test-Wow64() {
return (Test-Win32) -and (test-path env:\PROCESSOR_ARCHITEW6432)
}
# Is this a 64 bit process
function Test-Win64() {
return [IntPtr]::size -eq 8
}
# Is this a 32 bit process
function Test-Win32() {
return [IntPtr]::size -eq 4
}
function Get-ProgramFiles32() {
if (Test-Win64 ) {
return ${env:ProgramFiles(x86)}
}
return $env:ProgramFiles
}
function Invoke-Admin() {
param ( [string]$program = $(throw "Please specify a program" ),
[string]$argumentString = "",
[switch]$waitForExit )
$psi = new-object "Diagnostics.ProcessStartInfo"
$psi.FileName = $program
$psi.Arguments = $argumentString
$psi.Verb = "runas"
$proc = [Diagnostics.Process]::Start($psi)
if ( $waitForExit ) {
$proc.WaitForExit();
}
}
# Run the specified script as an administrator
function Invoke-ScriptAdmin() {
param ( [string]$scriptPath = $(throw "Please specify a script"),
[switch]$waitForExit,
[switch]$use32=$false )
$argString = ""
for ( $i = 0; $i -lt $args.Length; $i++ ) {
$argString += $args[$i]
if ( ($i + 1) -lt $args.Length ) {
$argString += " "
}
}
$p = "-Command & "
$p += resolve-path($scriptPath)
$p += " $argString"
$psPath = Get-PowershellPath -use32:$use32
write-debug ("Running: $psPath $p")
Invoke-Admin $psPath $p -waitForExit:$waitForExit
}
</code></pre>
|
Changing font colour in Textboxes in IE which are disabled <p>I noticed that you can change the colour of text in textboxes which are disabled in Firefox applying a simple class but could not get a way to do it in IE 6/7. Does anyone out there have a elegant solution to achieve this.</p>
| <blockquote>
<p>I noticed that you can change the colour of text in textboxes which are disabled in Firefox</p>
</blockquote>
<p>I think what the question is trying to say is that this:</p>
<pre><code><textarea disabled="disabled" style="color: red;">Hello</textarea>
</code></pre>
<p>Results in grey text in IE, vs. red in Fox. FWIW, Opera also gives grey, whilst the WebKit browsers give red.</p>
<p>This is a pure CSS issue to do with how much form fields are rendered according to the OS's widget set and how much according to the CSS rules. This has always been an area of great cross-browser difference. Scripting is not relevant, much though SO would like âuse jQueryâ to be the answer to every question.</p>
<p>The usual workaround is to use âreadonlyâ instead of âdisabledâ, then use styling (eg. based off âclass="disabled"â) to reproduce whatever shaded disabled effect you want. âreadonlyâ controls are not turned into OS-level-disabled widgets, giving you more latitude to style them.</p>
|
$.blockUI loading mask <p>i am using jQuery BlockUI Plugin (v2) to block and unblock while loading and when on clicking some button.but my problem is masking is working fine while loading page but it is not working when we click button,here is my code</p>
<pre><code>$("input[name^=filtera]").click(function(){
$.blockUI({message:'<h3><img src="images/spinner.gif" /> Please Wait...</h3>'});
$.ajax({
url : "ChangeRequestSearch.action?last_date_modified=" + modifiedDate ,
cache: false,
success : function (data) {
$("#tableLoader").html(data);
}
});
$().ajaxStop($.unblockUI);
});
</code></pre>
<p>i am getting the Error: $.blockUI is not a function</p>
<p>let me know what is the problem</p>
<p>Thanks
Usman.sk</p>
| <p>You can rearrange the code a bit here to call it using <a href="http://api.jquery.com/ajaxStart/" rel="nofollow"><code>$.ajaxStart()</code></a> to go with your <a href="http://api.jquery.com/ajaxStop/" rel="nofollow"><code>$.ajaxStop()</code></a> like this:</p>
<pre><code>$(document).ajaxStart(function() {
$.blockUI({message:'<h3><img src="images/spinner.gif" /> Please Wait...</h3>'});
}).ajaxStop(function() {
$.unblockUI();
});
</code></pre>
<p>Note that in jQuery 1.4+ you should use <code>$(document)</code> instead of <code>$()</code> for these bindings, since <code>$()</code> no longer returns the <code>document</code> wrapped in a jQuery object.</p>
|
Best place to check for property values <p>Assuming you have a class Photo:</p>
<pre><code>class Photo
{
public string Title {get; set;}
public string FileExtension {get; set;}
public void Save()
{
// Save to backing store here
}
}
</code></pre>
<p>Which would be the best place to check whether the values have been set correctly. In the propert setter or the Save method.</p>
<p>Edit: What if it is an Update method? If photos are added through a PhotoManager, using a method like PhotoManager.Add(Photo p), then which is the best place to do the validation.</p>
<p>Kind regards,</p>
| <p>If those are the only options, then in the property setter. <a href="http://en.wikipedia.org/wiki/Separation%5Fof%5Fconcerns" rel="nofollow">Separation of concerns</a> dictates that <code>Save</code> should do the saving, and not anything else.</p>
<p>Also, that is the beauty of properties. They look like fields, but they can have enhanced logic behind the getting and setting of the value in the backing field.</p>
|
Mod rewrite issue <p>As many others I am having issues with doing some very simple mod_rewriting in apache.</p>
<p>I have the following in my .htaccess:</p>
<pre><code>Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^view/([0-9]+)/([0-9]+)$ view.php?advertId=$1&publisherId=$2 [NC,QSA,L]
</code></pre>
<p>Which is supposed to translate /view/4093/203?qs=val -> /view.php?advertId=4093&publisherId=203?qs=val</p>
<p>Now, it works when calling it with /View..., but when doing lowercase /view, it redirects to the right file, but advertId and publisherId is not set within my PHP script as it is with the first-letter-uppercase View and I simply put have no clue whatsoever with what is going on on that front (I have been testing and watching that behavior simply by doing a on my view.php).</p>
<p>Anyone know why this is happening?</p>
<p>I may want to add, my server info is as follows:</p>
<pre><code>Apache/2.2.9 (Debian) PHP/5.2.6-1+lenny2 with Suhosin-Patch mod_python/3.3.1 Python/2.5.2 mod_perl/2.0.4 Perl/v5.10.0
</code></pre>
<p>IE. a stock brand new debian install with default debian packages + php-mssql.</p>
| <p><a href="http://httpd.apache.org/docs/2.2/content-negotiation.html#multiviews"><code>MultiViews</code></a> might cause this behavior, that is trying to map the request to a siminar existing file before passing the request to mod_rewrite. Try to disable it:</p>
<pre><code>Options -MultiViews
</code></pre>
|
may COM server reallocate ([in, out] CACLSID * arg)? <p>With a COM interface method declared as this:</p>
<pre><code>[ object,
uuid(....),
]
interface IFoo : IUnknown
{
HRESULT Foo([in, out] CACLSID * items);
}
</code></pre>
<p>With regards to marshalling, is the server allowed to reallocate the counted array? (I <em>think</em> it is, but I am not sure anymore)</p>
<p>Its current implementation only replaces the existing ID's, but I'd like to implement a change (that would not break contract) that may return more items without introducing a new interface.</p>
<p><strong>[edit]</strong> please note that <a href="http://msdn.microsoft.com/en-us/library/bb401564.aspx" rel="nofollow">CACLSID</a> is already an array, containing a count and a pointer. </p>
| <p>I have not done COM for a very long time but is it even possible to allocate a new array? In that case should it not be <code>CACLSID ** items</code> ?</p>
|
How to initialize an NSObject's subclass on iPhone? <p>I want to write some methods in a class so that other classes can call these methods using <code>[instance methodName:Parameter]</code>.</p>
<p>If the class is a subclass of <code>UIViewController</code>, I can use <code>initWithNibName</code> to initialize it. But I want to write the methods in an <strong>NSObject's</strong> subclass, how can I initialize it?</p>
| <p>iphony is correct, but he or she doesn't say that you need to write the init method yourself. Your init method should generally look something like this:</p>
<pre><code>- (id) init
{
if (self = [super init])
{
myMember1 = 0; // do your own initialisation here
myMember2 = 0;
}
return self;
}
</code></pre>
<p>Although the <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/init">apple documentation</a> says </p>
<blockquote>
<p>The init method defined in the NSObject class does no initialization; it simply returns self.</p>
</blockquote>
<p>and one can just be tempted to write</p>
<pre><code>- (id) init
{
myMember1 = 0; // do your own initialisation here
myMember2 = 0;
return self;
}
</code></pre>
<p>this is WRONG and not following what is explicitly stated in documentation:</p>
<blockquote>
<p>In a custom implementation of this (init) method, you must invoke superâs
designated initializer then initialize and return the new object.</p>
</blockquote>
<p>MUST. Not should, could, ought to, etc.</p>
<p>You should not assume NSObject's init does not change in future; nor the superclass from which your custom class derives.</p>
|
How can I use C++ class in Python? <p>I have implemented a class in C++. I want to use it with Python.
<strong>Please suggest step by step method and elaborate each step.</strong>
Somthing like this...</p>
<pre><code>class Test{
private:
int n;
public:
Test(int k){
n=k;
}
void setInt(int k){
n = k;
}
int getInt(){
return n;
}
};
</code></pre>
<p>Now, in Python </p>
<pre><code>>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32
</code></pre>
<p>Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.</p>
| <p>Look into <a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/python/doc/index.html">Boost.Python</a>. It's a library to write python modules with C++.</p>
<p>Also look into <a href="http://www.swig.org/">SWIG</a> which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them within python. Works great.</p>
<p>You can do it manually by using the <a href="http://docs.python.org/c-api/">Python/C API</a>, writing the interface yourself. It's pretty lowlevel, but you will gain a lot of additional knowledge of how Python works behind the scene (And you will need it when you use SWIG anyway).</p>
|
how do I override a setter function at runtime in actionscript? <p>I have an AS class with setter and getter functions.
I need to tweak one of this class's instances so that it's setter function will process the input before assigning it to the local variable.</p>
<p>or, in a more elaborated way, what should I use instead of $$$ in the example below?</p>
<pre><code>class MyClass{
private var _legend:Array;
function set legend(legend:Array):void{
_legend= legend;
}
function get legend():Array{
return _legend;
}
function someFunction():void{
foo();
}
}
var mc:MyClass = new MyClass();
mc.someFunction = function():void{
bar();
}
mc.$$$ = new function(legend:Array):void{
_legend = process(legend);
}
</code></pre>
| <p>Why don't you pass the instance a processed input? </p>
<pre><code>mc.legend = process(legend);
</code></pre>
<p>If this is not possible, you can modify the setter in MyClass and take an optional boolean to do processing.</p>
<pre><code>function set legend(legend:Array, flag:bool = false):void{
_legend = flag ? process(legend) : legend;
}
</code></pre>
<p>Note that prototype inheritance does not restrict itself to a particular instance. From the documentation:</p>
<blockquote>
<p>Prototype inheritance - is the only inheritance mechanism in previous versions of ActionScript and serves as an alternate form of inheritance in ActionScript 3.0. Each class has an associated prototype object, and the properties of the prototype object are shared by all instances of the class.</p>
</blockquote>
|
TFS Client APIs for creating workitem templates? <p>Of course, it is pretty possible to create work items, get a list of work items etc in TFS.</p>
<p>In addition to this, we need to have the functionality of allowing our users to create their own work item templates, for various file types.</p>
<p>Whether the TFS Client APIs are capable of uploading work item templates to TFS server? </p>
| <p>There is a method to get the (XML) definition: <a href="http://msdn.microsoft.com/en-gb/library/microsoft.teamfoundation.workitemtracking.client.workitemtype.export.aspx"><code>Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemType.Export</code></a></p>
<p>And, <a href="http://msdn.microsoft.com/en-gb/library/microsoft.teamfoundation.workitemtracking.client.workitemtypecollection.import.aspx"><code>Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemTypeCollection.Import</code></a> which looks like you can upload XML to create a new work item type.</p>
<p>Suggestion, set up a VM with an instance of TFS Workgroup and perform lots of testing.</p>
|
How would you programmatically test a file for viruses? <p>I want to programmatically test a file for viruses.</p>
<p>I'm aware of <a href="http://stackoverflow.com/questions/446999/is-there-any-anti-virus-product-which-provides-a-net-or-com-api">this thread</a>, which didn't get a satisfactory answer in my opinion, but I'm not looking for an API here. Any kind of workaround to make it possible to test a file would be fine.</p>
<p>Of course, an API would probably be the best solution (I'm using .net on a Windows platform), but maybe it's possible to drop the file in the folder, and to then check whether I can still open it or if it's been quarantined by the antivirus software.</p>
<p>Has someone run into the same sort of situation? </p>
| <p>Assuming you wish to integrate with whatever antivirus is already present on the system rather than bundling your own, you should check out the way Firefox 3 does this.</p>
<blockquote>
<p>Bugs 103487
and 408153
- Inform anti-virus software when Firefox downloads an executable (using
the Windows "<a href="http://msdn.microsoft.com/en-us/library/ms537365%28VS.85%29.aspx">IOfficeAntiVirus</a>" and
"IAttachmentExecute" APIs).</p>
</blockquote>
<p>(of course if you wish to bundle your own, check out ClamAV/ClamWin, but then you must deal with updates, etc, and you should probably first check there is not a fully updated solution on the target system for politeness)</p>
|
Can I selectively create a backup of Postgres database, with only certian tables? <p>Can I programatically(or whichever way works fine) create the backup of a database, with only the tables I want? I have around 100 tables in my database and I want only 10 tables backup(ofcourse all are interdependant). How can I achieve this? And by the way I have a postgresql database.</p>
| <p>Of course. <a href="http://www.postgresql.org/docs/8.3/interactive/app-pgdump.html">pg_dump</a> lets you pass list of tables with parameter <code>-t</code> </p>
<p>To clear some doubts. True, the <code>-t</code> parameter accepts only one pattern. But it's a <a href="http://www.postgresql.org/docs/8.3/interactive/app-psql.html#APP-PSQL-PATTERNS">pattern</a> very similar to regular expression, so if you want to dump tables A, B & C you can do:</p>
<pre><code>pg_dump -t '(A|B|C)'
</code></pre>
|
Hibernate: Identifier <p>When using Hibernate:</p>
<p>Must I identify an id or composite id for each entity,
What about if I want to use table without any primary key and without composite key ...</p>
<p>Thanx in advance</p>
| <p>A table without a key isn't a good relational model. I would not recommend it.</p>
<p>Hibernate's best practices say you should have an id. Composite ids are workable for legacy apps, but not always the best idea.</p>
<p>If you really must have a table without a key, I'd suggest that you shouldn't use Hibernate. It's an ORM tool, and it sounds like you're thinking about neither objects nor relational tables properly. Start with JDBC.</p>
|
Multiple MySQL versions <p>We have a Linux server running Red Hat Enterprise 3 and MySQL 3.23. This server has a number of websites on it.</p>
<p>We have a new website that we want to put on this server that uses MySQL 4/5. Is it possible to run the two versions of MySQL in parallel?</p>
<p>If so, how?</p>
| <p>Yes, it's possible, but tricky.</p>
<p>Firstly, it's probably best not to use the RedHat supplied RPMS - they'll cause all sorts of dependency issues.</p>
<p>In essence, all you need to do is to build the two versions, and install them into completely different directories.</p>
<p>Then you need to make sure that they're configured with separate:</p>
<ul>
<li>data directories</li>
<li>TCP ports</li>
<li>Local connection sockets</li>
<li>PID state files</li>
</ul>
<p>In practise that can be done my creating two <code>my.cnf</code> files, and making sure those are chosen in the command line parameters in the daemon start up scripts.</p>
<p>Note also that you'll need to be <em>very</em> careful with any shared libraries that might get built, particularly if you're running any client applications on the same server.</p>
<p>This gets nasty if, for example, you want Perl::DBD::mysql running, as it's not simple to arrange for there to be two copies, with each linked against a different version of the shared libraries.</p>
|
ExecuteXmlReader and null Resultset Throws TargetInvocationException <p>I'm calling a stored procedure on a SQL Server 2005 database which returns an XML resultset. Sometimes it will return an null resultset becuase there are not rows to return. When this happens athe ExecuteXmlReader method throws a TargetInvocationException. This seems to be a known issue (see: <a href="http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/5e90e3c0-605b-406d-848a-dea7b16f458e/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataproviders/thread/5e90e3c0-605b-406d-848a-dea7b16f458e/</a>).<br />
What is the best way to handle this exception?</p>
| <p>I can think of 3 choices</p>
<ol>
<li>Modify <strong>stored procedure</strong> to return a dummy/empty value</li>
<li>Modify <strong>code</strong> - catch exception and do nothing - or log error</li>
<li>Use <strong>DataSet</strong> - You should get an empty DataSet so just check if DataSet is empty or not.</li>
</ol>
<p>As a related SO post for the 3rd choice, here is a SO question on how to check if DataSet is empty or not</p>
<p><a href="http://stackoverflow.com/questions/47833/in-c-what-is-the-best-way-to-test-if-a-dataset-is-empty">In C#, what is the best way to test if a dataset is empty?</a></p>
|
Should I return an array or a collection from a function? <p>What's the preferred container type when returning multiple objects of the same type from a function? </p>
<p>Is it against good practice to return a simple array (like MyType[]), or should you wrap it in some generic container (like ICollection<MyType>)? </p>
<p>Thanks!</p>
| <p>Eric Lippert has a good <a href="http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx" rel="nofollow">article</a> on this. In case you can't be bothered to read the entire article, the answer is: return the interface.</p>
|
Using a Website-specific ConnectionString with a DLL <p><strong>The Setup:</strong></p>
<p>I have a DLL that uses a ConnectionString to connect to a SQL database. When I add the DLL to my website i have to add the connectionstring into my web.config in order for my DLL to function properly (this is by design). Once I add it into the web.config then everything works fine (as expected).</p>
<p><strong>The Problem:</strong></p>
<p>The problem begins when I want to move the connectionstring into my Website's ASP.NET Application settings found in IIS > Default Website > Properties > ASP.NET tab > Edit Global Configuration... > Connection string manager</p>
<p>If I remove it from my web.config and put it there my DLL fails to work. If I use the connectionstring anywhere else in my website (and not from a DLL) I can access the database just fine through this method but for some reason my DLL can only access it if it's in the web.config.</p>
<p><strong>The Question:</strong></p>
<p>How can I get my DLL to use the connectionstring that's listed in the ASP.NET Configuration Settings Connection String Manager instead of the web.config?</p>
| <p>You have to look for the section from the general ASP.Net configuration settings, which can be retrieved through the WebConfigurationManager class, rather than looking for a connection string via ConfigurationManager.ConnectionStrings.</p>
<pre><code> // Get the connectionStrings section.
ConnectionStringsSection connectionStringsSection =
WebConfigurationManager.GetSection("connectionStrings")
as ConnectionStringsSection;
// Get the connectionStrings key,value pairs collection.
ConnectionStringSettingsCollection connectionStrings =
connectionStringsSection.ConnectionStrings;
// Get the collection enumerator.
IEnumerator connectionStringsEnum =
connectionStrings.GetEnumerator();
</code></pre>
|
How do you fight design complexity? <p>I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.</p>
<p>It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.</p>
<p>And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.</p>
<p>We've all heard the refrain: Keep It Simple, Stupidâ¢.</p>
<p>How do you fight with overcomplexity in your team?</p>
<p><hr /></p>
<p>One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.</p>
| <p>Tooth and nail, and sometimes you lose. The problem is that it's always easy to be tempted to build something <em>cool</em>.</p>
<blockquote>
<p><em>Why build something simple and efficient when it can be complicated and wonderful?</em></p>
</blockquote>
<p>Try to remind people of the XP rule of building the simplest thing that can possibly work.</p>
|
Multi-language build tools <p>I have a build process for a large enterprise system comprising several dozen separate EXEs and DLLs. These use multiple languages, C, C++, Fortran, Python, Awk and a couple more. The build scripts are 4DOS batch processes which evolved over 4 decades. They are large and unwieldy and need constant care and feeding.</p>
<p>I must keep the Visual Studio solution and project files as the basic compile/link entities. What's the best tool for wrapping these disparate languages all together. 4DOS is very old and cumbersome.</p>
<p>EDIT:</p>
<p>Thanks gang. I think I'll try SCONS first because it's Python. We have plenty of people well versed in Python to be able to update and maintain it. I'm 61 now and it's not going to be me supporting this in the long term. I don't like anything requiring JAVA or XML because those are not languages already in our product mix and we have enough in play. </p>
<p>Those blog posts were good. He concluded that SCONS was best but simply too slow for his purposes. I'm not looking for speed in nightly builds. It's got until 7 AM. I want readability and maintainability.</p>
| <p>For example <a href="http://ant.apache.org/" rel="nofollow">Apache Ant</a></p>
|
Need help understanding jQuery .val() function <pre><code>alert("data going into $hidden: " + selected.data[1]);
hidden.val(selected.data[1]);
alert("data now in $hidden: " + $hidden.val());
</code></pre>
<p>What would be a reason that $hidden.val() in the last line above would return undefined? I have verified that selected.data[1] contains an integer value.</p>
<p><strong>Edit #1:</strong> Some additional context per comments: ($hidden is a hidden input field)</p>
<pre><code>$.fn.extend({
autocomplete: function(urlOrData, hidden, options) {
var isUrl = typeof urlOrData == "string";
var $hidden = $(hidden);
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);
// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() {
new $.Autocompleter(this, options, $hidden);
});
</code></pre>
<p>and...</p>
<pre><code>$.Autocompleter = function(input, options, $hidden) {
//...
function selectCurrent() {
var selected = select.selected();
if (!selected)
return false;
var v = selected.result;
previousValue = v;
if (options.multiple) {
var words = trimWords($input.val());
if (words.length > 1) {
v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
}
v += options.multipleSeparator;
}
alert("data going into $hidden: " + selected.data[1]);
$hidden.val(selected.data[1]);
alert("data now in $hidden: " + $hidden.val());
</code></pre>
<p><strong>Edit #2:</strong> More details.... I'm trying to use the jQuery autocomplete extension on a form with multiple textbox controls (each implement the autocomplete). There's a seperate button on the form beside each textbox that submits the form to a handler function that needs to find the value of the item selected and save it to the db. The way I thought to go about this was to include a hidden field on the form to hold the selected value. </p>
| <p>Thanks Paolo Bergantino. I discovered that I wasn't passing the initial hidden in with a # in front of the hidden field id, so $hidden was never getting set properly. It was difficult for me to debug because the the autocomplete is inside an ascx control as an embedded resource. Once I ensured that the value of hidden was including the # it worked properly. </p>
|
madExcept + UPX <p>I'm having problems using madExcept + UPX on Delphi 2007.
Whenever I open the compressed application, a Windows exception dialog appears code 0xc0000005.
Anyone has the solution for this?</p>
<p>Thanks!</p>
| <p>Stack tracing on exceptions etc. requires mapping in-memory code addresses to virtual addresses as stored in the executable, so that they can be correlated with either a .map file or debug info which indicates the function or source file and line. Normally, the mapping is straight-forward and relatively linear.</p>
<p>Executable compression mucks this up because it doesn't have a straight-forward mapping, particularly not one in line with the PE spec. This is because the executable compression replaces the initialization routine in the executable with one that extracts data from disk into memory (this also means that compressed executables don't share pages with other instances, and use more memory than uncompressed executables, since they need to page in everything all at once), before forwarding to the newly-expanded original initialization routine.</p>
<p>So, without quite clever relative-address storage of code locations in the stack tracing, it's unlikely that the two techniques will work together.</p>
<p>FWIW, I personally don't recommend using executable packers.</p>
|
Making a WPF application retain focus at all times <p>I've got an issue with a WPF application that I'm writing. The app needs to be able to keep focus at all times. The computer it's running on is a highly specialized machine with the only purpose of running this application. </p>
<p>There is no keyboard connected to the machine (it has a touch screen), so the only thing that can steal focus is windows own "needy windows", such as windows update etc.</p>
<p>How can I make it so that my app retains focus at all times? Is it possible to make the entire app modal?</p>
<h1>EDIT:</h1>
<p>Thank you both for your answers. I think I'll end up using Topsmost for now, but I'll definitely check out the source of babysmash as that application works exactly the way I want mine to, in regards to the way it handles focus.</p>
| <p>Look at the source of <a href="http://www.codeplex.com/babysmash" rel="nofollow">BabySmash</a>. It is specifically designed to keep focus even under quite bizar circumstances. (It is a program designed to run at full screen and let babys smash on a keyboard - so quite some focus went into capturing all kinds of weird keyboard combinations and alert messages).</p>
|
GUI frontend for cURL for testing an API <p>I'm (manually) testing a RESTful API that makes full use of GET/POST/PUT/DELETE methods. Rather than using cURL on the command line to quickly test different input options, it would be handy if there were a windows GUI application to make this easier. Does anything like that exist?</p>
| <p>Use <a href="https://addons.mozilla.org/en-US/firefox/addon/2691">Poster</a> with <a href="http://www.mozilla.com/firefox/">Firefox</a>.</p>
|
Legacy ASP.NET 1.1 with jQuery integration problem <p>I am working on a legacy web application written in VB.NET for ASP.NET 1.1. One particular page has a form with a number of fields. In response to a drop down box changing value, I am clearing a number of fields, resetting a number of drop down boxes to the first option, and setting them all to "disabled" in the UI. To do this, I'm using jQuery. I add a css class to all of these fields, and then my jQuery selector is something like the following: $("*.my-css-class"). Here's some sample code to explain.</p>
<pre><code>var fields = $("*.fields");
if( some_condition )
{
fields.val("");
fields.attr("selectedIndex", 0);
fields.attr("disabled", "disabled");
}
</code></pre>
<p>The UI updates as expected in response to the above js code, but when I post back the page in response to a button click, the original values still persist on the server side related to these controls. For instance, txtSomething is one of the fields with a css class "fields" (so it will get selected by the above jQuery selector). The user types "1234" in this text box and submits the form. Either the same page is posted back to itself retaining its values, or I return to this page and prepopulate the values on the server side (for example, the user clicks an Edit button on a summary page), so the control txtSomething is initialized on the client with the value "1234". My jQuery code clears the value as far as the user sees it in the UI, and then the user clicks a submit button. If I interrogate the value with a jQuery selector, the value of this field is an empty string. When the page is posted back and I'm stepping through the code (or doing something with the value of this control), it is still "1234".</p>
<p>A very important point to make is that these values are sent back to the browser after being submitted once. So, picture a form being submitted, or any case where these values are bound or set on the server side and outputted to the browser pre-populated (as opposed to being output to the browser with default or empty values). If I load the page as default (empty text boxes), enter some text, and then trigger the js function to clear these fields, the value I typed never makes it to the server.</p>
| <p>why do you need to disable those fields? Disabling controls can make them not post values to the server ... at least that is what happens when an asp.net control is disabled server side.</p>
<p><strong>Update 1:</strong> couldn't take having the doubt if it was only server side, so I looked it up :) <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1" rel="nofollow">http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1</a> ... "In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form.", so I was right, even when disabling it client side it won't post the value</p>
|
Security Warning message displayed on some pages <p>I am using Jboss application server.
I have implemented the whole website on ssl (https), the site is working fine on internet explorer browser but the site displays the below information on Mozilla/Konqueror browser but only on a particular page.</p>
<p><strong>Security Warning :
Although this page is encrypted, the information you hav enetered is to be sent over an unencrypted connection and could easily be read by a third party.
Are you sure you want to continue ?
continue cancel</strong></p>
<p>Is it a Jboss feature ? </p>
<p>If the whole site is running on https then why only n a particular page this information dislays ?</p>
<p>What should I do to get rid of this problem ?</p>
<p>Please do help me !!!!!!!!! My mailid is <strong>[redacted]</strong></p>
<p>Thanks and regards,</p>
<p>AKhtar Bhat</p>
| <p>Check for images or other resources that are being requested from non-SSL locations. This is usually the problem.</p>
|
asp:Button inside asp:hyperlink does not navigate to page in internet explorer <p>I have an asp:button which is inside an asp:hyperlink. When you click the button in firefox, it goes to the correct url specified by the asp:hyperlink, but if you click the button in internet explorer, it stays on the same page. I am just using the PostBackUrl property on the button to resolve the issue, but here is an example of the code:</p>
<pre><code><asp:Hyperlink ID="hyp" runat="server" NavigateUrl="Page2.aspx">
<asp:Button ID="btn" runat="server" Text="Submit" /></asp:Hyperlink>
</code></pre>
<p><strong>Why does the above work in firefox, but not IE?</strong></p>
| <p>What you did is not very correct.</p>
<p>Just add the button and in its click handler do:</p>
<pre><code>Response.Redirect("Page2.aspx");
</code></pre>
<p>Alternatively you can write a line of javascript:</p>
<pre><code><input type="button" value="Text" onclick="location='Page2.aspx'" />
</code></pre>
|
What do you keep in your Perl toolbox? <p>I am a Perl developer and have gravitated towards a specific suite of modules that I use for almost everything. I primarily build GIS and database oriented web applications for reporting and data entry and the like.</p>
<p>I'm curious what groups of modules other Perl devs have settled on using regularly.</p>
<p>Mine:</p>
<ul>
<li>CGI</li>
<li>DBI </li>
<li>Spreadsheet::WriteExcel </li>
<li>Spreadsheet::ParseExcel </li>
<li>HTML::Template </li>
<li>Text::Template </li>
<li>PDF::Template </li>
<li>PDF::API2 </li>
<li>Geo::Shapefile </li>
<li>LWP::Simple </li>
<li>XML::Simple</li>
</ul>
| <p>Checking over recent stuff, here's what I see most often: </p>
<ul>
<li><a href="http://search.cpan.org/perldoc?Getopt::Long" rel="nofollow">Getopt::Long</a> and <a href="http://search.cpan.org/perldoc?Pod::Usage" rel="nofollow">Pod::Usage</a> make options and man pages a breeze</li>
<li><a href="http://search.cpan.org/perldoc?File::Find" rel="nofollow">File::Find</a> because I finally get it, and as much as I want to use <a href="http://search.cpan.org/perldoc?File::Find::Rule" rel="nofollow">File::Find::Rule</a> instead, I keep forgetting</li>
<li><a href="http://search.cpan.org/perldoc?Data::Dumper" rel="nofollow">Data::Dumper</a> - aka, the best debugger you never knew you already had</li>
<li><a href="http://search.cpan.org/perldoc?Carp" rel="nofollow">Carp</a> to figure out what else I did wrong</li>
<li><a href="http://search.cpan.org/perldoc?Storable" rel="nofollow">Storable</a> for when a proper database is just too much</li>
<li><a href="http://search.cpan.org/perldoc?POSIX" rel="nofollow">POSIX</a> but almost only ever for <code>strftime</code></li>
<li><a href="http://search.cpan.org/perldoc?ack" rel="nofollow">App::Ack</a> - I almost forgot it because I use it constantly, but not so much in Perl as instead of Grep on the command line.</li>
</ul>
|
Left Outer Join and Exists in Linq To SQL C# .NET 3.5 <p>I'm stuck on translating a left outer join from LINQToSQL that returns unique parent rows.</p>
<p>I have 2 tables (Project, Project_Notes, and it's a 1-many relationship linked by Project_ID). I am doing a keyword search on multiple columns on the 2 table and I only want to return the unique projects if a column in Project_Notes contains a keyword. I have this linqtoSQl sequence going but it seems to be returning multiple Project rows. Maybe do an <code>Exist</code> somehow in LINQ? Or maybe a groupby of some sort?</p>
<p>Here's the LINQToSQL: </p>
<pre><code> query = from p in query
join n in notes on p.PROJECT_ID equals n.PROJECT_ID into projectnotes
from n in notes.DefaultIfEmpty()
where n.NOTES.Contains(cwForm.search1Form)
select p;
</code></pre>
<p>here's the SQL it produced from profiler </p>
<blockquote>
<p>exec sp_executesql N'SELECT [t2].[Title], [t2].[State], [t2].[PROJECT_ID],
[t2].[PROVIDER_ID], [t2].[CATEGORY_ID], [t2].[City], [t2].[UploadedDate],
[t2].[SubmittedDate], [t2].[Project_Type]FROM ( SELECT ROW_NUMBER() OVER (ORDER BY
[t0].[UploadedDate]) AS [ROW_NUMBER], [t0].[Title], [t0].[State], [t0].[PROJECT_ID],
[t0].[PROVIDER_ID], [t0].[CATEGORY_ID], [t0].[City], [t0].[UploadedDate],
[t0].[SubmittedDate], [t0].[Project_Type] FROM [dbo].[PROJECTS] AS [t0] LEFT OUTER JOIN
[dbo].[PROJECT_NOTES] AS [t1] ON 1=1 WHERE ([t1].[NOTES] LIKE @p0) AND
([t0].SubmittedDate] >= @p1) AND ([t0].[SubmittedDate] < @p2) AND ([t0].[PROVIDER_ID] =
@p3) AND ([t0].[CATEGORY_ID] IS NULL)) AS [t2] WHERE [t2].[ROW_NUMBER] BETWEEN @p4 + 1
AND @p4 + @p5 ORDER BY [t2].[ROW_NUMBER]',N'@p0 varchar(9),@p1 datetime,@p2 datetime,@p3
int,@p4 int,@p5 int',@p0='%chicago%',@p1=''2000-09-02 00:00:00:000'',@p2=''2009-03-02
00:00:00:000'',@p3=1000,@p4=373620,@p5=20</p>
</blockquote>
<p>This query returns all mutiples of the 1-many relationship in the results. I found how to do an <code>Exists</code> in LINQ from here. <a href="http://www.linq-to-sql.com/linq-to-sql/t-sql-to-linq-upgrade/linq-exists/" rel="nofollow">http://www.linq-to-sql.com/linq-to-sql/t-sql-to-linq-upgrade/linq-exists/</a></p>
<p>Here is the LINQToSQL using <code>Exists</code>:</p>
<pre><code>query = from p in query
where (from n in notes
where n.NOTES.Contains(cwForm.search1Form)
select n.PROJECT_ID).Contains(p.PROJECT_ID)
select p;
</code></pre>
<p>The generated SQL statement:</p>
<blockquote>
<p>exec sp_executesql N'SELECT COUNT(*) AS [value] FROM [dbo].[PROJECTS] AS [t0] WHERE
(EXISTS(SELECT NULL AS [EMPTY] FROM [dbo].[PROJECT_NOTES] AS [t1] WHERE
([t1].PROJECT_ID] = ([t0].[PROJECT_ID])) AND ([t1].[NOTES] LIKE @p0))) AND
([t0].[SubmittedDate] >= @p1) AND ([t0].[SubmittedDate] < @p2) AND ([t0].[PROVIDER_ID] =
@p3) AND ([t0].[CATEGORY_ID] IS NULL)',N'@p0 varchar(9),@p1 datetime,@p2 datetime,@p3
int',@p0='%chicago%',@p1=''2000-09-02 00:00:00:000'',@p2=''2009-03-02
00:00:00:000'',@p3=1000</p>
</blockquote>
<p>I get a SQL timeout from the <code>databind()</code> from using <code>Exists</code>.</p>
| <blockquote>
<p>it seems to be returning multiple Project rows</p>
</blockquote>
<p>Yes, that's how join works. If a project has 5 matching notes, it show up 5 times.</p>
<p><hr /></p>
<p>What if the problem is - "Join" is the wrong idiom!</p>
<p>You want to filter the projects to those whose notes contain certain text:</p>
<pre><code>var query = db.Project
.Where(p => p.Notes.Any(n => n.NoteField.Contains(searchString)));
</code></pre>
|
Inline member functions in C++ <p>ISO C++ says that the inline definition of member function in C++ is the same as declaring it with inline. This means that the function will be defined in every compilation unit the member function is used. However, if the function call cannot be inlined for whatever reason, the function is to be instantiated "as usual". (<a href="http://msdn.microsoft.com/en-us/library/z8y1yy88%28VS.71%29.aspx">http://msdn.microsoft.com/en-us/library/z8y1yy88%28VS.71%29.aspx</a>) The problem I have with this definition is that it does not tell in which translation unit it would be instantiated.
The problem I encountered is that when facing two object files in a single static library, both of which have the reference to some inline member function which cannot be inlined, the linker might "pick" an arbitrary object file as a source for the definition. This particular choice might introduce unneeded dependencies. (among other things)</p>
<p>For instance:
<strong>In a static library</strong></p>
<pre><code>A.h:
class A{
public:
virtual bool foo() { return true; }
};
</code></pre>
<p>U1.cpp:</p>
<pre><code>A a1;
</code></pre>
<p>U2.cpp:</p>
<pre><code>A a2;
</code></pre>
<p><em>and lots of dependencies</em></p>
<p><strong>In another project</strong>
main.cpp:</p>
<pre><code>#include "A.h"
int main(){
A a;
a.foo();
return 0;
}
</code></pre>
<p>The second project refers the first. How do I know which definition the compiler will use, and, consequently which object files with their dependencies will be linked in? Is there anything the standard says on that matter? (Tried, but failed to find that)</p>
<p>Thanks</p>
<p>Edit: since I've seen some people misunderstand what the question is, I'd like to emphasize: <em>If the compiler decided to create a symbol for that function (and in this case, it will, because of 'virtualness', there will be several (externally-seen) instantiations in different object file, which definition (from which object file?) will the linker choose?)</em></p>
| <p>Just my two cents. This is not about virtual function in particular, but about inline and member-functions generally. Maybe it is useful.</p>
<h3>C++</h3>
<p>As far as Standard C++ is concerned, a inline function <em>must</em> be defined in every translation unit in which it is used. And an non-static inline function will have the same static variables in every translation unit and the same address. The compiler/linker will have to merge the multiple definitions into one function to achieve this. So, always place the definition of an inline function into the header - or place no declaration of it into the header if you define it only in the implementation file (".cpp") (for a non-member function), because if you would, and someone used it, you would get a linker error about an undefined function or something similar. </p>
<p>This is different from non-inline functions which must be defined only once in an entire program (<em>one-definition-rule</em>). For inline functions, multiple definitions as outlined above are rather the normal case. And this is independent on whether the call is atually inlined or not. The rules about inline functions still matter. Whether the Microsoft compiler adheres to those rules or not - i can't tell you. If it adheres to the Standard in that regard, then it will. However, i could imagine some combination using virtual, dlls and different TUs could be problematic. I've never tested it but i believe there are no problems.</p>
<p>For member-functions, if you define your function in the class, it is implicitly inline. And because it appears in the header, the rule that it has to be defined in every translation unit in which it is used is automatically satisfied. However, if you define the function out-of-class and in a header file (for example because there is a circular dependency with code in between), then that definition has to be inline if you include the corresponding file more than once, to avoid multiple-definition errors thrown by the linker. Example of a file <code>f.h</code>:</p>
<pre><code>struct f {
// inline required here or before the definition below
inline void g();
};
void f::g() { ... }
</code></pre>
<p>This would have the same effect as placing the definition straight into the class definition.</p>
<h3>C99</h3>
<p>Note that the rules about inline functions are more complicated for C99 than for C++. Here, an inline function can be defined as an <em>inline definition</em>, of which can exist more than one in the entire program. But if such a (inline-) definition is used (e.g if it is called), then there <em>must</em> be also <em>exactly one</em> external definition in the entire program contained in another translation unit. Rationale for this (quoting from a PDF explaining the rationale behind several C99 features):</p>
<blockquote>
<p>Inlining in C99 does extend the C++ specification in two ways. First, if a function is declared inline in one translation unit, it need not be declared inline in every other translation unit. This allows, for example, a library function that is to be inlined within the library but available only through an external definition elsewhere. The alternative of using a wrapper function for the external function requires an additional name; and it may also adversely impact performance if a translator does not actually do inline substitution.</p>
<p>Second, the requirement that all definitions of an inline function be "exactly the same" is replaced by the requirement that the behavior of the program should not depend on whether a call is implemented with a visible inline definition, or the external definition, of a function. This allows an inline definition to be specialized for its use within a particular translation unit. For example, the external definition of a library function might include some argument validation that is not needed for calls made from other functions in the same library. These extensions do offer some advantages; and programmers who are concerned about compatibility can simply abide by the stricter C++ rules.</p>
</blockquote>
<p>Why do i include C99 into here? Because i know that the Microsoft compiler supports some stuff of C99. So in those MSDN pages, some stuff may come from C99 too - haven't figured anything in particular though. One should be careful when reading it and when applying those techniques to ones own C++ code intended to be portable C++. Probably informing which parts are C99 specific, and which not. </p>
<p>A good place to test small C++ snippets for Standard conformance is the <a href="http://www.comeaucomputing.com/tryitout/">comeau online compiler</a>. If it gets rejected, one can be pretty sure it is not strictly Standard conforming. </p>
|
Finding a Thinkmap-like engine <p>I try to find a Thinkmap-like engine on flash to visualize structured data. Does anybody know any free engines?</p>
| <p>Your best bet is <a href="http://flare.prefuse.org/">flare</a>.</p>
|
Submitting HTML Forms with Slider as input (WebFX) <p>How can I submit the value of <a href="http://webfx.eae.net/dhtml/slider/slider.html" rel="nofollow">this slider</a> to a CGI application (like you would a check box)?
Not sure if the input tag for the slider is messing something up?</p>
<pre><code><div class="slider" id="slider-1" tabIndex="1">
<input class="slider-input" id="slider-input-1"
name="slider-input-1"/>
</div>
</code></pre>
| <p>If I were you, I'd try tweaking the <code><input></code> tag's <code>type</code> attribute, setting it to <code>text</code> or <code>hidden</code>.</p>
<p>(I don't know enough about the framework/environment you're using to say for sure.)</p>
|
Reading a formatted array into a variable from a file <p>I am trying to read a formatted 2D array from a file on disk into a variable. I have the write operation, which is rather simple, but am stuck on reading the same file. Could someone point me to a sample/writeup on how to do this? The net seems saturated, but I can't find a useful article. </p>
<p>By the way, the reason for the formatted file is to keep it human readable as it contains configuration options.</p>
| <p>I've actually found that the physical documentation that comes with the compiler is generally the most readable and most informative for Fortran compilers. Of course, that's not an option if you're using g95 or something like that.</p>
<p>Here's a <a href="http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap05/format.html" rel="nofollow">pretty good page</a> describing most of the technical specs of the read statement. Particularly, see the section on "Format Edit Descriptors" - very handy.</p>
<p>On a side note, if you have the exact write format string, you can usually drop that into a read format string, but if you're writing with <code>WRITE(*,*)</code> or something like that, you probably won't have a valid write format statement to use.</p>
<p>Finally, if you're dumping this out to ASCII so people can read it, and you don't have to worry about backward compatibility, consider dumping everything out as fixed-length fields, as they are by far the easiest things to read back in.</p>
<p>Sorry I can't think of better online resources, but Fortran is woefully underdocumented on the web. I remember once checking to see if g95 had Fortran reference docs, but they mostly only have docs on their specific compiler settings. Good luck, though!</p>
|
How to make use of Tags property of an xml node to get its information and attributes? <p>How would I make use of the Tags property of a node, so that I can get the attributes of an xml node?</p>
<p>I have to display an xml tree in a Windows Form. When I click on any node, its attributes should get displayed on a list box in same form. </p>
<p>I want to make use of tags property, but I need to convert that tree node in the form into an xml node. I wanted to store the tree node in the tag and then typecast that tag to an xml node. </p>
<p>How can I accomplish this?</p>
| <p>When adding the TreeNode class, your code would look like this:</p>
<pre><code>// Create the node.
TreeNode newNode = new TreeNode();
// Configure.
...
// Set the tag property to hold the XML element.
XmlElement currentElement = ...;
newNode.Tag = currentElement;
// Add to the tree view.
...
</code></pre>
<p>Then when you have the tree view node, you would get the element like this:</p>
<pre><code>TreeNode currentNode = ...;
// Get the XmlElement.
XmlElement currentElement = (XmlElement) currentNode.Tag;
// Process the element.
...
</code></pre>
|
Using Linq to map facebook profile with my user info <p>After reading a book on LINQ I'm thinking about re-writing a mapper class that I wrote in c# to use LINQ. I'm wondering if anyone can give me a hand. Note: its a bit confusing, but the User object is the local user and user (lowercase) is the object generated from the Facebook XSD.</p>
<p><strong>Original Mapper</strong></p>
<pre><code>public class FacebookMapper : IMapper
{
public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
var facebookUsers = GetFacebookUsers(users);
return MergeUsers(users, facebookUsers);
}
public Facebook.user[] GetFacebookUsers(IEnumerable<User> users)
{
var uids = (from u in users
where u.FacebookUid != null
select u.FacebookUid.Value).ToList();
// return facebook users for uids using WCF
}
public IEnumerable<User> MergeUsers(IEnumerable<User> users, Facebook.user[] facebookUsers)
{
foreach(var u in users)
{
var fbUser = facebookUsers.FirstOrDefault(f => f.uid == u.FacebookUid);
if (fbUser != null)
u.FacebookAvatar = fbUser.pic_sqare;
}
return users;
}
}
</code></pre>
<p>My first two attempts hit walls</p>
<p><strong>Attempt 1</strong></p>
<pre><code>public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
// didn't have a way to check if u.FacebookUid == null
return from u in users
join f in GetFacebookUsers(users) on u.FacebookUid equals f.uid
select AppendAvatar(u, f);
}
public void AppendAvatar(User u, Facebook.user f)
{
if (f == null)
return u;
u.FacebookAvatar = f.pic_square;
return u;
}
</code></pre>
<p><strong>Attempt 2</strong></p>
<pre><code>public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
// had to get the user from the facebook service for each single user,
// would rather use a single http request.
return from u in users
let f = GetFacebookUser(user.FacebookUid)
select AppendAvatar(u, f);
}
</code></pre>
| <p>Okay, it's not clear exactly what <code>IMapper</code> has in it, but I'd suggest a few things, some of which may not be feasible due to other restrictions. I've written this out pretty much as I've thought about it - I think it helps to see the train of thought in action, as that'll make it easier for you to do the same thing next time. (Assuming you like my solutions, of course :)</p>
<p>LINQ is inherently functional in style. That means that ideally, queries shouldn't have side-effects. For instance, I'd expect a method with a signature of:</p>
<pre><code>public IEnumerable<User> MapFrom(IEnumerable<User> users)
</code></pre>
<p>to return a new sequence of user objects with extra information, rather than mutating the existing users. The only information you're currently appending is the avatar, so I'd add a method in <code>User</code> along the lines of:</p>
<pre><code>public User WithAvatar(Image avatar)
{
// Whatever you need to create a clone of this user
User clone = new User(this.Name, this.Age, etc);
clone.FacebookAvatar = avatar;
return clone;
}
</code></pre>
<p>You might even want to make <code>User</code> fully immutable - there are various strategies around that, such as the builder pattern. Ask me if you want more details. Anyway, the main thing is that we've created a new user which is a copy of the old one, but with the specified avatar.</p>
<p><strong>First attempt: inner join</strong></p>
<p>Now back to your mapper... you've currently got three <em>public</em> methods but my <em>guess</em> is that only the first one needs to be public, and that the rest of the API doesn't actually need to expose the Facebook users. It looks like your <code>GetFacebookUsers</code> method is basically okay, although I'd probably line up the query in terms of whitespace.</p>
<p>So, given a sequence of local users and a collection of Facebook users, we're left doing the actual mapping bit. A straight "join" clause is problematic, because it won't yield the local users which don't have a matching Facebook user. Instead, we need some way of treating a non-Facebook user as if they were a Facebook user without an avatar. Essentially this is the null object pattern.</p>
<p>We can do that by coming up with a Facebook user who has a null uid (assuming the object model allows that):</p>
<pre><code>// Adjust for however the user should actually be constructed.
private static readonly FacebookUser NullFacebookUser = new FacebookUser(null);
</code></pre>
<p>However, we actually want a <em>sequence</em> of these users, because that's what <code>Enumerable.Concat</code> uses:</p>
<pre><code>private static readonly IEnumerable<FacebookUser> NullFacebookUsers =
Enumerable.Repeat(new FacebookUser(null), 1);
</code></pre>
<p>Now we can simply "add" this dummy entry to our real one, and do a normal inner join. Note that this <em>assumes</em> that the lookup of Facebook users will always find a user for any "real" Facebook UID. If that's not the case, we'd need to revisit this and not use an inner join.</p>
<p>We include the "null" user at the end, then do the join and project using <code>WithAvatar</code>:</p>
<pre><code>public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
var facebookUsers = GetFacebookUsers(users).Concat(NullFacebookUsers);
return from user in users
join facebookUser in facebookUsers on
user.FacebookUid equals facebookUser.uid
select user.WithAvatar(facebookUser.Avatar);
}
</code></pre>
<p>So the full class would be:</p>
<pre><code>public sealed class FacebookMapper : IMapper
{
private static readonly IEnumerable<FacebookUser> NullFacebookUsers =
Enumerable.Repeat(new FacebookUser(null), 1);
public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
var facebookUsers = GetFacebookUsers(users).Concat(NullFacebookUsers);
return from user in users
join facebookUser in facebookUsers on
user.FacebookUid equals facebookUser.uid
select user.WithAvatar(facebookUser.pic_square);
}
private Facebook.user[] GetFacebookUsers(IEnumerable<User> users)
{
var uids = (from u in users
where u.FacebookUid != null
select u.FacebookUid.Value).ToList();
// return facebook users for uids using WCF
}
}
</code></pre>
<p>A few points here:</p>
<ul>
<li>As noted before, the inner join becomes problematic if a user's Facebook UID might not be fetched as a valid user.</li>
<li>Similarly we get problems if we have duplicate Facebook users - each local user would end up coming out twice!</li>
<li>This replaces (removes) the avatar for non-Facebook users.</li>
</ul>
<p><strong>A second approach: group join</strong></p>
<p>Let's see if we can address these points. I'll assume that if we've fetched <em>multiple</em> Facebook users for a single Facebook UID, then it doesn't matter which of them we grab the avatar from - they should be the same.</p>
<p>What we need is a group join, so that for each local user we get a sequence of matching Facebook users. We'll then use <code>DefaultIfEmpty</code> to make life easier.</p>
<p>We can keep <code>WithAvatar</code> as it was before - but this time we're only going to call it if we've got a Facebook user to grab the avatar from. A group join in C# query expressions is represented by <code>join ... into</code>. This query is reasonably long, but it's not too scary, honest!</p>
<pre><code>public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
var facebookUsers = GetFacebookUsers(users);
return from user in users
join facebookUser in facebookUsers on
user.FacebookUid equals facebookUser.uid
into matchingUsers
let firstMatch = matchingUsers.DefaultIfEmpty().First()
select firstMatch == null ? user : user.WithAvatar(firstMatch.pic_square);
}
</code></pre>
<p>Here's the query expression again, but with comments:</p>
<pre><code>// "Source" sequence is just our local users
from user in users
// Perform a group join - the "matchingUsers" range variable will
// now be a sequence of FacebookUsers with the right UID. This could be empty.
join facebookUser in facebookUsers on
user.FacebookUid equals facebookUser.uid
into matchingUsers
// Convert an empty sequence into a single null entry, and then take the first
// element - i.e. the first matching FacebookUser or null
let firstMatch = matchingUsers.DefaultIfEmpty().First()
// If we've not got a match, return the original user.
// Otherwise return a new copy with the appropriate avatar
select firstMatch == null ? user : user.WithAvatar(firstMatch.pic_square);
</code></pre>
<p><strong>The non-LINQ solution</strong></p>
<p>Another option is to only use LINQ very slightly. For example:</p>
<pre><code>public IEnumerable<User> MapFrom(IEnumerable<User> users)
{
var facebookUsers = GetFacebookUsers(users);
var uidDictionary = facebookUsers.ToDictionary(fb => fb.uid);
foreach (var user in users)
{
FacebookUser fb;
if (uidDictionary.TryGetValue(user.FacebookUid, out fb)
{
yield return user.WithAvatar(fb.pic_square);
}
else
{
yield return user;
}
}
}
</code></pre>
<p>This uses an iterator block instead of a LINQ query expression. <code>ToDictionary</code> will throw an exception if it receives the same key twice - one option to work around this is to change <code>GetFacebookUsers</code> to make sure it only looks for distinct IDs:</p>
<pre><code> private Facebook.user[] GetFacebookUsers(IEnumerable<User> users)
{
var uids = (from u in users
where u.FacebookUid != null
select u.FacebookUid.Value).Distinct().ToList();
// return facebook users for uids using WCF
}
</code></pre>
<p>That assumes the web service works appropriately, of course - but if it doesn't, you probably want to throw an exception anyway :)</p>
<p><strong>Conclusion</strong></p>
<p>Take your pick out of the three. The group join is probably hardest to understand, but behaves best. The iterator block solution is possibly the simplest, and should behave okay with the <code>GetFacebookUsers</code> modification.</p>
<p>Making <code>User</code> immutable would almost certainly be a positive step though.</p>
<p>One nice by-product of all of these solutions is that the users come out in the same order they went in. That may well not be important to you, but it can be a nice property.</p>
<p>Hope this helps - it's been an interesting question :)</p>
<p><strong>EDIT: Is mutation the way to go?</strong></p>
<p>Having seen in your comments that the local User type is actually an entity type from the entity framework, it <em>may</em> not be appropriate to take this course of action. Making it immutable is pretty much out of the question, and I suspect that most uses of the type will <em>expect</em> mutation. </p>
<p>If that's the case, it may be worth changing your interface to make that clearer. Instead of returning an <code>IEnumerable<User></code> (which implies - to some extent - projection) you might want to change both the signature and the name, leaving you with something like this:</p>
<pre><code>public sealed class FacebookMerger : IUserMerger
{
public void MergeInformation(IEnumerable<User> users)
{
var facebookUsers = GetFacebookUsers(users);
var uidDictionary = facebookUsers.ToDictionary(fb => fb.uid);
foreach (var user in users)
{
FacebookUser fb;
if (uidDictionary.TryGetValue(user.FacebookUid, out fb)
{
user.Avatar = fb.pic_square;
}
}
}
private Facebook.user[] GetFacebookUsers(IEnumerable<User> users)
{
var uids = (from u in users
where u.FacebookUid != null
select u.FacebookUid.Value).Distinct().ToList();
// return facebook users for uids using WCF
}
}
</code></pre>
<p>Again, this isn't a particularly "LINQ-y" solution (in the main operation) any more - but that's reasonable, as you're not really "querying"; you're "updating".</p>
|
PHP File Operations list <p>I'm looking for a list of each file operation. I Googled on <a href="http://www.google.se/search?q=Php+File+Operations" rel="nofollow">http://www.google.se/search?q=Php+File+Operations</a>, but didn't found anything. </p>
<p>Do you know a where I could find a list of PHP file operations?</p>
<pre><code>$file = fopen("words.txt","**r**"); the r is once File Operation
</code></pre>
| <p>Your question needs clarifying, but try the <a href="http://uk3.php.net/ref.filesystem" rel="nofollow">PHP Filesystem Functions</a> section in the PHP manual. (All I did was search for 'PHP file functions' on Google).</p>
<p>If what you're looking for is the <strong>file open <em>modes</em></strong> (such as "r", etc.), then you need to look at <a href="http://uk3.php.net/fopen" rel="nofollow">the fopen() page</a> in the manual (there's a table just down the page).</p>
|
Using GetSaveFileName. I specify OFN_EXPLORER flag, but always get old dialog appearance unless I avoid using both hook and template <p>Using GetSaveFileName. I specify the OFN_EXPLORER flag, but I always get old dialog appearance unless I avoid using both hook and template. (lpfnHook and lpfnTemplate (and their respective "enable" flags) in OPENFILENAME structure) </p>
<p>If I avoid using just one or the other, I still get the old dialog appearance. I also tried no template, but use the hook... but always return TRUE from it (I saw mention of "always returning false" from the hook as a way to GET the old interface). It didn't seem to have any effect, though.</p>
<p>EDIT: Added relevant code:</p>
<pre><code>ofn.lStructSize=sizeof(OPENFILENAME);
ofn.hInstance=RhInst;
ofn.hwndOwner=MainWh;
ofn.lpstrFilter=s;
ofn.lpstrCustomFilter=null;
ofn.nMaxCustFilter=0;
ofn.nFilterIndex=sel;
ofn.lpstrFile=fname;
ofn.nMaxFile=lstrl;
ofn.lpstrFileTitle=tfile;
ofn.nMaxFileTitle=lstrl;
if (path && lstrlen(path)) ofn.lpstrInitialDir=path;
else ofn.lpstrInitialDir=drive;
lstrcpy(SE_DefExt,ext);
ofn.lpstrDefExt=SE_DefExt;
if (titleid) ofn.lpstrTitle=title;
else ofn.lpstrTitle=null;
ofn.lpfnHook=(CommHookProc)MakeProcInstance((FARPROC)SEOpen32Hook,hInst);
ofn.lpTemplateName=NULL;
ofn.Flags=OFN_SHOWHELP | OFN_OVERWRITEPROMPT | OFN_ENABLEHOOK | OFN_EXPLORER
| OFN_PATHMUSTEXIST | OFN_HIDEREADONLY;
if(allowfit)
{
ofn.lpTemplateName = MAKEINTRESOURCE(SAVETOFIT);
ofn.Flags |= OFN_ENABLETEMPLATE;
}
if (GetSaveFileName(&ofn))
{
// <snip>
}
</code></pre>
<p>Note that "allowfit" is non-zero/true in this case. If I comment out the setting of the flag for both OFN_ENABLEHOOK and OFN_ENABLETEMPLATE, I get the "new" dialog appearance.</p>
<p>**EDIT 2:<br />
It looks now like I was confused on what I was seeing. I believe in both cases, I'm getting the "new" OFN_EXPLORER behavior and appearance. When I remove the OFN_EXPLORER flag, I get a very old style dialog box. </p>
<p>What I am trying to get to is the style of Save File dialog that has the Back and Forward button in the upper right, and (most importantly) an address box that I can type in. All my previous comments and code descriptions (above) still apply; when I remove the Template and the Hook, I get my "back & forward" buttons, and my typeable address box (plus left-side browse tree)... when I leave the template and the hook in place -- I do not (instead has "Save in" picklist at top, and "standard places" along the left ("Recent places", "Desktop", ...).</p>
| <p>If you use both <code>OFN_EXPLORER</code> and <code>OFN_ENABLEHOOK</code> in Windows Vista and 7, you will get the dialog boxes with XP style. If you remove <code>OFN_EXPLORER</code> you will get the older Win2k style. If you use <code>OFN_ENABLEHOOK</code> (or <code>OFN_ENABLETEMPLATE</code>) then the system will not use Vista/7 style.</p>
<p>Since Vista if you want to customize such dialogs you are advised to use the COM interfaces <code>IFileDialog</code>, <code>IFileOpenDialog</code>, and <code>IFileSaveDialog</code>. See <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/bb776913(v=vs.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/desktop/bb776913(v=vs.85).aspx</a>.</p>
|
Attaching chained methods to collections of elements in JavaScript <p>This isâat least at the momentâpurely experimentation, but I'm curious: is there a way to attach methods (via prototyping) to collections of elements? I've tested the following code:</p>
<pre><code><div>a</div>
<div>b</div>
<div>c</div>
<script>
NodeList.prototype._ = function(s)
{
for (x = 0; x < this.length; x++)
{
eval('this[x]' + '.' + s);
}
return this;
}
document.getElementsByTagName('div')._("style.backgroundColor = 'red'")._('innerHTML += x');
</script>
</code></pre>
<p>At the moment, it works perfectly in Opera; just as would be expected, the _ method is being called on all of the div elements, and then eval()'ing the string passed to it <em>onto</em> each element in turn. Note that the _ method allows for chaining, and that's been demonstrated as well, calling _ to append the predicted <strong>x</strong> iterator variable to the innerHTML of each element.</p>
<p>Now, two questions...</p>
<p>First, is there a better way of going about this? I have for the longest wished I could just do <code>document.getElementsByTagName('div').style.backgroundColor = "red";</code>, but alas, it simply hasn't yet come to be. This is why I am doing this in the first place, and why I named the method so succinctly; I'm trying to emulate it as closely as possible.</p>
<p>Secondly, assuming this is a sane usage, how would I go about getting it to work in Firefox? That browser's equivalent of <code>NodeList</code> is <code>HTMLCollection</code>, but trying to prototype the latter simply doesn't succeed. Suggestions?</p>
| <p>I've cooked up what I suppose could stay as a viable solution; is there anything fundamentally bad about using this method to chain-modify a collection of elements?</p>
<pre><code><script>
_ = function()
{
for (x = 0; x < arguments[0].length; x++)
{
for (y = 0; y < arguments[1].length; y++)
{
eval('arguments[0][x]' + '.' + arguments[1][y]);
}
}
}
</script>
</code></pre>
<p>Usage:</p>
<pre><code>divs = document.getElementsByTagName('div');
_(divs, ["style.color = 'red'", "innerHTML += x"]);
</code></pre>
|
Serialize Flex Objects to Save/Restore Application State <p>Is it possible to serialize a hierarchy of objects in Flex, send the binary data to a URL for storage/retrieval on/from a server, and deserialize the data to restore the objects' original state?</p>
<p>I know it's possible to convert the objects into an XML format (haven't tried it yet), but I'm hoping to avoid parsing XML and rebuilding the objects manually. It would be nice to have functionality which can serialize/deserialize objects to a simple binary format (I did something similar in the past in Java, though not quite as easily as I would have liked). The 'eval' function in Perl is similar to what I'm looking for, sans saving code, of course.</p>
<p>In pseudo-code, here's what I would like to do:</p>
<pre><code>private var contentToSave:HBox = new HBox();
private function saveState(event:Event):void {
var toSave:HBox = this.contentToSave;
var data:? = /* serialize 'toSave' ActionScript classes to binary data*/;
sendDataToServer(data, filename);
}
private function restoreState(filename):void {
var data:? = getDataFromServer(filename);
var savedData:HBox = /* deserialize binary 'data' to ActionScript classes */;
this.contentToSave = savedData;
}
</code></pre>
| <p>Take a look at <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/utils/ByteArray.html#writeObject%28%29" rel="nofollow">ByteArray.writeObject()</a>. which saves the passed object in AMF format into the byte array. I have not used this function too much, I don't exactly know what kind of objects it can serialize, but definitely not all.</p>
|
WCF Test Client error: Failed to Invoke the service <p>I'm getting an error when trying to use the WCF Test Client with my WCF service. Here is the service code:</p>
<pre><code>[ServiceContract]
public interface IEmployeeService
{
[OperationContract(Name = "GetEmployee")]
[WebGet(RequestFormat = WebMessageFormat.Xml,
UriTemplate = "/Employees/{employeeNumber}")]
Employee GetEmployee(string employeeNumber);
}
public Employee GetEmployee(string employeeNumber)
{
var employeeNumberValue = Convert.ToInt32(employeeNumber);
var employee = DataProvider.GetEmployee(employeeNumberValue);
return employee;
}
<system.serviceModel>
<services>
<service name="Employees.Services.EmployeeService"
behaviorConfiguration="metaBehavior">
<endpoint address=""
behaviorConfiguration="webHttp"
binding="webHttpBinding"
contract="Employees.Services.IEmployeeService">
</endpoint>
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webHttp">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="metaBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</code></pre>
<p>I am able to connect to the service using the WCF Test Client, but when I try to invoke GetEmployee(employeeNumber) I get the following error:</p>
<p><em>Failed to invoke the service. Possible causes: The service is offline or inaccessible; the client-side configuration does not match the proxy; the existing proxy is invalid. Refer to the stack trace for more detail. You can try to recover by starting a new proxy, restoring to default configuration, or refreshing the service.</em></p>
<p>I was able to successfully call this service by sending a request from the browser.</p>
<p>Any idea why I can't use the WCF Test Client?</p>
| <p>Please ignore my earlier answer. I don't think the problem is at the client-side config.</p>
<p>See <a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/deabd25b-a219-4e95-9826-d40dc2f75543/">WCF Test Client and WebHttpBinding</a>.</p>
<blockquote>
<p>This is a limitation of the web
programming model itself. Unlike SOAP
endpoints (i.e., those with
BasicHttpBinding, WSHttpBinding, etc)
which have a way to expose metadata
about itself (WSDL or Mex) with
information about all the operations /
parameters in the endpoint, there's
currently no standard way to expose
metadata for a non-SOAP endpoint - and
that's exactly what the
webHttpBinding-based endpoints are. In
short, the WCF Test Client won't be
useful for web-based endpoints. If
some standard for representing
web-style endpoints emerges when WCF
ships its next version, we'll likely
update the test client to support it,
but for now there's none widely
adopted.</p>
</blockquote>
|
Software Bandwidth/Database Growth Formulas <p>Are there any industry standard formulas or rules of thumb for determining:</p>
<ol>
<li>Application bandwidth usage/requirements</li>
<li>Database growth requirements</li>
</ol>
<p>I have recently started managing a new .NET 3.5/SQL Server project and would like to take a more structured approach than previously when determining exactly what my application needs in terms of storage and bandwidth. If anyone out there has any pointers I would greatly appreciate it!</p>
| <p>I am not an SQL Server expert, but in general, for database Sizing, the best way to go forward is to understand the schema little bit. For example, are there partitions present in the database ? Are there lot of indexes etc.
Now Multiply number of records coming to the database in each transaction with the frequency of transactions per hour. This gives the total number of records coming to the database per hour. Multiply this with the average row size, this provides the size of the database without partition and index space overhead. To calculate partition overhead, need to understand the type of partition like range partition or hash partition etc, number of partitions that will be created per hour or per day and add up the space overhead for partitions. Usually this number needs to be bumped up by 50% to estimate the size of the database.
In case of network, there are many ways to do it. I run etheral to capture the network traffic. If you capture network traffic, it becomes interesting - how the seasonality of the data is - like when the peack hours are, what is the max usage of bandwidth at the busy hours etc. Then you need a good tool to do the forecasting - like which will take care of seasonality in the data, understand the trend of the data and forecast approximately what will happen if you increase the load. A simple graph and a line fitting curve using y=mx+c will also help you here.</p>
|
Switch from Microsofts STL to STLport <p>I'm using quite much STL in performance critical C++ code under windows. One possible "cheap" way to get some extra performance would be to change to a faster STL library.</p>
<p>According to this <a href="http://garrys-brain.blogspot.com/2007/01/development-stlport-versus-microsoft.html">post</a> STLport is faster and uses less memory, however it's a few years old.</p>
<p>Has anyone made this change recently and what were your results? </p>
| <p>I haven't compared the performance of STLPort to MSCVC but I'd be surprised if there were a <em>significant</em> difference. (In release mode of course - debug builds are likely to be quite different.) Unfortunately the link you provided - and any other comparison I've seen - is too light on details to be useful.</p>
<p>Before even considering changing standard library providers I recommend you heavily profile your code to determine where the bottlenecks are. This is standard advice; always profile before attempting any performance improvements!</p>
<p>Even if profiling does reveal performance issues in standard library containers or algorithms I'd suggest you first analyse <em>how you're using them</em>. Algorithmic improvements and appropriate container selection, especially considering Big-O costs, are <em>far more</em> likely to bring greater returns in performance. </p>
|
"Padding is invalid and cannot be removed" using AesManaged <p>I'm trying to get simple encryption/decryption working with AesManaged, but I keep getting an exception when trying to close the decryption stream. The string here gets encrypted and decrypted correctly, and then I get the CryptographicException "Padding was invalid and cannot be removed" after Console.WriteLine prints the correct string.</p>
<p>Any ideas?</p>
<pre><code>MemoryStream ms = new MemoryStream();
byte[] rawPlaintext = Encoding.Unicode.GetBytes("This is annoying!");
using (Aes aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
aes.Key = new byte[128/8];
aes.IV = new byte[128/8];
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(),
CryptoStreamMode.Write))
{
cs.Write(rawPlaintext, 0, rawPlaintext.Length);
cs.FlushFinalBlock();
}
ms = new MemoryStream(ms.GetBuffer());
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(),
CryptoStreamMode.Read))
{
byte[] rawData = new byte[rawPlaintext.Length];
int len = cs.Read(rawData, 0, rawPlaintext.Length);
string s = Encoding.Unicode.GetString(rawData);
Console.WriteLine(s);
}
}
</code></pre>
| <p>The trick is to use <code>MemoryStream.ToArray()</code>.
I also changed your code so that it uses the <code>CryptoStream</code> to Write, in both encrypting and decrypting. And you don't need to call <code>CryptoStream.FlushFinalBlock()</code> explicitly, because you have it in a <code>using()</code> statement, and that flush will happen on <code>Dispose()</code>. The following works for me. </p>
<pre><code>byte[] rawPlaintext = System.Text.Encoding.Unicode.GetBytes("This is all clear now!");
using (Aes aes = new AesManaged())
{
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 128; // in bits
aes.Key = new byte[128/8]; // 16 bytes for 128 bit encryption
aes.IV = new byte[128/8]; // AES needs a 16-byte IV
// Should set Key and IV here. Good approach: derive them from
// a password via Cryptography.Rfc2898DeriveBytes
byte[] cipherText= null;
byte[] plainText= null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(rawPlaintext, 0, rawPlaintext.Length);
}
cipherText= ms.ToArray();
}
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherText, 0, cipherText.Length);
}
plainText = ms.ToArray();
}
string s = System.Text.Encoding.Unicode.GetString(plainText);
Console.WriteLine(s);
}
</code></pre>
<p>Also, I guess you know you will want to explicitly set the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.mode.aspx">Mode</a> of the AesManaged instance, and use <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx">System.Security.Cryptography.Rfc2898DeriveBytes</a> to derive the Key and IV from a password and salt.</p>
<p>see also:<br>
- <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.aesmanaged.aspx">AesManaged</a> </p>
|
how to parse hex or decimal int in Python <p>I have a string that can be a hex number prefixed with "0x" or a decimal number without a special prefix except for possibly a minus sign. "0x123" is in base 16 and "-298" is in base 10.</p>
<p>How do I convert this to an int or long in Python?</p>
<p>I don't want to use eval() since it's unsafe and overkill.</p>
| <pre><code>int("0x123", 0)
</code></pre>
<p>(why doesn't <code>int("0x123")</code> do that?)</p>
|
Good, secure encryption <p>Hi im thinking about developing a sort of File Transfer program and was wondering if i want as good encryption that i can get what should i use?</p>
<p>ill be developing this with c# so i got access to the .net lib :P
having a certificate with me on my usb to access the server is no problem if that would increase the security!</p>
| <p>The simplest built in way with the .NET Framework is probably to use the <a href="http://msdn.microsoft.com/en-us/library/system.net.security.sslstream.aspx" rel="nofollow">SslStream </a> class which is built in. Example of usage <a href="http://geekswithblogs.net/luskan/archive/2007/10/01/115758.aspx" rel="nofollow">here</a>.</p>
|
Detect web user's language, e.g. in JavaScript? <p>I'm thinking of doing multiple language versions of my website (e.g. English and German). I'd like to offer a reasonable default based on the user's language.</p>
<p>What's the easiest and least obstrusive way to do that?</p>
<p>EDIT: The ideal solution would be not to use any server-side technology, but to encode everything in the html-files. Currently, I have a starting page that auto-forwards to the main page. If possible, I'd like to make that a bit "smarter" so that it forwards to either the German or the English version.</p>
| <p>The easiest way would be to parse the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4" rel="nofollow"><code>Accept-Language</code> header field</a>.</p>
|
Flash Encoding (FLV): What are the prefered bitrates? <p>I inherited a project that is sending videos off to a remote encoder to encode into FLVs.</p>
<p>Today, I noticed that we are asking them to encode at 1024kbps To me, this seems extremely high. </p>
<p>What is everyone else using? What is YouTube using for "standard" vs. "high quality" versions?</p>
<p>Thank you in advance.</p>
| <p>Typically somewhere between 400-600kbps is average for 'standard' quality video. Higher quality video is often 800-1200kbps, but for many people this is too high a bit rate to maintain, so you shouldn't really have something this high as your only rate unless you know your target audience will have fast connections. </p>
<p>It's also a good idea to offer a low bit-rate stream (somewhere around 250-300kbps) for people with really slow connections, although it's hard to get video to look good at this rate even with H.264, and if you're still using VP6 then don't bother because it will look awful.</p>
<p>If you're producing HD (720p) content then bit-rates start to look pretty good at around 2500kbps but this is out of the reach of many internet users. (Note that YouTube uses 1000kbps for what they call HD, but it really isn't, because the digital blocking is awful. They'd be better off using a lower resolution.)</p>
<p>We use 272kbps/544kbps/1088kbps for low/medium/high quality video respectively.</p>
|
Global keyboard capture in C# application <p>I want to capture a keyboard shortcut in my application and trigger a dialog to appear if the user presses a keyboard combo even outside of the app. Similar to Google Desktop Search's Ctrl, Ctrl to bring up the search dialog.</p>
<p>I have tried using some keyboard hook modules out there that basically use Win32 interop to get this effect but each implementation I've tried ties down the keyboard to some extent to where you start getting weird behaviors when the application is doing something intensive. Such as loading a large amount of data, this would cause the keyboard and mouse to lockup.</p>
<p>I'm looking for a lightweight solution that would allow this to be done without tying down the keyboard and mouse.</p>
| <p>Stephen Toub <a href="http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx" rel="nofollow">wrote a great article</a> on implementing global keyboard hooks in C#:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;
class InterceptKeys
{
private const int WH_KEYBOARD_LL = 13;
private const int WM_KEYDOWN = 0x0100;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
public static void Main()
{
_hookID = SetHook(_proc);
Application.Run();
UnhookWindowsHookEx(_hookID);
}
private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)vkCode);
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
</code></pre>
|
ADO.net without writing SQL (esp. WHERE) <p>I have this idea that using SQL VIEWS to abstract simple database computations (such as a count on a relation) is sufficient, and you don't need procedures (== procedural code)</p>
<p>A simple sql <strong><em>view</em></strong> + a <strong><em>where</em></strong> clause >> a stored procedure with parameters sometimes</p>
<p>While making this point I imagined a way of retrieving table/view data without writing SQL and without writing the where clause..</p>
<p>But, to my surprise, there does not seem a way to accomplish this in ADO.NET 2.0 or later.</p>
<p>Let me tell you what I tried:</p>
<ul>
<li><p>SqlDataAdapter + SqlCommandBuilder still requires you to write "SELECT ... FROM" and the <strong>WHERE CLAUSE</strong> in strings (plus, if you put the 'where', you dont have much use of Update/Insert/DeleteCommand)</p></li>
<li><p>typed DataSets only allow you to retrieve _entire DataTable_s and then applying filters to them. Filters are strings, without escaping aid... (must double the single quote!)</p></li>
<li><p>SQL to Entities looked promising but they seem to: be limited to MSSQL, generate bloated SQL queries, generate a whole new stack of DAOs (besides the existing Domain Model classes), reqiuire .net 3.5+ for all this etc. (that is, all these are disadvantages for me)</p></li>
</ul>
<p>Other ORMs have similar problems as SQL to Entities.</p>
<p>What I'm looking for is a strong-typed method of accessing database tables/<strong><em>views</em></strong> that:</p>
<ul>
<li>doesn't come with another set of DAOs (K.I.S.S)</li>
<li>allows me to query a table without writing "SELECTs" in strings (strong-typed)</li>
<li>allows me to filter(<strong><em>WHERE</em></strong>) a table with properly-escaped parameters (and without retrieving the whole data beforehand)</li>
<li>can later issue updates/inserts/deletes</li>
</ul>
<p>I am fairly new to .Net but not stupid: does this exist?</p>
<p>Thanks.</p>
| <p><a href="http://fluentado.codeplex.com/" rel="nofollow">FluentADO</a></p>
|
Using SVG to create separate images files <p>I've previously processed XSLT to output single HTML files that were supposed to be viewed in a browser.</p>
<p>Now I was hoping if someone could outline would it be possible to use XML data and XSLT to create separate image files auto magically?</p>
| <p>If your XSLT processor supports EXSLT, the <a href="http://exslt.org/exsl/elements/document/index.html" rel="nofollow">exsl:document</a> element will allow you to create multiple output files from a single input file.</p>
<p>AFAIK, only <a href="http://xmlsoft.org/XSLT/" rel="nofollow">libxslt</a>-based processors support this tag, currently, but this includes <a href="http://us.php.net/manual/en/book.xsl.php" rel="nofollow">PHP 5</a> and, of course, xsltproc.</p>
<p><strong>EDIT:</strong></p>
<p>As you've found, XSLT 2.0 provides the similar <a href="http://www.w3.org/TR/xslt20/#element-result-document" rel="nofollow">xsl:result-document</a> tag. The XSLT 2.0 processors I'm aware of are <a href="http://saxon.sourceforge.net/" rel="nofollow">Saxon</a>, <a href="http://www.altova.com/altovaxml.html" rel="nofollow">Altova XML</a>, and <a href="http://www.gobosoft.com/eiffel/gobo/gexslt/" rel="nofollow">Gexslt/Gestalt</a>.</p>
|
How to deny Assert with CAS? <p>In this code, I'd like the ReadFileSystem method to be forbidden to Assert a permission on the filesystem.</p>
<p>I expected this will throw at fileIo.Assert(), but it doesn't. Why?</p>
<pre><code>using System.Security.Permissions;
static void Main(string[] args)
{
var fileIo = new FileIOPermission(PermissionState.Unrestricted);
var secuPerm = new SecurityPermission(SecurityPermissionFlag.Assertion);
PermissionSet set = new PermissionSet(PermissionState.Unrestricted);
set.AddPermission(fileIo);
set.AddPermission(secuPerm);
set.Deny();
ReadFileSystem();
Console.Read();
}
private static void ReadFileSystem()
{
var fileIo = newFileIOPermission(PermissionState.Unrestricted);
fileIo.Assert();
DirectoryInfo dir = new DirectoryInfo("C:/");
dir.GetDirectories();
}
</code></pre>
<p><strong><em>Update</em></strong></p>
<p>Great link here on CAS : <a href="http://blogs.msdn.com/shawnfa/archive/2004/08/25/220458.aspx" rel="nofollow">http://blogs.msdn.com/shawnfa/archive/2004/08/25/220458.aspx</a></p>
| <p>The subsequent Assert negates the effects of the Deny.</p>
<p>The ability to assert FileIOPermission mainly depends on whether your assembly is trusted. It is not affected by a previous Deny of FileIOPermission. It turns out that it is also not affected by the previous Deny of the Assertion SecurityPermission. <strong>This is because SecurityPermissionFlag.Assertion is checked as a link time demand.</strong> This is not clearly documented; I found it <a href="http://www.grimes.demon.co.uk/workshops/secWSSix.htm#link%5Fdemands" rel="nofollow">here</a>.</p>
<p>To force the CLR to not trust your assembly for FileIOPermission, you can use the following at the top of your file following the using statements. When you add this to your file, the assert will not take effect. This affects the entire assembly. There is no finer granularity.</p>
<pre><code>[assembly:FileIOPermission(SecurityAction.RequestRefuse, Unrestricted=true)]
</code></pre>
|
Getting at unmanaged C++ functions from C# <p>I have some ANSI standard C code which is authoritative. What that means is that although I have the source, I can not translate to another language nor modify calling arguments, as those actions would invalidate the authority. There are over 150 functions.</p>
<p>I can make incidental changes, such as change the file names from .C to .CPP so that it compiles using Visual Studio 2009's C++ compiler, which I have done. Compiler directives and such can also be added. I can also go through a wrapper layer, if necessary.</p>
<p>Another restriction is my company does <b>not</b> want me to use the <b>unsafe</b> key word in any C# code.</p>
<p><b>I need to get at these functions from a C# program.</b></p>
<p>A typical C/C++ function looks like this:<br><code>
double SomeFunction(double a, double[3] vec, double[3][3] mat);</code><br>
Where the array contents are sometimes input, sometimes output, and rarely both.</p>
<p>I first tried making an unmanaged DLL (with the functions marked Extern C). Functions with only simple arguments (int, double) worked fine, but I could not determine how to Marshal the arrays. (Actually, I did find some sample code, but it was extremely complex and unreasonable to duplicate 150 times.)</p>
<p>I then tried two projects within the same solution, one in C++ and the other in C#. In the C++ project, I created a managed function which just called the original function which was marked as unmanaged. This was extremely clean and simple, and again, simple arguments worked fine. But for arrays, I couldn't find how to make the argument types match across the C# to C++ boundary:<br>
<code><i> Argument '2': cannot convert from 'double[]' to 'double*'</i></code><br>
(and as mentioned above, I can't use unsafe to get a pointer).</p>
<p>Certainly what I am trying to do must be possible.<br>
What is the best way to get at these functions?<br>
(Sample code using the above function would be really cool.)</p>
| <p>Sample C/C++ implementation:</p>
<pre><code>extern "C" __declspec(dllexport)
double SomeFunction(double a, double vec[3], double mat[3][3]) {
double sum = a;
for (int ix = 0; ix < 3; ++ix) {
sum += vec[ix];
for (int iy = 0; iy < 3; ++iy) {
sum += mat[ix][iy];
}
}
return sum;
}
</code></pre>
<p>Sample C# usage:</p>
<pre><code>private void Form1_Load(object sender, EventArgs e) {
double[] vec = new double[3];
double[,] mat = new double[3, 3];
for (int ix = 0; ix < 3; ++ix) {
vec[ix] = ix;
for (int iy = 0; iy < 3; ++iy) {
mat[ix, iy] = (ix + 1) * iy;
}
}
double sum = SomeFunction(1, vec, mat);
}
[System.Runtime.InteropServices.DllImport("cpptemp8.dll")]
private static extern double SomeFunction(double a, double[] vec, double[,] mat);
</code></pre>
|
Converting/accessing QueryString values in ASP.NET <p>I'm curious what everyone does for handling/abstracting the QueryString in ASP.NET. In some of our web apps I see a lot of this all over the site:</p>
<pre><code>int val = 0;
if(Request.QueryString["someKey"] != null)
{
val = Convert.ToInt32(Request.QueryString["someKey"]);
}
</code></pre>
<p>What are some better ways to handle this grossness?</p>
| <p>I tend to like the idea of abstracting them as properties.
For example:</p>
<pre><code> public int age {
get
{
if (Request.QueryString["Age"] == null)
return 0;
else
return int.Parse(Request.QueryString["Age"]);
}
}
</code></pre>
<p>You could add more validation if you wanted to. But I tend to like wrapping all of my query string variables this way.</p>
<p>EDIT: ---
Also as another poster pointed out that you have to create these properties on every page. My answer is no you do not. You can create these properties in a single class that you can call "QueryStrings" or something. Then you can instantiate this class in every page where you want to access your query strings, then you can simply do something like </p>
<pre><code>var queryStrings = new QueryStrings();
var age = queryStrings.age;
</code></pre>
<p>This way you can encapsulate all of the logic for accessing and handling each type of query variable in a single maintainable location. </p>
<p>EDIT2: ---
And because it is an instance of the class, you could also use dependency injection to inject the QueryStrings class in every place you are using it. <a href="http://structuremap.github.io/" rel="nofollow">StructureMap</a> does a good job of that. This also allows you to mock up the QueryStrings class and inject that if you wanted to do automated unit testing. It is much easier to mock this up than ASP.Net's Request object.</p>
|
Sending login information via AJAX <p>Im using jQuery validate plugin and every form has multiple validation levels.</p>
<ol>
<li>level is by validate plugin</li>
<li>level is:
<ul>
<li>data is submitted to site</li>
<li>I get a reply
<ul>
<li>if everything is ok -> JS redirects to url</li>
<li>if there is an error, it shows warnings</li>
</ul></li>
</ul></li>
</ol>
<p>Now I wonder, is it safe to send login info via ajax? I know that with addons like firebug, I am also able to get all POST parameters with normal submit. But can somebody else interfere with ajax login request and steal precious data? </p>
| <blockquote>
<p>is it safe to send login info via ajax</p>
</blockquote>
<p>You do use HTTPS, do you? If you do it's as safe as form submit.</p>
|
Read file access/modification timestamp <p>What win32 API C functions can I use to read the modification/access/created dates of a file?</p>
| <p>Use the <a href="http://msdn.microsoft.com/en-us/library/ms724320%28VS.85%29.aspx" rel="nofollow">GetFileTime</a> function. You need to open the file to use this function.</p>
<p>Also, the appropriately named <a href="http://msdn.microsoft.com/en-us/library/ms724933%28VS.85%29.aspx" rel="nofollow">SetFileTime</a> function will let you modify the times.</p>
|
Is there a way to put inner controls inside a ASP.NET Custom Control? <p>I want to do something like (Updated example):</p>
<pre><code><uc:Tabs>
<Tab Name="A handy tab">
<Node Url="~/Default.aspx" />
<Node Url="~/Node2.aspx" />
</Tab>
<Tab Name="Another handy tab">
<Node Url="~/Neato.aspx" />
<Node Url="~/Node3.aspx" />
<Node Url="~/Node4.aspx" />
</Tab>
<uc:Tabs>
</code></pre>
<p>Possible? Any tutorials or how-to's? I'm not sure what to even search on or what this is called so haven't found anything so far. Inner controls? Inner collection something something...?</p>
| <p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.parsechildrenattribute.aspx">ParseChildrenAttribute</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.persistchildrenattribute.aspx">PersistChildrenAttribute</a> attributes:</p>
<pre><code>[ParseChildren(false)]
[PersistChildren(true)]
public class MyControl : UserControl { }
</code></pre>
<p>This will cause any controls you put inside the reference:</p>
<pre><code><uc:MyControl runat="server">
<asp:TextBox runat="server" />
<uc:MyControl>
</code></pre>
<p>To be appended to the end of the Controls collection of your UserControl contents.</p>
<p>However, if you want to have a collection of controls, you should probably use a server control and not a user control. For a control that works like this:</p>
<pre><code><foo:TabControl runat="server">
<Tabs>
<foo:Tab CssClass="myclass" Title="Hello World" />
</Tabs>
</foo:TabControl>
</code></pre>
<p>You need a Control class that has a Tabs property; the Tabs property should be a Collection; and it should contain objects of type Tab. I've created the three classes here:</p>
<pre><code>[ParseChildren(true, "Tabs")]
public class TabControl: WebControl, INamingContainer
{
private TabCollection _tabs;
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public TabCollection Tabs
{
get
{
if (_tabs == null)
{
_tabs = new TabCollection();
}
return _tabs;
}
}
protected override void Render(HtmlTextWriter writer)
{
foreach (Tab tab in Tabs)
{
writer.WriteBeginTag("div");
writer.WriteAttribute("class", tab.CssClass);
writer.Write(HtmlTextWriter.TagRightChar);
writer.Write("this is a tab called " + tab.Title);
writer.WriteEndTag("div");
}
}
}
</code></pre>
<p>And the tab class:</p>
<pre><code>public class Tab
{
public string CssClass { get; set; }
public string Title { get; set; }
}
</code></pre>
<p>And the tab collection:</p>
<pre><code>public class TabCollection : Collection<Tab> { }
</code></pre>
|
Uploading multiple images + text fields in ASP.NET MVC <p>I'm very new to ASP.net MVC, so please be as descriptive as possible in your answer :)</p>
<p>Let me simplify what I'm trying to do. Imagine I have a form where you want to enter some information about a car. The fields might be: Make, Model, Year, Image1, Image2.</p>
<p>On the bottom of the form is a "Save" button. The associated Controller method will save Image1 and Image2 to disk, obtain their filenames and associate them with the car model, which will then be saved to the database.</p>
<p>Any ideas?</p>
<p>Thanks guys!</p>
<p><strong>Edit</strong></p>
<p><a href="http://stackoverflow.com/questions/604640/uploading-multiple-images-text-fields-in-asp-net-mvc/604720#604720">winob0t</a> got me most of the way there. The only outstanding issue is the following: Image1 and Image2 are not required fields, so I now I can save 0,1 or 2 images; but if the user only uploads 1 picture I have no way of knowing if it came from imageUpload1 or imageUpload2.</p>
<p>Again, any help is appreciated!</p>
| <p>In your controller you can access the uploaded files as:</p>
<pre><code> if(Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) {
HttpPostedFileBase postFile = Request.Files.Get(0);
string filename = GenerateUniqueFileName(postFile.FileName);
postFile.SaveAs(server.MapPath(FileDirectoryPath + filename));
}
protected virtual string GenerateUniqueFileName(string filename) {
// get the extension
string ext = Path.GetExtension(filename);
string newFileName = "";
// generate filename, until it's a unique filename
bool unique = false;
do {
Random r = new Random();
newFileName = Path.GetFileNameWithoutExtension(filename) + "_" + r.Next().ToString() + ext;
unique = !File.Exists(FileDirectoryPath + newFileName);
} while(!unique);
return newFileName;
}
</code></pre>
<p>The text fields will arrive at your controller action as per usual i.e. Request.Form[...]. Note that you will also need to set the enctype on the form to "multipart/form-data". It sounds like you understand enough about ASP.NET MVC to do the rest. Note also that you can declare your form tag in the aspx view as follows, though you can use the more traditional approach if you like.</p>
<pre><code><% using(Html.BeginForm<FooController>(c => c.Submit(), FormMethod.Post, new { enctype = "multipart/form-data", @id = formId, @class = "submitItem" })) { %>
<% } %>
</code></pre>
|
XDocument.Descendants() not returning any elements <p>I'm trying to bind a Silverlight DataGrid to the results of a WCF service call. I was not seeing the data displayed in the grid, so when I ran through the debugger, I notice that XDocument.Descendants() was not returning any elements even when I was passing in a valid element name. Here is the XML that is passed back from the service:</p>
<pre><code><ArrayOfEmployee xmlns="http://schemas.datacontract.org/2004/07/Employees.Entities" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Employee>
<BirthDate>1953-09-02T00:00:00</BirthDate>
<EmployeeNumber>10001</EmployeeNumber>
<FirstName>Georgi</FirstName>
<Gender>M</Gender>
<HireDate>1986-06-26T00:00:00</HireDate>
<LastName>Facello</LastName>
</Employee>
<Employee>
<BirthDate>1964-06-02T00:00:00</BirthDate>
<EmployeeNumber>10002</EmployeeNumber>
<FirstName>Bezalel</FirstName>
<Gender>F</Gender>
<HireDate>1985-11-21T00:00:00</HireDate>
<LastName>Simmel</LastName>
</Employee>
</ArrayOfEmployee>
</code></pre>
<p>And here is the method I use to load the results into a collection of anonymous objects, using Linq to XMl, and then bind the collection to the grid.</p>
<pre><code>void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs args)
{
if (args.Error != null) return;
var xml = XDocument.Parse(args.Result);
var employees = from e in xml.Descendants("Employee")
select new
{
EmployeeNumber = e.Element("EmployeeNumber").Value,
FirstName = e.Element("FirstName").Value,
LastName = e.Element("LastName").Value,
Birthday = e.Element("BirthDate").Value
};
DataGrid.SelectedIndex = -1;
DataGrid.ItemsSource = employees;
}
</code></pre>
<p>Any idea why <code>xml.Descendants("Employee")</code> doesn't return anything?</p>
<p>Thanks!</p>
| <p>The string parameter passed to Descendents is actually implicitly converted to an XName object. An XName represents a fully qualified element name.</p>
<p>The document defines a namespace "i", therefore I believe you need to use the fully qualified name to access Employee. ie. i:Employee, where the prefix "i: actually resolves to the full namespace string.</p>
<p>Have you tried something like:</p>
<pre><code>XName qualifiedName = XName.Get("Employee", "http://www.w3.org/2001/XMLSchema-instance");
var employees = from e in xml.Descendants(qualifiedName)
...
</code></pre>
|
Select from MySQL records that sums <p>I know there are a few post out here about selecting records until a certain number is met from the sum of one field but there isn't any that suits me. I'm using PHP and MySQL.</p>
<p>I have a table named quantity. Inside there are records of product name, product price and product quantity. Besides these, there are a few others that helps me select the last records based on date and position, aswell as a GROUP BY the field named price because there are different quantities with different prices for the same product. So, I currently select my product specific price and quantity like this:</p>
<pre><code>SELECT `price`,`quantity` FROM (SELECT `price`,`quantity` FROM `quantity` WHERE `product_name` = 'DELL' ORDER BY `date` DESC, `position`) AS `Actions` GROUP BY `price`
</code></pre>
<p>This query is a workaround because I need to get data like this:</p>
<pre><code>product_name | price | quantity
DELL | 100 | 30
DELL | 120 | 10
DELL | 130 | 2
</code></pre>
<p>asuming that I have multiple records like these and I need to get the latest of them. Anyway, from this query I need to do the following: I need to select the records who's quantity summed with another product's quantity equals 35. So, by using my query I know that it should stop at line 2 because I can take the 30 products that came with the price of $100 and another 5 products from the line 2 that has price of 120. And then I would need to enter my updates. So, the new data would look like: </p>
<pre><code>product_name | price | quantity
DELL | 100 | 0
DELL | 120 | 5
DELL | 130 | 2
</code></pre>
<p>How in the world am I going to achieve this ? I hope my details are clear. Please, ask any question.</p>
<p>Thank you for your time!</p>
| <p><strong>Option 1: Use program logic instead of a query:</strong></p>
<p>There is nothing wrong with using the programming layer to do more advanced database interactions. SQL is not an answer to everything... (Also consider a stored procedure).</p>
<pre><code>enough = 35
running_total = 0
START TRANSACTION
while running_total < enough:
select one record order by price limit 1 FOR UPDATE
add to running_total
UPDATE records...
COMMIT
</code></pre>
<p><hr /></p>
<p><strong>Option 2: Use a query with a running total:</strong></p>
<p>In this option, you obtain a running total using a derived query, and then filter that down to specific records in the outer query. If you intend on updating them, you should wrap this in a transaction with the right isolation level.</p>
<pre><code>SET @running_total = 0;
SELECT
row_id,
product_name,
price,
quantity
FROM
(
SELECT
row_id,
product_name,
price,
quantity,
@running_total := @running_total + quantity AS running_total
FROM
sometable
WHERE
quantity > 0
ORDER BY
quantity
LIMIT
35 /* for performance reasons :) */
) as T1
WHERE
running_total < 35
</code></pre>
<p><hr /></p>
<p>I would tend to prefer option 1 because it is more "obvious", but perhaps this will give you some food for thought.</p>
|
Subdomain mapping to another external subdomain <p>I'm trying to map help.domain1.com to help.domain2.com. I've seen this on UserVoice. They let you map something.yourdomain.com to something.uservoice.com.</p>
<p>On domain1.com I've set up a CNAME to help.domain2.com.</p>
<p>It works fine but when I open help.domain1.com I get the content of domain2.com instead of help.domain2.com.</p>
<p>After some experimenting I've realized that this is an expected behavior. </p>
<p>So my question is what do I have to do on domain2.com (or maybe on domain1.com?) to have it show content of subdomain "help.domain2.com" when I navigate help.domain1.com?</p>
<p>(I'm using Plesk and the OS is Windows Server 2003)</p>
| <p>I was facing the same problem for the last couple of days, and just found the solution...</p>
<p>In /etc/apache2/site-available/default, I had two virtual hosts, first one was for my domain, and the second one was for my sub domain. All I had to do was reverse the order of the virtual host blocks, placing the sub domain in front of the domain, and it worked! :D</p>
|
Flex: Passing MXML file as XML Parameter <p>Is it Possible to pass MXML it self as parameter(XML param) from external application and load in Flash Player dynamically to create page. For e.g</p>
<p>passing xml = <mx:canvas><mx:label text="hello" /></mx:canvas> to Flex and flex should create canvas with label control in it. Is there any example related to it.</p>
<p>Thanx</p>
| <p>MXML code needs to be compiled down to ActionScript before Flash Player can do anything with it. MXML is not interpreted by Flash Player at runtime.</p>
|
Interesting test of Javascript RegExp <p>I wrote a Javascript RegExp test to detect date string format, I added an redundant "g" flag by mistake and found something interesting.</p>
<pre class="lang-js prettyprint-override"><code>var s = "2009/03/10";
var regex=/^\d{4}[/]\d{2}[/]\d{2}$/g;
alert(regex.test(s));
alert(regex.test(s));
alert(regex.test(s));
alert(regex.test(s));
</code></pre>
<p>I got a 'true' followed by a 'false', then another 'true', then another 'false'.</p>
<p>If I use a loop to execute it, I found something more interesting, I got four "true" in IE and Safari, and true,false,true,false in FF, Chrome.</p>
<pre class="lang-js prettyprint-override"><code>for (var i=0; i&lt;4; i++)
{
var s = "2009/03/10";
var regex=/^\d{4}[/]\d{2}[/]\d{2}$/g;
alert(regex.test(s));
}
</code></pre>
<p>Does anybody has idea to explain why the Javascript regex behaves like that and what cause browsers return different results? ( related to variable declaration and life scope? )</p>
| <p>When you use a global flag on a JS RegExp the "test" and "exec" methods each halt at the first match but keep a pointer to where they stopped searching in the string. That pointer can be inspected on the <code>lastIndex</code> property. When you call "test" or "exec" again it begins searching for a match starting at the <code>lastIndex</code>.</p>
<p>So, when you test a RegExp on a string that matches the entire string the lastIndex is set to the end of the string. The next time you test it starts at the end of the string, returns <code>false</code>, and sets <code>lastIndex</code> back to zero.</p>
<p>The MDC has a <a href="https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Global%5FObjects/RegExp/lastIndex">decent explanation</a> of this behavior.</p>
|
Can I do STI and still use polymorphic path helpers? <p>I am using Single Table Inheritance and have comments on all the subclasses. I am only using 1 controller for all the different STI types. When the form_for helper generates a URL for a subtype it tries to use a helper for the subtype, but I want it to use the helper for the parent. </p>
<p>This is the error I get:</p>
<pre><code>undefined method `subclasstypename_comments_path' for #<ActionView::Base:0x41ef27c>
</code></pre>
<p>The path helper it 'should' use is</p>
<pre><code>parentclasstypename_comments_path
</code></pre>
| <p>Yep, just use <code>AR::Base#becomes</code>.</p>
<p>Say your base class is <code>Account</code>, which is subclassed to <code>GuestAccount</code> and <code>LoginAccount</code>.</p>
<pre><code>@account.is_a? LoginAccount? #=> true
</code></pre>
<p>Then you can just do a</p>
<pre><code>form_for [@account.becomes(Account), @comment] do |f|
...
</code></pre>
|
Nant, Booc, and x64 <p>I have a .NET project that's always been built/run by/on 32 bit machines. I got a new a 64 bit computer and am trying to tackle the task of getting it working there. The build script is in nant, and at one point we compile some boo code using the nant task. The boo code references our core DLL, which is built from c# source earlier in the build process.</p>
<p>I've tried two things: build it to run in 32bit mode and build it to run in 64bit mode. By using corflags on several programs (including booc), I was able to build the project built in 32bit mode, but ended up with a bunch of downstream issues at runtime. So I need to get it built in 64bit mode, which I think is preferable anyway.</p>
<p>According to the nant/booc source code, the booc nant task calls the booc.exe in-process using the CLR's Process class, so (I think) it should inherit 32bitness or 64bitness from the parent process. That doesn't reflect what I'm seeing, though.</p>
<p>Here's what I've done:</p>
<ol>
<li>Used the 64bit version of powershell to invoke nant</li>
<li>Specified platform="x64" on my tasks. I feel like I shouldn't have to do this because anycpu should be fine, but it seems to make a difference.</li>
</ol>
<p>Here's the error I'm getting:</p>
<pre><code>[booc] Compiling 5 files to 'C:\dev\build\MyProjectBoo.dll'.
[booc] BCE0106: Failed to access the types defined in assembly 'MyProject, Version=5.5.0.0, Culture=neutral, PublicKeyToken=null' - (C:\dev\build\MyProject.dll):Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
[booc] is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)
[booc] is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)
[booc] .
[booc] 1 error(s).
</code></pre>
<p>Which means, according to the booc source code, "I tried to reflectively list the types in your referenced assembly but failed". I don't know if that means, "I think I'm 32bit but these are 64bit dlls" or what, and I'm very confused.</p>
<p>Any ideas on how I can get this to work?</p>
<p><strong>Update</strong> after some work, I've discovered that the issue has nothing to do with boo. I wrote a quick c# program that reflectively loads the dll and it breaks in the same way. So for some reason, no matter what I set as the platform (x86, x64 or anycpu), I can't load it reflectively on an x64 machine. So not really boo's fault. So I'm going to dig into this and repost if I have a better question.</p>
<p><strong>Newer Update</strong>
Turns out that one of my main DLL's third party dependencies insists on being in a 32 bit environment, even though it isn't built with corflags. This causes assembly.GetTypes() fail in 64 bit mode.</p>
| <p>The problem is dependencies on third-party DLL's that require 32 bit mode, which is possible even if they don't have corflags set.</p>
|
How to get SSRS Data Source credentials and open an SQL Connection in .NET <p>I am using an ASP.Net and C# front end to run some reports. I want to open an SQL Connection to the data source used by the report.</p>
<p>When the report uses integrated security it is easy enough to create a connection, however I want to create a connection when the user name and password are stored by the reporting server.</p>
<p>I can get SQL Server path and initial catalogue, using </p>
<pre><code> DataSource[] dataSources;
DataSourceReference dsReference;
DataSourceDefinition dsDefinition;
string dsPath;
ReportingService2005 rs = new ReportingService2005();
dataSources = rs.GetItemDataSources(reportPath);
if (dataSources.Length > 0)
{
dsReference = (DataSourceReference)dataSources[0].Item;
dsPath = dsReference.Reference;
dsDefinition = rs.GetDataSourceContents(dsPath);
// ....
}
</code></pre>
<p>I can also get the user name using</p>
<pre><code> username = dsDefinition.UserName;
</code></pre>
<p>however if I use</p>
<pre><code> password = dsDefinition.Password;
</code></pre>
<p>password = null, and can't be used to open the Sql Connection.</p>
<p><strong>Is there a way to create an SQLConnection that uses the connection string and username and password credentials of a data source?</strong></p>
<p>I am using Reporting Services 2008, and .NET 3.5 with web references to ReportService2005.asmx and ReportExecution2005.asmx</p>
| <p>I really don't think it's possible, as this would pretty much constitute a security hole. I know this isn't the answer you are looking for, but I would parameterise the location of your reports (i.e. the IP/name of your MSRS server) and store them in your web.config along with a matching SQL instance. While it's not exactly what you're after, I think that's about as close as you are going to get.</p>
|
Setting a cell's format using Excel 2007 Interop and C# <p>I'm using the office 2007 interop assemblies to create some excel spreadsheets.</p>
<p>There are plenty of questions on here about getting started and MSDN contains heaps of articles, like <a href="http://msdn.microsoft.com/en-us/library/bb491102.aspx" rel="nofollow">this one</a>.</p>
<p>The API is funky, and sometimes a bit confusing.</p>
<p>When I set a value of a cell, is there a way to set it's format?
I'd like to mark particular fields as Date's so my customer can run excel macros on them.
Also, numbers would be useful.</p>
<p>Thanks!</p>
| <p>VBA based code. However same should work with c# (ignore the syntax).</p>
<pre>
<code>
cells(1,1).Value = 39875
cells(1,1).NumberFormat = "dd-mmm-yyyy"
</code>
</pre>
<p>The best way to learn Excel Object Model is to create a macro of actions you wish to take, look at the code & modify the parts which require external input. Also, the object model is pretty easy to understand (Application -> Workbook -> Worksheets -> Worksheet -> Range (Cell)).</p>
|
NTFS Alternate Data Streams - .NET <p>How would I create/ delete/ read/ write/ NTFS alternate data streams from .NET?</p>
<p>If there is no native .NET support, which Win32 API's would I use? Also, how would I use them, as I don't think this is documented?</p>
| <p>Here is a version for C#</p>
<pre><code>using System.Runtime.InteropServices;
class Program
{
static void Main(string[] args)
{
var mainStream = NativeMethods.CreateFileW(
"testfile",
NativeConstants.GENERIC_WRITE,
NativeConstants.FILE_SHARE_WRITE,
IntPtr.Zero,
NativeConstants.OPEN_ALWAYS,
0,
IntPtr.Zero);
var stream = NativeMethods.CreateFileW(
"testfile:stream",
NativeConstants.GENERIC_WRITE,
NativeConstants.FILE_SHARE_WRITE,
IntPtr.Zero,
NativeConstants.OPEN_ALWAYS,
0,
IntPtr.Zero);
}
}
public partial class NativeMethods
{
/// Return Type: HANDLE->void*
///lpFileName: LPCWSTR->WCHAR*
///dwDesiredAccess: DWORD->unsigned int
///dwShareMode: DWORD->unsigned int
///lpSecurityAttributes: LPSECURITY_ATTRIBUTES->_SECURITY_ATTRIBUTES*
///dwCreationDisposition: DWORD->unsigned int
///dwFlagsAndAttributes: DWORD->unsigned int
///hTemplateFile: HANDLE->void*
[DllImportAttribute("kernel32.dll", EntryPoint = "CreateFileW")]
public static extern System.IntPtr CreateFileW(
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
[InAttribute()] System.IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
[InAttribute()] System.IntPtr hTemplateFile
);
}
public partial class NativeConstants
{
/// GENERIC_WRITE -> (0x40000000L)
public const int GENERIC_WRITE = 1073741824;
/// FILE_SHARE_DELETE -> 0x00000004
public const int FILE_SHARE_DELETE = 4;
/// FILE_SHARE_WRITE -> 0x00000002
public const int FILE_SHARE_WRITE = 2;
/// FILE_SHARE_READ -> 0x00000001
public const int FILE_SHARE_READ = 1;
/// OPEN_ALWAYS -> 4
public const int OPEN_ALWAYS = 4;
}
</code></pre>
|
How to display a customized code in C# & DevExexpress TextEditor with mask <p>I am trying to display a code like ABC/DEF/00012 or ABC/EDF/01234 or ABC/DEF/00009</p>
<p>I use RegEx mask \w{3}/\w{3}/?????</p>
<p>The question mark is hard part that I could not figure it out.</p>
<p>Basically, I try to display the code with characters and numbers. I want to automatically add leading zeros on the number.</p>
<p>Byron</p>
| <p>Seems that you're trying to match 5 digits at the end:</p>
<p>\w{3}/\w{3}/\d{5}</p>
|
how to run the batch file from any folder <pre><code>cd ../../jobs
set CLASSPATH=.;../xyz.jar;../mysql-connector-java-5.1.6-bin.jar
java folser.folder1 ../Files/MySQL.xml
cd ..
</code></pre>
<p>I need to run the batch file from any directory. I have set the paths for java. Can anybody help me?</p>
| <p>Under *nix (e.g. Linux):</p>
<pre><code>cd "`dirname \"$0\"`"
# your current directoy is now the script's directory
cd ../../jobs
set CLASSPATH=.:../xyz.jar:../mysql-connector-java-5.1.6-bin.jar
java folder.folder1 ../Files/MySQL.xml
cd ..
# when the script terminates, you are automatically
# back to the original directory
</code></pre>
<p>Under Windows NT/XP/etc.:</p>
<pre><code>SETLOCAL
PUSHD .
REM current directory has been saved and environment is protected
CD /d %~dp0
REM your current directoy is now the script's directory
CD ..\..\jobs
SET CLASSPATH=.;..\xyz.jar;..\mysql-connector-java-5.1.6-bin.jar
java folder.folder1 ..\Files\MySQL.xml
CD ..
REM before the script terminates, you must explicitly
REM return back to the original directory
POPD
ENDLOCAL
</code></pre>
|
Socket Programming <p>Am trying to create a server application in c#.In the code am using the TcpListener class.</p>
<pre>
<code>
TcpListener t = new TcpListener(5555);
t.Start();
</code>
</pre>
<p>However it is providing an error saying: Invalid token '(' in class, struct, or interface member declaration. </p>
<p>Are there additional references required?.<br />
Please help.</p>
<pre>
<code>
namespace WindowsApplication1
{
public partial class lanmessenger : Form
{
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);
public lanmessenger()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder(this.textBox1.Text);
sb.AppendLine(this.textBox2.Text);
this.textBox1.Text = sb.ToString();
this.textBox2.Text = "\0";
HideCaret(this.textBox1.Handle);
}
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
HideCaret(this.textBox1.Handle);
}
StreamWriter streamWriter;
StreamReader streamReader;
NetworkStream networkStream;
TcpListener t = new TcpListener(5555);
t.Start();
}
}
</code>
</pre>
<p>This is the full source code upto now. Am unable to find the error.</p>
| <p>Works fine for me. You need to add following line in your code.</p>
<p>using System.Net.Sockets;</p>
|
Non-collapsing but still (line-)breakable space in HTML? <p>What can I use in HTML if I want to have whitespace in the middle of the line that looks like three spaces, but can still be broken if the line gets too long?</p>
<p>Regular whitespace gets collapsed (a run of spaces looks the same as a single space), and at the non-breaking space (&nbsp) the line cannot be broken.</p>
<p><strong>Update</strong>: I think what I really want is a ï¼preï¼ tag that can still break long lines (I need to display source code).</p>
| <p>I actually have the exact answer youâre looking for. I searched everywhere for this answer and nothing anyone suggested worked perfectly. So, I thought up a solution and tried it and was floored that it worked without any flaw!</p>
<p><a href="http://stackoverflow.com/a/605470/578288">Garrow</a> was actually right (he just didnât explain it or take it all the way). The solution is instead of putting <code>&nbsp;</code> alone, put <code>&nbsp;<wbr></code>. Just do a simple search and replace and add the <code><wbr></code> tag after every <code>&nbsp;</code>. Works perfectly!</p>
<p>The <code><wbr></code> tag is a little-known tag supported in all major browsers that tells the browser to put a newline here ONLY if it is needed.</p>
<p>Update: I found one browser that this doesnât work exactly right in â IE 8! They actually took out the <code><wbr></code> tag! I solved this issue by creating a class that says:</p>
<pre class="lang-css prettyprint-override"><code>.wbr:before { content: "\200B" }
</code></pre>
<p>and instead of replacing <code>&nbsp;</code> with <code>&nbsp;<wbr></code>, replace it with the following:</p>
<pre class="lang-html prettyprint-override"><code>&nbsp;<wbr><span class='wbr'></span>
</code></pre>
<p>In PHP, this would look like:</p>
<pre class="lang-php prettyprint-override"><code>$text = str_replace(" ","&nbsp;<wbr><span class='wbr'></span>", $text);
</code></pre>
<p>Donât forget to add the class as well.</p>
<p>Obviously this is getting quite a bit excessive, replacing a single space with all of that, but it does work just as desired and since I never saw the markup it worked for me. </p>
<p>If this is too messy, another solution is to exchange double spaces for a <code>&nbsp;</code> followed by a normal space. This will alternate <code>&nbsp;</code> and normal spaces and works in my tests.</p>
<p>In PHP, this would look like:</p>
<pre class="lang-php prettyprint-override"><code>$text = str_replace(" ","&nbsp; ", $text);
</code></pre>
<p>Hope this helps! I put enough research into this; I thought I should pass it on.</p>
|
Working over networks <p>I am using a aix box over a network.
I am using putty to work on the box. The problem is its too slow,But we do have a high speed network.</p>
<p>Is there any terminal program other than putty that can help me work comfortably..by doing some buffering or other mechanism by which i wont feel like i m working on a dialup.</p>
<p>Thanks.</p>
| <p>PuTTY is perfectly fast - I've never had any problems with it.</p>
<p>Have you established where the bottleneck is? What's the exact setup of the network between your client and the server? Is perhaps the AIX server too heavily loaded?</p>
|
How can one compute the optimal parameters to a start-step-stop coding scheme? <p>A start-step-stop code is a data compression technique that is used to compress number that are relatively small.</p>
<p>The code works as follows: It has three parameters, start, step and stop. Start determines the amount of bits used to compute the first few numbers. Step determines how many bits to add to the encoding when we run out and stop determines the maximum amount of bits used to encode a number.</p>
<p>So the length of an encoding is given by l = start + step * i.</p>
<p>The "i" value of a particular code is encoded using unary. That is, a number of 1 bits followed by a terminating 0 bit. If we have reached stop then we can drop the terminating 0 bit. If i is zero we only write out the 0 bit.</p>
<p>So a (1, 2, 5) start-step-stop code would work as follows:</p>
<p>Value 0, encoded as: 0 0<br/>
Value 1, encoded as: 0 1<br/>
Value 2, encoded as: 10 000<br/>
Value 9, encoded as: 10 111<br/>
Value 10, encoded as: 11 00000<br/>
Value 41, encoded as: 11 11111<br/></p>
<p>So, given a file containing several numbers, how can we compute the optimal start-step-stop codes for that file? The optimal parameters are defined as those that will result in the greatest compression ratio.</p>
| <p>These "start-step-stop" codes looks like a different way of calling <a href="http://en.wikipedia.org/wiki/Huffman%5Fcoding" rel="nofollow">Huffman codes</a>. See the <a href="http://en.wikipedia.org/wiki/Huffman%5Fcoding#Basic%5Ftechnique" rel="nofollow">basic technique</a> for an outline of the pseudo-code for calculating them.</p>
<p>Essentially this is what the algorithm does:</p>
<p>Before you start the Huffman encoding you need to gather the statistics of each symbol you'll be compressing (Their total frequency in the file to compress).</p>
<p>After you have that you create a <a href="http://en.wikipedia.org/wiki/Binary%5Ftree" rel="nofollow">binary tree</a> using that info such that the most frequently used symbols are at the top of the tree (and thus use less bits) and such that no encoding has a <a href="http://en.wikipedia.org/wiki/Prefix%5Fcode" rel="nofollow">prefix code</a>. Since if an encoding has a common prefix there could be ambiguities decompressing.</p>
<p>At the end of the Huffman encoding your start value will be depth of the shallowest leaf node, your step will always be 1 (logically this makes sense, why would you force more bits than you need, just add one at a time,) and your stop value will be the depth of the deepest leaf node.</p>
<p>If the frequency stats aren't sorted it will take O(nlog n) to do, if they are sorted by frequency it can be done in O(n).</p>
<p>Huffman codes are guaranteed to have the best average compression for this type of encoding:</p>
<blockquote>
<p>Huffman was able to design the most
efficient compression method of this
type: no other mapping of individual
source symbols to unique strings of
bits will produce a smaller average
output size when the actual symbol
frequencies agree with those used to
create the code.</p>
</blockquote>
<p>This should help you implement the ideal solution to your problem.</p>
<p><strong>Edit:</strong> Though similar, this isn't what the OP was looking for.</p>
<p>This <a href="http://www.stevenpigeon.org/Publications/publications/ssc%5Ffull.pdf" rel="nofollow">academic paper</a> by the creator of these codes describes a generalization of start-step-stop codes, start-stop codes. However, the author briefly describes how to get optimal start-step-stop near the end of section 2. It involves using a statistical random variable, or brute-force funding the best combination. Without any prior knowledge of the file the algorithm is O((log n)^3).</p>
<p>Hope this helps.</p>
|
PHP Parse error <pre><code><?php
$this_is_my_array = array("John","Johan");
for(int i = 5; i < 5; i++){
echo "$this_is_my_array[i] ";
}
//Adding name Markus
array_push($this_is_my_array,"Markus");
for(int i = 5; i < 5; i++){
echo "$this_is_my_array[i] ";
}
//Removing name from array
$this_is_my_array2= array_pop($this_is_my_array);
for(int i = 5; i < 5; i++) {
echo "$this_is_my_array2[i] ";
}
</code></pre>
<p>I just playing/learning php but this code gives me error. </p>
<pre><code>PHP Parse error: parse error, expecting ';' in C:\main.php php on line 3
</code></pre>
<p>What im going wrong?</p>
| <p>For starters, your variable i should be $i, with a dollar sign. That's the bulk of your error. But there's a few other problems. Try this.</p>
<pre><code>echo("start");
$this_is_my_array = array("John","Johan");
for($i = 5; $i < 5; $i++){
echo $this_is_my_array[$i];
}
//Adding name Markus
array_push($this_is_my_array,"Markus");
for($i = 5; $i < 5; $i++){
echo "$this_is_my_array[$i] ";
}
//Removing name from array
$this_is_my_array2= array_pop($this_is_my_array);
for($i = 5; $i < 5; $i++) {
echo "$this_is_my_array2[$i] ";
}
echo "end";
</code></pre>
<p>But look at your for loop, it says</p>
<p>$i = 5</p>
<p>while $i is less than 5, do something</p>
<p>But $i is already 5. </p>
|
Multiplying 23 bit datatypes in a system with no long long <p>I am trying to implement floating point operations in a microcontroller and so far I have had ample success.</p>
<p>The problem lies in the way I do multiplication in my computer and it works fine:</p>
<pre><code>unsigned long long gig,mm1,mm2;
unsigned long m,m1,m2;
mm1 = f1.float_parts.mantissa;
mm2 = f2.float_parts.mantissa;
m1 = f1.float_parts.mantissa;
m2 = f2.float_parts.mantissa;
gig = mm1*mm2; //this works fine I get all the bits I need since they are all long long, but won't work in the mcu
gig = m1*m2//this does not work, to be precise it gives only the 32 least significant bits , but works on the mcu
</code></pre>
<p>So you can see that my problem is that the microcontroller will throw an undefined refence to <code>__muldi3</code> if I try the <code>gig = mm1*mm2</code> there. </p>
<p>And If I try with the smaller data types, it only keeps the least significant bits, which I don't want it to. I need the 23 msb bits of the product. </p>
<p>Does anyone have any ideas as to how I can do this?</p>
| <p>Apologizes for the short answer, I hope that someone else will take the time to write a fuller explanation, but basically you do exactly as when you multiply two big numbers by hand on a paper! It's just that instead of working with base 10, you work in base 256. That is, treat your numbers as a byte vectors, and do with each byte what you do to a digit when you "hand multiply".</p>
|
Web service cast exception why? <pre><code>Error Cannot implicitly convert type 'string[]' to 'System.Collections.Generic.List<string>'
</code></pre>
<p>The above error is caused when I call a method to a web service</p>
<pre><code>List<string> bob = myService.GetAllList();
</code></pre>
<p>Where: GetAllList =</p>
<pre><code>[WebMethod]
public List<string> GetAllList()
{
List<string> list ....
return list;
}
</code></pre>
<p>I have rebuilt the whole solution, updated the service references and still I get a cast exception any ideas?</p>
| <p>you need to do this:</p>
<pre><code>List<string> bob = new List<string>(myService.GetAllList());
</code></pre>
<p>An overload for the constructor of a generic list takes an IEnumerable of the specified type to initialize the array. You can not, like the exception states, implicitly cast it staright to that type.</p>
<p>Andrew</p>
|
Indy Write Buffering / Efficient TCP communication <p>I know, I'm asking a lot of questions...but as a new delphi developer I keep falling over all these questions :)</p>
<p>This one deals with TCP communication using indy 10. To make communication efficient, I code a client operation request as a single byte (in most scenarios followed by other data bytes of course, but in this case only one single byte). Problem is that</p>
<pre><code>var Bytes : TBytes;
...
SetLength (Bytes, 1);
Bytes [0] := OpCode;
FConnection.IOHandler.Write (Bytes, 1);
ErrorCode := Connection.IOHandler.ReadByte;
</code></pre>
<p>does not send that byte immediately (at least the servers execute handler is not invoked). If I change the '1' to a '9' for example everything works fine. I assumed that Indy buffers the outgoing bytes and tried to disable write buffering with</p>
<pre><code>FConnection.IOHandler.WriteBufferClose;
</code></pre>
<p>but it did not help. How can I send a single byte and make sure that it is immediatly sent? And - I add another little question here - what is the best way to send an integer using indy? Unfortunately I can't find function like WriteInteger in the IOHandler of TIdTCPServer...and</p>
<pre><code>WriteLn (IntToStr (SomeIntVal))
</code></pre>
<p>seems not very efficient to me. Does it make a difference whether I use multiple write commands in a row or pack things together in a byte array and send that once?</p>
<p>Thanks for any answers!</p>
<p>EDIT: I added a hint that I'm using Indy 10 since there seem to be major changes concerning the read and write procedures.</p>
| <p>Write buffering is disabled by default. You can check write buffering to see if it's active in your code by testing the fConnection.IOHandler.WriteBufferingActive property.</p>
<p>As far as the best way to send an integer... 'it depends' on your protocol and overall goals. Specifically, use FConnection.IOHandler.Write() as there are overloaded methods to write just about any type of data, including an integer.</p>
<p>Taken from IdIOHandler:</p>
<pre><code>// Optimal Extra Methods
//
// These methods are based on the core methods. While they can be
// overridden, they are so simple that it is rare a more optimal method can
// be implemented. Because of this they are not overrideable.
//
//
// Write Methods
//
// Only the ones that have a hope of being better optimized in descendants
// have been marked virtual
procedure Write(const AOut: string; const AEncoding: TIdEncoding = enDefault); overload; virtual;
procedure WriteLn(const AEncoding: TIdEncoding = enDefault); overload;
procedure WriteLn(const AOut: string; const AEncoding: TIdEncoding = enDefault); overload; virtual;
procedure WriteLnRFC(const AOut: string = ''; const AEncoding: TIdEncoding = enDefault); virtual;
procedure Write(AValue: TStrings; AWriteLinesCount: Boolean = False; const AEncoding: TIdEncoding = enDefault); overload; virtual;
procedure Write(AValue: Byte); overload;
procedure Write(AValue: Char; const AEncoding: TIdEncoding = enDefault); overload;
procedure Write(AValue: LongWord; AConvert: Boolean = True); overload;
procedure Write(AValue: LongInt; AConvert: Boolean = True); overload;
procedure Write(AValue: SmallInt; AConvert: Boolean = True); overload;
procedure Write(AValue: Int64; AConvert: Boolean = True); overload;
procedure Write(AStream: TStream; ASize: Int64 = 0; AWriteByteCount: Boolean = False); overload; virtual;
</code></pre>
<p>Another question you had was "Does it make a difference whether I use multiple write commands in a row or pack things together in a byte array and send that once?" For the majority of cases, yes it makes a difference. For highly stressed servers you are going to have to get more involved in how bytes are sent back and forth, but at this level you should abstract out your sends into a separate protocol type class that builds the data to be sent and sends it in a burst and have a receiving protocol that receives a bunch of data and processes it as a complete unit instead of breaking things down to sending/receiving an integer, character, byte array, etc..</p>
<p>As a very rough quick example:</p>
<pre><code>TmyCommand = class(TmyProtocol)
private
fCommand:Integer;
fParameter:String;
fDestinationID:String;
fSourceID:String;
fWhatever:Integer;
public
property Command:Integer read fCommand write fCommand;
...
function Serialize;
procedure Deserialize(Packet:String);
end;
function TmyCommand.Serialize:String;
begin
//you'll need to delimit these to break them apart on the other side
result := AddItem(Command) +
AddItem(Parameter) +
AddItem(DestinationID) +
AddItem(SourceID) +
AddItem(Whatever);
end;
procedure TMyCommand.Deserialize(Packet:String);
begin
Command := StrToInt(StripOutItem(Packet));
Parameter := StripOutItem(Packet);
DesintationID := StripOutItem(Packet);
SourceID := StripOutItem(Packet);
Whatever := StrToInt(StripOutItem(Packet));
end;
</code></pre>
<p>Then send this via:</p>
<pre><code> FConnection.IOHandler.Write(myCommand.Serialize());
</code></pre>
<p>On the other side you can receive the data via Indy and then</p>
<pre><code> myCommand.Deserialize(ReceivedData);
</code></pre>
|
How to select html nodes by ID with jquery when the id contains a dot? <p>If my html looked like this:</p>
<pre><code><td class="controlCell">
<input class="inputText" id="SearchBag.CompanyName" name="SearchBag.CompanyName" type="text" value="" />
</td>
</code></pre>
<p>How could I select #SearchBag.CompanyName with JQuery?
I can't get it to work and I fear it's the dot that's breaking it all.
The annoying thing is that renaming all my id's would be a lot of work, not to mention the loss in readability.</p>
<p><strong>Note:</strong><br>
Please let's not start talking about how tables are not made for lay-outing. I'm very aware of the <a href="http://meyerweb.com/eric/thoughts/2009/02/17/wanted-layout-system/">value and shortcomings of CSS</a> and try hard to use it as much as possible.</p>
| <p>@Tomalak in comments:</p>
<blockquote>
<p>since ID selectors must be preceded by a hash #, there should be no ambiguity here</p>
</blockquote>
<p>â#id.classâ is a valid selector that requires both an id and a separate class to match; it's valid and not always totally redundant.</p>
<p>The correct way to select a literal â.â in CSS is to escape it: â#id\.moreidâ. This used to cause trouble in some older browsers (in particular IE5.x), but all modern desktop browsers support it.</p>
<p>The same method does seem to work in jQuery 1.3.2, though I haven't tested it thoroughly; quickExpr doesn't pick it up, but the more involved selector parser seems to get it right:</p>
<pre><code>$('#SearchBag\\.CompanyName');
</code></pre>
|
Entity framework and VARBINARY <p>Iâm using the .NET entity framework and Iâve got one entity containing a varbinary. Is there an easy way to get the size of the varbinary in the codebehind, efter itâs been retrieved from the database?</p>
<p>Iâm thinking there might be some way to get the size directly from the entity, something like entity.Context.Size â or do one need to handle it differently?</p>
| <p>A varbinary translates to a byte[] field in the entity framework, which means you can check the Length property of the array:</p>
<pre><code>int fieldSize = entity.MyVarBinaryField.Length;
</code></pre>
<p>As mentioned by <a href="http://stackoverflow.com/a/5409481/137471">tster</a>: In a LINQ to Entities query, you can call the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.sqlclient.sqlfunctions.datalength.aspx">DataLength</a> method of the <a href="http://msdn.microsoft.com/en-us/library/dd466188.aspx">SqlFunctions</a> class, which will translate into a <a href="http://msdn.microsoft.com/en-us/library/ms173486.aspx">DATALENGTH</a> function call in the generated SQL statement. This only works with SQL Server and Entity Framework 4 or later:</p>
<pre><code>int? fieldSize = repository.Entity
.Select(e => SqlFunctions.DataLength(e.MyVarBinaryField)).Single();
</code></pre>
|
Reasons for why a WinForms label does not want to be transparent? <p>Why can't I set the BackColor of a Label to Transparent? I have done it before, but now it just don't want to...</p>
<p>I created a new UserControl, added a progressbar and a label to it. When I set the BackColor of the label to transparent it is still gray =/ Why is this?</p>
<p>What I wanted was to have the label on top of the progressbar so that its text was "in" the progressbar...</p>
| <p>Add a new class to your project and post the code shown below. Build. Drop the new control from the top of the toolbox onto your form.</p>
<pre><code>using System;
using System.Windows.Forms;
public class TransparentLabel : Label {
public TransparentLabel() {
this.SetStyle(ControlStyles.Opaque, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
}
protected override CreateParams CreateParams {
get {
CreateParams parms = base.CreateParams;
parms.ExStyle |= 0x20; // Turn on WS_EX_TRANSPARENT
return parms;
}
}
}
</code></pre>
|
Command line video editing tools <p>I'm looking for (linux) command line tools that can help with video editing. I am mostly interested in:</p>
<ul>
<li>Cutting</li>
<li>Transitions</li>
<li>Effects</li>
</ul>
<p>Any pointers would be appreciated (I know ffmpeg can do basic cutting, but not much beyond that afaik).</p>
| <p>Two tools I use are <a href="http://www.transcoding.org/cgi-bin/transcode" rel="nofollow">transcode</a> and <a href="http://en.wikipedia.org/wiki/MEncoder" rel="nofollow">mencoder</a>.</p>
<blockquote>
<p>Transcode is a suite of command line
utilities for transcoding video and
audio codecs, and for converting
beween different container formats.</p>
<p>A variety of video and audio pre and
post-processing filters are available,
including (but not limited to):</p>
<ul>
<li>framerate conversion</li>
<li>smoothing</li>
<li>cutting</li>
</ul>
<p>MEncoder is a free command line video decoding, encoding and filtering tool based on mplayer.</p>
</blockquote>
|
What is the current best validation framework for asp.net apps? <p>To make sure its a DRY approach all validation logic should of course go in the business logic (model).</p>
<ul>
<li>How are validation messages presented to views, should be able to localize error messages</li>
<li>Can you generate javascript from the validation framework. Compatibility with JQuery would be perfect</li>
<li>Is the framework compatible with a DbC approach?</li>
</ul>
<p>Edit:
I think this is the nicest one until now, Castle validator + live validation
<a href="http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/" rel="nofollow">http://blog.codeville.net/2008/04/30/model-based-client-side-validation-for-aspnet-mvc/</a></p>
| <p><a href="http://msdn.microsoft.com/en-us/library/cc309509.aspx" rel="nofollow">Validation Application Block</a></p>
<p>from Microsoft is one alternative but I have no experience with it</p>
|
Saving element position and size (JQuery ui resizable and draggable) <p>I'm new to jquery and even javascript. I'm trying to create a system where you can edit very simple, static page by logging in and just dragging and resizing divs. The system works to the point where you get to edit the site, but the problem is how to save the coordinates and sizes of the divs. </p>
<p>The system doesn't use mysql, since the login is just for the site author. I'd also like to try to not require javascript to just view the page (get the coordinates and sizes from a file via php).</p>
<p>So, basically I need a way to check div width, height, left and top and store them into a file when the author hits the save-button.</p>
| <p>You could store the variables in a cookie on the user's machine (jQuery doesn't have native cookie support, but <a href="http://plugins.jquery.com/project/cookie" rel="nofollow">this plugin</a> gives it to you).</p>
<p>However, that requires Javascripw, which you mention that you don't want to require. However, if you want the user to be able to drag modules on a page around, then you aren't going to be able to do this without the aid of js.</p>
<p>If you do want to store this data server-side, then all I can suggest short of using a database is to store them in a file-based cache.</p>
|
Ruby? How to ignore newlines in cut and pasted user input? <p>I've written a little Ruby script that requires some user input. I anticipate that users might be a little lazy at some point during the data entry where long entries are required and that they might cut and paste from another document containing newlines.</p>
<p>I've been playing with the <a href="http://rubyforge.org/projects/highline/" rel="nofollow">Highline</a> gem and quite like it. I suspect I am just missing something in the docs but is there a way to get variable length multiline input?</p>
<p>Edit: The problem is that the newline terminates that input and the characters after the newline end up as the input for the next question.</p>
| <p>Here's what the author uses in his example: (from highline-1.5.0/examples)</p>
<pre><code>#!/usr/local/bin/ruby -w
# asking_for_arrays.rb
#
# Created by James Edward Gray II on 2005-07-05.
# Copyright 2005 Gray Productions. All rights reserved.
require "rubygems"
require "highline/import"
require "pp"
grades = ask( "Enter test scores (or a blank line to quit):",
lambda { |ans| ans =~ /^-?\d+$/ ? Integer(ans) : ans} ) do |q|
q.gather = ""
end
say("Grades:")
pp grades
</code></pre>
<p>General documentation on <code>HighLine::Question#gather</code> (from highline-1.5.0/lib/highline/question.rb)</p>
<pre><code># When set, the user will be prompted for multiple answers which will
# be collected into an Array or Hash and returned as the final answer.
#
# You can set _gather_ to an Integer to have an Array of exactly that
# many answers collected, or a String/Regexp to match an end input which
# will not be returned in the Array.
#
# Optionally _gather_ can be set to a Hash. In this case, the question
# will be asked once for each key and the answers will be returned in a
# Hash, mapped by key. The <tt>@key</tt> variable is set before each
# question is evaluated, so you can use it in your question.
#
attr_accessor :gather
</code></pre>
<p>These seem to be your main options w/in the library. Anything else, you'd have to do yourself.</p>
|
Updating multiple selected INofityPropertyChange objects in DataGridView <p>I'm working with a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.aspx" rel="nofollow"><code>DataGridView</code> (Windows Forms)</a> with MultiSelect enabled which is placed in a User Control. I'd like to update all selected rows from outside the User Control by calling a public method that implements the following code:</p>
<pre><code>foreach(DataGridViewRow dr in dataGridView.SelectedRows)
{
MyBusiness business = (MyBusiness)dr.DataBoundItem;
business.Rating = 5;
}
</code></pre>
<p>Unfortunately, when multiple rows are selected, only one <code>DataGridViewRow</code> is immediately refreshed, namely the one that was last selected. The underlying objects are changed, and the NotifyPropertyChange-event is fired. Moreover, when I change the selection after update, I see all rows updated exactly as I'd like them to be immediately.</p>
<p>Second thing, very strange: When I set a breakpoint in the Setter of the <code>Rating</code>-property where NotifyPropertyChange is fired and wait there a few seconds before continuing code execution, everything works well (all rows are immediately updated). If I don't wait but press F5 very quickly each time the breakpoint is passed, I get the effect described above.</p>
<p>My business object looks like this (significantly shortened of course):</p>
<pre><code>public class MyBusiness : INotifyPropertyChanged
{
private int _rating;
public int Rating
{
get { return _rating; }
set
{
if(_rating != value)
{
_rating = value;
NotifyPropertyChanged("Rating");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
</code></pre>
<p>Has anybody already noticed this behavior too, or even knows a solution (or a workaround)?</p>
| <p>If your DGV is bound to a regular List, it only subscribes to the PropertyChanged event for the currently-selected row. Try using a BindingList instead, or calling BindingSource.ResetItem(n) for each item changed.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms184414.aspx" rel="nofollow">MSDN gives an example</a> which uses a BindingList and also (pointlessly) calls ResetItem. Play with their example, and you can see that either removing the call to ResetItem, or replacing the BindingList with a regualr List<> will operate as intended.</p>
|
How can I change the color of the gridlines of a Grid in WPF? <p>I have a <code>Grid</code> (not a DataGrid, but a real Grid), with <code>GridLines</code> set to <code>True</code>. How can I change the color of the gridlines?
Hardcoded in XAML is ok, since it is just for development-reasons.</p>
<pre><code><Grid ShowGridLines="True" />
</code></pre>
| <p>Sorry, can't be done with ShowGridLines - you need to style the elements contained.</p>
<p><strong>Exhibit A:</strong> </p>
<p>MSDN docs say "Only dotted lines are available because this property is intended as a design tool to debug layout problems and is not intended for use in production quality code. If you want lines inside a Grid, style the elements within the Grid to have borders."</p>
<p><strong>Exhibit B - The WPF Source Code:</strong></p>
<p>Notice the Brushes.Blue and Brushes.Yellow hard-coded in this sealed internal class which System.Windows.Controls.Grid uses to draw the lines.</p>
<p>From Grid.cs</p>
<pre><code> /// <summary>
/// Helper to render grid lines.
/// </summary>
internal class GridLinesRenderer : DrawingVisual
{
/// <summary>
/// Static initialization
/// </summary>
static GridLinesRenderer()
{
s_oddDashPen = new Pen(Brushes.Blue, c_penWidth);
DoubleCollection oddDashArray = new DoubleCollection();
oddDashArray.Add(c_dashLength);
oddDashArray.Add(c_dashLength);
s_oddDashPen.DashStyle = new DashStyle(oddDashArray, 0);
s_oddDashPen.DashCap = PenLineCap.Flat;
s_oddDashPen.Freeze();
s_evenDashPen = new Pen(Brushes.Yellow, c_penWidth);
DoubleCollection evenDashArray = new DoubleCollection();
evenDashArray.Add(c_dashLength);
evenDashArray.Add(c_dashLength);
s_evenDashPen.DashStyle = new DashStyle(evenDashArray, c_dashLength);
s_evenDashPen.DashCap = PenLineCap.Flat;
s_evenDashPen.Freeze();
}
</code></pre>
|
WPF RichTextBox does not delete text <p>I am trying to cancel (prevent) some text editing in RichTextBox.
I am using TextChanged event, but I did not find the way how to cancel or rollback some changes, any ideas?</p>
<pre><code>private void mainRTB_TextChanged(object sender, TextChangedEventArgs e)
{
TextRange text = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);
if (text.Text.Length >= this.MaxLenght)
{
mainRTB.Document.ContentEnd.DeleteTextInRun(-1);
mainRTB.IsReadOnly = true;
}
}
</code></pre>
<p>By executing mainRTB.Document.ContentEnd.DeleteTextInRun(-1); does not delete any text.</p>
<p>mainRTB -> System.Windows.Controls.RichTextBox</p>
<p>Thks</p>
| <p>I do not believe there is a way to prevent the edit because there is only a ChangedEvent and no Changing or PreviewChange event. What you could try though is undoing the change.</p>
<pre><code>private void mainRTB_TextChanged(object sender, TextChangedEventArgs e) {
TextRange text = new TextRange(mainRTB.Document.ContentStart, mainRTB.Document.ContentEnd);
if (text.Text.Length >= this.MaxLenght && mainRTB.CanUndo)
{
mainRTB.Undo();
mainRTB.IsReadOnly = true;
}
}
</code></pre>
|
Launching a C# dialog from an unmanaged C++ mfc active x dll <p>I've been told to write a dialog in C# which must be instantiated from an unmanaged c++ dll. We do this in other places in our code by simply adding a managed c++ class to the C++ project, then calling the C# dll from the managed c++ class. However I'm finding that doesn't work for me from where I have to do it. I think because the c++ dll is an MFCActiveX project. As soon as i set the clr on any file in this project, it will no longer register correctly. When i attempt to register it, i get three errors, then a message that it registered. However when i try to use it i get a 0x80040111 "ClassFactory cannot supply requested class" error.
If anyone has any idea what the problem is here i would greatly appreciate it. I either need to be able to accomplish this (preferred) or prove that it's not possible.</p>
<p>Thanks</p>
| <p>You must now register it with "regasm" instead of "regsvr32".</p>
|
NHibernate mappings when self-join relationships have additional properties <p>How do you map a class to other instances of the same class <em>when that relationship has properties itself</em>?</p>
<p>I have a class called Person which is mapped to a table Person</p>
<pre><code>PersonID PersonName PersonAge
----------------------------------
1 Dave Dee 55
2 Dozy 52
3 Beaky 45
4 Mick 55
5 Tich 58
</code></pre>
<p>I want a many-to-many relationship between Person and Person using a join table called PersonPerson:</p>
<pre><code> PersonPersonID PersonID RelatedPersonID RelationshipID
--------------------------------------------------------
1 1 5 1
2 3 4 2
3 2 1 3
</code></pre>
<p>I want the following attributes in the PersonPerson table:</p>
<pre><code>RelationshipID RelationshipName
--------------------------------
1 Colleague
2 Manager
3 Tutor
</code></pre>
<p><a href="http://stackoverflow.com/questions/350311/using-additional-data-on-intermediate-table-with-nhibernate/350702#350702">This question</a> and the linked-to <a href="http://devlicio.us/blogs/billy_mccafferty/archive/2008/07/11/when-to-use-many-to-one-s-vs-many-to-many-with-nhibernate.aspx" rel="nofollow">post by Billy McCafferty</a> explains that the PersonPerson relationship has to be promoted from a normal JOIN to an entity in its own right because of the additional columns in the PersonPerson table. However it doesn't explain what to when it is a self-join. The difference being that if I ask for all the related people to <b>Dave Dee</b> (ID = 1), not only should I get <b>Tich</b> (ID = 5), but I should get also get <b>Dozy</b> (ID = 2) as well because Dave Dee is also in the RelatedPersonID column.</p>
<p>What my solution is so far, is to have two properties in my Person class.</p>
<pre><code>public virtual IList<PersonPerson> PersonPersonForward {get;set;}
public virtual IList<PersonPerson> PersonPersonBack {get;set;}
private List<PersonPerson> personPersonAll;
public virtual List<PersonPerson> PersonPersonAll
{
get
{
personPersonAll = new List<PersonPerson>(PersonPersonForward);
personPersonAll.AddRange(PersonPersonBack);
return personPersonAll;
}
}
</code></pre>
<p>And have the following in the hbm:</p>
<pre><code> <bag name="PersonPersonForward" table="PersonPerson" cascade="all">
<key column="PersonID"/>
<one-to-many class="PersonPerson" />
</bag>
<bag name="PersonPersonBack" table="PersonPerson" cascade="all">
<key column="RelatedPersonID"/>
<one-to-many class="PersonPerson" />
</bag>
</code></pre>
<p>This seems a trifle clunky and inelegant. NHibernate usually has elegant solutions to most everyday problems. Is the above the sensible way of doing this or is there a better way?</p>
| <p>I think I would do it like that as well, but, I think it is a bit 'clumsy' to model it like this.
I mean: you have a collection of persons to which a certain person is related, but you also have a 'back-relation'.<br />
Is this really necessary ? Isn't it an option to remove this back-collection and instead, specify a method on the PersonRepository which can give you all persons back that have some kind of relation with a given person ? </p>
<p>Hmm, this can maybe sound a bit obscure, so here 's some code (note that for the sake of brevity, I left out the 'virtual' modifiers etc... (I also prefer not to have those modifiers, so in 99% of the time, I specify 'lazy=false' at my class-mapping).</p>
<pre><code>public class Person
{
public int Id {get; set;}
public string Name {get; set;}
public IList<PersonPerson> _relatedPersons;
public ReadOnlyCollection<PersonPerson> RelatedPersons
{
get
{
// The RelatedPersons property is mapped with NHibernate, but
// using its backed field _relatedPersons (can be done using the
// access attrib in the HBM.
// I prefer to expose the collection itself as a readonlycollection
// to the client, so that RelatedPersons have to be added through
// the AddRelatedPerson method (and removed via a RemoveRelatedPerson method).
return new List<PersonPerson) (_relatedPersons).AsReadOnly();
}
}
public void AddRelatedPerson( Person p, RelationType relatesAs )
{
...
}
}
</code></pre>
<p>As you can see, the Person class only has one collection left, that is a collection of PersonPerson objects that represents relations that this Person has.
In order to get the Persons that have relations with a given Person, you could create a specific method on your PersonRepository that returns those Persons, instead of having them in a collection on the Person class. I think this will improve performance as well.</p>
<pre><code>public class NHPersonRepository : IPersonRepository
{
...
public IList<Person> FindPersonsThatHaveARelationShipWithPerson( Person p )
{
ICriteria crit = _session.CreateCriteria <Person>();
crit.AddAlias ("RelatedPersons", "r");
crit.Add (Expression.Eq ("r.RelatedWithPerson", p));
return crit.List();
}
}
</code></pre>
<p>The 'back-reference' is not a member of the Person class; it has to be accessed via the repository.
This is also what Eric Evans says in his DDD - book: in some cases , it is better to have a specialized method on the repository that can give you access to related objects, instead of having them (= the related objects) to carry around with the object itself.</p>
<p>I didn't test the code, I just typed it in here, so I also didn't check for syntax error, etc... but I think it should clarify a bit on how I would see this.</p>
|
How can I debug a regular expression in python? <p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p>
<p>EDIT: here is how regexes can be debugged in perl :</p>
<pre><code>
use re 'debug';
my $str = "GET http://some-site.com HTTP/1.1";
if($str =~/get\s+(\S+)/i) {
print "MATCH:$1\n";
}
</code></pre>
<p>The code above produces the following output on my computer when ran :</p>
<pre><code>
Compiling REx "get\s+(\S+)"
Final program:
1: EXACTF (3)
3: PLUS (5)
4: SPACE (0)
5: OPEN1 (7)
7: PLUS (9)
8: NSPACE (0)
9: CLOSE1 (11)
11: END (0)
stclass EXACTF minlen 5
Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1"
Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars)
0 | 1:EXACTF (3)
3 | 3:PLUS(5)
SPACE can match 1 times out of 2147483647...
4 | 5: OPEN1(7)
4 | 7: PLUS(9)
NSPACE can match 20 times out of 2147483647...
24 | 9: CLOSE1(11)
24 | 11: END(0)
Match successful!
MATCH:http://some-site.com
Freeing REx: "get\s+(\S+)"
</code></pre>
| <pre>
<code>
>>> p = re.compile('.*', re.DEBUG)
max_repeat 0 65535
any None
>>>
</code>
</pre>
<p><a href="http://stackoverflow.com/questions/580993/regex-operator-vs-separate-runs-for-each-sub-expression/582227#582227">http://stackoverflow.com/questions/580993/regex-operator-vs-separate-runs-for-each-sub-expression/582227#582227</a></p>
|
XAML Vector to Illustrator or similar <p>I can easily enough go from Adobe Illustrator and make a XAML file via the XPS Virtual Printer, but is there any way to import Vector graphics defined in XAML into Adobe Illustrator to continue working on it?</p>
<p>Cheers</p>
<pre><code>Nik
</code></pre>
| <p>You could try using <a href="http://www.inkscape.org/">Inkscape</a> to convert your XAML into a format Illustrator understands. It support XAML import and export.</p>
|
Is there a cross browser way of setting style.float in Javascript? <p>Usually, if you need to set a style attribute in JavaScript, you say something like:</p>
<pre><code>element.style.attribute = "value";
</code></pre>
<p>There are slight variations but usually the attribute name is a similar, albeit camelcased, version of the HTML attribute name.</p>
<p>The problem for me is that the float attribute doesn't work. Float is a keyword in JavaScript and so style.float makes all the JavaScript for the page break. I looked in MSDN, and it said to use styleFloat like so:</p>
<pre><code>element.style.styleFloat = "value";
</code></pre>
<p>That only works in IE. Firefox, Safari, Chrome, Opera - none of them seem to have an answer. Where am I going wrong? There has to be a simple answer to this.</p>
| <p>Use cssFloat as in...</p>
<pre><code>element.style.cssFloat = "value";
</code></pre>
<p>That works in everything <em>except</em> IE 8 and older, but you can always detect the browser and switch, or just set them both. Unfortuantely, there is no way to set just one style value to work in all browsers.</p>
<p>So to summarize, everyone you need to set the float, just say:</p>
<pre><code>element.style.styleFloat = "value";
element.style.cssFloat = "value";
</code></pre>
<p>That <em>should</em> work everywhere.</p>
|
subversion/cruise control/nant/nunit with visual studio projects and solutions <p>I work in a team of 2 developers and currently we use VSS and have no continuous integration or daily build and few Unit tests.</p>
<p>I'm looking to change our source control to Subversion and at the same time get up and running with a more professional process.</p>
<p>Subversion/cruise control/nant/nunit appears quite a popular combination from what I've seen so far and I've just installed these onto a spare machine.</p>
<p>I've downloaded the subversion manual and that is 400 pages long for just one of the tools!</p>
<p>Really I just want to get up and running using tried and tested patterns proven already in the wild and then tweak as required and as my familiarity with the tools increases.</p>
<p>Is anyone aware of any book/tutorial/walkthrough that covers just the essentials to get me up and running ASAP with this particular combination of tools?</p>
| <p>I've been using subversion for quite some years now and I have to say that the best introduction I've found is included in the help file for TortoiseSVN. TortoiseSVN is another free client for Windows with Explorer integration. I highly recommend reading the Tortoise help first, even before the original subversion docs. Where necessary it refers you to the official docs.</p>
<p>Tortoise also happens to be my favorite client. In fact, on most machines it is the only subversion component I need. It performs all of the functions I use routinely, including repository creation. While that is no knock to the regular command-line tools, and I do install those as well in most cases, I only find the cli tools necessary for automation from scripts and (infrequent) repository maintenance functions.</p>
<p>I'm in the process of rearchitecting our own build environment at work so I'm going through the options for a lot of build/development tools. Here are tools I can recommend or come with good recommendations from others:</p>
<p>WinMerge: highly recommended free diff tool, install after TortoiseSVN for the best integration. I use this tool on a daily basis for many purposes, some outside of development.</p>
<p>TeamCity: CI server that seems to be well-polished. I haven't tried this one yet but it's the leading contender over CC.NET given my experience with CC.NET (a year) and the good reviews it receives. Hudson is another well-reviewed option.</p>
<p>VisualSVN Server: a recommended free http(s) server for SVN that features AD integration for permissions and a microsoft-style msc console. I just finished implementing it at work and it's very simple. A must if you want remote (IP) check-in/check-out, ssl encryption, repository hook scripts and other server-based features.</p>
<p>VisualSVN: a well-reviewed Visual Studio plug-in for SVN. Haven't tried this one but it is regarded as a no-brainer purchase. [Edit: according to what I've read here on overflow, AnkhSVN is a free option that works about the same.]</p>
<p>SVN-Monitor: recommended free monitor software that alerts you to changes in the repository. Configurable as to what it monitors and the action it takes. Depends on TortoiseSVN being installed.</p>
<p>BugTracker.NET: recommended free issue-tracking server. Features SVN integration to tie issues being tracked to subversion revisions. Not sure if TeamCity has a similar feature but we already use this outside of development to track helpdesk issues and it is great for a free package.</p>
<p>I don't have experience with unit testing, coverage, documentation tools for .NET, so I can't comment there.</p>
<p>I am a Pythonista though, so I'll plug one thing Python can be useful for wrt SVN, which is that you can use the PySVN library to perform any kind of automated repository work that's too complex for scripting with the command-line tools. I use it for creating tags once a build is ready to be tagged and deployed.</p>
<p>Pick some of these tools and you'll be ahead of the game. Developing processes around them and training personnel, well, that's still a job for you. :)</p>
|
How to validate the clients database against my database schema? <p>Our clients use SQLServer/Oracle databases. Over the years, we've sent them many update scripts which they had to run manually. Most of the time, everything went smooth, but every now and then a script did not run completely to the end or had some errors in it (which weren't detected at the time of the upgrade). Also, sometimes even "smart users" added indexes/tables into those databases themselves, for whatever reason. Later on, those irregularities lead to problems. </p>
<p>Now I have been tasked to figure out a way to verify/validate our clients databases against our own database schema (tables, datatypes, indexes, views, ...). The output should be some kind of difference file indicating what is missing/what should not be in the database. I could do this in code (C++) from inside our application or I can create an external tool for just this one purpose. </p>
<p>Now before I start coding, I wanted to ask if there is already a tool out there that would produce the necessary results, or that at least could help me produce a decent xml file from our master-databases (Oracle and SQLServer)? Or is there a library which could help me write my own tool? </p>
| <p>I've used this technique before and it doesn't require buying any tools. </p>
<p>Enterprise Manager has a "Create Script" feature. Perform this on your reference database and the comparison database. Select the appropriate options to generate scripts for the objects you care about. Next, just compare the two generated files with your favorite diff tool.</p>
<p>You can do a similar procedure with Oracle tools that let you export the DDL scripts.</p>
|
Generating and Displaying PDF file in Flex/Java <p>We have Flex on the front end and Java on the back end. When a user will request for a PDF file, request will go to the Java backend, where a PDF file will be generated using Jasper Reports. What we dont know is how to display this PDF file in browser; since we dont want to use JSP/Servlets etc - It has to be flex only. Any suggestions?</p>
| <p>Flash Player cannot natively render PDF files. This is possible using Adobe AIR but not in a Flex application. Your best bet is to call navigateToURL() and open a Servlet in a new browser tab/window. The Servlet can simply write contents of the PDF file to the OutputStream and set the appropriate HTTP headers.</p>
|
Does Msbuild recognise any build configurations other than DEBUG|RELEASE <p>I created a configuration named Test via Visual Studio which currently just takes all of DEBUG settings, however I employ compiler conditions to determine some specific actions if the build happens to be TEST|DEBUG|RELEASE. </p>
<p>However how can I get my MSBUILD script to detect the TEST configuration?? </p>
<p>Currently I build </p>
<pre><code> <MSBuild Projects="@(SolutionsToBuild)" Properties="Configuration=$(Configuration);OutDir=$(BuildDir)\Builds\" />
</code></pre>
<p>Where @(SolutionsToBuild) is a my solution. In the <a href="http://msdn.microsoft.com/en-us/library/bb629394.aspx">Common MsBuild Project Properties</a> it states that $(Configuration) is a common property but it always appears blank? </p>
<p>Does this mean that it never gets set but is simply reserved for my use or that it can ONLY detect DEBUG|RELEASE. If so what is the point in allowing the creation of different build configurations? </p>
| <p>I haven't done much with defining an MSBUILD configuration file but I have done builds of different configurations using a batch file like this</p>
<pre><code>msbuild /v:n /p:Configuration=Release "Capture.sln"
msbuild /v:n /p:Configuration=ReleaseNoUploads "Capture.sln"
</code></pre>
<p>I defined the <strong>ReleaseNoUploads</strong> configuration inside Visual Studio.</p>
<p>Here's what I had to do for that (this is Visual Studio 2005):</p>
<ul>
<li>Open the <em>Tools:Options</em> menu, go to the <em>Projects and Solutions:General</em> option, and check <strong>Show advanced build configurations</strong>.</li>
<li>From there, go to the <em>Build:Configuration</em> Manager menu</li>
<li>In the dialog that pops up, click on the <em>Active solution configuration</em> pulldown and click <strong><New...></strong> to create a new build configuration.</li>
</ul>
|
Can I use VS2005 to build extensions for a Python system built with VS2003 <p><a href="http://rdflib.net/" rel="nofollow">RDFLib</a> needs C extensions to be compiled to install on ActiveState Python 2.5; as far as I can tell, there's no binary installer anywhere obvious on the web. On attempting to install with <code>python setup.py install</code>, it produces the following message:</p>
<p><code>error: Python was built with Visual Studio 2003;</code><br>
<code>extensions must be built with a compiler than can generate compatible binaries.</code><br>
<code>Visual Studio 2003 was not found on this system. If you have Cygwin installed,</code><br>
<code>you can try compiling with MingW32, by passing "-c mingw32" to setup.py.</code></p>
<p>There are <a href="http://boodebr.org/main/python/build-windows-extensions" rel="nofollow">various</a> <a href="http://isegserv.itd.rl.ac.uk/blogs/alistair/" rel="nofollow">resources</a> on the web about configuring a compiler for distutils that discuss using MinGW, although I haven't got this to work yet. As an alternative I have VS2005. </p>
<p>Can anyone categorically tell me whether you can use the C compiler in VS2005 to build Python extension modules for a VS2003 compiled Python (in this case ActiveState Python 2.5). If this is possible, what configuration is needed?</p>
| <p>The main problem is C run-time library. Python 2.4/2.5 linked against msvcr71.dll and therefore all C-extensions should be linked against this dll.</p>
<p>Another option is to use gcc (mingw) instead of VS2005, you can use it to compile python extensions only. There is decent installer that allows you to configure gcc as default compiler for your Python version:</p>
<p><a href="http://www.develer.com/oss/GccWinBinaries" rel="nofollow">http://www.develer.com/oss/GccWinBinaries</a></p>
|
Link to table showing CultureInfo for ALL cultures <p>I'm losing my mind trying to find a table showing all the formats of datetimes for cultures</p>
<p>I've been googling like crazy and all i want is that table! ARG</p>
<p>i.e. </p>
<p>en-CA = DD/MM/YYYY 0.00
en-FR = MM/DD/YYYY 0,00</p>
<p>I'm looking for a link to MSDN or wikipedia - I know I've seen this in the past before</p>
| <pre><code>foreach (var c in System.Globalization.CultureInfo.
GetCultures(CultureTypes.AllCultures))
{
Console.WriteLine("{0} = {1}", c.Name,
c.DateTimeFormat.FullDateTimePattern);
}
</code></pre>
|
Numeric precision issue in Excel 2007 when saving as XML <p>I am encountering a strange issue when saving documents in XML Spreadsheet 2003 format using Excel 2007.</p>
<p>It seems to randomly change numeric values such as "0.58" to "0.57999999999999996".</p>
<p>What's really odd is that you CANNOT see this issue when you are in Excel. You can only see this when viewing the XML data directly from a text editor. </p>
<p>Has anyone encountered this before? If so, is there any sort of fix or workaround?</p>
| <p>Excel stores numeric data as floating point. The number to the right of the decimal place (the fractional portion) is only approximate. There is no work around, 0.58 cannot be represented as a floating point number that is exactly 0.58.</p>
<p>When loading the XML file at that point you should convert the number back to floating point or better yet a fixed digit decimal class (eg. Decimal in C#). </p>
|
Is there a Java library to access the native Windows API? <p>Is there a Java library to access the native Windows API? Either with COM or JNI.</p>
| <p>You could try these two, I have seen success with both.</p>
<p><a href="http://jawinproject.sourceforge.net">http://jawinproject.sourceforge.net</a></p>
<blockquote>
<p>The Java/Win32 integration project
(Jawin) is a free, open source
architecture for interoperation
between Java and components exposed
through Microsoft's Component Object
Model (COM) or through Win32 Dynamic
Link Libraries (DLLs).</p>
</blockquote>
<p><a href="https://github.com/twall/jna/">https://github.com/twall/jna/</a></p>
<blockquote>
<p>JNA provides Java programs easy access
to native shared libraries (DLLs on
Windows) without writing anything but
Java codeâno JNI or native code is
required. This functionality is
comparable to Windows' Platform/Invoke
and Python's ctypes. Access is dynamic
at runtime without code generation.</p>
<p>JNA allows you to call directly into
native functions using natural Java
method invocation. The Java call looks
just like it does in native code. Most
calls require no special handling or
configuration; no boilerplate or
generated code is required.</p>
</blockquote>
<p>Also read up here:</p>
<p><a href="http://en.wikipedia.org/wiki/Java_Native_Interface">http://en.wikipedia.org/wiki/Java_Native_Interface</a></p>
<blockquote>
<p>The Java Native Interface (JNI) is a
programming framework that allows Java
code running in a Java Virtual Machine
(JVM) to call and to be called<a href="https://github.com/twall/jna/">1</a> by
native applications (programs specific
to a hardware and operating system
platform) and libraries written in
other languages, such as C, C++ and
assembly.</p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/Java_Native_Access">http://en.wikipedia.org/wiki/Java_Native_Access</a></p>
<blockquote>
<p>Java Native Access provides Java
programs easy access to native shared
libraries without using the Java
Native Interface. JNA's design aims to
provide native access in a natural way
with a minimum of effort. No
boilerplate or generated glue code is
required.</p>
</blockquote>
|
What should I do when my boss tells me to make passwords the same as usernames by default in our software? <p>My boss is against requiring our users to have secure passwords, even going so far to request they be setup by default to have passwords the same as their username. What should I do in this situation? What would you do?</p>
<p><strong>Update</strong> - Some users have brought up the question of whether the application needs high security. This isn't credit card information for example but does include sensitive information and a mailing list management and sending functionality.</p>
| <p>Make the best case you can for strong passwords and then, unfortunately, if they do not see your point of view either do what they asked or find a better job.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.