input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
ActionScript 3.0 Preloader Issues <p>First off, I greatly appreciate any help, as always....</p>
<p>I have created a preloader from <a href="http://www.portentinteractive.com/blog/advanced-actionscript-3-preloa.htm" rel="nofollow">Jarrod's Advanced AS3 Preloader Tutorail</a>. I searched elsewhere and this seemed like my best option as it was the only one I understood that did not require 2 SWF files.</p>
<p>My code is really in 2 classes, my <strong>preloader</strong> class and my <strong>program</strong> class. My problem is that the preloader is only loading the graphics that are in my flash and not actually initiating the program class. My question is <em>how do I get my preloading to initiate the program class?</em> The full code for both files are below.</p>
<p><strong>Preloader.as</strong></p>
<pre><code>package {
import flash.display.*;
import flash.text.*;
import flash.events.*;
import fl.containers.ScrollPane;
import flash.filters.*;
public class Preloader extends MovieClip {
public static const ENTRY_FRAME:Number=3;
public static const DOCUMENT_CLASS:String='Program';
public var myText:TextField;
public var myFormat:TextFormat;
private var progressBar:Sprite;
private var progressText:TextField;
public function Preloader() {
stop();
progressBar = getChildByName("loadbar_mc") as Sprite;
progressText = getChildByName("loading_txt") as TextField;
progressBar.scaleX = 0;
myFormat = new TextFormat();
myFormat.font="Helvetica";
myFormat.color = 0x000000;
myFormat.size = 24;
loaderInfo.addEventListener(Event.INIT, initHandler);
loaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
loaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
}
private function initHandler(event:Event):void {
progressBar.scaleX = 0;
progressText.text = "Loading 0%";
}
private function progressHandler(event:ProgressEvent):void {
var loaded:uint = event.bytesLoaded;
var total:uint = event.bytesTotal;
var percentLoaded:Number = Math.round((loaded/total) * 50);
progressBar.scaleX = loaded/total;
progressText.text = "Loading " + percentLoaded + "%";
}
private function completeHandler(event:Event):void {
play();
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
private function enterFrameHandler(event:Event):void {
if (currentFrame >= Preloader.ENTRY_FRAME) {
removeEventListener(Event.ENTER_FRAME, enterFrameHandler);
stop();
main();
}
}
private function errorHandler(event:IOErrorEvent):void {
myText.text = ("Sorry, there was an error. " + event);
myText.setTextFormat(myFormat);
}
private function main():void {
var programClass:Class = loaderInfo.applicationDomain.getDefinition(Preloader.DOCUMENT_CLASS) as Class;
var program:Sprite = new programClass() as Sprite;
addChild(program);
}
}
}
</code></pre>
<p><strong>Program.as</strong></p>
<pre><code>package {
import flash.display.*;
import flash.events.*;
import flash.filters.*;
import flash.text.*;
import fl.controls.TextInput;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.containers.ScrollPane;
import flash.geom.Rectangle;
import fl.controls.Label;
public class Program extends Sprite {
public function Program() {
//define variable
var startX:Number;
var startY:Number;
var counter:Number = 0;
var intMessages:Number = 550;
var limit:Number = 10;
var intBoardSize:Number = 476*(Math.round(intMessages/15)+1);
var intMessageMinX:Number = 35;
var intMessageMaxX:Number = intBoardSize-99;
var intMessageMinY:Number = 50;
var intMessageMaxY:Number = 310;
var activeGloveName:String = ""
var intDegreeHigh:Number = 45;
var intDegreeLow:Number = -45;
var newGlove:mcGlove;
//create objects
var myGlove:mcGlove = new mcGlove();
var showGlove:mcGlove = new mcGlove
var mcglovetarget:mcGloveTarget = new mcGloveTarget();
var myDropShadowFilterSmall = new DropShadowFilter (2,45,0x000000,0.65,3,3,2,3,false,false,false);
var myDropShadowFilterDown = new DropShadowFilter (3,45,0x000000,0.65,5,5,2,3,false,false,false);
var myDropShadowFilterUp = new DropShadowFilter (5,45,0x000000,0.65,7,7,2,3,false,false,false);
var topShadow = new DropShadowFilter (3,90,0x000000,0.35,8,8,2,3,false,false,false);
var pinkline:Sprite = new Sprite();
var searchBox:Sprite = new Sprite();
var txtSearchBox:TextInput = new TextInput();
var sSearchBox_Label:String = "Go to glove #";
var messageFormat:TextFormat = new TextFormat();
var messageTextField:Label = new Label();
var searchBoxLFormat:TextFormat = new TextFormat();
var txtSearchBox_Label:TextField = new TextField();
var SearchBoxBg:Sprite = new Sprite();
var topShadowBox:Sprite = new Sprite();
var searchButton:searchBtn = new searchBtn();
var alertRect:Rectangle = new Rectangle(0,0,848,393);
var errorMessage:AlertBox = new AlertBox(alertRect);
var holder:MovieClip = new MovieClip();
var aMessages:Array = new Array();
//Create a glove for each message
for (var gloveCount = 0; gloveCount < intMessages; gloveCount++){
aMessages[gloveCount] = new mcGlove();
aMessages[gloveCount] = createMessage(aMessages[gloveCount], gloveCount, gloveCount);
}
var scrollPane:ScrollPane = new ScrollPane();
scrollPane.verticalScrollPolicy = "false";
scrollPane.move(374, 0);
scrollPane.setSize(476, 370);
scrollPane.horizontalLineScrollSize = 120;
topShadowBox.graphics.beginFill(0x333333);
topShadowBox.graphics.drawRect(0,0,870,5);
topShadowBox.x = -10;
topShadowBox.y = -5;
topShadowBox.filters = [topShadow];
pinkline.graphics.beginFill(0xDB9195);
pinkline.graphics.drawRect(0,0,476,2);
pinkline.x = 374;
pinkline.y = 353;
searchBox.graphics.beginFill(0xDB9195);
searchBox.graphics.drawRect(0,0,476,25);
searchBox.x = 374;
searchBox.y = 370;
SearchBoxBg.graphics.beginFill(0xffffff);
SearchBoxBg.graphics.drawRect(0,0,35,17);
SearchBoxBg.x = 475;
SearchBoxBg.y = 374;
txtSearchBox.width = 35;
txtSearchBox.height = 15;
txtSearchBox.move(475,375);
txtSearchBox.restrict = "0-9";
txtSearchBox.maxChars = 4;
//txtSearchBox.background = "0xffffff";
//txtSearchBox.border = "0x0xDB9195";
searchBoxLFormat.font="Helvetica";
searchBoxLFormat.color = 0xffffff;
searchBoxLFormat.bold = true;
searchBoxLFormat.size = 10;
txtSearchBox_Label.x = 400;
txtSearchBox_Label.y = 374;
txtSearchBox_Label.width = 70;
txtSearchBox_Label.height = 17;
txtSearchBox_Label.text = sSearchBox_Label;
txtSearchBox_Label.setTextFormat(searchBoxLFormat);
searchButton.x = 534;
searchButton.y = 382;
//add to frame
sortObjects();
scrollPane.source = holder;
//create instance names for referancing/compairing objects
myGlove.name = "mcglove";
myGlove.setGloveMessage("My Sister Suzy, I pray that she will be ok. I love here so much, she is the best sister ever. I miss you RIP");
mcglovetarget.name = "mcglovetarget";
messageFormat.font="Helvetica";
messageFormat.color = 0xffffff;
messageFormat.bold = true;
messageFormat.size = 17;
messageFormat.align = "center";
messageTextField.x = -85;
messageTextField.y = -40;
messageTextField.width = 135;
messageTextField.height = 140;
messageTextField.text = myGlove.getGloveMessage();
messageTextField.wordWrap = true;
messageTextField.mouseEnabled = false;
messageTextField.buttonMode = true;
messageTextField.setStyle("textFormat", messageFormat);
//messageTextField.hitArea = 0;
myGlove.addChild(messageTextField);
//position the glove and modify apperiance
myGlove.x = 163;
myGlove.y = 211;
myGlove.filters = [myDropShadowFilterDown];
//myGlove.addChild(messageTextField);
showGlove.x = 163;
showGlove.y = 211;
showGlove.filters = [myDropShadowFilterDown];
mcglovetarget.x = 615;
mcglovetarget.y = 211;
mcglovetarget.alpha = 0
//action listeners
myGlove.addEventListener(MouseEvent.MOUSE_DOWN, selectGlove);
myGlove.addEventListener(MouseEvent.MOUSE_UP, releaseGlove);
searchButton.addEventListener(MouseEvent.CLICK, searchMessages);
txtSearchBox.addEventListener(KeyboardEvent.KEY_UP, checkForEnter);
function selectGlove(event:MouseEvent):void {
event.currentTarget.startDrag(true);
var myTargetName:String = event.currentTarget.name + "target";
var myTarget:DisplayObject = getChildByName(myTargetName);
myGlove.filters = [myDropShadowFilterUp];
addChild(myTarget);
event.currentTarget.parent.addChild(event.currentTarget);
addChild(topShadowBox);
myTarget.alpha = .5;
startX = event.currentTarget.x;
startY = event.currentTarget.y;
}
function releaseGlove(event:MouseEvent):void {
event.currentTarget.stopDrag();
var myTargetName:String = event.currentTarget.name + "target";
var myTarget:DisplayObject = getChildByName(myTargetName);
event.currentTarget.filters = [myDropShadowFilterDown];
myTarget.alpha = 0;
if (event.currentTarget.dropTarget != null && event.currentTarget.dropTarget.parent == myTarget){
event.currentTarget.removeEventListener(MouseEvent.MOUSE_DOWN, selectGlove);
event.currentTarget.removeEventListener(MouseEvent.MOUSE_UP, releaseGlove);
event.currentTarget.x = myTarget.x;
event.currentTarget.y = myTarget.y;
var myTween:Tween = new Tween(getChildByName(event.currentTarget.name), "scaleX",Strong.easeOut,getChildByName(event.currentTarget.name).scaleX,.28,2,true);
var myTween2:Tween = new Tween(getChildByName(event.currentTarget.name), "scaleY",Strong.easeOut,getChildByName(event.currentTarget.name).scaleY,.28,2,true);
holder.addChild(getChildByName(event.currentTarget.name));
event.currentTarget.removeChild(messageTextField);
scrollPane.source = holder;
holder.getChildByName(event.currentTarget.name).x=Math.round(Math.random() * (470+Math.round(scrollPane.horizontalScrollPosition) - Math.round(scrollPane.horizontalScrollPosition))) + Math.round(scrollPane.horizontalScrollPosition);
holder.getChildByName(event.currentTarget.name).y=Math.round(Math.random() * (intMessageMaxY - intMessageMinY)) + intMessageMinY;
holder.getChildByName(event.currentTarget.name).addEventListener(MouseEvent.MOUSE_DOWN, clickMessage);
holder.getChildByName(event.currentTarget.name).addEventListener(MouseEvent.MOUSE_UP, releaseMessage);
event.currentTarget.name = "" + intMessages;
addChild(showGlove);
messageTextField.text = "Select a glove to view its message here.";
showGlove.addChild(messageTextField);
} else {
event.currentTarget.x = startX;
event.currentTarget.y = startY;
}
//sortObjects();
addChild(mcglovetarget);
addChild(scrollPane);
addChild(pinkline);
addChild(searchBox);
addChild(SearchBoxBg);
addChild(txtSearchBox);
addChild(txtSearchBox_Label);
addChild(searchButton);
addChild(topShadowBox);
}
function position(target) {
target.x = Math.round(Math.random() * (intMessageMaxX - intMessageMinX)) + intMessageMinX;
target.y = Math.round(Math.random() * (intMessageMaxY - intMessageMinY)) + intMessageMinY;
for (var i:uint=0; i<aMessages.length -1 ; i++) {
if(target.hitTestObject(aMessages[i]) && counter < limit){
counter++;
position(target);
//return false;
};
}
}
function createMessage(newGlove:mcGlove, sName:String, sMessage:String){
newGlove.scaleX = .28;
newGlove.scaleY = .28;
counter = 0;
position(newGlove);
newGlove.rotation = (0, 0, 0, Math.round(Math.random() * (intDegreeHigh - intDegreeLow)) + intDegreeLow);
newGlove.filters = [myDropShadowFilterSmall];
newGlove.name = sName;
holder.addChild(newGlove);
newGlove.setGloveMessage(sMessage);
newGlove.addEventListener(MouseEvent.MOUSE_DOWN, clickMessage);
newGlove.addEventListener(MouseEvent.MOUSE_UP, releaseMessage);
newGlove.buttonMode = true;
return newGlove;
}
function clickMessage(event:MouseEvent):void{
selectMessage(event.target);
}
function checkForEnter(event:KeyboardEvent):void
{
if (event.keyCode == 13) // If Keypress is Enter
{
searchMessages();
}
}
function searchMessages():void{
if (showGlove.parent == mcglovetarget.parent){
if ( txtSearchBox.text != "" ){
var searchTarget:DisplayObject = holder.getChildByName(txtSearchBox.text);
if (searchTarget){
selectMessage(searchTarget);
scrollPane.horizontalScrollPosition = searchTarget.x - 220;
}else if(1==1){ //if in file
gloveCount = aMessages.length;
aMessages[gloveCount] = new mcGlove();
aMessages[gloveCount] = createMessage(aMessages[gloveCount], txtSearchBox.text, txtSearchBox.text);
selectMessage(aMessages[gloveCount]);
scrollPane.horizontalScrollPosition = aMessages[gloveCount].x - 220;
}else{
errorMessage.setAlertText("Sorry, the glove you are searching for does not exist.");
addChild(errorMessage);
}
}
}else{
errorMessage.setAlertText("You must post your message first, otherwise your message will be lost.");
addChild(errorMessage);
}
}
function selectMessage(object:mcGlove):void{
if (showGlove.parent == mcglovetarget.parent){
if (activeGloveName != ""){
var activeGlove:DisplayObject = holder.getChildByName(activeGloveName);
activeGlove.filters = [myDropShadowFilterSmall];
activeGlove.scaleX = .28;
activeGlove.scaleY = .28;
holder.addChild(activeGlove);
}
activeGloveName = object.name;
//event.target.dragIt();
holder.addChild(object);
object.filters = [new GlowFilter(0xABEEFC, .65, 15, 15, 1, 1, false, false)];
object.scaleX = .35;
object.scaleY = .35;
messageTextField.text = object.getGloveMessage();
}else{
errorMessage.setAlertText("You must post your message first, otherwise your message will be lost.");
addChild(errorMessage);
}
}
function releaseMessage(event:MouseEvent):void{
event.target.dropIt();
}
function sortObjects():void{
addChild(mcglovetarget);
addChild(scrollPane);
addChild(pinkline);
addChild(searchBox);
addChild(SearchBoxBg);
addChild(txtSearchBox);
addChild(txtSearchBox_Label);
addChild(searchButton);
addChild(myGlove);
addChild(topShadowBox);
}
myGlove.buttonMode = true;
searchButton.buttonMode = true;
}
}
}
</code></pre>
| <p>in the preloader main, you istantiate the program like this</p>
<pre><code>var program:Sprite = new programClass() as Sprite;
</code></pre>
<p>I think you should do:</p>
<pre><code>var program:Sprite = new Program();
</code></pre>
<p>Note that you don't need to cast Program as a Sprite, since it is already a Sprite.
ps: are you really writing nested functions in the Program constructor? omg :-/</p>
|
How to tell user events from synthetic events? <p>I have a JFace editor that is mostly made up of a <code>TreeViewer</code>. This is hooked up to a <code>ContentOutlinePage</code> to bring the Outline view to life.</p>
<p>When either one receives a <code>SelectionChangedEvent</code> they call the others <code>setSelection()</code> method ... and therein lies the problem. <code>setSelection()</code> generates another <code>SelectionChangedEvent</code> ... and thus the infinite loop is joined.</p>
<p>Is there a means of telling if the <code>SelectionChangedEvent</code> was created by actual user interaction rather than by another object calling <code>setSelection()</code>?</p>
<p>Is there a better means still of stopping this sort of deadly-embrace?</p>
<p>Clues welcomed.</p>
| <p>Generally, you would check a flag in the beginning of the routine to check to see if you are in the middle of the event handler. If the flag is set, then you exit without processing.</p>
<p>If the flag is not set, you set the flag, process, then set the flag back.</p>
|
Changing checkboxes using Javascript <p>I have a series of checkboxes on an HTML page and I would like to check the checkboxes based on corresponding HTML query string params.</p>
<p>e.g.</p>
<pre><code>...path/page.html?i=1&j=1&x=0
</code></pre>
<p>would cause a page with three checkboxes to check 1 and 2 on load.</p>
<p>Can someone show me how to do this or point me in the direction of a suitable tutorial?</p>
<p>Many Thanks,</p>
<p>EDIT: A clarification, i, j and x are just picked off the top of my head, but they are boolean variables (1 = true, 0 = false) and each corresponds to a checkbox so:</p>
<pre><code>i = one checkbox, the value in the example is 1, so the checkbox should be checked.
j = as above
x = one checkbox, the value in the example is 0, so the checkbox should not be checked.
</code></pre>
| <p>Partially from <a href="http://www.w3schools.com/JS/tryit.asp?filename=try_dom_input_checked" rel="nofollow">W3Schools</a>. This file will crate a single checkbox and check it depending on the <a href="http://example.com/index.html?j=" rel="nofollow">http://example.com/index.html?j=</a><strong>?</strong> URL</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function doStuff()
{
var GETVars = getUrlVars();
if (GETVars['j']==1)
{
document.getElementById("myCheck").checked=true;
}
}
</script>
<body onload="doStuff();">
<form>
<input id='myCheck' type="checkbox" />
</form>
</body>
</html>
</code></pre>
|
c# compare two generic values <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/390900/cant-operator-be-applied-to-generic-types-in-c">Canât operator == be applied to generic types in C#?</a> </p>
</blockquote>
<p>I've coded something like this:</p>
<pre><code>public bool IsDataChanged()
{
T value1 = GetValue2;
T value2 = GetValue1();
return (valueInDB != valueFromView);
}
</code></pre>
<p>Right now the function doesn't compile with the error "<em>Operator '!=' cannot be applied to operands of type 'T' and 'T'</em>". What do I have to do to make this function work ?</p>
| <p>You cannot use operators on generic types (except for foo == null which is special cased) unless you add where T : class to indicate it is a reference type (then foo == bar is legal)</p>
<p>Use <code>EqualityComparer<T></code>.Default to do it for you. This will <strong>not</strong> work on types which only supply an operator overload for == without also either:</p>
<ul>
<li>implement <code>IEquatable<T></code></li>
<li>overrides object.Equals()</li>
</ul>
<p>In general implementing the == operator and not also doing at least one of these would be a very bad idea anyway so this is not likely to be an issue.</p>
<pre><code>public bool IsDataChanged<T>()
{
T value1 = GetValue2;
T value2 = GetValue1();
return !EqualityComparer<T>.Default.Equals(value1 , value2);
}
</code></pre>
<p>If you do not restrict to <code>IEquatable<T></code> then the EqualityComparer default fallback may cause boxing when used with value types if they do not implement <code>IEquatable<T></code> (if you control the types which are being used this may not matter). I am assuming you were using =! for performance though so restricting to the Generic type will avoid <strong>accidental</strong> boxing via the Object.Equals(object) route.</p>
|
Can I change the owner of the file saved through IIS (with ASP.NET) <p>Is there a way to change owner of saved file using IIS on Windows Server. The easier the better. It doesn't matter either this will have to be done during saving or changing file owner after file is already saved to disc. An example in ASP.NET is highly apriciated. </p>
| <p>In theory it should be fairly straight forward. You <em>should</em> be able to do something like this to change the ownership of an existing file:</p>
<pre><code>string domain = "domain";
string user = "username";
FileInfo info = new FileInfo(@"c:\test.txt");
FileSecurity security = info.GetAccessControl();
System.Security.Principal.NTAccount newOwner =
new System.Security.Principal.NTAccount(domain, user);
security.AddAccessRule(
new FileSystemAccessRule(newOwner, FileSystemRights.FullControl,
AccessControlType.Allow));
security.SetAccessRuleProtection(true, false);
security.SetOwner(newOwner);
info.SetAccessControl(security);
</code></pre>
<p>In practice however this doesn't actually work because of a limitation that Windows imposes. Windows won't allow you to the change the owner of the file to anything other than the current user or the administrators group.</p>
<p>When it hits the last line you will get the exception "The security identifier is not allowed to be the owner of this object".</p>
<p>Googling suggests that it may be possible to work round this problem, but I have failed to get the work arounds to work when I have tried in the past. I'd be very interested to hear if anyone had successfully achieved the work around.</p>
|
Is it possible to insert a multi-line code snippet relative to the cursor position in Visual Studio? <p>When using code snippets in Visual Studio that contain multiple lines the following lines will preserve the whitespace that was set in the .snippet file instead of positioning the code relative to the original cursor placement.</p>
<p>When using the foreach snippet you'll get code like this:</p>
<pre><code> foreach (var item in collection)
{
}
</code></pre>
<p>Instead of:</p>
<pre><code> foreach (var item in collection)
{
}
</code></pre>
<p>Is there a way to change this behavior? Is there a keyword that needs to be used in the .snippet file?</p>
| <p>The code portion of a snippet file is contained in a CDATA which preserves whitespace. The best thing I can tell you is to go into the file and edit it to suit your needs. Your only other option is to do a quick <kbd>Ctrl+K</kbd> and <kbd>Ctrl+D</kbd> after you use the snippet to auto-format the code which will fix the indenting.</p>
|
How does IE7's "View Source" button interact with javascript? <p>I'm debugging someone else's code for a web page that is made with ASP.NET with some javascript effects. It's a form that we are pre-populating with edit-able data, and one of the text boxes is getting populated with an incorrect value. </p>
<p>I know that the text box is getting filled with the correct value in the code behind, but somewhere between there and the browser it gets overwritten. </p>
<p>In trying to find out where that happened, I came across an interesting situation. If I right-click near the offending element and select "view page source," I can scroll down to the element and see</p>
<pre><code><input name="RecurrenceProperties$TextBox57" type="text" value="HEY ITS THE RIGHT VALUE" id="RecurrenceProperties_TextBox57" />
</code></pre>
<p>But the wrong value is in both the rendered html and the IE developer toolbar. </p>
<p>This seems like a hell of a clue, but I don't know enough about how "View Source" works to tell what is going on behind the curtain. What happens between the generation of the "View Source" source and the page actually rendering?</p>
<p>EDIT: I found where it was going wrong by putting a break-point on everywhere that ID occurs in javascript (not exactly elegant, but I found it). </p>
<p>Suggestions to disable javascript and use IE8 were very helpful. thanks. </p>
| <p>What you see with "view source" is the raw HTML that has been fetched. The HTML doesn't include any changes that were done via DHTML/JavaScript.</p>
<p><hr /></p>
<h2>Update</h2>
<p>Inspired by Manik's comment, here's a cross-browser<sup>1</sup> bookmarklet to display what's <strong>rendered</strong> inside <code><body></code>:</p>
<pre><code>javascript:"<pre>"+document.body.innerHTML.replace(/([&<>])/g,function(c){return"&"+{"&":"amp","<":"lt",">":"gt"}[c]+";";})+"</pre>"
</code></pre>
<p><sup>1</sup> Doesn't seem to work on Safari though. Anyone know why?</p>
|
How can I request the database product name with ADO.NET? <p>I develop a product with a custom database configuration. I use ADO.NET with System.Data.Odbc.OdbcConnection for it. To make some differences between the databases is there a simple solution to detect the current DBMS of a connection.</p>
| <p>I think that the OdbcConnection.Driver property may be more appropriate in the OP's context, since ServerVersion should return only the version number.</p>
<p>The Driver property will return the name of the DLL, such as "Sqlsrv32.dll" in case of SQL server. Then the OP can apply case based logic.</p>
|
Wix major upgrade <p>How do I use WIX to prevent overwriting a config file during a 'Major Upgrade'?</p>
<p>I want the file to be installed on the initial install, removed on uninstall, and left unchanged on a 'Major Upgrade'.</p>
<p>Thanks</p>
| <p>The most straight forward way would be to schedule your RemoveExistingProducts after InstallExecute or InstallFinalize. That way the config file is not removed and then installed again (like if you schedule before InstallInitialize). Of course, scheduling RemoveExistingProduct so late means you need to be very careful about your Component Rules.</p>
<p>My personal favorite is to treat configuration like "user data" and not have the installtouch it at all. You ship defaults with the application but any changes are made by the user in their private user profile. Gets you out of all kinds of nasty migration problems that just aren't solved well during setup.</p>
|
calculate exponential moving average in python <p>I have a range of dates and a measurement on each of those dates. I'd like to calculate an exponential moving average for each of the dates. Does anybody know how to do this?</p>
<p>I'm new to python. It doesn't appear that averages are built into the standard python library, which strikes me as a little odd. Maybe I'm not looking in the right place.</p>
<p>So, given the following code, how could I calculate the moving weighted average of IQ points for calendar dates?</p>
<pre><code>from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
</code></pre>
<p>(there's probably a better way to structure the data, any advice would be appreciated)</p>
| <p>EDIT:
It seems that <a href="http://www.scipy.org/scipy/scikits/browser/trunk/timeseries/scikits/timeseries/lib/moving_funcs.py"><code>mov_average_expw()</code></a> function from <a href="http://pytseries.sourceforge.net/lib/moving_funcs.html">scikits.timeseries.lib.moving_funcs</a> submodule from <a href="http://scikits.appspot.com/">SciKits</a> (add-on toolkits that complement <a href="http://scipy.org/">SciPy</a>) better suits the wording of your question. </p>
<p><hr /></p>
<p>To calculate an <a href="http://en.wikipedia.org/wiki/Exponential_smoothing">exponential smoothing</a> of your data with a smoothing factor <code>alpha</code> (it is <code>(1 - alpha)</code> in Wikipedia's terms):</p>
<pre><code>>>> alpha = 0.5
>>> assert 0 < alpha <= 1.0
>>> av = sum(alpha**n.days * iq
... for n, iq in map(lambda (day, iq), today=max(days): (today-day, iq),
... sorted(zip(days, IQ), key=lambda p: p[0], reverse=True)))
95.0
</code></pre>
<p>The above is not pretty, so let's refactor it a bit:</p>
<pre><code>from collections import namedtuple
from operator import itemgetter
def smooth(iq_data, alpha=1, today=None):
"""Perform exponential smoothing with factor `alpha`.
Time period is a day.
Each time period the value of `iq` drops `alpha` times.
The most recent data is the most valuable one.
"""
assert 0 < alpha <= 1
if alpha == 1: # no smoothing
return sum(map(itemgetter(1), iq_data))
if today is None:
today = max(map(itemgetter(0), iq_data))
return sum(alpha**((today - date).days) * iq for date, iq in iq_data)
IQData = namedtuple("IQData", "date iq")
if __name__ == "__main__":
from datetime import date
days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
IQ = [110, 105, 90]
iqdata = list(map(IQData, days, IQ))
print("\n".join(map(str, iqdata)))
print(smooth(iqdata, alpha=0.5))
</code></pre>
<p>Example:</p>
<pre><code>$ python26 smooth.py
IQData(date=datetime.date(2008, 1, 1), iq=110)
IQData(date=datetime.date(2008, 1, 2), iq=105)
IQData(date=datetime.date(2008, 1, 7), iq=90)
95.0
</code></pre>
|
<ol> with numbers another color <pre><code><ol>
<li>test</li>
<li>test</li>
</ol>
</code></pre>
<p>will show as:</p>
<ol>
<li>test</li>
<li>test</li>
</ol>
<p>I want to have numbers coloured and text black!</p>
<p>I can edit the css, but I do not have access to the HTML.</p>
| <p>The <a href="http://www.w3.org/TR/CSS2/generate.html#counters">CSS spec</a> gives an example of doing just this. Unfortunately, while it works on Firefox 3, it doesn't appear to work on IE7:</p>
<pre><code><html>
<head>
<style>
ol { counter-reset: item; }
ol li { display: block; }
ol li:before {
content: counter(item) ". ";
counter-increment: item;
color: red;
}
</style>
</head>
<body>
<ol>
<li>item</li>
<li>item</li>
<li>item</li>
</ol>
</body>
</html>
</code></pre>
|
OOP approach for inventory system <p>We're developing a system to track inventory at our field offices.</p>
<p>At its core, the system will have a list of "Assets" - things like Bikes, Computers, Tents. Each Asset goes through states like "Active", "Lost", "Checked Out", "Inventoried". Some states have additional information, like "Checked Out To" or "Inventoried By".</p>
<p>So, I'm thinking each State will be a subclass of a parent class or perhaps implement a iState interface. That part is clear to me.</p>
<p>What I'm stuck on is a good OOP design to put the business logic of what states can follow the previous state (The Asset object will store it's "last" state). For example, Checked In can only follow Checked Out. Active must be the first state recorded on an Asset.</p>
<p>Any ideas or pointers would be helpful. None of the GoF design patterns jumped out at me on this one.</p>
<p>And yes, I know we should be looking at COTS, but management has decided to proceed with rolling our own tool for now.</p>
| <p>You sort of answered your own question. Check out the <a href="http://www.dofactory.com/Patterns/PatternState.aspx" rel="nofollow">State</a> pattern.</p>
|
Reporting Services: Tablix RepeatColumnHeaders doesn't work on some reports <p>So I've got various reports that consist of a DataSet rendered in a Tablix... pretty garden variety stuff. There is a property for the Tablix control named <em>RepeatColumnHeaders</em>, which I have set to <strong>True</strong> for each report in question. The explanation for this property states “Indicates whether column headers are repeated on each page on which part of the data region appear.” Sounds pretty straightforward, but on some reports it works and on others it does not. I can't seem to find what's different about the reports that might affect this. On one report where the headers do repeat, there is some fairly arcane grouping mojo, but in an example where it doesn't work the Tablix only has one level--no grouping. I would expect the multi-nested one to be the problem, not the flat one.</p>
<p>Maybe it's a different problem altogether. I threw together a simple Tablix rendering <strong>SELECT * FROM Foo</strong>, accepted all the default values, which results in RepeatColumnHeaders being set to <strong>False</strong>, and lo and behold the column headers <em>do</em> repeat for that report... Grrr.</p>
<p>Any insights greatly appreciated.</p>
| <p>It's a bit wonky from what I've managed to dig up. In your grouping pane, select advanced mode, then select your outermost static row. You should then see the "RepeatOnNewPage" property.</p>
<p><strong>Update: finding Advanced Mode</strong>:<br>
The comment by @HCL links to the <a href="http://stackoverflow.com/questions/488900/reporting-services-tablix-repeatcolumnheaders-doesnt-work-on-some-reports/2986024#2986024">other answer by @user359904</a>, that has the info on how to find and enter Advanced Mode:</p>
<ol>
<li>Select the tablix</li>
<li>Below the report are "Row Groups" and "Column Groups", all the way to the right of "Column Groups" is a small downward arrow.</li>
<li>Click the arrow, choose Advanced Mode.</li>
</ol>
|
Which Java MVC frameworks integrate easily with StringTemplate? <p>It's hard to see how <em>StringTemplate</em> integrates easily (or not) with <em>popular</em> Java web MVC frameworks.</p>
<p><strong>Which Java MVC frameworks integrate easily with StringTemplate?</strong></p>
<p>A good answer:</p>
<ul>
<li>mentions <strong>one solution</strong> to integrate with a framework,</li>
<li>includes a <strong>link</strong> to something useful and applicable, like:
<ul>
<li>a <strong>tutorial</strong>,</li>
<li>or <strong>documentation</strong>,</li>
<li>or a reference to <strong>source code</strong>:
<ul>
<li><strong>free</strong>,</li>
<li>and <strong>open source</strong> or <strong>public domain</strong>.</li>
</ul></li>
</ul></li>
</ul>
<p><strong>Readers/Voters</strong>, please vote for a solution if you know it's true and great.</p>
<p>In the scope of this question, I am <em>not interested in any other templating engine than StringTemplate</em>.</p>
| <p>I've gotten StringTemplate to work with Spring. Basically, all it took was a custom view.</p>
<p>But first, a disclaimer: This is an experimental hack. I've never used this in production code, and it could use some improvement before that happens. I think it is adequate to answer your question about how easily StringTemplate integrates with a Web MVC framework, however.</p>
<p>Reference: <a href="http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html">Spring Web MVC documentation</a></p>
<p>StringTemplateView.java:</p>
<pre><code>import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.view.InternalResourceView;
public class StringTemplateView extends InternalResourceView {
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Provides a Spring resource descriptor referring to the .st file
Resource templateFile = getApplicationContext().getResource(getUrl());
// Kind of redundant...
StringTemplateGroup group = new StringTemplateGroup("group", templateFile.getFile().getParent());
StringTemplate template = group.getInstanceOf(getBeanName());
template.setAttributes(model);
// Output to client
PrintWriter writer = response.getWriter();
writer.print(template);
writer.flush();
writer.close();
}
}
</code></pre>
<p>And an example view resolver definition:</p>
<pre><code><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="myapp.web.view.StringTemplateView"/>
<property name="prefix" value="/WEB-INF/st-views/"/>
<property name="suffix" value=".st"/>
</bean>
</code></pre>
|
SQL Logical AND operator for bit fields <p>I have 2 tables that have a many to many relationship; An Individual can belong to many Groups. A Group can have many Individuals. </p>
<p>Individuals basically just have their Primary Key ID</p>
<p>Groups have a Primary Key ID, IndividualID (same as the ID in the Individual Table), and a bit flag for if that group is the primary group for the individual</p>
<p>In theory, all but one of the entries for any given individual in the group table should have that bit flag set to false, because every individual must have exactly 1 primary group.</p>
<p>I know that for my current dataset, this assumption doesn't hold true, and I have some individuals that have the primary flag for ALL their groups set to false.</p>
<p>I'm having trouble generating a query that will return those individuals to me.</p>
<p>The closest I've gotten is:</p>
<p>SELECT * FROM Individual i
LEFT JOIN Group g ON g.IndividualID = i.ID
WHERE g.IsPrimaryGroup = 0</p>
<p>but going further than that with SUM or MAX doesn't work, because the field is a bit field, and not a numeric. </p>
<p>Any suggestions?</p>
| <p>Don't know your data...but....that LEFT JOIN is an INNER JOIN</p>
<p>what happens when you change the WHERE to AND</p>
<pre><code>SELECT * FROM Individual i
LEFT JOIN Group g ON g.IndividualID = i.ID
AND g.IsPrimaryGroup = 0
</code></pre>
<p>Here try running this....untested of course since you didn't provide any ample data</p>
<pre><code>SELECT SUM(convert(int,g.IsPrimaryGroup)), i.ID
FROM Individual i
LEFT JOIN [Group] g ON g.IndividualID = i.ID
AND g.IsPrimaryGroup = 0
GROUP BY i.ID
HAVING COUNT(*) > 1
</code></pre>
|
Context agnostic JavaScript Testing Framework <p>I'm looking for a JavaScript Testing Framework that I can easily use in whatever context, be it browser, console, XUL, etc.</p>
<p>Is there such a framework, or a way to easily retrofit an existing framework so its context agnostic?</p>
<p>Edit: The testing framework should <strong>not</strong> be tied to any other framework such as jQuery or Prototype.js and shouldn't depend on a DOM (or document object) being present. I'm looking for something to test <strong>pure JavaScript</strong>. </p>
| <p>OK, here's something I just brewed based on some earlier work. I hope this would meet your needs.</p>
<h2><a href="http://jsunity.com/" rel="nofollow">jsUnity</a></h2>
<p>Lightweight Universal JavaScript Testing Framework </p>
<blockquote>
<p><strong>jsUnity</strong> is a lightweight universal JavaScript testing framework that is
context-agnostic. It doesn't rely on
any browser capabilities and therefore
can be run inside HTML, ASP, WSH or
any other context that uses
JavaScript/JScript/ECMAScript.</p>
</blockquote>
<h2>Sample usage inside HTML</h2>
<pre><code><pre>
<script type="text/javascript" src="../jsunity.js"></script>
<script type="text/javascript">
function sampleTestSuite() {
function setUp() {
jsUnity.log("set up");
}
function tearDown() {
jsUnity.log("tear down");
}
function testLessThan() {
assertTrue(1 < 2);
}
function testPi() {
assertEquals(Math.PI, 22 / 7);
}
}
// optionally wire the log function to write to the context
jsUnity.log = function (s) { document.write(s + "</br>"); };
var results = jsUnity.run(sampleTestSuite);
// if result is not false,
// access results.total, results.passed, results.failed
</script>
</pre>
</code></pre>
<p>The output of the above:</p>
<pre>
2 tests found
set up
tear down
[PASSED] testLessThan
set up
tear down
[FAILED] testPi: Actual value does not match what's expected: [expected] 3.141592653589793, [actual] 3.142857142857143
1 tests passed
1 tests failed
</pre>
|
Text Box vs Labels <p>I am developing a winForm App in C# and I have come across something that has always bothered me.</p>
<p><strong>Is it better practice to use a Label or a TextBox when displaying data to the user?</strong></p>
<p>Things like Name, Phone #, etc. My gut says to use a TextBox and just set it to read-only until the time comes that I need to allow editing from that particular spot. Plan for the future, as it were. </p>
<p>As a young <em>Lone Wolf</em> developer I would really appreciate any insight here. Are there any pro's and con's to either? Is there something else I am not thinking of?</p>
| <p>One useful thing to consider is that text in a textbox is selectable so it's easier for your users to copy/paste the content. </p>
<p>Premature optimizations like using labels because they are more light weight should take a backseat to defensive programming that, as you suspect, could save you time in the future. </p>
|
CSS in sharepoint <p>I need to apply a CSS to a Sharepoint site (WSS3.0) based on the theme applied to a site.
The CSS would be saved at root site in 'Document Library'.
How do I apply the CSS programmatically on the page? </p>
<p>Thanks!</p>
| <p>Put in the page layout or master page.
E.g.</p>
<pre><code><SharePointWebControls:CssRegistration ID="CssRegistrationMyCSS" name="<% $SPUrl:~sitecollection/Style Library/~language/Core Styles/myCSS.css %>" runat="server"/>
</code></pre>
<p>Programatically changing it requires you to modify the control on page load. Not sure how well it would work though.</p>
|
Caching and Session state management using Microsoft Velocity and Memcached <p>I was looking at Microsoft Velocity and memcached to find a solution for some session management issues -</p>
<p>What is the difference between caching that is provided by Microsoft Velocity, memcached and session state management? I mean memcached and microsoft veolocity provide distributed caching capabilities... so using these to store session state would mean that session state would also be distributed .. Am i right in this assumption</p>
| <p>The difference between caching an session state management is that caching is at the application level(caches data for all sessions). Also cache can timeout many times during a session. Use cache for holding frequently used information(i.e information from a lookup table). This way your application wont have to access your data source unnecessarily.</p>
|
Vertically align text next to an image? <p>Why won't <code>vertical-align: middle</code> work? And yet, <code>vertical-align: top</code> <em>does</em> work.</p>
<pre><code><div>
<img style="width:30px;height:30px">
<span style="vertical-align:middle">Doesn't work.</span>
</div>
</code></pre>
| <p>Actually, in this case it's quite simple: apply the vertical align to the image. Since it's all in one line, it's really the image you want aligned, not the text.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- moved "vertical-align:middle" style from span to img -->
<div>
<img style="vertical-align:middle" src="https://placehold.it/60x60">
<span style="">Works.</span>
</div></code></pre>
</div>
</div>
</p>
<p>Tested in FF3.</p>
|
HQL - row identifier for pagination <p>Does anyone know if HQL has a keyword to identify rows such as ROWID or ROWNUM?</p>
<p>I would like to implement pagination with HQL but I am not able to use .setMaxResult() or .setFirstResult() because I don't work with the session object directly and therefore don't use the Query object but simply create my query as a string and use the .find() method. </p>
<p>I tried using LIMIT and OFFSET in my query, but HQL seems to be ignoring these keywords and is returning the whole result to me no matter what.</p>
<p>I'm also not able to use Hibernate criteria because it does not have support for the "HAVING" clause that appears in my query.</p>
<p>My last resort is to restrict the result set using the ROWNUM/ROWID keyword. Does anyone else have any other suggestions?</p>
| <p>this is one situation where hibernate shines:</p>
<p>typical solution with hql query.</p>
<pre><code>int elementsPerBlock = 10;
int page = 2;
return getSession().createQuery("from SomeItems order by id asc")
.setFirstResult(elementsPerBlock * (page-1) + 1 )
.setMaxResults(elementsPerBlock)
.list();
</code></pre>
<p>hibernate will translate this to a pattern that is understood by the database according to its sql dialect.
on oracle it will create a subselect with ROWNUM < X.
on postgresql it will issue a LIMIT / OFFSET
on msSQL server it will issue a TOP..</p>
<p>to my knowledge it is not possible to achieve this with "pure" hql.</p>
|
How would you write this query? <p>I'm looking to refactor the below query to something more readable and modifiable. The first half is identical to the second, with the exception of the database queried from (table names are the same though.)</p>
<pre><code> SELECT
Column 1 AS c1,
...
Column N AS cN
FROM
database1.dbo.Table1
UNION
SELECT
'Some String' as c1,
...
NULL as cN
FROM
database1.dbo.Table2
UNION
SELECT
Column 1 AS c1,
...
Column N AS cN
FROM
database2.dbo.Table1
UNION
SELECT
'Some String' as c1,
...
NULL as cN
FROM
database2.dbo.Table2
</code></pre>
<p>This query is the definition of DRY and is calling to me to be re-written, but I have no idea how!</p>
<p><strong>EDIT</strong>: We can't use linq and we desire distinct results; I'm looking to make the query smaller in physical file size, not in results returned.</p>
<p><strong>EDIT</strong>: The database I'm querying off is a proprietary ERP database. Restructuring it is not an option.</p>
| <p>I'm going to go out on a limb here, and say, based on the information you've given us; </p>
<p><strong>That's as good as it's going to get</strong> </p>
|
Does ActionScript 3 require an error event handler for XML? <p>In a Flash game I am developing, there are some settings that are set by an external XML file. When I run the SWF file through the Flash IDE, it loads fine. If I run the same file as a projector (.exe) or the independent SWF file, it does not load the XML file.</p>
<p>My (unexpected) fix was to assign an <em>error</em> event listener to the loader object. When I published the file again, the XML loaded properly in the projector and standalone SWF files. (I have since verified that commenting out the error event handler restores the bug).</p>
<p>Here's the block of code involved (<del>with extraneous code and function calls removed</del>):</p>
<pre><code>public function getSettings():void {
outputBox = getChildByName("output_box") as TextField;
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, loadXML, false, 0, true);
xmlLoader.addEventListener(ErrorEvent.ERROR, function (e:Error)
{ outputBox.appendText(e.message) });
try {
xmlLoader.load(xmlPath);
}
catch(err:Error) {
trace(err.message);
outputBox.appendText(err.message);
checkChances("0");
}
function loadXML(e:Event):void {
try {
xmlData = new XML(e.target.data);
var chances:String = xmlData.chances.text();
var dbURL:String = xmlData.database.text();
trace("Chances are set to: " + chances);
trace("Database URL is set to: " + dbURL);
outputBox.appendText("Chances are set to: " + chances);
}
catch(err:Error) {
outputBox.appendText(err.message);
}
checkChances(chances);
dbPath = new URLRequest(dbURL);
}
</code></pre>
<p>}</p>
<p>Let me know if you have run into this, or if you can shed some light on what may be happening. Thanks!</p>
<p>EDIT:</p>
<p>Here is the code which does <em>not</em> work. (I also edited the code that does work to show all the other bits that I took out, just in case they might be effecting it):</p>
<pre><code>public function getSettings():void {
outputBox = getChildByName("output_box") as TextField;
var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlLoader.addEventListener(Event.COMPLETE, loadXML, false, 0, true);
/*xmlLoader.addEventListener(ErrorEvent.ERROR, function (e:Error)
{ outputBox.appendText(e.message) });*/
try {
xmlLoader.load(xmlPath);
}
catch(err:Error) {
trace(err.message);
outputBox.appendText(err.message);
checkChances("0");
}
function loadXML(e:Event):void {
try {
xmlData = new XML(e.target.data);
var chances:String = xmlData.chances.text();
var dbURL:String = xmlData.database.text();
trace("Chances are set to: " + chances);
trace("Database URL is set to: " + dbURL);
outputBox.appendText("Chances are set to: " + chances);
}
catch(err:Error) {
outputBox.appendText(err.message);
}
checkChances(chances);
dbPath = new URLRequest(dbURL);
}
</code></pre>
<p>}</p>
| <p>On the first addEventListener you're telling it to use weak references (that last argument to the call). Your loadXML function is defined within your getSettings() method. Once you leave the getSettings() scope loadXML goes out of scope. The only thing left referencing loadXML is the event listener, but since you tell it to use a weak reference that will not prevent it from being garbage collected. So, by the time the event is raised the loadXML method is probably garbage collected.</p>
<p>My guess is that when you define the other listener the anonymous method defined there keeps the getSettings() scope around (as it's part of that method's scope), which will keep loadXML() in scope.</p>
<p>What you really should do is refactor your loadXML method into an actual member function on your object, not an anonymous method defined in getSettings(). That will keep things cleaner, and would prevent the garbage collection you're seeing, as the method would stay in scope as long as the object does.</p>
<p>If for some reason you don't want to make loadXML a member function then removing the weak reference flag should be enough to fix it. However, you may end up with a bit of a memory leak due to the way those anonymous method work.</p>
|
import csv file/excel into sql database asp.net <p>I am starting a project with asp.net visual studio 2008 / SQL 2000 (2005 in future) using c#.</p>
<p>The tricky part for me is that the existing DB schema changes often and the import files columns will all have to be matched up with the existing db schema since they may not be one to one match on column names. (There is a lookup table that provides the tables schema with column names I will use)</p>
<p>I am exploring different ways to approach this, and need some expert advice. Is there any existing controls or frameworks that I can leverage to do any of this?</p>
<p>So far I explored FileUpload .NET control, as well as some 3rd party upload controls to accomplish the upload such as <a href="http://krystalware.com/Products/SlickUpload/" rel="nofollow">SlickUpload</a> but the files uploaded should be < 500mb</p>
<p>Next part is reading of my csv /excel and parsing it for display to the user so they can match it with our db schema. I saw <a href="http://www.codeproject.com/KB/database/CsvReader.aspx" rel="nofollow">CSVReader</a> and others but for excel its more difficult since I will need to support different versions.</p>
<p>Essentially The user performing this import will insert and/or update several tables from this import file. There are other more advance requirements like record matching but and preview of the import records, but I wish to get through understanding how to do this first.</p>
<p>Update: I ended up using csvReader with LumenWorks.Framework for uploading the csv files. </p>
| <p>Check out the excellent FileHelpers library - there an <a href="http://www.codeproject.com/KB/database/filehelpers.aspx" rel="nofollow">article on CodeProject</a> about it, and it's hosted <a href="http://www.filehelpers.com/" rel="nofollow">here</a>.</p>
<p>It's pure C#, and it can import just about any flat-file, CSV, and it deals with Excel, too. The import is totally configurable - you can define things like delimiters, rows and/or columns to skip, and so on - lots of options.</p>
<p>I've successfully used it in various projects and it just works flawlessly - highly recommended.</p>
|
Do Real Values sort different than floats in SQL Server queries? <p>Can anyone think of a reason to do this:</p>
<p>SELECT * FROM TableA
ORDER BY cast(cast(RealColumnA as nvarchar(50))as float)
--where RealColumnA is defined as real in the table</p>
<p>A former developer of mine insisted this was necessary to get reals to sort correctly. Can anyone think of a reason that may be true?</p>
<p>The cast in the orderby clause is a big performance killer. But I need to be sure it is not necessary before I remove it.</p>
| <p>Remove it. ORDER BY is what you expect it to be. And it certainly would be a performance killer.</p>
<p>Rule #1 about SQL. Question (and test) all your (and other peoples') assumptions. (Especially weird ones like this.)</p>
|
What are some common uses for Python decorators? <p>While I like to think of myself as a reasonably competent Python coder, one aspect of the language I've never been able to grok is decorators.</p>
<p>I know what they are (superficially), I've read tutorials, examples, questions on Stack Overflow, and I understand the syntax, can write my own, occasionally use @classmethod and @staticmethod, but it never occurs to me to use a decorator to solve a problem in my own Python code. I never encounter a problem where I think, "Hmm...this looks like a job for a decorator!"</p>
<p>So, I'm wondering if you guys might offer some examples of where you've used decorators in your own programs, and hopefully I'll have an "A-ha!" moment and <em>get</em> them.</p>
| <p>I use decorators mainly for timing purposes</p>
<pre><code>def time_dec(func):
def wrapper(*arg):
t = time.clock()
res = func(*arg)
print func.func_name, time.clock()-t
return res
return wrapper
@time_dec
def myFunction(n):
...
</code></pre>
|
Code Dependency documentation software <p>I am looking for a tool to document legacy source code for an embedded C project I work with. I had it in my mind that there was a tool that would create charts of the various C and .h files, but I can't recall what it is called. Does anyone know of such a tool?</p>
| <p><a href="http://www.cppdepend.com">CppDepend</a> The NDepend like for C\C++</p>
|
Can I indicate to clients that SPNEGO is supported but NTLM is not for HTTP requests? <p>The two WWW-Authenticate additions Microsoft makes use of that I am currently aware of are</p>
<ul>
<li>NTLM</li>
<li>Negotiate</li>
</ul>
<p>If Negotiate is sent down from the server, based on a set of conditions Kerberos will be used</p>
<ul>
<li>Intranet Zone</li>
<li>Accessing the server using a Hostname rather then IP</li>
<li>Integrated Windows Authentication in IE is enabled, the host is trusted in Firefox</li>
<li>The Server is not local to the browser</li>
<li>The client's Kerberos system is authenticated to a domain controller</li>
</ul>
<p>Then Kerberos will be attempted between the server and the client, if something above is not met, then NTLM will be attempted.</p>
<p>My question is, is there some way for the server to indicate that NTLM should not be sent? I currently handle this by keeping track of the request in the session, and if a NTLM message is received, it disables Kerberos and WWW-Authenticate for the rest of that sessions life.</p>
| <p>Yes you can. Take a look at the <a href="http://spnego.sourceforge.net/reference%5Fdocs.html" rel="nofollow">reference docs</a> of the SPNEGO HTTP Servlet Filter project.</p>
|
NHibernate not evicting objects from a session <p>I'm mapping a ProductCategory tree using Fluent NHibernate and everything was going fine until I tried to walk the tree that is returned from the database to ensure it's saving and retreiving appropriately.</p>
<p>Here's how I'm testing:</p>
<ol>
<li>Instantiate 4 categories: Beverages, Beer, Light Beer, and Dark Beer</li>
<li>Add Beer to Beverages, then Light Beer and Dark Beer to Beer.</li>
<li>Save Beverages (cascade is set to AllDeleteOrphan)</li>
<li>Flush the session, which persists the entire tree</li>
<li>Evict each of the ProductCategories from the session</li>
<li>Load Beverages from the database</li>
<li>Check that the loaded object (fromDB) is EqualTo but not SameAs Beverages.</li>
<li>Check that fromDB has only one child ProductCategory</li>
<li>Check that the only child in fromDB is EqualTo but not SameAs Beer</li>
</ol>
<p>The test fails because the child is the SameAs Beer. Which means that it's not actually loading the object from the database, because it's still in the NHibernate session somewhere.</p>
<p>Any insight will be much appreciated.</p>
<p><strong>Edit:</strong> In response to Sean's comments below. I am using an in memory SQLite database, so as soon as the session/connections are closed the database is blown away.</p>
| <p>Just figured it out, turns out it was a copy&paste bug. Heh, PEBKAC.</p>
<p>I added 4 assertions that verify that the objects are not in the session:</p>
<pre><code>Assert.That(Session.Contains(_beveragesCategory), Is.False);
Assert.That(Session.Contains(_beerCategory), Is.False);
Assert.That(Session.Contains(_darkBeerCategory), Is.False);
Assert.That(Session.Contains(_lightBeerCategory), Is.False);
</code></pre>
<p>When all of those passed (the first time I ran them) I took a closer look at the code that was asserting that the objects were differenta nd found that the assertions were wrong.</p>
<p>Was:</p>
<pre><code>Assert.That(_beverageCategory.ChildCategories[0], Is.Not.SameAs(_beerCategory));
</code></pre>
<p>Should have been:</p>
<pre><code>Assert.That(fromDB.ChildCategories[0], Is.Not.SameAs(_beerCategory));
</code></pre>
|
QScintilla scrollbar <p>When I add a QsciScintilla object to my main window the horizontal scrollbar is active and super wide (tons of apparent white space). Easy fix?</p>
| <p>Easy fix:</p>
<pre><code>sc.SendScintilla(sc.SCI_SETHSCROLLBAR, 0)
</code></pre>
|
Best way to validate URL parameters in Spring MVC website? <p>I am using Spring MVC to build my web application, and I have a question about validating parameters I receive in the URL. <strong>What is the best way to detect invalid parameters and display errors to the user?</strong></p>
<p>Suppose I have a "View User Profile" page. The profile that is displayed is based on a user ID parameter specified in the URL. I might go to the following address to view the profile of the user with ID 92:</p>
<blockquote>
<p><a href="http://www.somedomain.com/profile.html?id=92" rel="nofollow">http://www.somedomain.com/profile.html?id=92</a></p>
</blockquote>
<p>I have created a <code>ProfileControlller</code> object which will do the following:</p>
<ol>
<li>Get the <code>id</code> parameter from the <code>request</code> object</li>
<li>Load a <code>UserProfile</code> object from my database</li>
<li>Add the <code>UserProfile</code> object to the model</li>
<li>Construct a <code>ModelAndView</code> with my model and the "View User Profile" JSP</li>
</ol>
<p>That works fine if the user enters a valid ID number. My <code>UserProfile</code> object is loaded and displayed perfectly using JSP. But what if someone passes user ID <code>-30294</code> to my page? My data access layer will simply return a <code>null</code> object if the ID is invalid, but I would like to show a friendly error message to the user. Is checking for a <code>null</code> <code>UserProfile</code> object in the JSP code really the best solution here?</p>
<p>Since I am new to Spring, I'm not sure. I like the way <code>Validator</code> classes can be used with <code>FormController</code> objects, if that is any help.</p>
| <p>If the DAO returns null, simply return a ModelAndView for an error page. </p>
<p>Example:</p>
<pre><code>UserProfile profile = userProfileDao.findUserProfileById(userId);
if (profile == null) {
return new ModelAndView("Error", "message", "Invalid user ID");
} else {
// process accordingly.
}
</code></pre>
<p>In the Spring 2.5 distribution, check the jpetstore application in the samples directory. Find the org.springframework.samples.jpetstore.web.spring.SignonController for a simple example with an application.</p>
|
JSP template inheritance <p>Coming from a background in Django, I often use "template inheritance", where multiple templates inherit from a common base. Is there an easy way to do this in JSP? If not, is there an alternative to JSP that does this (besides Django on Jython that is :)</p>
<h2>base template</h2>
<pre><code><html>
<body>
{% block content %}
{% endblock %}
</body>
<html>
</code></pre>
<h2>basic content</h2>
<pre><code>{% extends "base template" %}
{% block content %}
<h1>{{ content.title }} <-- Fills in a variable</h1>
{{ content.body }} <-- Fills in another variable
{% endblock %}
</code></pre>
<p>Will render as follows (assuming that conten.title is "Insert Title Here", and content.body is "Insert Body Here")</p>
<pre><code><html>
<body>
<h1>Insert title Here <-- Fills in a variable</h1>
Insert Body Here <-- Fills in another variable
</body>
<html>
</code></pre>
| <p>You can do similar things using JSP tag files. Create your own <code>page.tag</code> that contains the page structure. Then use a <code><jsp:body/></code> tag to insert the contents.</p>
|
Favorite (Clever) Defensive Programming Best Practices <p>If you had to choose your <strong>Favorite</strong> (clever) techniques for defensive coding, what would they be? Although my current languages are Java and Objective-C (with a background in C++), feel free to answer in any language. Emphasis here would be on <em>clever</em> defensive techniques other than those that 70%+ of us here already know about. So now it is time to dig deep into your bag of tricks.</p>
<p>In other words try to think of other than this <strong>uninteresting</strong> example:</p>
<ul>
<li><code>if(5 == x)</code> <strong>instead of</strong> <code>if(x == 5)</code>: to avoid unintended assignment</li>
</ul>
<p>Here are some examples of some <strong>intriguing</strong> best defensive programming practices (language-specific examples are in Java):</p>
<p><strong>- Lock down your variables until you know that you need to change them</strong></p>
<p>That is, you can declare <em>all</em> variables <code>final</code> until you know that you will need to change it, at which point you can remove the <code>final</code>. One commonly unknown fact is that this is also valid for method params:</p>
<pre><code>public void foo(final int arg) { /* Stuff Here */ }
</code></pre>
<p><strong>- When something bad happens, leave a trail of evidence behind</strong></p>
<p>There are a number of things you can do when you have an exception: obviously logging it and performing some cleanup would be a few. But you can also leave a trail of evidence (e.g. setting variables to sentinel values like "UNABLE TO LOAD FILE" or 99999 would be useful in the debugger, in case you happen to blow past an exception <code>catch</code>-block).</p>
<p><strong>- When it comes to consistency: the devil is in the details</strong></p>
<p>Be as consistent with the other libraries that you are using. For example, in Java, if you are creating a method that extracts a range of values make the lower bound <em>inclusive</em> and the upper bound <em>exclusive</em>. This will make it consistent with methods like <code>String.substring(start, end)</code> which operates in the same way. You'll find all of these type of methods in the Sun JDK to behave this way as it makes various operations including iteration of elements consistent with arrays, where the indices are from Zero (<em>inclusive</em>) to the length of the array (<em>exclusive</em>). </p>
<p>So what are some favorite defensive practices of yours?</p>
<p><strong>Update: If you haven't already, feel free to chime in. I am giving a chance for more responses to come in before I choose the <em>official</em> answer.</strong></p>
| <p>In c++, I once liked redefining new so that it provided some extra memory to catch fence-post errors. </p>
<p>Currently, I prefer avoiding defensive programming in favor of <a href="http://en.wikipedia.org/wiki/Test-driven_development">Test Driven Development</a>. If you catch errors quickly and externally, you don't need to muddy-up your code with defensive maneuvers, your code is <a href="http://c2.com/cgi/wiki?DontRepeatYourself">DRY</a>-er and you wind-up with fewer errors that you have to defend against. </p>
<p><a href="http://wikiknowledge.net/wiki/VB_Classic/Effective_Programming#Avoid_Defensive_Programming.2C_Fail_Fast_Instead">As WikiKnowledge Wrote</a>:</p>
<blockquote>
<p><strong>Avoid Defensive Programming, Fail Fast Instead.</strong> </p>
<p>By defensive programming I
mean the habit of writing code that
attempts to compensate for some
failure in the data, of writing code
that assumes that callers might
provide data that doesn't conform to
the contract between caller and
subroutine and that the subroutine
must somehow cope with it.</p>
</blockquote>
|
LoaderLock error on program termination <p>I have recently integrated the .NET NLog logging component into one of our applications which developed purely in unmanaged code (C++ and VB6 components compiled in Visual Studio 6). We have a bunch of C++ application talking to NLog via a COM interface.</p>
<p>Everything is working fine at the moment but I do notice that the following message pops up (in the output window if debugging the C++ component in VS6; as a prompt in the IDE if debugging NLog via VS 2005) during program termination:</p>
<blockquote>
<p>LoaderLock was detected Message:
Attempting managed execution inside OS
Loader lock. Do not attempt to run
managed code inside a DllMain or image
initialization function since doing so
can cause the application to hang.</p>
</blockquote>
<p>The DllMain is as follows:</p>
<pre><code>extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
_Module.Init(ObjectMap, hInstance);
DisableThreadLibraryCalls(hInstance);
}
else if (dwReason == DLL_PROCESS_DETACH)
_Module.Term();
return TRUE; // ok
}
</code></pre>
<p>My guess is that <code>_Module.Term();</code> now includes the releasing of some .NET references (I am keeping a reference to a NLog object in one of my C++ classes to avoid having to instantiate and release each time) which is causing this warning to pop up.</p>
<p>My question: is this safe to ignore? If it isn't, what is a good workaround? (the best I can think of is to instantiate a reference to that NLog object and release it every time I want to write to the log file...not the most elegant of solutions)</p>
| <p>It is most definitely not safe to ignore this message. If you hit this message, you've almost certainly created a real loader lock policy violation. This is a very serious error and can cause unpredictable behavior in a program (including deadlock). </p>
<p>The best way to avoid this is to not access any other .Net Objects/Functions directly or indirectly inside of DLL main. For your case, it's probably best to use a different cache policy. Perhaps create a ref counted object to hold the .Net reference. That way the object will be released before DllMain is called for unload (the dll can't be unloaded until all of your objects are destroyed). </p>
|
PHP session seemingly not working <p>Session variables are apparently not working for me. I don't know what I'm doing wrong. This is the code that I'm using to check for a valid password:</p>
<pre><code>if ($input_password_hash == $password_hash)
{
session_start();
$_SESSION['is_user'] = 1;
header("Location: ../new_look"); //or Location: index.php
}
else echo "Wrong password.";
</code></pre>
<p>in the index.php file (where it redirects to), I have this code:</p>
<pre><code>if ($_SESSION['is_user'] == 1)
{
//show index page with navigation bar for registered user
}
else
{
//do something else
}
</code></pre>
<p>but it's not working at all.</p>
<p>The session does apparently start and that can be verified by checking the cookie.</p>
<p>What am I doing wrong?</p>
| <p>You know that you've got to write <code>session_start()</code> before you use the <code>$_SESSION</code> variable in any request, right? It looks like you haven't put it in index.php anywhere.</p>
|
PHP array problem <p>I'm sending some data over AJAX to a PHP file. It's about filter options. Anyway, I am sending it like this:</p>
<pre><code>filter[0][data][type] string
filter[0][data][value] automobiles
filter[0][field] product
filter[1][data][type] numeric
filter[1][data][value] 6000
filter[1][field] price
</code></pre>
<p>This above is taken from FireBug console. Then, in PHP:</p>
<pre><code>$filter = $_POST['filter'.$i];
if (is_array($filter)) {
for ($i=0;$i<count($filter);$i++){
switch($filter[$i]['data']['type']){
case 'string' :
// I'm doing my select from database based on that and so on
</code></pre>
<p>So, the translation of this would be:
"Get me all the records from database that are: <em>hmm, let's check the filters</em>... I'm getting the first filter type witch is "string" witch needs to be applied to the mysql column named "product"...So I'm searching for the value of "automobiles" there...But I'm not finished yet, the second filter refers to a numeric filter for the column "price" from database. so I'm taking its value and add it to the query. So I'll end up selecting all the automobiles that have a price greater than 6000.</p>
<p>So far so good. The problem is that my way of getting data have changed and I can't send my data in this format no more. The new format is an URL witch looks like this:</p>
<pre><code>filter[0][field]=prodct&filter[0][data][type]=string&filter[0][data][value]=automobiles&filter[1][field]=price&filter[1][data][type]=numeric&filter[1][data][value]=6000
</code></pre>
<p>I can do an explode on this one by the "&" and end up with an array...I can do a lot... The problem is that I don't know how to adjust my query building script to work with that kind of received data..So that I can do a "switch($filter[$i]['data']['type']){" again...</p>
<p>Any ideas for modifying the code ?</p>
<p>Thank you!</p>
| <p><a href="http://www.php.net/parse_str" rel="nofollow">parse_str</a>($queryString); and then do everything as normal. That method will process the query string and import the variables to the global namespace (which could be dangerous), so maybe use its second form (listed on the manual page):</p>
<pre><code>$result = array();
parse_str($queryString, $result)
$filters = $result['filter'];
foreach($filters as $filter) {
// your code
}
</code></pre>
|
How to add NHibernate configuration file to use NHibernate.Search? <p>I try to use NHibernate.Search that I built from trunk and use with NHibernate 2.0.1. When I add some NHibernate.Search properties config into configuaration file:</p>
<pre><code><property name="hibernate.search.default.directory_provider">NHibernate.Search.Storage.RAMDirectoryProvider, NHibernate.Search</property>
<property name="hibernate.search.default.indexBase">~\index\</property>
</code></pre>
<p>I get an invalid System.Xml.Schema.XmlSchemaException: The Enumeration constraint failed. When I use :</p>
<pre><code>var configuration = new Configuration().Configure();
</code></pre>
<p>So how can I solve this problem?</p>
| <p>Make sure that the NHibernate.Search properties you define are included in the nhs-configuration block and not in the standard NHibernate configuration block.
Your web.config should look like this:</p>
<pre><code><section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
<section name="nhs-configuration" type="NHibernate.Search.Cfg.ConfigurationSectionHandler, NHibernate.Search" />
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<!-- nhibernate configuration block -->
</hibernate-configuration>
<nhs-configuration xmlns='urn:nhs-configuration-1.0'>
<search-factory>
<property name='hibernate.search.default.directory_provider'>NHibernate.Search.Store.FSDirectoryProvider, NHibernate.Search</property>
<property name='hibernate.search.default.indexBase'>...</property>
</search-factory>
</nhs-configuration>
</code></pre>
|
Virtual address space in 64 bit systems running in compatibility mode <p>I saw that on a 64 bit windows OS the user virtual address space available is 8 terra bytes. But if the program we are executing on this is running in 32 bit compatibility mode is this much of user space still available ? or does it behave like a normal 32 bit OS and gives only 2GB user address space?</p>
| <p>Microsoft has a chart showing the various limits: <a href="http://msdn.microsoft.com/en-us/library/aa366778.aspx">Memory Limits for Windows Releases</a></p>
<p>To summarize just the user-mode virtual address space:</p>
<ul>
<li>32-bit Windows:
<ul>
<li>32-bit process: 2 GB by default; 3 GB with <code>/LARGEADDRESSAWARE:YES</code> and 4GT</li>
</ul></li>
<li>64-bit Windows (x64 architecture):
<ul>
<li>32-bit process: 2 GB by default; 4 GB with <code>/LARGEADDRESSAWARE:YES</code></li>
<li>64-bit process: 8 TB by default; 2 GB with <code>/LARGEADDRESSAWARE:NO</code></li>
</ul></li>
</ul>
<p>4GT is 4-gigabyte tuning:</p>
<ul>
<li>XP: <code>/3GB</code> boot.ini switch</li>
<li>Vista: <code>bcdedit /set increaseuserva 3072</code></li>
</ul>
<p>Mark Russinovich made a blog post explaining many these limits: <a href="http://blogs.technet.com/markrussinovich/archive/2008/11/17/3155406.aspx">Pushing the Limits of Windows: Virtual Memory</a> </p>
|
Add Colors in Combo box in .NET Windows application <p>How to add 'Colors' (not color name, color itself ) as an item in combo box in C#?</p>
| <p>You'll have to use an owner drawn combobox. <a href="http://www.codeproject.com/KB/combobox/ownerdrawncombobox.aspx" rel="nofollow">This article</a> on <a href="http://www.codeproject.com/" rel="nofollow">CodeProject</a> is a good reference.</p>
|
What are the advantages and disadvantages of the Properties Pattern? <p>Steve Yegge describes the <strong>Properties Pattern</strong> in a <a href="http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html#Property">blog post</a> of his.</p>
<p>For someone using a static language like C# or Java, what are the advantages and disadvantages of this approach? In what kind of projects would you want to use the Properties Pattern, and when would you want to avoid it?</p>
| <p>I've been digging into this pattern quite a bit myself lately, and I can tell you that finding information on it is pretty tough. Yegge calls it prototype or properties, but both of those are pretty heavily overused, and well known as two other, different patterns. Some people refer to systems like the one Yegge proposes as "stringly[sic] typed" so that's another avenue of research.</p>
<p>It's a really neat idea, and one that has a lot of merit in some applications, and a lot of faults in others. What you gain is essentially a very flexible means of building "types" at runtime, but you lose out on a lot of the languages strong-type checking to do it. The easiest way to implement it would be as a <code>Dictionary<string,string></code>. Then you have to use casts to get your string values back out as actual values. The key to keeping such a design manageable is to never directly reference a property in code if you can avoid it. Stuff like <code>theProtoObject["owner"] = "protoman"</code> will kill you if the "canonical" name of that slot changes. It can also lead to issues like JavaScript (which uses this pattern underneath as it's object model) where if you misspell the key name, you'll add a new slot.</p>
<p>One very likely upgrade you'd probably make in a production system is to use some kind of specialized types for values, and some kind of "heavy key" for the key, so you can get a bit of extra typing and safety info on your model.</p>
<p>I've seen a few applications that use it. One surprising example hit me recently while looking up open source code in my industry: insurance quoting. <a href="http://openquote.appliedindustriallogic.com/">OpenQuote</a> is a very flexible project for quoting insurance of any general type. It's written in Java, but if you know C# it should read quite well. At the very heart of it, lies the <code>Type</code> object, which contains this bit of code:</p>
<pre><code>/** A dynamic collection of attributes describing type */
private List<Attribute> attribute = new ArrayList<Attribute>();
</code></pre>
<p>And what is an <code>Attribute</code>? This:</p>
<pre><code>* An attribute is defined as "One of numerous aspects, as of a subject". Generally, another
* type will own a (composite) collection of Attributes which help describe it.
</code></pre>
<p>So basically <code>Attribute</code> is a kind of key-value pair containing a unique string ID (the field name) and a string value, and an enumeration of types combined with some regex to verify and process the values. In this way, it can store values of many types, and convert them back out into java values, while providing a bit of safety.</p>
<p>It then goes on to build many domain specific model types on top of that core. So an insurance policy object can be treated as having a flexible, extensible list of benefits on it, which can added or removed or modified at runtime. Each benefit can have properties extended or reduced on them as well.</p>
<p>So that's an example of the pattern in use, and a decent use case for it: insurance policies can be very flexible, at the whim of the underwriters up to the moment of sale, so a highly flexible model works well for it.</p>
<p>The downsides are pretty much what Yegge outlines though. Performance can be bad, especially with a naive implementation. Type-checking and safety take a hit, and your objects are more difficult to reason about because you don't know for sure what properties are on them.</p>
|
How to move the environment details outside the EAR <p>Our project is a medium size web application developed using RAD 7.0 on WAS 6.1/hibernate/struts which moved to production. Currently we have hardcoded the ip address of the production system in the property file and database schema details in the hibernate config file. </p>
<p>Our client wants us to come up with the solution for keeping the environment details out side the EAR, so that they can change the environment/db details in future with out opening the EAR .</p>
<p>Any pointers would be very helpful. Thanks.</p>
| <p>You can use JNDI for this. You should create the appropriate entries and in your code read them like this:</p>
<pre><code>Context initialContext = new InitialContext();
URL ip = (URL) initialContext.lookup("java:comp/env/myip");
</code></pre>
<p>See <a href="http://www.developer.com/open/article.php/3559931">this</a> article on how to use a JNDI Data Source in hibernate configuration files.</p>
|
Keeping an array sorted in PHP <p>I have a PHP script which reads a large CSV and performs certain actions, but only if the "username" field is unique. The CSV is used in more than one script, so changing the input from the CSV to only contain unique usernames is not an option.</p>
<p>The very basic program flow (which I'm wondering about) goes like this:</p>
<pre><code>$allUsernames = array();
while($row = fgetcsv($fp)) {
$username = $row[0];
if (in_array($username, $allUsernames)) continue;
$allUsernames[] = $username;
// process this row
}
</code></pre>
<p>Since this CSV could actually be quite large, it's that <code>in_array</code> bit which has got me thinking. The most ideal situation when searching through an array for a member is if it is already sorted, so <strong>how would you build up an array from scratch, keeping it in order</strong>? Once it is in order, would there be a more efficient way to search it than using <code>in_array()</code>, considering that it probably doesn't know the array is sorted?</p>
| <p>Not keeping the array in order, but how about this kind of optimization? I'm guessing <code>isset()</code> for an array key should be faster than <code>in_array()</code> search.</p>
<pre><code>$allUsernames = array();
while($row = fgetcsv($fp)) {
$username = $row[0];
if (isset($allUsernames[$username])) {
continue;
} else {
$allUsernames[$username] = true;
// do stuff
}
}
</code></pre>
|
Notifying the user after a long Ajax task when they might be on a different page <p>I have an Ajax request to a web service that typically takes 30-60 seconds to complete. In some cases it could take as long as a few minutes. During this time the user can continue working on other tasks, which means they will probably be on a different page when the task finishes.</p>
<p>Is there a way to tell that the original request has been completed? The only thing that comes to mind is to:</p>
<ul>
<li>wrap the web service with a web service of my own</li>
<li>use my web service to set a flag somewhere</li>
<li>check for that flag in subsequent page requests</li>
</ul>
<p>Any better ways to do it? I am using jQuery and ASP.Net, if it matters.</p>
| <p>You could add another method to your web service that allows you to check the status of a previous request. Then you can use ajax to poll the web service every 30 seconds or so. You can store the request id or whatever in Session so your ajax call knows what request ID to poll no matter what page you're on.</p>
|
Including boost::filesystem produces linking errors <p>Ok first off, I am linking to boost_system and boost_filesystem.</p>
<p>My compiler is a <a href="http://nuwen.net/mingw.html" rel="nofollow">custom build of MinGW with GCC 4.3.2</a></p>
<p>So when I include:</p>
<pre><code>#include "boost/filesystem.hpp"
</code></pre>
<p>I get linking errors such as:</p>
<pre><code>..\..\libraries\boost\libs\libboost_system.a(error_code.o):error_code.cpp:
(.text+0xe35)||undefined reference to `_Unwind_Resume'|
..\..\libraries\boost\libs\libboost_system.a(error_code.o):error_code.cpp:
(.eh_frame+0x12)||undefined reference to `__gxx_personality_v0'|
</code></pre>
<p>Which after a little searching I found is most commonly when you try to link a C++ program with gcc, the GNU C compiler. But I printed out the exact build command that <a href="http://www.codeblocks.org/" rel="nofollow">Code::Blocks</a> is running, and it is definitely linking with g++.</p>
<p>If I comment out this include, everything works fine.</p>
<p>Any ideas? Also, as a side, anyone know of a good place to get windows binaries for boost? The build system is giving me issues, so I'm using some binaries that came with this <a href="http://nuwen.net/mingw.html#contents" rel="nofollow">custom MinGW package</a></p>
| <p>Ok, I found the problem. It's a bit convoluted.</p>
<p>GCC is gradually becoming more IS 14882 compliant in the 4.x branch. As they go on, they are removing deprecated non-standards complaint features.</p>
<p>While 4.1.x seem to only have them deprecated and not removed, 4.3.x seems to actually have them removed. What this means is 4.3.x and greater have some backwards compatibility issues with things compiled in the 3.x branch (which used the deprecated and now removed features)</p>
<p>I was using a mix and match combination of binaries that had been compiled with GCC 3.x, 4.1.x and 4.3.x so no matter which one I used, I got a similar error, because at least one binary I was linking to was incompatible with the compiler I was trying at the moment.</p>
<p>I'm now using GCC 4.1.2 and most of my binaries have been compiled with it. I am still how ever using a few binaries from 3.x, which is why I am not upgrading to 4.3.x just yet.</p>
<p>Hope that was less confusing to read than it was to write...</p>
<p><a href="http://archives.devshed.com/forums/development-94/what-is-the-preferred-gcc-version-3-x-or-4t-2287902.html" rel="nofollow">This</a> seems to be a good post addressing some of the issues as they were with 4.1.x</p>
|
F# Units of measure, problems with genericity 2 <p>Following on from <a href="http://stackoverflow.com/questions/460766/f-units-of-measure-problems-with-genericity">this</a> question, I still seem to be battling at the frontiers of what is possible, though I don't think that I'm doing anything particularly bleeding edge:</p>
<pre><code>type Vector2d = { X: float<'u>; Y: float<'u> }
</code></pre>
<p>Gives me <em>error FS0039: The unit-of-measure parameter 'u' is not defined.</em></p>
<p>And </p>
<pre><code>type Vector2d = { X: float<_>; Y: float<_> }
</code></pre>
<p>Gives me <em>error FS0191: anonymous unit-of-measure variables are not permitted in this declaration.</em></p>
<p>Is it the case that functions can handle 'generic' units of measure, but types can't?</p>
| <pre><code>type Vector2d<[<Measure>]'u> = { X: float<'u>; Y: float<'u> }
</code></pre>
<p>should do the trick</p>
<p>Note: This is correct as of the 1.9.6.2 CTP release but this api is not currently viewed as stable</p>
|
Converting Value Type of a Dictionary in VB.net <pre><code>Public Class A
Public Class B : Inherits A
Dim DictA As Dictionary(Of Integer, A)
Dim DictB As New Dictionary(Of Integer, B)
DictA = DictB
</code></pre>
<p>This doesn't work, as the type can't be converted. Is this somehow possible?</p>
| <p>No. You're running into the problem of generic variance, which isn't supported in .NET except in a few very particular ways.</p>
<p>Here's the reason: after your last line, you've got a single dictionary with two "views" onto it, effectively. Now imagine you wrote:</p>
<pre><code>DictA.Add(1, New A())
</code></pre>
<p>(Apologies if my VB is slightly off.) That's inserted a "non-B" into the dictionary, but DictB thinks that all the values will be instances of B.</p>
<p>One of the main purposes of generics is to catch potential type failures at compile time rather than execution time - which means this code should fail to compile, which indeed it does precisely because of the lack of variance.</p>
<p>It's a bit counter-intuitive when you're used to normal inheritance, but it does make sense. A bunch of bananas isn't just a collection of fruit - it's a collection <em>of bananas</em>.</p>
<p>Java takes a somewhat different stance on this using wildcarding from the caller's side - it would let you see just the "adding" side of the dictionary for DictB, for instance, as anything you add to DictB would be fine in DictA. Java's generics are very different to .NET generics though...</p>
|
Does modified Open Source code HAS-TO-BE open-sourced? <p>We have taken an open-source application, released under GPL ver1.09 and have modified some parts of its source and have made some customisations/enhancements as per our requirement.</p>
<p>We are using this application for non-commercial, internal purposes only.</p>
<p><strong>Is it mandatory that we have to publish the modified code in open-source, if we wish to use it?</strong></p>
<p>EDIT : Does it vary in any way, depending upon its user-base? (e.g. Just the company employees or outsiders as well?)</p>
| <p>If you're not going to distribute it, you can do what you want with it.</p>
<p>See <a href="http://www.gnu.org/licenses/gpl-faq.html#GPLRequireSourcePostedPublic" rel="nofollow">this entry in the GPL FAQ</a>.</p>
|
How do I unset an element's CSS attribute using jQuery? <p>If I set a CSS value on a specific element using:</p>
<pre><code>$('#element').css('background-color', '#ccc');
</code></pre>
<p>I want to be able to unset that element-specific value and use the cascaded value, along the lines of:</p>
<pre><code>$('#element').css('background-color', null);
</code></pre>
<p>But that syntax doesn't seem to work -- is this possible using another syntax?</p>
<p>Thanks in advance!</p>
<p><strong>Edit:</strong> The value isn't inherited from the parent element -- the original values comes from an element-level selector. Sorry for any confusion!</p>
| <p>From the <a href="http://api.jquery.com/css/">jQuery docs</a>: </p>
<blockquote>
<p>Setting the value of a style property to an empty string â e.g. <code>$('#mydiv').css('color', '')</code> â removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's <code>.css()</code> method, or through direct DOM manipulation of the <code>style</code> property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <code><style></code> element.</p>
</blockquote>
|
How would I require a password for all files except one using .htaccess? <p>I have a new website I'm working on that the client wants to keep a secret, but at the same time, I want to put an under construction page with some info on it. I would like to have everything except index.html require a user/password--index.html would be available to everyone.</p>
<p>I have the following, but I'm not sure what I need to add:</p>
<pre><code>AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/file/.htpasswd
AuthGroupFile /dev/null
require valid-user
</code></pre>
<p>There are too many files and possibly new files to say "for this set of files require a user/password".</p>
<p>I think it has something to do with something similar to:</p>
<pre><code><Files index.html>
order deny,allow
allow from all
</Files>
</code></pre>
<p>But I'm not exactly sure how.</p>
| <pre><code>AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/file/.htpasswd
AuthGroupFile /dev/null
<Files "*">
Require valid-user
</Files>
<Files "index.html">
Allow from all
Satisfy any
</Files>
</code></pre>
|
run a web project developed in Java run on both windows and Linux platform <p>I have a web project developed in java. I am using the Windows platform and accessing the project from the Windows machine itself. How can I make the project run on a Linux machine? I am using jboss server and deploying the project.</p>
<p>Regards</p>
| <p>Java is Cross-Platform, MySQL also. You can have your application server running on one server and the database on another. You can even have your Appserver on Linux and your database on Windows and your client on MacOS.</p>
<p>If you run into any specific problem, please let us know, but everything should be transparent unless you wrote some very bad Java code ...</p>
|
Should I still learn C if I already know Assembly? <p>Often one of the main reasons given for learning C is that it brings you closer to programming at a low level which gives you insights into how things really work in higher level languages.</p>
<p>I've been programming in various Assembly flavors for awhile and you can't get any lower level than what I have been coding in and I have no illusions about what reference types or pointers really are. It should be pointed out that I also am fairly prolific in Java and C#. I don't only know assembly.</p>
<p>Is it still worth the effort cracking open <a href="http://en.wikipedia.org/wiki/The_C_Programming_Language_(book)" rel="nofollow">K&R</a> and spending some valuable time learning the intricacies of the C language or would my time best be served learning something else?</p>
| <blockquote>
<p>Often one of the main reasons given for learning C is that it brings you closer to programming at a low level </p>
</blockquote>
<p>Well, scratch that one off, look at the others and decide for yourself. If you want to:</p>
<ul>
<li>remain close to low level but gain portability</li>
<li>be able to work with the huge codebase that C has already</li>
<li>just learn something new</li>
</ul>
<p>then you might want to learn C. </p>
|
friend class : inherited classes are not friend as well? <p>In C++, I have a class A which is friend with a class B.</p>
<p>I looks like inherited classes of B are not friend of class A.</p>
<p>I this a limitation of C++ or my mistake ?</p>
<p>Here is an example. When compiling, I get an error on line "return new Memento":</p>
<p>Memento::Memento : impossible to access private member declared in Memento.</p>
<pre><code>class Originator;
class Memento
{
friend class Originator;
Memento() {};
int m_Data;
public:
~Memento() {};
};
class Originator
{
public:
virtual Memento* createMemento() = 0;
};
class FooOriginator : public Originator
{
public:
Memento* createMemento()
{
return new Memento; // Impossible to access private member of Memento
}
};
void main()
{
FooOriginator MyOriginator;
MyOriginator.createMemento();
}
</code></pre>
<p>I could of course add FooOriginator as friend of Memento, but then, this means I would have to add all Originator-inherited classes as friend of Memento, which is something I'd like to avoid.</p>
<p>Any idea ?</p>
| <p>Friendship is not inherited, you have to explicitly declare every friend relationship. (See also "<a href="http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4" rel="nofollow">friendship isn't inherited, transitive, or reciprocal</a>")</p>
|
System information as desktop wall-paper on Remote Desktop <p>When opening Remote Desktop to different Windows servers, it is easy to confuse two remote desktops.</p>
<p>How do I get each remote server to automatically display some system information as desktop wallpaper, ie. Computer Name, Operating System, IP Address, etc.</p>
| <p>I've used <a href="http://technet.microsoft.com/en-us/sysinternals/bb897557.aspx">BGInfo</a> from the SysInternals guys to do this in the past.</p>
|
How to convert standard IP address format string to hex and long? <p>Does anyone know how to get the IP address in decimal or hex from standard IP address format string ("xxx.xxx.xxx.xxx")?</p>
<p>I've tried to use the inet_addr() function but didn't get the right result.</p>
<p>I tested it on "84.52.184.224"</p>
<p>the function returned 3770168404 which is not correct (the correct result is 1412741344).</p>
<p>Thanks!</p>
| <p>You have just got the bytes reversed from what you expected - they are in <a href="https://en.wikipedia.org/wiki/Endianness#Networking" rel="nofollow">network byte order</a></p>
<pre><code>3770168404 = 0xE0 B8 34 54 network byte order
| |
\ /
\ /
\ /
\ /
/\
/ \
/ \
/ \
| |
1412741344 = 0x54 34 B8 E0 machine order
</code></pre>
<p>You could use <a href="http://msdn.microsoft.com/en-us/library/ms740069(VS.85).aspx" rel="nofollow">ntohl()</a> convert from network order to machine order.</p>
|
Maximum lookup fields in a list <p>In SharePoint 2007, is there a limit to the number of lookup-fields that you can have in a list?</p>
| <p>No, however you might want to bear in mind the 'rule of 2000'.</p>
<p>Microsoft states the following:</p>
<p>2,000 columns per document library and 4,096 per list</p>
<p>But these are not hard limits they are prformace guidelines. You can see a full <a href="http://technet.microsoft.com/en-us/library/cc262787.aspx" rel="nofollow">TechNet article on SharePoint architecture and performance limitations here</a></p>
|
Is Dynamic SQL more vulnerable to SQL Injection/hacking? <p>Is Dynamic SQL more vulnerable to SQL Injection/hacking?
If yes, how to prevent?</p>
| <p>If you use parameters instead of string concatenation to specify your filter-criteria, then it should not be vulnerable for Sql injection.</p>
<p>For instance:</p>
<p>do this:</p>
<pre><code>string sqlQuery = "SELECT * FROM Persons WHERE Persons.Name LIKE @name";
SqlCommand cmd = new SqlCommand ( sqlQuery );
...
cmd.Parameters.Add ("@name", SqlDbType.VarChar).Value = aName + "%";
</code></pre>
<p>instead of this:</p>
<pre><code> string sqlQuery = "SELECT * FROM Persons WHERE Persons.Name LIKE \'" + aName + "%\'";
</code></pre>
<p>The first example is not vulnerable for sql injection, but the 2nd example is very much vulnerable.</p>
<p>The same applies for dynamic SQL that you use in stored procedures for instance.
There, you can create a dynamic sql statement that uses parameters as well; You should then execute the dynamic statement using <code>sp_executesql</code> which enables you to specify parameters.</p>
|
Anybody know any good silverlight tutorials? <p>As the title says :)</p>
<p>I've been waiting for Wrox to release "Professional silverlight 2.0" for ages but it's been delayed by nearly a year and I want to have a Play with silverlight.</p>
<p>Ignoring the silverlight.net site, does anyone know of any good beginners tutorials that focus on coding in Visual Studio instead of Blend?</p>
<p>Jon</p>
| <p>I'm currently running through this <a href="http://weblogs.asp.net/scottgu/pages/silverlight-2-end-to-end-tutorial-building-a-digg-search-client.aspx" rel="nofollow">set of tutorials</a>. Have been quite useful as a very basic primer into the world of Silverlight.</p>
|
Creating an isset if function using php to avoid and update if the input is empty for a MYSQL update <p>Hi I am newish to php and I have created an update page for Content Management System. I have a file upload in this case a picture. I have other inputs that contain text and I can get them to populate my form and thats fine and works great because the user can see what has already been entered. But the file name for the photo can not have a value so if the user doesn't pick the picture from the directory again it will update minus the picture. <strong>What I think I need is a isset function that says if the file (picture) input is left blank don't update this field and use whatever what already in the database for it, that way if it was left blank when created it will still be, and if the user has changed it this time it will change; or if they want to leave it the same it won't leave their picture blank. Hope that makes sence.</strong> </p>
<p>Here is my coding currently for the Form: </p>
<pre><code> <p>
Photo:
</p>
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input type="file" name="photo"/>
</code></pre>
<p>Below is my php code for my update if the update button is pressed:</p>
<pre><code> $con = mysql_connect("localhost","******","********");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*******", $con);
// run this only, once the user has hit the "Update" button
if (isset($_POST['update'])) {
// assign form inputs
$name = $_POST['nameMember'];
$position = $_POST['bandMember'];
$pic = $_POST['photo'];
$about = $_POST['aboutMember'];
$bands = $_POST['otherBands'];
// add member to database
$result = mysql_query("UPDATE dbProfile SET nameMember='".$name."',bandMember='".$position."',photo='".$pic."',aboutMember='".$about."',otherBands='".$bands."' WHERE id='".$id."'");
mysql_close($con);
Header("Location: listMember.php");
exit;
}
else { // read member data from database
$result = mysql_query ("SELECT * FROM dbProfile WHERE id='".$id."'");
while($row = mysql_fetch_array($result))
{
$name = $row['nameMember'];
$position = $row['bandMember'];
$pic = $row['photo'];
$about = $row['aboutMember'];
$bands = $row['otherBands'];
}
}
mysql_close($con);
?>
</code></pre>
<p>If you could help I would be very please and greatful. </p>
| <p>You have to use the <a href="http://docs.php.net/manual/en/reserved.variables.files.php" rel="nofollow"><code>$_FILES</code> variable</a> for uploaded files. For further information, see <a href="http://docs.php.net/manual/en/features.file-upload.php" rel="nofollow">Handling file uploads</a> in the PHP manual.</p>
|
ASP.NET MVC Framework 'REST-like' API <p>I have developed a 'REST-like' XML API that I wish to expose for consumption by third-party web applications. I'm now looking to implement a security model for the exchange of data between a third-party application and the 'REST-like' XML API. I would appreciate suggestions for a suitable asymmetric encryption model.</p>
| <p>If you want encryption why not just use SSL to encrypt the connection rather than encrypting the response data? If 128-bit SSL isn't sufficient, then you'll either need to integrate some existing PKI infrastructure using an external, trusted authority or develop a key distribution/sharing infrastructure yourself and issue your public key and a suitable private key/identifier to your API consumers. Choose one of the cryptography providers in System.Security.Cryptography that supports public/private key exchange.</p>
|
Is there a KDE systray epplet for Enlightment? <p>Enlightenment DR16 is packaged with openSUSE 11.1 but it's a bit painful to use with KDE apps as there's no obvious (on the Enlightenment site, google etc.) way to provide a systray for KDE apps that require one (e.g., ktorrent).</p>
<p>Anyone know of a way around this?</p>
<p>I'm not using e for the eye-candy - I'm running on a 2.6GHz Celeron and KDE (4.1) performance isn't exactly stellar so I'm trying out a few alternatives.</p>
| <p><a href="http://packages.debian.org/unstable/x11/trayer" rel="nofollow">trayer</a> is a standalone system tray. It should work regardless of what environment you're in, including e16.</p>
|
Should I use Perl or Python for network monitoring? <p>I want to have some work done on the Network front, pinging numerous computers on a LAN and retrieving data about the response time. Which would be the most useful and productive to work with: Perl or Python?</p>
| <p>I agree that it is pretty subjective which programming language you use - essentially I would rather get the job done as quickly and efficiently as possible which making it supportable - so that depends on your infrastructure...</p>
<p>Can I suggest that you look at <a href="http://www.nagios.org/">Nagios</a> rather than re-inventing the wheel yourself? </p>
<p>While Nagios might require a greater learning curve in terms of configuration, it will be worth it in the long run, and if you can't find a plugin to suit your requirements, then it is easy to write your own. <a href="http://www.joelonsoftware.com/items/2008/01/22.html">Joel Spolsky</a> has written an interesting article on this.</p>
|
How can I stop cl.exe from terminating when a user logs out? <p>We have an automated build server that produces builds using Visual Studio 2005 and <a href="http://ccnet.thoughtworks.com/" rel="nofollow">CruiseControl.NET</a> (on Windows XP x64). Normally nobody is logged into the system, but occasionally we have to log in via Remote Desktop in order to perform maintenance.</p>
<p>We have noticed that if <code>cl.exe</code> is running (Microsoft's C++ compiler) at the instant we log out from remote desktop, then <code>cl.exe</code> will terminate with error result 4:</p>
<blockquote>
<p>Project : error PRJ0002 : Error result 4 returned from 'C:\Program Files (x86)\Microsoft Visual Studio 8\VC\bin\cl.exe'.</p>
</blockquote>
<p>This obviously causes the current build to fail with a pretty mysterious message. <strong>Does anyone know how to prevent this from happening?</strong></p>
| <p>Did you try to run ccnet service under some other, non-admin, account.</p>
|
" NSRangeException " problem <p>I am trying to build an iPhone app. But at the time of compiling there is a message showing that </p>
<pre><code>[Session started at 2009-01-29 18:25:40 +0600.]
2009-01-29 18:25:44.238 SimpleGame[3691:20b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (1) beyond bounds (0)'
2009-01-29 18:25:44.247 SimpleGame[3691:20b] Stack: ( .........
</code></pre>
<p>Actually when I do active these code then this message is shown, code are:</p>
<pre><code>NSMutableArray *todoArray = [[NSMutableArray alloc] init];
self.todos = todoArray;
[todoArray release];
</code></pre>
<p>How can I overcome this problem?</p>
| <p>It seems like you're trying to access outside the bounds of an empty array.</p>
|
How to use jQuery in Firefox Extension <p>I want to use jQuery inside a firefox extension,
I imported the library in the xul file like this:</p>
<pre><code><script type="application/x-javascript" src="chrome://myExtension/content/jquery.js"> </script>
</code></pre>
<p>but the $() function is not recognized in the xul file neither do the jQuery().</p>
<p>I googled about the problem and found some solutions but no one did work with me:
<a href="http://gluei.com/blog/view/using-jquery-inside-your-firefox-extension">http://gluei.com/blog/view/using-jquery-inside-your-firefox-extension</a>
<a href="http://forums.mozillazine.org/viewtopic.php?f=19&t=989465">http://forums.mozillazine.org/viewtopic.php?f=19&t=989465</a></p>
<p>I've also tried to pass the 'content.document' object(which refrences the 'document' object) as the context parameter to the jQuery function like this:</p>
<pre><code>$('img',content.document);
</code></pre>
<p>but still not working,
does any one came across this problem before?</p>
| <p>I use the following <code>example.xul</code>:</p>
<pre><code><?xml version="1.0"?>
<overlay id="example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<head></head>
<script type="application/x-javascript" src="jquery.js"></script>
<script type="application/x-javascript" src="example.js"></script>
</overlay>
</code></pre>
<p>And here is an <code>example.js</code></p>
<pre><code>(function() {
jQuery.noConflict();
$ = function(selector,context) {
return new jQuery.fn.init(selector,context||example.doc);
};
$.fn = $.prototype = jQuery.fn;
example = new function(){};
example.log = function() {
Firebug.Console.logFormatted(arguments,null,"log");
};
example.run = function(doc,aEvent) {
// Check for website
if (!doc.location.href.match(/^http:\/\/(.*\.)?stackoverflow\.com(\/.*)?$/i))
return;
// Check if already loaded
if (doc.getElementById("plugin-example")) return;
// Setup
this.win = aEvent.target.defaultView.wrappedJSObject;
this.doc = doc;
// Hello World
this.main = main = $('<div id="plugin-example">').appendTo(doc.body).html('Example Loaded!');
main.css({
background:'#FFF',color:'#000',position:'absolute',top:0,left:0,padding:8
});
main.html(main.html() + ' - jQuery <b>' + $.fn.jquery + '</b>');
};
// Bind Plugin
var delay = function(aEvent) {
var doc = aEvent.originalTarget; setTimeout(function() {
example.run(doc,aEvent);
}, 1);
};
var load = function() {
gBrowser.addEventListener("DOMContentLoaded", delay, true);
};
window.addEventListener("pageshow", load, false);
})();
</code></pre>
|
How can I get the CPU core number from within a user-space app (Linux, C)? <p>Presumably there is a library or simple asm blob that can get me the number of the current CPU that I am executing on. </p>
| <p>Use <code>sched_getcpu</code> to determine the CPU on which the calling thread is running. See <code>man getcpu</code> (the system call) and <code>man sched_getcpu</code> (a library wrapper). However, note what it says:</p>
<blockquote>
<p>The information placed in cpu is only guaranteed to be current at the time of the call: unless the CPU affinity has been fixed using sched_setaffinity(2), the kernel might change the CPU at any time. (Normally this does not happen because the scheduler tries to minimize movements between CPUs to keep caches hot, but it is possible.) The caller must be prepared to handle the situation when cpu and node are no longer the current CPU and node.</p>
</blockquote>
|
How do you remove a self-installed DLL? <p>I have a DLL on a server that has somehow been registered as self installed instead of a Component Service it is under Microsoft/COM3/SelfReg/CLSID with the ID and information for this DLL stored there - this component needs to be replaced or removed for updating how do you remove it regsvr32 will not work and there is no visible entry for it other than in the registry. How to Unregister this is all that is required. </p>
| <p>One of the reasons people claim self-registration is evil is that there is no guarantee that rollback will work. If regsvr32 refuses to unregister it and there's nothing in add/remove programs (which there could be if someone manually added the registry entries as part of a component), then deleting the registry entries manually may be the best you can do. Some people who make dlls just make the assumption that once installed, they should never be deleted.</p>
|
Hide authorized menu item in asp.net web.sitemap <p>I have a web.sitemap with security trimming enabled, however I need to hide a menu item based on a role to a page that has no access rules in the web.config.</p>
<p>i.e I have a Campaign page that is used to view existing campaigns as well as to add new campaigns, but I want the "New Campaigns" menu item to be hidden for anonymous users.
I tried adding the role name to the roles attribute in the web.sitemap but this has no effect.</p>
<p>I'm sure there must be a quick way to do this without modifying the sitemap provider which is my next port of call.</p>
| <p>If this is just a special case for anonymous users, you could create a second SiteMap.</p>
<p>Create a new file WebAnon.sitemap.<br />
Create a new sitemap provider in the web.config </p>
<pre><code><add name="anonProvider" type="System.Web.XmlSiteMapProvider" siteMapFile="WebAnon.sitemap" securityTrimmingEnabled="true"/>
</code></pre>
<p>Set the SiteMapDataSource's <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sitemappath.sitemapprovider.aspx" rel="nofollow">SiteMapProvider</a> property to "anonProvider" in the code behind if its an anonymous user.</p>
|
Toolbar with VLC ActiveX in VB.NET <p>I've used the <strong>VideoLAN <a href="http://wiki.videolan.org/ActiveX" rel="nofollow">VLC ActiveX</a> Plugin 2</strong> (available in the <a href="http://www.videolan.org/vlc/download-windows.html" rel="nofollow">VLC 0.9.4 installation</a>) in my VB.NET App.</p>
<p>I've noticed that:</p>
<ul>
<li>The controller toolbar (seek bar, control buttons, volume) do NOT appear at all</li>
<li>Even after playing a file</li>
<li>And the <strong>"Toolbar" property</strong> cannot be set to TRUE, read-only?</li>
</ul>
<p>So my questions are:</p>
<ol>
<li>Is the <strong>"Toolbar" property</strong> a useless thing or is there a special way to get it to TRUE?</li>
<li>Will the <strong>Toolbar appear</strong> at all or would I have to implement it myself?</li>
<li>If I have to make a custom seek slider with control buttons, what are the <strong>API calls</strong> I can use to control media playback and seek-to-frame? VB.NET?</li>
<li>Is there <strong>ANY other way</strong> I can get the VLC player <strong>with its Toolbar</strong> in my App? <a href="http://wiki.videolan.org/Libvlc" rel="nofollow">Libvlc?</a></li>
</ol>
<p><img src="http://wiki.videolan.org/images/Vlc-en.png" alt="alt text" /></p>
<p>^ This is <a href="http://wiki.videolan.org/images/Vlc-en.png" rel="nofollow">the toolbar</a> that I would like to have in my VB.NET App.</p>
| <p>the toolbar is not implemented on Windows VLC ActiveX control</p>
|
Concatenating Lambda Functions in C# <p>Using C# 3.5 I wanted to build up a predicate to send to a where clause piece by piece. I have created a very simple Console Application to illustrate the solution that I arrived at. This works perfectly. Absolutely perfectly. But I have NO idea how or why.</p>
<pre><code> public static Func<Tran, bool> GetPredicate()
{
Func<Tran, bool> predicate = null;
predicate += t => t.Response == "00";
predicate += t => t.Amount < 100;
return predicate;
}
</code></pre>
<p>When I say 'predicate +=', what does that mean? predicate -= appears to do nothing and ^=, &=, *=, /= aren't liked by the compiler.</p>
<p>The compiler doesn't like 'predicate = predicate + t => t.Response....' either.</p>
<p>What have I stumbled on? I know what it does, but how does it do it?</p>
<p>If anyone wants to go delve into more complicated lambda's, please do so.</p>
| <p>"delegate += method" is operator for multicast delegate to combine method to delegate.
In the other hand "delegate -= method" is operator to remove method from delegate.
It is useful for Action.</p>
<pre><code>Action action = Method1;
action += Method2;
action += Method3;
action -= Method2;
action();
</code></pre>
<p>In this case, only Method1 and Method3 will run, Method2 will not run because you remove the method before invoke the delegate.</p>
<p>If you use multicast delegate with Func, the result will be last method.</p>
<pre><code>Func<int> func = () => 1;
func += () => 2;
func += () => 3;
int result = func();
</code></pre>
<p>In this case, the result will be 3, since method "() => 3" is the last method added to delegate. Anyway all method will be called.</p>
<p>In your case, method "t => t.Amount < 100" will be effective.</p>
<p>If you want to combine predicate, I suggest these extension methods.</p>
<pre><code>public static Func<T, bool> AndAlso<T>(
this Func<T, bool> predicate1,
Func<T, bool> predicate2)
{
return arg => predicate1(arg) && predicate2(arg);
}
public static Func<T, bool> OrElse<T>(
this Func<T, bool> predicate1,
Func<T, bool> predicate2)
{
return arg => predicate1(arg) || predicate2(arg);
}
</code></pre>
<p>Usage</p>
<pre><code>public static Func<Tran, bool> GetPredicate() {
Func<Tran, bool> predicate = null;
predicate = t => t.Response == "00";
predicate = predicate.AndAlso(t => t.Amount < 100);
return predicate;
}
</code></pre>
<p>EDIT: correct the name of extension methods as Keith suggest.</p>
|
Risk of using contentEditable in IE <p>We have to add a basic HTML editor to our product. As we only support IE at present (most customers are still on IE 6), I have been told to use the Internet Explorer built-in XHTML editing capabilities â e.g. <code><div contentEditable="true"></code> as explained at "<a href="http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML12/jsdhtml12-02.htm">Editing a Web Page</a>" .</p>
<p><strong>Apart</strong> from not working in other browsers. (The management does not consider it being a problem. Our customers will put up with our software only working with IE. We have never lost any money by our software only working in IE; most customers will only let their staff use IE6 at present anyway)</p>
<p>What <strong>other</strong> problem are we likely to get with contentEditable?</p>
<p><hr /></p>
<p><strong>Update</strong></p>
<p>The HTML editor I wrote with âcontentEditableâ proved to very hard to get reliable, with many <a href="http://stackoverflow.com/questions/527866/why-is-contenteditable-removing-id-from-div">problems</a>. If I had to do this again, I would push <strong>very hard</strong> to one of the many open source solutions (e.g. TinyMCE) or buy in a supported HTML editor. </p>
<p>No doubt that a very skilled jscript programmer can get âcontentEditableâ to work well given enough time. It just that all the examples on the web looks so simple, until you test common operations like doing a cut/paste from word and trying to edit the resulting HTML. (just the sort of things a customer will do)</p>
<p>(Just search for âcontentEditableâ on stackoverflow to get some ideal of the problems other people have had)</p>
| <p>The contentEditable property works in Safari, Firefox 3, and Opera 9. </p>
<p>Since manipulation will undoubtably be through selections, your biggest problem will be getting the selection/ranges working across browsers (<a href="http://stackoverflow.com/questions/361130/get-selected-text-and-selected-nodes-on-a-page/364476#364476">see here)</a>. </p>
<p>There are also numerous <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=454191">little bugs</a> across browsers which may or may not bite you. These include incompatible case-sensitivity, incompatible methods of turning it off again (removeAttribute vs. setting to false).</p>
<p>Despite these flaws, I find it works rather well.</p>
|
How Many Tables Should be Placed on the Same Partition Scheme? <p>My company just provided me with SQL Server 2005 Enterprise Edition and I wanted to partition some tables with large(r) amounts of data. I have about about 5 or 6 tables which would be a good fit to partition by datetime.</p>
<p>There will be some queries that need 2 of these tables in the course of the same query.</p>
<p>I was wondering if I should use the same partition scheme for all of these tables or if I should copy the partition scheme and put different tables on each one.</p>
<p>Thanks for any help in advance.</p>
| <p>You should define your partition by what makes sense for your domain. i.e. if you deal primarily in year quarters, create 5 partitions (4 quarters + 1 overspill). </p>
<p>You should also take into account physical file placement. From the MSDN article:</p>
<blockquote>
<p>The first step in partitioning tables
and indexes is to define the data on
which the partition is keyed. The
partition key must exist as a single
column in the table and must meet
certain criteria. The partition
function defines the data type on
which the key (also known as the
logical separation of data) is based.
The function defines this key but not
the physical placement of the data on
disk. The placement of data is
determined by the partition scheme. In
other words, the scheme maps the data
to one or more filegroups that map the
data to specific file(s) and therefore
disks. The scheme always uses a
function to do this: if the function
defines five partitions, then the
scheme must use five filegroups. The
filegroups do not need to be
different; however, you will get
better performance when you have
multiple disks and, preferably,
multiple CPUs. When the scheme is used
with a table, you will define the
column that is used as an argument for
the partition function.</p>
</blockquote>
<p>These two articles may be useful:</p>
<p><a href="http://www.simple-talk.com/sql/sql-server-2005/partitioned-tables-in-sql-server-2005/" rel="nofollow">Partitioned Tables in SQL Server 2005</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms345146.aspx" rel="nofollow">Partitioned Tables and Indexes in SQL Server 2005</a></p>
|
AJAX/JQUERY/PHP issue <p>I am trying to use an ajax 'POST' call through the jquery $.ajax function to send data to a php file. For some reason the callback is a success but the data is not getting to the php file. Here is an example of the code:</p>
<pre><code>
In JS file:
$.ajax({ type: "POST",
url: "setData.php",
data: "myPOSTvar=myData"
success: function(){ alert("Data Saved"); }
});
In php file:
$var = $_POST['myPOSTvar']
...
</code></pre>
<p>$var ends up with a default value instead of the data it is sent.</p>
<p>Any ideas?</p>
<p>Sorry about the syntax errors...at work right now and don't have my code in front of me...the syntax is all correct in the actual script, just typed to quick when posting here...</p>
| <p>Try this and see if you get any info.</p>
<pre><code>$.post("setData.php", { myPOSTvar: "myData" },
function(data){
alert("Data saved");
});
</code></pre>
|
How can I edit a registry key with VB.NET or VB6? <p>I need to edit a registry key and set the data value to "4"</p>
<p>I know how to do it through the command prompt but am trying to find some Visual Basic code to do it.</p>
<p>If it helps, this is the key:</p>
<blockquote>
<p>HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\USBSTOR\Start</p>
</blockquote>
| <p>Here's how'd you do it in Visual Basic .NET</p>
<pre><code> Dim key As RegistryKey = Registry.LocalMachine
Dim subkey As RegistryKey
subkey = key.OpenSubKey("SYSTEM\CurrentControlSet\Services\USBSTOR", True)
subkey.SetValue("Start", 4)
</code></pre>
<p>You'll need to make sure to add </p>
<pre><code>Imports System
Imports Microsoft.Win32
</code></pre>
<p>at the top of your code.</p>
|
T4 vs CodeDom vs Oslo <p>In an application scaffolding project on which I'm working, I'm trying to decide whether to use <a href="http://msdn.microsoft.com/en-us/oslo/default.aspx">Oslo</a>, <a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/">T4</a> or <a href="http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx">CodeDom</a> for generating code. Our goals are to keep dependencies to a minimum and drive code generation for a domain driven design from user stories. The first step will be to create the tests from the user stories, but we want the domain experts to be able to write their stories in a variety of different media (e.g. custom app, Word, etc.) and still generate the tests from the stories.</p>
<p>What I know so far:</p>
<ol>
<li>CodeDom requires .NET but can only output .NET class files (e.g. .cs, .vb). Level of difficulty is fairly high.</li>
<li>T4 requires CodeDom and VS Standard+. Level of difficulty is fairly reasonable, especially with the <a href="http://www.codeplex.com/t4toolbox">T4 Toolbox</a>.</li>
<li>Oslo is very new. I have no idea of the dependencies, but I imagine you must be on at least .NET 3.5. I'm also not certain as to the code generation abilities or the complexity for adding new grammars. However, domain experts could probably write user stories in Intellipad quite easily. Also not sure about ease of converting stories in Word to an MGrammar.</li>
</ol>
<p>What are your thoughts, experiences, etc. with any of the above tools. We want to stick with Microsoft or open source tools.</p>
| <p>Go with T4 - easy decision. </p>
<ul>
<li>Oslo is too new and the tools are too raw to be anything than an eval-only technology</li>
<li>CodeDOM is powerfull, if you need to generate CLR classes at run-time, and are willing to sacrifice easy modification to your generated output.</li>
<li>T4 (with the T4 toolkit) is a easy to use general purpose code generation tool. Only difficulty I've had so far is in build-time integrations.</li>
</ul>
|
Distributing applications where the configuration settings are encrypted using Entrerprise library <p>I have a thought about this but could not come with a good solution. </p>
<p>I have a windows application. I use enterprise library (3.1) Data Access Application Block. Now I use the DataProtectionConfigurationProvider to encrypt the connection strings.
This application has to be deployed across multiple machines. I don't want the end users to open EntLibConfig.exe and configure the connection strings. How do I go about this?</p>
<p>Thanks,
Ramjee</p>
| <p>You should use the RsaProtectedConfigurationProvider as this allows the exporting of your key container for installation on another machine. This is not supported in the DataProtectionConfigurationProvider .</p>
<p>See this link for more details:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/yxw286t2%28VS.80%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/yxw286t2%28VS.80%29.aspx</a></p>
|
Drag window from a grid <p>I have created a custom window set to windowStyle="none", (no title or maximize - minimize buttons) and i am trying to implement a DragMove operation when the user clicks and drags on a grid. (this is wired up by calling DragMove on a MouseLeftButtonDown Handler) </p>
<p>First weird issue that this event nevers gets fired if the grid has no backround.
Adding some background color does make the event to get fired, but after the first drag i get this error: </p>
<p>"Can only call DragMove when primary mouse button is down"</p>
<p>Code Snipet: </p>
<pre><code>Private Sub Grid1_MouseLeftButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Grid1.MouseLeftButtonDown
DragMove()
End Sub
</code></pre>
<p>I know that this would work fine for a label, but isnt there a way to make it work for a grid? </p>
| <p>OK, I found the answer.. </p>
<p>I used a border to wrap the grid and then caught the Border1_MouseLeftButtonDown event. </p>
<p>I also had to set the borders Background to "Transparent", and now everything works like a charm. </p>
<pre><code>Private Sub Border1_MouseLeftButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Border1.MouseLeftButtonDown
DragMove()
End Sub
</code></pre>
|
Hibernate and IDs <p>Is it possible in hibernate to have an entity where some IDs are assigned and some are generated?</p>
<p>For instance:</p>
<p>Some objects have an ID between 1-10000 that are generated outside of the database; while some entities come in with no ID and need an ID generated by the database.</p>
| <p>I would avoid this and simply have an auxiliary column for the information about the source of the object and a column for the external identifier (assuming the external identifier was an important value you wanted to keep track of).</p>
<p>It's generally a bad idea to use columns for mixed purposes - in this case to infer from the nature of a surrogate key the source of an object.</p>
|
Blocking and waiting for an event <p>It sometimes want to block my thread while waiting for a event to occur.</p>
<p>I usually do it something like this:</p>
<pre><code>private AutoResetEvent _autoResetEvent = new AutoResetEvent(false);
private void OnEvent(object sender, EventArgs e){
_autoResetEvent.Set();
}
// ...
button.Click += OnEvent;
try{
_autoResetEvent.WaitOne();
}
finally{
button.Click -= OnEvent;
}
</code></pre>
<p>However, it seems that this should be something that I could extract to a common class (or perhaps even something that already exists in the framework).</p>
<p>I would like to be able to do something like this:</p>
<pre><code>EventWaiter ew = new EventWaiter(button.Click);
ew.WaitOne();
EventWaiter ew2 = new EventWaiter(form.Closing);
ew2.WaitOne();
</code></pre>
<p>But I can't really find a way to construct such a class (I can't find a good valid way to pass the event as an argument). Can anyone help?</p>
<p>To give an example of why this can be useful, consider something like this:</p>
<pre><code>var status = ShowStatusForm();
status.ShowInsertUsbStick();
bool cancelled = WaitForUsbStickOrCancel();
if(!cancelled){
status.ShowWritingOnUsbStick();
WriteOnUsbStick();
status.AskUserToRemoveUsbStick();
WaitForUsbStickToBeRemoved();
status.ShowFinished();
}else{
status.ShowCancelled();
}
status.WaitUntilUserPressesDone();
</code></pre>
<p>This is much more concise and readable than the equivalent code written with the logic spread out between many methods. But to implement WaitForUsbStickOrCancel(), WaitForUsbStickToBeRemoved and WaitUntilUserPressesDone() (assume that the we get an event when usb sticks are inserted or removed) I need to reimplement "EventWaiter" each time. Of course you have to be careful to never run this on the GUI-thread, but sometimes that is a worthwhile tradeoff for the simpler code.</p>
<p>The alternative would look something like this:</p>
<pre><code>var status = ShowStatusForm();
status.ShowInsertUsbStick();
usbHandler.Inserted += OnInserted;
status.Cancel += OnCancel;
//...
void OnInserted(/*..*/){
usbHandler.Inserted -= OnInserted;
status.ShowWritingOnUsbStick();
MethodInvoker mi = () => WriteOnUsbStick();
mi.BeginInvoke(WritingDone, null);
}
void WritingDone(/*..*/){
/* EndInvoke */
status.AskUserToRemoveUsbStick();
usbHandler.Removed += OnRemoved;
}
void OnRemoved(/*..*/){
usbHandler.Removed -= OnRemoved;
status.ShowFinished();
status.Done += OnDone;
}
/* etc */
</code></pre>
<p>I find that much harder to read. Admittedly, it is far from always that the flow will be so linear, but when it is, I like the first style.</p>
<p>It is comparable to using ShowMessage() and Form.ShowDialog() - they also block until some "event" occurs (though they will run a message-loop if they are called on the gui-thread).</p>
| <p>Don't pass the event, pass a delegate that matches the event handler signature. This actually sounds hacky to me, so be aware of potential dead lock issues.</p>
|
How do I extract all {} tokens from a string using .Net's RegEx? <p>I need to extract tokens that are marked with curly brackets from a given string.</p>
<p>I have tried using Expresso to construct something that will parse...</p>
<pre><code>-------------------------------------------------------------
"{Token1}asdasasd{Token2}asd asdacscadase dfb db {Token3}"
-------------------------------------------------------------
</code></pre>
<p>and produce "Token1", "Token2", "Token3"</p>
<p>I tried using..</p>
<pre><code>-------------------------------------------------------------
({.+})
-------------------------------------------------------------
</code></pre>
<p>...but that seemed to match the entire expression.</p>
<p>Any thoughts?</p>
| <p>Try</p>
<pre><code>\{(.*?)\}
</code></pre>
<pre>
The \{ will escape the "{" (which has meaning in a RegEx).
The \} likewise escapes the closing } backet.
The .*? will take minimal data, instead of just .*
which is "greedy" and takes everything it can.
</pre>
<pre>
If you have assurance that your tokens will (or need to)
be of a specific format, you can replace .* with an appropriate
character class. For example, in the likely case you
want only words, you can use (\w*) in place of the (.*?)
This has the advantage that closing } characters are not
part of the class being matched in the inner expression,
so you don't need the ? modifier).
</pre>
|
Least used delimiter character in normal text < ASCII 128 <p>For coding reasons which would horrify you (I'm too embarrassed to say), I need to store a number of text items in a single string.</p>
<p>I will delimit them using a character.</p>
<p>Which character is best to use for this, i.e. which character is the least likely to appear in text? Must be printable and probably less than 128 in ASCII to avoid locale issues.</p>
| <p>Assuming for some embarrassing reason you can't use CSV I'd say go with the data. Take some sample data, and do a simple character count for each value 0-127. Choose one of the ones which doesn't occur. If there is too much choice get a bigger data set. It won't take much time to write, and you'll get the answer best for you.</p>
<p>The answer will be different for different problem domains, so | (pipe) is common in shell scripts, ^ is common in math formulae, and the same is probably true for most other characters. </p>
<p>I personally think I'd go for | (pipe) if given a choice but going with real data is safest. </p>
<p>And whatever you do, make sure you've worked out an escaping scheme!</p>
|
How to display an image in flex with Content-Type: image/jpeg? <p>I have an .aspx page that generates thumbnails. It takes an ID and returns an image with response Content-Type: image/jpeg.</p>
<p>How do I display this image in Flex? </p>
| <p>I believe this should work:</p>
<pre>
<code>
<mx:Image source="http://localhost/webform.aspx?ID=1"/>
</code>
</pre>
<p>You can obviously set the source in ActionScript or make the URL a bindable string so that you can pass in the ID.</p>
|
Audio file tagging (read/write) library? <p>TagLib seems like a good choice, but I don't use C++ and bindings for other languages are limited. Currently I use the ATL library, but it hasn't been maintained since 2005 and I'm having a hard time doing this myself. So I'm looking for another open source alternative that is actively developed. Do you know of one?</p>
| <p>Do you mean id3 tags? The Jedi project has components to do that:
<a href="http://sourceforge.net/project/showfiles.php?group_id=45786" rel="nofollow">http://sourceforge.net/project/showfiles.php?group_id=45786</a>
Look for JvID3v1 and JvID3v2.</p>
|
SQL Server 2008 Backup Compression Standard Edition <p>I'm trying to backup a database in SQL Server 2008 and have the database compressed using the new compression feature. However, when I run the following code, I get a weird error message:</p>
<pre><code>Backup Database <Database> To Disk 'C:\Backup' With Compression
</code></pre>
<p>I get this error message:</p>
<blockquote>
<p>Backup Database With Compression is not supported on Standard Edition</p>
</blockquote>
<p>Does this mean I have to upgrade to the full version or is there a way to enable compression in standard edition?</p>
| <p>Backup Compression is not supported on SQL 2008 Express, Workgroup, or Standard editions, only on Enterprise. There is no way to turn this on without upgrading your version to Enterprise.</p>
<p>Although you can't backup with compression on those versions, you can RESTORE from compressed backups.</p>
<p>See <a href="http://technet.microsoft.com/en-us/library/bb964719.aspx">http://technet.microsoft.com/en-us/library/bb964719.aspx</a> for more info.</p>
|
How to execute COM+ libraries from Java using a free method <p>I have a COM+ component developed with VB6.</p>
<p>After registering it with the component services manager COM+ application, I can use it from ASP like this</p>
<pre><code>Set Comando = Server.CreateObject("JuiciosComando.clsComando")
ComandoExecute = Comando.execute(Xml)
Set Comando = Nothing
</code></pre>
<p>That's all I need, the component just receives a (maybe a huge) string and returns another (also possibly huge) string...</p>
<p>Is there some way to access this very same component from Java?</p>
<p>What I've found so far is <a href="http://j-integra.intrinsyc.com/support/com/doc/servlet_com/ServletToComPlusExample.html" rel="nofollow">J-Integra</a> but it's a commercial product.</p>
<p>I've also found <a href="http://www.codeguru.com/forum/archive/index.php/t-383429.html" rel="nofollow">this thread on codeguru.com</a> but my C++.NET knowledge is rather poor, besides I would rather just find a free, pure Java solution.</p>
| <p>As Eddie mentioned, you have two main methods of using COM via java: using C++ and writing a JNI wrapper or using a third party JAR to wrap the COM object.</p>
<p>I've attempted to use C++ to wrap a COM object in the past - it's not for the faint hearted - it is not easy to do and its very easy to leak resources.</p>
<p>I've also used two third party JAR's: ComfyJ and JACOB.</p>
<p>ComfyJ was really easy to use and also included a codegen utility to generate java wrapper classes for your COM classes.</p>
<p>It can be downloaded and trialed via <a href="http://www.teamdev.com/comfyj/index.jsf" rel="nofollow">http://www.teamdev.com/comfyj/index.jsf</a></p>
<p>(I am not affiliated with TeamDev in any way!)</p>
<p>If you are desperate for a totally free solution, you could also try JACOB (<a href="http://sourceforge.net/projects/jacob-project/" rel="nofollow">http://sourceforge.net/projects/jacob-project/</a>). </p>
<p>I had issues with documentation, but it was relatively stable.</p>
|
Making your javascript maintainable <p>I am in the process of converting an internal application to use more Ajax via jQuery. I am moving away from the standard code behind of the current ASP.NET application and incorporating JavaScript methods that are going to run client side. My concern is what is the best method for allowing this application to stay maintainable for those who come behind me. </p>
| <p>I've found that build scripts are the key to success in maintainable Javascript. Essentially in order to have something fast and concise on the final page you need a script to make that maintainable in development.</p>
<p>If you use a build process you can break your JS into files based on the functionality. You can use the debug versions of libraries during development, and leave glorious code comments smattered around your code with impunity.</p>
<p>A build script should:</p>
<ul>
<li><a href="http://www.jslint.com">Lint</a> all your code</li>
<li>Strip comments</li>
<li>Concatenate the files together</li>
<li><a href="http://javascript.crockford.com/jsmin.html">Minify</a>/Obfuscate/Compress the code</li>
<li>Version files for deployment</li>
<li>Push the version files to the server ready to be "turned on" in production</li>
</ul>
<p>This leaves you to work on files that make logical sense and it to tidy up after you for production.</p>
|
What are the security implications of not closing connection to the database after you are done with it? <p>What security issues can arise from not closing the database connection after using it? Doesn't PHP automatically close it once a new page loads?</p>
| <p>As the <a href="http://uk.php.net/mysql_close"><code>mysql_close()</code></a> documentation says:</p>
<blockquote>
<p>Using mysql_close() isn't usually
necessary, as non-persistent open
links are automatically closed at the
end of the script's execution. See
also freeing resources.</p>
</blockquote>
<p>Since the connections are managed by PHP there shouldn't be a security risk.</p>
|
How to display a windows/X window system window in 3d space on texture? <p>I'm wondering, how can I catch a window and display it on texture in 3D space. And how can I redirect mouse and keyboard input from 3D application to application running in background? I mean full 3D desktop.</p>
| <p>This can be a bit complex, and a "full" answer might not be suitable for this forum. Here's an idea/outline, though:</p>
<p>One way of doing it is through <a href="http://www.realvnc.com/" rel="nofollow">VNC</a>. Run a separate, invisible "virtual" desktop in a VNC server, then start the desired apps with it as the display. Your 3D rendering program on the "real" desktop can then connect to the VNC server, and get access to its desktop in bitmap format, and blast that onto textured polygons. Piping in input events is very doable, too.</p>
<p>I've actually done this, or at least half of it (the display). Here is a very old screenshot of what I managed to do, back then:
<img src="http://verse.sourceforge.net/shots/vnc-screen.png" alt="alt text" />
The black sky and blue/purple-ish "ground" are rendered by the 3D program on the real desktop, while the slanted quad shows a window in the "virtual" VNC desktop.</p>
<p>Fun!</p>
|
Which .NET data structure should I use? <p>Here is the structure of the data my object will need to expose (the data is NOT really stored in XML, it was just the easiest way to illustrate the layout):</p>
<pre><code><Department id="Accounting">
<Employee id="1234">Joe Jones</Employee>
<Employee id="5678">Steve Smith</Employee>
</Department>
<Department id="Marketing">
<Employee id="3223">Kate Connors</Employee>
<Employee id="3218">Noble Washington</Employee>
<Employee id="3233">James Thomas</Employee>
</Department>
</code></pre>
<p>When I de-serialize the data, how should I expose it in terms of properties on my object? If it were just Department and EmployeeID, I think I'd use a dictionary. But I also need to associate the EmployeeName, too.</p>
| <pre><code>Class Department
Public Id As Integer
Public Employees As List(Of Employee)
End Class
Class Employee
Public Id As Integer
Public Name As String
End Class
</code></pre>
<p>Something like that (can't remember my VB syntax). Be sure to use Properties versus Public members...</p>
|
Interacting With Java Applet <p>Does anyone know if it is possible to interact with a java applet via .net?</p>
<p>Edit: I was able to use the UI Automation framework to locate the java applet, and from there use OCR to read data and simulate mouse/keyboard input into the applet.</p>
| <p>You may well be able to do it using accessibility APIs, which are designed to let screen-readers and so on interact with programs. Have a look at:</p>
<p><a href="http://en.wikipedia.org/wiki/Microsoft_UI_Automation" rel="nofollow">http://en.wikipedia.org/wiki/Microsoft_UI_Automation</a></p>
|
jQuery and closure <p>I have a multiple menu's on my page which all use the same mouseover and click events, so I decided to get it into a function. However vars seem to always be assigned to the last of the arguments for the hover(function, function) function.</p>
<pre><code>$(document).ready( function() {
menuMouseOver = function() {
for(i=0, u=arguments.length; i<u; i++){
var parent = arguments[i].parent;
var active = arguments[i].active;
var childSelect = arguments[i].childSelect;
console.log(active); //logs the correct active
$(parent).children(childSelect)
.not('.'+active).each( function(i, e) {console.log(active);})
//The above console.log logs the correct active
.hover( function() {
console.log(active); //this one always logs menu2_active
$(this).addClass(active);
}, function() {
$(this).removeClass(active);
});
}
}
menuMouseOver( { parent: '#menu1',
active: 'menu1_active',
childSelect: ':gt(0)'},
{ parent: '#menu2',
active: 'menu2_active',
childSelect: ':gt(0)'});
});
</code></pre>
<p>Why is is that the last console.log will always logs the last <em>active</em> instead of the one that belongs to arguments[i].active. (In this example it always logs the <em>active</em> of arguments[1].active)
What am I doing wrong? </p>
<p>Also, the real function is more complex, but the problem is also present in this variant.</p>
| <p>JavaScript doesn't have block scope, so those variables you declare in the for loop have their values changed each iteration and all those functions reference the same variables. The trick is to create a new function scope within the for loop so that the variables you declare are bound during that iteration.</p>
<p>You can accomplish this by executing an anonymous function inside the loop:</p>
<pre><code>menuMouseOver = function() {
for(i=0, u=arguments.length; i<u; i++){
(function(){ // anonymous function to create new scope
var parent = arguments[i].parent;
var active = arguments[i].active;
var childSelect = arguments[i].childSelect;
console.log(active); //logs the correct active
$(parent).children(childSelect)
.not('.'+active).each( function(i, e) {console.log(active);})
//The above console.log logs the correct active
.hover( function() {
console.log(active); //this one always logs menu2_active
$(this).addClass(active);
}, function() {
$(this).removeClass(active);
});
})(); // execute the anonymous function
}
}
</code></pre>
<p>The way you had it before, all of you functions closed over the same variable references, and so used what ever the last value was, not the value of when the function was created. Using the function scope will have it behave as you intended.</p>
|
How can I get the values of the parameters of a calling method? <h2>Question</h2>
<p>I'm writing some code that needs to be able to get the <strong>values</strong> of the parameters from the method that called into the class. I know how to get all the way to the ParameterInfo[] array, but I don't know how to then get the values. Is this even possible?</p>
<p>If it is, I think it has something to do with using the MethodBody property from the MethodInfo object, which allows you to inspect the IL stream, including properties, but I don't know how to do it, and I haven't found applicable code on Google.</p>
<h2>Code</h2>
<pre><code>// Finds calling method from class that called into this one
public class SomeClass
{
public static void FindMethod()
{
for (int i = 1; i < frameCount; i++)
{
var frame = new StackFrame(i);
var methodInfo = frame.GetMethod();
if (methodInfo.DeclaringType != this.GetType())
{
string methodName = frame.GetMethod().Name;
var paramInfos = methodInfo.GetParameters();
// Now what?? How do I get the values from the paramInfos
break;
}
else if (i == frameCount - 1)
{
throw new TransportException("Couldn't find method name");
}
}
}
}
</code></pre>
| <p>You cannot do it without introspecting the stack yourself (and this is fragile since many optimizations may mean the stack frame is not what you expect, or even that the parameter passed is not in fact what the method signature would suggest (it is perfectly possible for an optimizing JIT compiler to spot that you are only using a sub field of an object/struct and pass that instead).</p>
<p>The ParameterInfo simply tells you the <em>signature</em> of the method as compiled, not the values that were passed.</p>
<p>The only realistic way to achieve this automatically is via code injection (via something like AOP) to create the data and do what you want with it based on analysing the IL.</p>
<p>This is generally not a good idea, if you need to debug something use a debugger, if you need to log something be explicit about what you are logging. </p>
<p>To be clear simple reflective techniques <strong>cannot</strong> achieve what you desire with full generality</p>
|
How to split a string while preserving line endings? <p>I have a block of text and I want to get its lines <strong>without</strong> losing the \r and \n at the end. Right now, I have the following (suboptimal code):</p>
<pre><code>string[] lines = tbIn.Text.Split('\n')
.Select(t => t.Replace("\r", "\r\n")).ToArray();
</code></pre>
<p>So I'm wondering - is there a better way to do it?</p>
<p><strong>Accepted answer</strong></p>
<pre><code>string[] lines = Regex.Split(tbIn.Text, @"(?<=\r\n)(?!$)");
</code></pre>
| <p>The following seems to do the job:</p>
<pre><code>string[] lines = Regex.Split(tbIn.Text, @"(?<=\r\n)(?!$)");
</code></pre>
<p>(?<=\r\n) uses 'positive lookbehind' to match after \r\n without consuming it.</p>
<p>(?!$) uses negative lookahead to prevent matching at the end of the input and so avoids a final line that is just an empty string.</p>
|
jquery $.ajax function call is slow first time <p>I am using $.ajax to update some values in the database. when the page makes the ajax call for the first time, it is slow. it is taking like 5 or 6 seconds to return the result. after the first request, it is fast. I am not sure if there is a way to make the first call also fast. if you have any ideas, please let me know.</p>
<p>Thanks,
sridhar</p>
| <p>My suspicion would be that the database is doing some caching and subsequent requests are filled from the cache. If this were only happening on the first request of the data, regardless of the data involved, then I would suspect that the web service that you're connecting to needs to be loaded into memory on the first operation.</p>
|
jQuery vs MicrosoftAjax in ASP.NET MVC <p>Under what circumstances would you use MicrosoftAjax over jQuery in an ASP.NET MVC application?</p>
<p>According to Scott Cate in this podcast <a href="http://www.hanselminutes.com/default.aspx?showID=146">Object Oriented AJAX with Scott Cate</a> MicrosoftAjax is good for sending and retrieving data to and from the server. And jQuery is good for manipulating your data via the DOM once it arrives at the client. Yet, with a simple form plugin for jQuery you can send and retrieve data with jQuery quite easily. Often with a single line of code.</p>
<p>So I'm wondering what the difference is between MicrosoftAjax and jQuery within ASP.NET MVC?</p>
| <p>Go with jQuery - even Microsoft has seen the error of their ways. The next version of Visual Studio will include jQuery and support it with intellisense. You're also entirely correct regarding the simple plugin. MS Ajax, while sometimes easier to work with initially, is slow and bloated. </p>
|
python: restarting a loop <p>i have:</p>
<pre><code>for i in range(2,n):
if(something):
do something
else:
do something else
i = 2 **restart the loop
</code></pre>
<p>But that doesn't seem to work. Is there a way to restart that loop? </p>
<p>Thanks</p>
| <p>You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.</p>
<p>perhaps a:</p>
<pre><code>i=2
while i < n:
if something:
do something
i += 1
else:
do something else
i = 2 #restart the loop
</code></pre>
|
SQL Server: Server-side blob cursor? <p>i'd like to read binary data from a blob, using the Stream interface around it.</p>
<p>But i don't want the blob to have to be loaded entirely client side and stored in memory, or in a file. </p>
<p>i want the code that uses the blob to be able to seek and read, and only as much data that is needed to support seek/read is brought over the wire.</p>
<p>i.e. <strong><em>Pretend</em></strong> the blob is a 250MB Photoshop image. The thumbnailer code knows how to read the first 8 bytes of an image, recognize it's a PSD file, seek to the offset that will contain the 3k thumbnail, and read that.</p>
<p>So rather than trying to allocate 250MB of memory, or having to create a temporary file, and having to wait for 250MB to be brought over the wire: the hypothetical SQLServerBlobStreamServerCursor class knows how to data traffic to what which is actually asked for.</p>
<p><hr /></p>
<h2>Research</h2>
<p><a href="http://support.microsoft.com/kb/317034" rel="nofollow">HOW TO: Read and Write a File to and from a BLOB Column by Using Chunking in ADO.NET and Visual Basic .NET</a>
Which talks about being able to read, and write, in chunks. But the code is unreadable being cut off like that i can't stand it. i'll look at it later.</p>
<p>Also <a href="http://stackoverflow.com/questions/252517/streaming-directly-to-a-database/252526#252526">this guy</a> mentioned a new SQL Server 2005 [<em>column</em>.Write()]3 T-SQL syntax to write data - <a href="http://weblogs.asp.net/alessandro/archive/2008/09/22/conserving-resources-when-writing-blob-values-to-sql-server-and-streaming-blob-values-back-to-the-client.aspx" rel="nofollow">could be used to write data in small chunks</a> (to avoid consuming all your server's memory). Maybe there's a [<em>column</em>].<strong>Read</strong>() pseudo-method</p>
<p>Microsoft has an article: <a href="http://msdn.microsoft.com/en-us/library/3517w44b(VS.80).aspx" rel="nofollow">Conserving Resources When Writing BLOB Values to SQL Server</a> </p>
| <p>With newer versions of SQL Server you can just use plain SQL with the SUBSTRING() function on binary data types as well as text.
See <a href="http://msdn.microsoft.com/en-us/library/ms187748.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms187748.aspx</a></p>
<p>To get the size of the image:</p>
<pre><code>select datalength(blobcolumn) from myimages where imgid = 12345;
</code></pre>
<p>To read the first 8 bytes:</p>
<pre><code>select substring(blobcolumn, 1, 8) from myimages where imgid = 12345;
</code></pre>
<p>To read 877 bytes, offset 115000 through 115876:</p>
<pre><code>select substring(blobcolumn, 115001, 877) from myimages where imgid = 12345;
</code></pre>
<p>Remember that the substring function is based on a 1-offset, not 0.</p>
<p>If you care about the column potentially changing between reading parts of it, you can put all the different selects within a transaction.</p>
<p>This is untested by me, but older versions of MS SQL Server apparently require the use of the (now deprecated) READTEXT verb and TEXTPTR() function. Such as:</p>
<pre><code>select textptr(blobcolumn) from myimages where imgid = 12345;
</code></pre>
<p>grab the returned pointer value, say PTR, and use it in the subsequent queries:</p>
<pre><code>readtext blobcolumn @PTR 115001 887
</code></pre>
|
How to PRINT a message from SQL CLR function? <p>Is there an equivalent of</p>
<pre><code>PRINT 'hello world'
</code></pre>
<p>which can be called from CLR (C#) code?</p>
<p>I'm trying to output some debug information in my function. I can't run the VS debugger because this is a remote server.</p>
<p>Thanks!</p>
| <p>Serguei,</p>
<p>The answer is that you cannot do the equivalent of</p>
<p><code>PRINT 'Hello World'</code></p>
<p>from inside a <code>[SqlFunction()]</code>. You can do it however from a <code>[SqlProcedure()]</code> using</p>
<p><code>SqlContext.Pipe.Send("hello world")</code></p>
<p>This is consistent with T-SQL, where you would get the error "Invalid use of a side-effecting operator 'PRINT' within a function" if you stick a PRINT inside a function. But not if you do it from a stored procedure.</p>
<p>For workarounds i suggest:</p>
<ol>
<li>Use <strong>Debug.Print</strong> from your code, and attach a debugger to the SQL Server (I know this doesnt work for you as you explained). </li>
<li>Save the messages in a global variable, for instance <code>List<string> messages</code>, and write another table-valued function that returns the contents of <code>messages</code>. Of course, the access to <code>messages</code> needs to be synchronized because several threads might try to access it at the same time.</li>
<li>Move your code to a <code>[SqlProcedure()]</code></li>
<li>Add a parameter 'debug' that when =1 the function will return the messages as part of the returned table (assuming there is a column with text..)</li>
</ol>
|
How do I configure Subversion 1.5 support in Xcode? <p>According to the release notes for the iPhone 2.2.1, SDK Xcode now officially supports Subversion 1.5. I've converted my working copy to use the new 1.5 format; however, Xcode now will no longer track changes. I'm guessing there is somewhere in Xcode that I have to tell it to use the 1.5 format. Has anyone found it yet?</p>
| <p>Google is your friend:</p>
<p><a href="http://www.lemonteam.com/blog/2008/12/setting-up-subversion-15-on-xcode/" rel="nofollow">http://www.lemonteam.com/blog/2008/12/setting-up-subversion-15-on-xcode/</a></p>
<p>Please note the errors and caveats in the comments before you go blindly running the code in the tutorial. I have not tried it myself, so this is not a recommendation; merely the best search result I found. Like Brock Woolf I use Versions and the command line, and am quite happy with that workflow.</p>
|
Regex to strip lat/long from a string <p>Anyone have a regex to strip lat/long from a string? such as:</p>
<p>ID: 39.825 -86.88333</p>
| <p>To match one value</p>
<pre><code>-?\d+\.\d+
</code></pre>
<p>For both values:</p>
<pre><code>(-?\d+\.\d+)\ (-?\d+\.\d+)
</code></pre>
<p>And if the string always has this form:</p>
<pre><code>"ID: 39.825 -86.88333".match(/^ID:\ (-?\d+\.\d+)\ (-?\d+\.\d+)$/)
</code></pre>
|
Domain Model - Identifier Relationships vs. Hierarchal Objects <p>While fleshing out a hypothetical domain model, I have found myself wondering whether the better approach in relating domain objects would be to have a parent domain object contain a pointer (the identifier of the child) or if it would be a better approach to use the child objects to build a composite within the parent object.</p>
<p>I can see the pros and cons of each approach, mostly a trade off of size versus complexity, being what it boils down to. I would tend to lean more towards a identifier relationship approach, as I am not anticipating the need for doing any sort of lazy loading.</p>
<p>Although not directly related, the domain objects are simple POCOs (.NET-equivalent of POJOs). They are explicitly marked as serializable, as there is a good chance that they will eventually cross between application domains. LINQ makes the relational identifier approach viable, in my opinion, and I would not consider it at all if LINQ were not available.</p>
<p>Any thoughts would be appreciated!</p>
<p><strong>Edit: A couple of more thoughts that might have me lean towards an identifier-only approach. First would be that the caching policy of the objects. It is entirely possible that a parent and child object have different TTLs, as defined by their policies. The second would be that the reference holding might limit object reuse, in that the same child might be held by multiple parents - in the case of reusable data. Both of these also relate to the overall size of the serialized objects, as well.</strong></p>
| <p>I use both on my POCOs. I generate them with a list of children on the parent class and one parent instance on the child class.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.