input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Implementing sort/page feature when using POCOs with ASP.net Data Controls <p>I am not a big fan of datasets so I use POCO to return data. I have achieved paging and sorting using custom methods that I create for a POCO type that work on page size and give me a set of the complete POCO collection at a time, I use methods that check for name of the DataItem clicked and sort order to do that sort. Creating such methods over and over for every POCO that you plan to use with an ASP.net data control like Gridview is pretty painful.</p>
<p>Is there a technique to automate this so that I do not need to make such methods every time for a new POCO so that it works as if you were using a DataTable? I can provide some more explanation if required.</p>
<p>NOTE: Some people may call POCO as DTOs .</p>
<p>EDIT : I found this <a href="http://geekswithblogs.net/czumbano/archive/2006/03/27/73532.aspx" rel="nofollow">article</a> on this topic. Is this the only possible way to get to what i am trying to do??</p>
| <p>I agree with the base class idea as this will save all the duplicate code. One thing I did that takes a step in this direction is to create a class to handle the sorting of any generic list (for DTO/POCO). This allowed me to sort a list in my presenter or code-behind with only 1 line of code.</p>
<p>Typically for SortExpression I return the property name of the DTO you want to sort on. In addition, the SortDirection would be a simple "Ascending" Or "Decending"</p>
<pre><code>List<Supplier> SupplierList = mSupplierService.GetSuppliers();
SupplierList.Sort(new GenericComparer<Supplier>(mView.SortExpression, mView.SortDirection));
mView.Suppliers = SupplierList;
</code></pre>
<p>Here is the class I used</p>
<pre><code>public class GenericComparer<T> : IComparer<T>
{
private string mDirection;
private string mExpression;
public GenericComparer(string Expression, string Direction)
{
mExpression = Expression;
mDirection = Direction;
}
public int Compare(T x, T y)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(mExpression);
IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
if (mDirection == "Ascending") {
return obj1.CompareTo(obj2);
}
else {
return obj2.CompareTo(obj1);
}
}
}
</code></pre>
|
Capture characters from standard input without waiting for enter to be pressed <p>I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).</p>
<p>Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.</p>
| <p>That's not possible portably in pure C++, because it depends too much on the terminal used that may be connected with stdin (they are usually line buffered). You can, however use a library for that:</p>
<ol>
<li>conio available with windows compilers. Use the function <code>_getch()</code> to give you a character without waiting for the enter key. I'm not a frequent windows developer, but i've seen my classmates just include <code>conio.h</code> and use it. See <a href="http://en.wikipedia.org/wiki/Conio.h">conio.h</a> at wikipedia. It lists <code>getch</code>, which is declared deprecated in Visual C++. </li>
<li>curses available for linux, compatible curses implementations are available for windows too. It has also a <code>getch</code> function. (try <code>man getch</code> to view its manpage). See <a href="http://en.wikipedia.org/wiki/Curses_%28programming_library%29">Curses</a> at wikipedia. </li>
</ol>
<p>I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (i believe that's called "raw mode", as opposed to "cooked mode" (look into <code>man stty</code>)). Curses would handle that for you in a portable manner if i'm not mistaken. </p>
|
Do you keep your build tools in version control? <p>Do you keep tools that are necessary to build your project under version control?</p>
<p>If you do, what are your guidelines for which tools to include? I guess noone puts Visual Studio in version control, but how about your unit-test-runner? The Nant/Ant/Maven executable?</p>
<p>How about external dependencies? Do you have Boost in version control? The JDK? NUnit/JUnit? Where do you draw the limit here?</p>
<p>(See also <a href="http://stackoverflow.com/questions/191533/svn-and-binaries">this question</a>).</p>
<p><strong>EDIT:</strong>
I guess my question was not completely clear: I did not want to know whether you kept them in version control vs. or some shared drive. I really wanted to know whether you checked the tools necessary for building a project into version control <em>together</em> with the project, so that when you checked the project out, you would automatically get the tools.</p>
<p>As a general follow-up to those who answer no: what is your process for keeping track of those tools? Do your script download them?</p>
| <p>Yes, I keep EVERYTHING that is part of the process of delivering a software production in version control.</p>
|
What Are the Pros and Cons of Filemaker? <p>A potential customer has asked me to look at some promotional flyers for a couple of apps which fall into the contact management / scheduler category. Both use Filemaker as their backend. It looks like these two apps are sold as web apps. At any rate I had not heard of Filemaker in about ten years, so it was surprising to see it pop up twice in the same sitting. I think it started out as a Mac platform db system.</p>
<p>I am more partial to SQL Server, MY SQL, etc, but before make any comments on Filemaker, I'd like to know some of the pros and cons of the system. It must be more than Access for Mac's, but I have never run across it as a player in the client / server or web app arena.</p>
<p>Many thanks
Mike Thomas</p>
| <p>Pros:</p>
<ul>
<li>It's cheap</li>
</ul>
<p>Cons:</p>
<ul>
<li>It's cheap(ly made) </li>
<li>It's non-standard (easy to find
MySQL/Oracle/MSSQL/Access experts
but nobody knows Filemaker)</li>
</ul>
<p>Using subpar and/or nonstandard technologies only creates <a href="http://onstartups.com/tabid/3339/bid/165/Development-Short-Cuts-Are-Not-Free-Understanding-Technology-Debt.aspx">technology debt</a>. I've never found a respectable dev that actually enjoyed (or wanted to) using this niche product.</p>
<p>In my opinion this product exists because it is Access for Macs, and it gained enough of a userbase and existing applications that enough people bought each upgrade to keep it in business. There are many products on the market that still exist because it's users are locked in, not because it's a good choice.</p>
|
ASP.NET Datagrid - hiding a specific row/column <p>I am using a Datagrid with several columns of data (call it myDG) and one of these columns is a DateTime bound to a datasource. Its value is dependent on a "job" object completing a job and assigning the date time value. Since this normally takes up to a minute the value is left unassigned at the beginning.</p>
<p>The column's asp.net definition is:</p>
<pre><code><asp:boundcolumn
DataField="CompletedDate"
HeaderText="Date Completed"
DataFormatString="{0:dd-MMM-yyyy <br> hh:mm:ss tt}" />
</code></pre>
<p>So the functionality works fine when the "job" has completed and it sets the time. But before that, while the row is being displayed, it shows as</p>
<p>01-Jan-0001
12:00:00 AM</p>
<p>I am wanting to hide this and determined that the best way would be to mask that particular row and column with a blank, or override the value temporarily. I am having problems doing this and finding a way to access that specific row and column.</p>
<p>It is the [3] column of the datagrid and always in the first row (since new rows are added at the top).</p>
<p>Is there a way to directly access this cell and temporarily 'hide' its contents, or mask them? Ideally it would be great if there was a way to blank out all rows that had a value equal to this in their column, but a way to manipulate the specific cell would work as well.</p>
<p>-thanks in advance!</p>
| <p>I would probably hook OnItemDataBound, check the value, and replace/reformat if required.</p>
|
In C# check that filename is *possibly* valid (not that it exists) <p>Is there a method in the System.IO namespace that checks the validity of a filename?</p>
<p>For example, <code>C:\foo\bar</code> would validate and <code>:"~-*</code> would not</p>
<p>Or a little trickier, <code>X:\foo\bar</code> would validate is there is an <code>X:</code> drive on the system, but wouldn't otherwise.</p>
<p>I suppose I could write such a method myself, but I'm more interested in a built-in one.</p>
| <p>Just do</p>
<pre><code>System.IO.FileInfo fi = null;
try
{
fi = new System.IO.FileInfo(fileName);
}
catch (ArgumentException) { }
catch (System.IO.PathTooLongException) { }
catch (NotSupportedException) { }
if (ReferenceEquals(fi, null))
{
...
// file name is not valid
}
else
{
...
// file name is valid... May check for existence by calling fi.Exists.
}
</code></pre>
<p>For creating a <code>FileInfo</code> instance the file does not need to exist.</p>
|
How to access the user profile in a Django template? <p>I'm storing some additional per-user information using the <a href="http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users"><code>AUTH_PROFILE_MODULE</code></a>.</p>
<p>We can access the user in a Django template using <code>{{ request.user }}</code> but how do we access fields in the profile since the profile is only accessible via a function <code>user.get_profile()</code> ?</p>
<p>Is it really required to explicitly pass the profile into the template every time?</p>
| <p>Use <code>{{ request.user.get_profile.whatever }}</code>. Django's templating language automatically calls things that are callable - in this case, the <code>.get_profile()</code> method.</p>
|
How can I include a CDATA section in a ConfigurationElement? <p>I'm using the .NET Fx 3.5 and have written my own configuration classes which inherit from ConfigurationSection/ConfigurationElement. Currently I end up with something that looks like this in my configuration file:</p>
<pre><code><blah.mail>
<templates>
<add name="TemplateNbr1" subject="..." body="Hi!\r\nThis is a test.\r\n.">
<from address="blah@hotmail.com" />
</add>
</templates>
</blah.mail>
</code></pre>
<p>I would like to be able to express the body as a child node of <code>template</code> (which is the <code>add</code> node in the example above) to end up with something that looks like:</p>
<pre><code><blah.mail>
<templates>
<add name="TemplateNbr1" subject="...">
<from address="blah@hotmail.com" />
<body><![CDATA[Hi!
This is a test.
]]></body>
</add>
</templates>
</blah.mail>
</code></pre>
| <p>In your custom configuration element class you need to override method <code>OnDeserializeUnrecognizedElement</code>. </p>
<p>Example:</p>
<pre><code>public class PluginConfigurationElement : ConfigurationElement
{
public NameValueCollection CustomProperies { get; set; }
public PluginConfigurationElement()
{
this.CustomProperties = new NameValueCollection();
}
protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)
{
this.CustomProperties.Add(elementName, reader.ReadString());
return true;
}
}
</code></pre>
<p>I had to solve the same issue. </p>
|
Php Framework or template engine or something else? <p>I have a relatively simple application up and working with some basic functionality which i have built as a bit of a project. I would like to now build on that, and add some more complex features, including login.</p>
<p>The code has got quite complex, and it's written in plain php, so all the presentation code is mixed in with the logic. I have decided that before I go any further I'd like to re factor it to separate this out, so it's easier to maintain and add to. I've been researching MVC and think that's the way i should be going.</p>
<p>I had decided to give the zend framework a go, and have spent a while trying to get to grips with it, however I have found the learning curve extremely steep as I have no object oriented experience.</p>
<p>Is there another framework or option that anyone could recommend? I am considering having a look at cake based on reading other posts in this forum but I'd accept any guidance - my "requirments" are</p>
<ul>
<li>easiest to learn for non OO experience</li>
<li>includes some login / authentication features</li>
<li>handles database interaction with mysql easily.</li>
</ul>
<p>All suggestions appreciated!</p>
| <p>As stated very eloquently <a href="http://stackoverflow.com/questions/350053/php-frameworks-are-they-solely-personal-preference">here already</a>, frameworks are good until you want to do something they're not suited for, plus they can <a href="http://stackoverflow.com/questions/313364/should-a-beginning-php-programmer-consider-frameworks">abstract the language</a> to the point where you're effectively learning them rather than the language you're coding in.</p>
<p>I would encourage you to roll your own. If you understand the principles of MVC and you have a fair-to-middling knowledge of PHP then it won't be too hard (there's <a href="http://stackoverflow.com/questions/62605/php-as-a-template-language-or-some-other-php-templating-script">already</a> <a href="http://stackoverflow.com/questions/62617/whats-the-best-way-to-separate-php-code-and-html">several</a> <a href="http://stackoverflow.com/questions/113077/keeping-my-php-pretty">pointers</a> <a href="http://stackoverflow.com/questions/385335/how-to-use-php-for-large-projects">around</a>), plus you'll come out of it far further ahead than if you'd just used someone else's.</p>
|
Difference between DBEngine.BeginTrans and DBEngine.Workspaces(0).BeginTrans <p>In Access, what is the difference between these two statements?</p>
<pre><code>DBEngine.BeginTrans
</code></pre>
<p>and</p>
<pre><code>DBEngine.Workspaces(0).BeginTrans
</code></pre>
<p>The documentation for both leads to the same place.</p>
| <p>Have a look here: <a href="http://msdn.microsoft.com/en-us/library/aa293491(VS.60).aspx">DAO Workspace</a><br />
And then here: <a href="http://msdn.microsoft.com/en-us/library/aa293489(VS.60).aspx">DAO Workspace: Opening a Separate Transaction Space</a></p>
<p>(The links are for MFC, but they're applicable to whatever you're coding in.)</p>
<p><code>DBEngine.Workspaces(0)</code> is the default workspace. Other workspaces can be created, which let you work with separate sessions; the idea is that <code>BeginTrans</code> and <code>EndTrans</code> apply to the whole workspace, but if you need to do stuff outside that transaction, you can create another workspace and use it independently of your transactions in the first workspace.</p>
<p>Personally, I never had occasion to use more than one workspace when doing DAO in VBA. * shrug *</p>
|
Using Factories in Presenters in a Model View Presenter and Domain Driven Design Project <p>In domain driven design, it appears to be a good practice to use Factories to create your domain objects in your domain layer (as opposed to using a direct constructor or IoC). </p>
<p>But what about using the domain object factories in a presenter layer. For instance, say that I was creating a domain object from user input obtained from the presenter. </p>
<p>Here's an example, say I have a Configuration domain object that has a number of decimal settings.</p>
<p>public class Configuration : PersistantObject
{</p>
<pre><code> public decimal temperature {get;set;}
...(times 20)
public decimal gravity {get;set;}
</code></pre>
<p>}</p>
<p>In order to create this object in the domain layer, rather than the presenter layer, I would have to pass each of these decimal values as function parameters. Creating an unwieldy function definition and call.</p>
<p>ie ConfigurationService.CreateConfiguration(temperature, ...(x20), gravity);</p>
<p>The perhaps better solution would be to create the Configuration object in the presenter layer, and assign all the values of the configuration object directly from the user input, skipping a lengthy function call.</p>
<p>Configuration config = ConfigurationFactory.CreateNewConfiguration();</p>
<p>config.temperature = temperature;</p>
<p>..(x20).. = ...;</p>
<p>config.gravity = gravity;</p>
<p>ConfigurationService.SaveNewConfiguration(config);</p>
<p>But I'm wondering if this approach is wrong and why?
If both of these approaches are wrong, what is the best approach for creating a lengthy object from user input and why?</p>
<p>Thanks!</p>
| <p>I'd advise against letting your domain objects out of the domain layer and into the presentation layer. Keep the presentation layer focused on presentation.</p>
<p>For this reason, I construct Data Transfer Objects to shuffle data to and from the domain and presentation layers. In your case, have the dialog populate a DTO that is passed to your service and translated into the corresponding domain object.</p>
<p>You wouldn't want to construct domain objects from DTOs every time, though. <a href="http://moffdub.wordpress.com/2008/10/29/one-domain-object-and-multiple-dtos-enter-one-solution-leaves/" rel="nofollow">Consider the case where a DTO represents only a subset of a domain object</a>. Re-constructing an existing domain object from such a DTO would give you a partial domain object. You'd probably want to maintain a light-weight cache that held the full domain object so you could do a proper update.</p>
<p>Essentially, you'd arrive at the DTO solution if you applied the <a href="http://www.refactoring.com/catalog/introduceParameterObject.html" rel="nofollow">Introduce Parameter Object</a> refactoring.</p>
|
write to fifo/pipe from shell, with timeout <p>I have a pair of shell programs that talk over a named pipe. The reader creates the pipe when it starts, and removes it when it exits.</p>
<p>Sometimes, the writer will attempt to write to the pipe between the time that the reader stops reading and the time that it removes the pipe.</p>
<pre><code>reader: while condition; do read data <$PIPE; do_stuff; done
writer: echo $data >>$PIPE
reader: rm $PIPE
</code></pre>
<p>when this happens, the writer will hang forever trying to open the pipe for writing.</p>
<p>Is there a <strong>clean</strong> way to give it a timeout, so that it won't stay hung until killed manually? I know I can do</p>
<pre><code>#!/bin/sh
# timed_write <timeout> <file> <args>
# like "echo <args> >> <file>" with a timeout
TIMEOUT=$1
shift;
FILENAME=$1
shift;
PID=$$
(X=0; # don't do "sleep $TIMEOUT", the "kill %1" doesn't kill the sleep
while [ "$X" -lt "$TIMEOUT" ];
do sleep 1; X=$(expr $X + 1);
done; kill $PID) &
echo "$@" >>$FILENAME
kill %1
</code></pre>
<p>but this is kind of icky. Is there a shell builtin or command to do this more cleanly (without breaking out the C compiler)?</p>
| <p>This question comes up periodically (though I couldn't find it with a search). I've written two shell scripts to use as timeout commands: one for things that read standard input and one for things that don't read standard input. This stinks, and I've been meaning to write a C program, but I haven't gotten around to it yet. I'd definitely recommend writing a <code>timeout</code> command in C once and for all. But meanwhile, here's the simpler of the two shell scripts, which hangs if the command reads standard input:</p>
<pre><code>#!/bin/ksh
# our watchdog timeout in seconds
maxseconds="$1"
shift
case $# in
0) echo "Usage: `basename $0` <seconds> <command> [arg ...]" 1>&2 ;;
esac
"$@" &
waitforpid=$!
{
sleep $maxseconds
echo "TIMED OUT: $@" 1>&2
2>/dev/null kill -0 $waitforpid && kill -15 $waitforpid
} &
killerpid=$!
>>/dev/null 2>&1 wait $waitforpid
# this is the exit value we care about, so save it and use it when we
rc=$?
# zap our watchdog if it's still there, since we no longer need it
2>>/dev/null kill -0 $killerpid && kill -15 $killerpid
exit $rc
</code></pre>
<p>The other script is online at <a href="http://www.cs.tufts.edu/~nr/drop/timeout" rel="nofollow">http://www.cs.tufts.edu/~nr/drop/timeout</a>.</p>
|
Canonical operator overloading? <p>Is there a canonical or recommended pattern for implementing arithmetic operator overloading in C++ number-like classes?</p>
<p>From the C++ FAQ, we have an exception-safe assignment operator that avoids most problems:</p>
<pre><code>class NumberImpl;
class Number {
NumberImpl *Impl;
...
};
Number& Number::operator=(const Number &rhs)
{
NumberImpl* tmp = new NumberImpl(*rhs.Impl);
delete Impl;
Impl = tmp;
return *this;
}
</code></pre>
<p>But for other operators (+, +=, etc..) very little advice is given other than to make them behave like the operators on built-in types.</p>
<p>Is there a standard way of defining these? This is what I've come up with - are there pitfalls I'm not seeing?</p>
<pre><code>// Member operator
Number& Number::operator+= (const Number &rhs)
{
Impl->Value += rhs.Impl->Value; // Obviously this is more complicated
return *this;
}
// Non-member non-friend addition operator
Number operator+(Number lhs, const Number &rhs)
{
return lhs += rhs;
}
</code></pre>
| <p>In Bjarne Stroustrup's book "<a href="http://rads.stackoverflow.com/amzn/click/0201700735" rel="nofollow">The C++ Programming Language</a>", in chapter 11 (the one devoted to Operator Overloading) he goes through witting a class for a complex number type (section 11.3). </p>
<p>One thing I do notice from that section is that he implements mixed type operations... this is probably expected for any numeric class. </p>
<p>In general, what you've got looks good.</p>
|
How do you debug app crash with no stack trace referencing source code? <p><a href="http://support.microsoft.com/kb/953102" rel="nofollow">http://support.microsoft.com/kb/953102</a></p>
<p>We spent about 50 hours during Christmas holiday to identify this problem, causing our business critical production app to crash randomly.</p>
<p>The problem was that there was no stack trace to the source code, only native code like NativeWindow.Callback on the bottom of the stack trace.</p>
<p>Any tools out there that you would have used to debug this kind of problem?</p>
| <p>If you can tolerate it, add lots of logging.</p>
<p>Take a guess at where it's happening and bracket that code in <code>entered Foo</code> and <code>exited Foo</code> logs. Then if you see one but not the other on a crash, you known it's in there somewhere so start a binary (or n-ary) search diving into functions as needed. To some extent you will need to roll up the carpet behind you to keep the size of the log down but as long as the crash can be produced reasonably often you should be able to zero in on it that way.</p>
<p>I have an app that I've done this with (I can't debug it any other way in it's intended environment) and found it to be effective, Also it's kinda impressive to say you've worked with 1M+ line log files (to much logging, and to big a test case <code><g></code>)</p>
|
Structure of a C++ Object in Memory Vs a Struct <p>If I have a class as follows</p>
<pre><code> class Example_Class
{
private:
int x;
int y;
public:
Example_Class()
{
x = 8;
y = 9;
}
~Example_Class()
{ }
};
</code></pre>
<p>And a struct as follows</p>
<pre><code>struct
{
int x;
int y;
} example_struct;
</code></pre>
<p>Is the structure in memory of the <code>example_struct</code> simmilar to that in <code>Example_Class</code></p>
<p>for example if I do the following</p>
<pre><code>struct example_struct foo_struct;
Example_Class foo_class = Example_Class();
memcpy(&foo_struct, &foo_class, sizeof(foo_struct));
</code></pre>
<p>will <code>foo_struct.x = 8</code> and <code>foo_struct.y = 9</code> (ie: the same values as the x,y values in the foo_class) ?</p>
<p>The reason I ask is I have a C++ library (don't want to change it) that is sharing an object with C code and I want to use a struct to represent the object coming from the C++ library. I'm only interested in the attributes of the object.</p>
<p>I know the ideal situation would be to have Example_class wrap arround a common structure between the C and C++ code but it is not going to be easy to change the C++ library in use.</p>
| <p>The C++ standard <em>guarantees</em> that memory layouts of a C <code>struct</code> and a C++ <code>class</code> (or <code>struct</code> -- same thing) will be identical, provided that the C++ <code>class</code>/<code>struct</code> fits the criteria of being <strong>POD</strong> ("Plain Old Data"). So what does POD mean?</p>
<p>A class or struct is POD if:</p>
<ul>
<li>All data members are public and themselves POD or fundamental types (but not reference or pointer-to-member types), or arrays of such</li>
<li>It has no user-defined constructors, assignment operators or destructors</li>
<li>It has no virtual functions</li>
<li>It has no base classes</li>
</ul>
<p>About the only "C++-isms" allowed are non-virtual member functions, static members and member functions.</p>
<p>Since your class has both a constructor and a destructor, it is formally speaking not of POD type, so the guarantee does not hold. (Although, as others have mentioned, in practice the two layouts are likely to be identical on any compiler that you try, so long as there are no virtual functions).</p>
<p>See section [26.7] of the <a href="http://www.parashift.com/c++-faq-lite/intrinsic-types.html#faq-26.7">C++ FAQ Lite</a> for more details.</p>
|
how to convert string to binary integer file using command line under linux <p>What i want is to take an integer represented as a string, for example "1234", and convert it to a file called int, containing a 32-bit big endian integer, with the value 1234.</p>
<p>The only way I have figured out to do this is something like</p>
<pre><code>echo 1234 | awk '{printf "0: %08X", $1}' | xxd -r > int
</code></pre>
<p>which is a bit nasty!</p>
<p>Does anyone know a better way?</p>
| <p>A slightly simpler way would be:</p>
<pre><code>printf "0: %08X" 1234 | xxd -r > int
</code></pre>
|
What's a good way to view dojo's javascript source files in Eclipse with Aptana? <p>I have Aptana installed within Eclipse. I'm working on a project with the dojo 1.2 JavaScript library installed. </p>
<p>When I open one of dojo's dijit .js files, the code is formatted in a rather difficult to read way. The Eclipse "Outline" view shows a list of functions with names like "_2" and "ew". Not very human friendly. </p>
<p>I'm talking about source code that looks like this:</p>
<blockquote>
<p>dojo.declare("dijit.InlineEditBox",dijit._Widget,{editing:false,autoSave:true,buttonSave:"",buttonCancel:"",renderAsHtml:false,editor:"dijit.form.TextBox",editorParams:{},onChange:function(_1){
},onCancel:function(){
},width:"100%",value:"",noValueIndicator:" ✍ ",constructor:function(){
this.editorParams={};
},postMixInProperties:function(){
this.inherited(arguments);
this.displayNode=this.srcNodeRef;
var _2={ondijitclick:"_onClick",onmouseover:"_onMouseOver",onmouseout:"_onMouseOut",onfocus:"_onMouseOver",onblur:"_onMouseOut"};
for(var _3 in _2){
this.connect(this.displayNode,_3,_2[_3]);
}
dijit.setWaiRole(this.displayNode,"button");
if(!this.displayNode.getAttribute("tabIndex")){
this.displayNode.setAttribute("tabIndex",0);
}
this.attr("value",this.value||this.displayNode.innerHTML);
},setDisabled:function(_4){
dojo.deprecated("dijit.InlineEditBox.setDisabled() is deprecated. Use attr('disabled', bool) instead.","","2.0");
this.attr("disabled",_4);</p>
</blockquote>
<p>How do I get a clearer, "friendlier" view of such a .js file? </p>
| <p>You should be able to download uncompressed versions of the library at <a href="http://www.dojotoolkit.org" rel="nofollow">dojotoolkit.org</a>.
<a href="http://download.dojotoolkit.org/release-1.2.2/dojo-release-1.2.2/" rel="nofollow">Here</a> is the source tree for 1.2.2.</p>
|
print_int and other F# print functions <p>I am trying to do simple tutorial in Visual Studio
let someNumber = (2 + 2)
print_int someNumber
but it says print_int is undefined. printfn works.
Could the book I'm using be outdated? </p>
| <p>print_int is a part of the F# power pack. Adding a reference to the PowerPack (c:\program files\FSharp-1.9.6.2\bin\FSharp.PowerPack.dll on my machine) should fix the issue.</p>
<p>Here is a blog entry from Don that mentions the current plans for the Power Pack:</p>
<p><a href="http://blogs.msdn.com/dsyme/archive/2008/12/10/fsharp-to-ship-as-part-of-visual-studio-2010.aspx" rel="nofollow">http://blogs.msdn.com/dsyme/archive/2008/12/10/fsharp-to-ship-as-part-of-visual-studio-2010.aspx</a></p>
|
Get source of website in java <p>I would like to use java to get the source of a website (secure) and then parse that website for links that are in it. I have found how to connect to that url, but then how can i easily get just the source, preferraby as the DOM Document oso that I could easily get the info I want.</p>
<p>Or is there a better way to connect to https site, get the source (which I neet to do to get a table of data...its pretty simple) then those links are files i am going to download.</p>
<p>I wish it was FTP but these are files stored on my tivo (i want to programmatically download them to my computer(</p>
| <p>You can get low level and just request it with a socket. In java it looks like</p>
<pre><code>// Arg[0] = Hostname
// Arg[1] = File like index.html
public static void main(String[] args) throws Exception {
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsock = (SSLSocket) factory.createSocket(args[0], 443);
SSLSession session = sslsock.getSession();
X509Certificate cert;
try {
cert = (X509Certificate) session.getPeerCertificates()[0];
} catch (SSLPeerUnverifiedException e) {
System.err.println(session.getPeerHost() + " did not present a valid cert.");
return;
}
// Now use the secure socket just like a regular socket to read pages.
PrintWriter out = new PrintWriter(sslsock.getOutputStream());
out.write("GET " + args[1] + " HTTP/1.0\r\n\r\n");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(sslsock.getInputStream()));
String line;
String regExp = ".*<a href=\"(.*)\">.*";
Pattern p = Pattern.compile( regExp, Pattern.CASE_INSENSITIVE );
while ((line = in.readLine()) != null) {
// Using Oscar's RegEx.
Matcher m = p.matcher( line );
if( m.matches() ) {
System.out.println( m.group(1) );
}
}
sslsock.close();
}
</code></pre>
|
Flex 3 - Must I add components before setting their attributes when using AS3? <p>Let us say that I have a Flex 3 mxml component, call it A. A has a get/set attribute called 'b'. Within A I have another internal component C, which is specified using mxml. When "instantiating" component A within mxml, I can specify the value of b at declaration, and everything works fine. However, when I initialize the component using Actionscript, I must first add the component to a rendered container before I can set the attribute (in this case 'b') of said component. This happens when the setter for attribute 'b' somehow accesses C within A.</p>
<p>So, this fails at runtime (it says that C is null)...</p>
<pre><code>var a:A = new A();
a.b = "woopy"; //Sets the Label (declared in mxml) withn A to "woopy"
this.addChild(a);
</code></pre>
<p>On the other hand, either of the following will work</p>
<pre><code><customNamespace:A b="woopy"/>
</code></pre>
<p>or</p>
<pre><code>var a:A = new A();
this.addChild(a);
a.b = "woopy"; //Sets the Label (declared in mxml) withn A to "woopy"
</code></pre>
<p>As shown, no runtime error message is thrown when a attribute is set after a component is added to a container. Ok, this makes sense, I suppose the internals of the component are not actually created until the component is added to a container. Still, this is kind of annoying. Is there any way to guarantee that the component internals are fully rendered without adding it to a container? I don't like the way it feels different when I am using actionscript vs mxml. I want a solution so that basically declaring A in mxml with no attribute "arguments" is equivalent to declaring A using the new operator in AS. At least, in terms of the internal state of A.</p>
| <p>To force a control to create its child controls you have to call the initialize method.</p>
<p>i.e. this should work :</p>
<pre><code>var a:A = new A();
a.initialize();
a.b = "woopy";
this.addChild(a);
</code></pre>
<p>However, what I've been doing so far when declaring mxml controls is binding the internal controls to public variables declared in a script block. e.g.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
[Bindable]
public var labelText:String = "[Default]";
]]>
</mx:Script>
<mx:Label text="{labelText}"/>
</mx:Canvas>
</code></pre>
<p>This way you can set your parameters without having to worry about whether the controls have been created or not.</p>
|
Ignoring try block in C# command line program <p>I have a command line program in C# that I've wrapped with a try-catch block to keep it from crashing the console. However, while I am debugging it, if an exception is thrown somewhere in the DoStuff() method, Visual Studio will break on the "catch" statement. I want Visual Studio to break where the exception occurred. What's the best way to do this? </p>
<p>Comment out the try?<br />
A setting in Visual Sudio?<br />
An #if DEBUG statement?</p>
<pre><code>static void Main(string[] args)
{
try
{
DoStuff();
}
catch (Exception e)
{ //right now I have a breakpoint here
Console.WriteLine(e.Message);
}
}
private void DoStuff()
{
//I'd like VS to break here if an exception is thrown here.
}
</code></pre>
| <p>You can turn on <a href="http://blogs.msdn.com/davidklinems/archive/2005/07/18/440150.aspx" rel="nofollow">First chance exceptions</a> in VS. This will allow you to be notified as soon as an exception is raised.</p>
|
Rails form validation conditional bypass <p>I have a rails model that validates uniqueness of 2 form values. If these 2 values aren't unique the validation errors are shows and the "submit" button is changed to "resubmit". I want to allow a user to click the "resubmit" button and bypass the model validation. I want to do something like this from the rails validation documentation:</p>
<blockquote>
<p><code>validates_uniqueness_of :value, :unless => Proc.new { |user| user.signup_step <= 2 }</code></p>
</blockquote>
<p>but I don't have a a value in my model that I can check for...just the params that have the "Resubmit" value.</p>
<p>Any ideas on how to do this?</p>
| <p>In my opinion this is the best way to do it:</p>
<pre><code>class FooBar < ActiveRecord::Base
validates_uniqueness_of :foo, :bar, :unless => :force_submit
attr_accessor :force_submit
end
</code></pre>
<p>then in your view, make sure you name the submit tag like</p>
<pre><code><%= submit_tag 'Resubmit', :name => 'foo_bar[force_submit]' %>
</code></pre>
<p>this way, all the logic is in the model, controller code will stay the same.</p>
|
How to speed up the eclipse project 'refresh' <p>I have a fairly large PHP codebase (10k files) that I work with using Eclipse 3.4/PDT 2 on a windows machine, while the files are hosted on a Debian fileserver. I connect via a mapped drive on windows.</p>
<p>Despite having a 1gbit ethernet connection, doing an eclipse project refresh is quite slow. Up to 5 mins. And I am blocked from working while this happens.</p>
<p>This normally wouldn't be such a problem since Eclipse theoretically shouldn't have to do a full refresh very often. However I use the subclipse plugin also which triggers a full refresh each time it completes a switch/update.</p>
<p>My hunch is that the slowest part of the process is eclipse checking the 10k files one by one for changes over samba.</p>
<p>There is a large number of files in the codebase that I would never need to access from eclipse, so I don't need it to check them at all. However I can't figure out how to prevent it from doing so. I have tried marking them 'derived'. This prevents them from being included in the build process etc. But it doesn't seem to speed up the refresh process at all. It seems that Eclipse still checks their changed status.</p>
<p>I've also removed the unneeded folders from PDT's 'build path'. This does speed up the 'building workspace' process but again it doesn't speed up the actual refresh that precedes building (and which is what takes the most time).</p>
| <p>Thanks all for your suggestions. Basically, JW was on the right track. Work locally.</p>
<p>To that end, I discovered a plugin called FileSync:
<a href="http://andrei.gmxhome.de/filesync/" rel="nofollow">http://andrei.gmxhome.de/filesync/</a></p>
<p>This automatically copies the changed files to the network share. Works fantastically. I can now do a complete update/switch/refresh from within Eclipse in a couple of seconds.</p>
|
How Ethernet receives the bits and forms the Data Link Layer Frame <p>I am curious to know how the incoming bits at the physical layer are properly framed and sent to the data link layer. How the OS deal with this process.</p>
<p>It would be grateful if you explained it in detail or give me some links/pdf.</p>
<p>I am interested to know in depth about Layer 1 and 2 operations.</p>
<p>Advance Thanks.</p>
| <p>The physical layer depends on your hardware. You're probably connected via ethernet, see <a href="http://en.wikipedia.org/wiki/Ethernet" rel="nofollow">here</a>. The operating system doesn't do a lot here, it's mostly left up to the network card and the device drivers written by the card's manufacturer.</p>
|
Can I symlink multiple directories into one? <p>I have a feeling that I already know the answer to this one, but I thought I'd check.</p>
<p>I have a number of different folders:</p>
<pre><code>images_a/
images_b/
images_c/
</code></pre>
<p>Can I create some sort of symlink such that this new directory has the contents of all those directories? That is this new "<code>images_all</code>" would contain all the files in <code>images_a</code>, <code>images_b</code> and <code>images_c</code>?</p>
| <p>No. You would have to symbolically link all the individual files.</p>
<p>What you <em>could</em> do is to create a job to run periodically which basically removed all of the existing symbolic links in <code>images_all</code>, then re-create the links for all files from the three other directories, but it's a bit of a kludge, something like this:</p>
<pre><code>rm -f images_all/*
for i in images_[abc]/* ; do; ln -s $i images_all/$(basename $i) ; done
</code></pre>
<p>Note that, while this job is running, it may appear to other processes that the files have temporarily disappeared.</p>
<p>You will also need to watch out for the case where a single file name exists in two or more of the directories.</p>
<hr>
<p>Having come back to this question after a while, it also occurs to me that you can minimise the time during which the files are not available.</p>
<p>If you link them to a <em>different</em> directory then do relatively fast <code>mv</code> operations that would minimise the time. Something like:</p>
<pre><code>mkdir images_new
for i in images_[abc]/* ; do
ln -s $i images_new/$(basename $i)
done
# These next two commands are the minimal-time switchover.
mv images_all images_old
mv images_new images_all
rm -rf images_old
</code></pre>
<p>I haven't tested that so anyone implementing it will have to confirm the suitability or otherwise.</p>
|
Why can't DynaLoader.pm load SSleay.dll for Net::SSLeay and Crypt::SSLeay? <p>I have Perl v5.10. I am trying to install Net::SSLeay 1.30 and Crypt::SSLeay 0.57.
I have already installed OpenSSL 0.9.8e.</p>
<p>For Net::SSLeay 1.30 I followed these steps:</p>
<pre>
perl Makefile.PL -windows C:\openssl
nmake
nmake test -- test fails
nmake install
perl test.pl
</pre>
<p>but I got an fatal error as:</p>
<pre>
D:\perl\Net_SSLeay.pm-1.30>perl -w test.pl
1..20
Can't load 'D:/perl/site/lib/auto/Net/SSLeay/SSLeay.dll' for module Net::SSLeay: load_file:The specified module could not be found at D:/perl/lib/DynaLoader.pm line 203.
at test.pl line 25
Compilation failed in require at test.pl line 25.
BEGIN failed--compilation aborted at test.pl line 25.
</pre>
<p>I got the same results for Crypt::SSLeay 0.57.</p>
| <p>Randy Kobes has <a href="http://www.mail-archive.com/perl-win32-users@listserv.activestate.com/msg32520.html" rel="nofollow">an answer for this on the Perl Win32 mailing list</a>. Does your PATH environment variable contain the directory that contains libeay32.dll or ssleay32.dll?</p>
<p>There are many other answers that you can find in Google too. In cases like these, I take the whole error message and shove it into the Google search bar. I start cutting out parts of the error message, such as the specific paths, until I get <a href="http://www.google.com/search?hl=en&client=safari&rls=en-us&q=module+Net%3A%3ASSLeay%3A+load_file%3AThe+specified+module+could+not+be+found&btnG=Search" rel="nofollow">some search results</a>. This almost always works for me since I'm rarely the first person to have a problem.</p>
<p>Good luck,</p>
|
Vehicle tracking system/Jan08 <p>we are developing cost effective vehicle tracking system,
for my knowledge Using GPS to track vehicle costs more.
So we are looking to develop using GPRS system which costs less.</p>
<p>my doubt is can track the vehicle using only GPRS (not using GPS at all)
is this possible .please correct if i am wrong if you any documentation or link it will be useful.</p>
<p>thanks in advance,
Mahesh</p>
| <p>If you don't need an exact location you can use cell tower information and some external api to get the coordinates for each tower.
It's the same function that google uses in their mobile Maps application.</p>
<p>Example:
<a href="http://www.codeproject.com/KB/mobile/DeepCast.aspx" rel="nofollow">http://www.codeproject.com/KB/mobile/DeepCast.aspx</a></p>
|
Using a #! comment in ruby running in Ubuntu <p>I am new to programming and am trying to follow an example which uses #! comment in ruby.</p>
<p>I am consistently get the message:
bash: matz.rb: command not found</p>
<p>I am using this comment:
#! /usr/bin/env ruby</p>
<p>I have tried it with and without the space after ! as well as with and without the env. </p>
<p>when I use the
$ which ruby </p>
<p>ruby is in: /usr/bin/ruby</p>
<p>I have also gone into the operating system and changed the permissions on the file matz.rb to rwx for all users w/ no effect. Am I doing something wrong or do I have my system set up incorrectly?</p>
| <p>The <code>/usr/bin/env</code> part is fine. You need to give bash the path to matz.rb when you run it. If you're in the directory with matz.rb, type "./matz.rb". The directory "." means the current directory - bash doesn't look there by default when running programs (like Windows does).</p>
<p>The env program (/usr/bin/env) searches the executable search path - the PATH environment variable - for the <code>ruby</code> program as if you typed it at the command prompt, and runs that program. The shebang comment doesn't do this. If you want to give your script to other people who might not have ruby installed in the same place as you, then you should use the "<code>#!/usr/bin/env ruby</code>" comment so that it will work as long as they can run ruby by typing "ruby".</p>
|
Accessing TextBox Column in RadGrid By Telerik <p>Hi There
Do you know how to access textboxes added to a radgrid that are not bound but are used to trap any row related input a user typed in to the textbox for that column.
I need to access this data server side when a postback occurs.
Your thoughts are greatly appreciated
Thanking you</p>
<p>Tony</p>
| <p>That depends on how those textboxes are being added/created. If by 'not bound' you mean they are in Template columns you should be able to use .FindControl in one of the grid's events to grab that textbox.
And again which event will depend on what is causing the postback to happen.
For the purpose of this code example I'll assume you are dealing with a Command item on the grid</p>
<pre><code>Private Sub radGrid_ItemCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.ItemCommand
Select Case e.CommandName
Case "Update"
Dim txt as Textbox
txt = e.Item.FindControl("textboxID")
If Not txt is Nothing Then someObject.someString = txt.Text
Case Else
'do something else
End Sub
</code></pre>
<p>Hope that helps.</p>
|
Grouping by a report item in SSRS 2005 - textbox - any workarounds? <p>I want to group by a report item, but that's not allowed.
So I tried creating a parameter...not allowed as well.
Tried referencing from footer...failed again.</p>
<p>This is somewhat complicated.
Let me explain:</p>
<p>I have textbox22, it's value is:</p>
<pre><code>=Code.Calc_Factor(Fields!xx.Value, fields!yy.Value...)
</code></pre>
<p>This is embedded VB code in the report that's called for each row to calculate a standard factor.</p>
<p>Now to calculate the deviation from the standard factor, I use textbox89, whose value is:</p>
<pre><code>=(Fields!FACTOR.Value - ReportItems!textbox22.Value)/ReportItems!textbox22.Value
</code></pre>
<p>Don't get confused between <code>Fields!FACTOR.Value</code> and <code>textbox22.Value</code>, they are different.
<code>Fields!FACTOR.Value</code> is the factor used, <code>textbox22.Value</code> is what it should be (standard factor).</p>
<p>Now I want to create a group which splits deviations into 2 groups, > 1% or not.
So I tried creating a group:</p>
<pre><code>=IIF(ReportItems!textbox89.Value > 1,0,1)
</code></pre>
<p>...But then SSRS complains about using report items.</p>
<p>I have run into a similar problem of using report items in the past, but this is a new case!</p>
<p>Any help greatly appreciated.</p>
| <p>Have you tried adding a calculated field to your dataset?</p>
<p>Here is how it works:</p>
<ul>
<li><p>While you are in the layout view of the report, open "datasets" tool window(in my environment it is on the left). </p></li>
<li><p>Right click on the DataSet you are working with and add a field, you can use a calculated field, and build your formula appropriately</p></li>
<li><p>Then you <em>should</em> be able to group on this field</p></li>
</ul>
<p>-Dan</p>
|
How to return more than one value from a function in Python? <p>How to return more than one variable from a function in Python?</p>
| <p>You separate the values you want to return by commas:</p>
<pre><code>def get_name():
# you code
return first_name, last_name
</code></pre>
<p>The commas indicate it's a tuple, so you could wrap your values by parentheses:</p>
<pre><code>return (first_name, last_name)
</code></pre>
<p>Then when you call the function you a) save all values to one variable as a tuple, or b) separate your variable names by commas</p>
<pre><code>name = get_name() # this is a tuple
first_name, last_name = get_name()
(first_name, last_name) = get_name() # You can put parentheses, but I find it ugly
</code></pre>
|
How to pass a COM method as a function argument? And Microsoft Compiler error C3867 <p>I would like to pass a COM method as a function argument but I get this error (Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86):</p>
<p>error C3867: 'IDispatch::GetTypeInfoCount': function call missing argument list; use '&IDispatch::GetTypeInfoCount' to create a pointer to member</p>
<p>What am I missing?</p>
<p>Thank you very much.</p>
<pre><code>#include <atlbase.h>
void update( HRESULT(*com_uint_getter)(UINT*), UINT& u )
{
UINT tmp;
if ( S_OK == com_uint_getter( &tmp ) ) {
u = tmp;
}
}
// only for compile purpose, it will not work at runtime
int main(int, char*[])
{
// I choose IDispatch::GetTypeInfoCount just for the sake of exemplification
CComPtr< IDispatch > ptr;
UINT u;
update( ptr->GetTypeInfoCount, u );
return 0;
}
</code></pre>
| <p>Looks like a straight c++ problem.</p>
<p>Your method expects a pointer to a function.</p>
<p>You have a member function - (which is different from a function).</p>
<p>Typically you will need to either:<br>
1. Change the function that you want to pass to being static.<br>
2. Change the type of pointer expected to a member function pointer.<br></p>
<p>The syntax for dealing with member function pointers is not the best...</p>
<p>A standard trick would be (1) and then pass the object this pointer explicitly
as an argument allowing you to then call non static members.</p>
|
C# multiple string match <p>I need C# string search algorithm which can match multiple occurance of pattern. For example, if pattern is 'AA' and string is 'BAAABBB' Regex produce match result Index = 1, but I need result Index = 1,2. Can I force Regex to give such result? </p>
| <p>Use a lookahead pattern:-</p>
<p>"A(?=A)"</p>
<p>This finds any A that is followed by another A without consuming the following A. Hence AAA will match this pattern twice.</p>
|
Change Control Document <p>I'm starting to lead a lot of reforms at the company where I work and the next thing I want try get in place is a decent change control document. I've searched but I can't find a template so far.</p>
<p>Would it be possible to maybe share some Change Control documents amongest ourselves?</p>
| <p>Found <a href="http://www.iturls.com/English/SoftwareEngineering/SE_c.asp" rel="nofollow">this</a> page from a quick Google search. Contains lots of links to document templates and checklists for all sorts of doc types, including change control.</p>
|
Integer.Parse vs. CInt <p>Basically, I have been using both <code>Integer.Parse</code> and <a href="https://msdn.microsoft.com/en-us/library/s2dy91zy.aspx" rel="nofollow">CInt</a> in most of my daily programming tasks, but I'm a little bit confused of what the difference is between the two.</p>
<p>What is the difference between <code>Integer.Parse</code> and <code>CInt</code> in VB.NET?</p>
| <p>CInt does a whole lot more than integer.Parse.</p>
<p>Cint will first check to see if what it was passed is an integer, and then simply casts it and returns it. If it's a double it will try to convert it without first converting the double to a string.</p>
<p>See this from the help for CInt and other <a href="http://msdn.microsoft.com/en-us/library/s2dy91zy.aspx">Type Conversion Functions</a></p>
<blockquote>
<p>Fractional Parts. When you convert a
nonintegral value to an integral type,
the integer conversion functions
(CByte, CInt, CLng, CSByte, CShort,
CUInt, CULng, and CUShort) remove the
fractional part and round the value to
the closest integer.</p>
<p>If the fractional part is exactly 0.5,
the integer conversion functions round
it to the nearest even integer. For
example, 0.5 rounds to 0, and 1.5 and
2.5 both round to 2. This is sometimes called banker's rounding, and its
purpose is to compensate for a bias
that could accumulate when adding many
such numbers together.</p>
</blockquote>
<p>So in short, it does much more than convert a string to an integer, e.g. applying specific rounding rules to fractions, short circuting unecessary conversions etc.</p>
<p>If what you're doing is converting a string to an integer, use integer.parse (or integer.TryParse), if you're coercing an unknown value (e.g. a <code>variant</code> or <code>object</code> from a database) to an integer, use CInt.</p>
|
In statement for LINQ to objects <p>Is there an equivalent of a SQL IN statement in LINQ to objects?</p>
| <p>Yes - <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.contains.aspx">Contains</a>.</p>
<pre><code>var desiredNames = new[] { "Jon", "Marc" };
var people = new[]
{
new { FirstName="Jon", Surname="Skeet" },
new { FirstName="Marc", Surname="Gravell" },
new { FirstName="Jeff", Surname="Atwood" }
};
var matches = people.Where(person => desiredNames.Contains(person.FirstName));
foreach (var person in matches)
{
Console.WriteLine(person);
}
</code></pre>
<p>(In LINQ to SQL this ends up as an "IN" query.)</p>
<p>Note that in LINQ to Objects the above isn't really very efficient. You'd be better off with a join:</p>
<pre><code>var matches = from person in people
join name in desiredNames on person.FirstName equals name
select person;
</code></pre>
<p>(This could still be done with dot notation of course, but it ends up being somewhat messier.)</p>
|
PHP Header redirect not working <pre><code>include('header.php');
$name = $_POST['name'];
$score = $_POST['score'];
$dept = $_POST['dept'];
$MyDB->prep("INSERT INTO demo (`id`,`name`,`score`,`dept`, `date`) VALUES ('','$name','$score','$dept','$date')");
// Bind a value to our :id hook
// Produces: SELECT * FROM demo_table WHERE id = '23'
$MyDB->bind(':date', $date);
// Run the query
$MyDB->run();
header('Location:index.php');
exit;
</code></pre>
<p>The above code keeps giving me an issue with the redirect. The error is: </p>
<pre><code>Warning: Cannot modify header information - headers already sent by (output
started at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php:15) in
/Applications/MAMP/htdocs/testygubbins/OO/test/form.php on line 16.
</code></pre>
<p>I am totally flummoxed by this. Does anyone know what I should be doing to make it work?</p>
<p>EDIT</p>
<p>header.php code:</p>
<pre><code><?php
include('class.user.php');
include('class.Connection.php');
$date = date('Y-m-j');
?>
<html>
<head>
<link rel=StyleSheet href="css/style.css" type="text/css" media=screen>
<title>Test</title>
</head>
<body>
<div id="page">
</code></pre>
| <p>Look carefully at your includes - perhaps you have a blank line after a closing ?> ?</p>
<p>This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls. </p>
<p>Note that it is legal to leave the close ?> off the include file, which is a useful idiom for avoiding this problem.</p>
<p><em>(EDIT: looking at your header, you need to avoid doing any HTML output if you want to output headers, or use output buffering to capture it).</em></p>
<p>Finally, as the <a href="http://php.net/header">PHP manual page for header</a> points out, you should really use full URLs to redirect:</p>
<blockquote>
<p>Note: HTTP/1.1 requires an absolute
URI as argument to <em>Location:</em>
including the scheme, hostname and
absolute path, but some clients accept
relative URIs. You can usually use
$_SERVER['HTTP_HOST'],
$_SERVER['PHP_SELF'] and dirname() to
make an absolute URI from a relative
one yourself:</p>
</blockquote>
|
PHP PDF-Generation - IE7/Acrobat8: "Website cannot be displayed" <p>I've got some trouble with displaying pdfs in IE7 (which were generated by R&OS' ezpdf).</p>
<p>IE7 with Acrobat Reader 8.1.2. says "The page cannot be displayed"</p>
<p>Other Browsers (like FF3/Acrobat 8.1.2. or IE6/Acrobat 7) have no problem with the file.</p>
<p>The following headers are returned by the server:</p>
<blockquote>
<p>Date: Thu, 08 Jan 2009 10:52:40 GMT<br>
Server: Apache/2.2.8 (Win32) mod_ssl/2.2.8 OpenSSL/0.9.8g PHP/5.2.5 DAV/2<br>
X-Powered-By: PHP/5.2.5<br>
Expires: Thu, 19 Nov 1981 08:52:00 GMT<br>
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0<br>
Pragma: no-cache<br>
Content-Length: 4750<br>
Keep-Alive: timeout=5, max=100<br>
Connection: Keep-Alive<br>
Content-Type: application/pdf<br></p>
</blockquote>
<p>Does anybody know how to fix this problem?</p>
| <blockquote>
<p>Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache</p>
</blockquote>
<p>...so IE won't store the file in the Temporary Internet Files folder. However the mechanism used to directly 'Open' a file from the browser in IE often requires it to be opened from inside Temporary Internet Files. Directly opening a file from a browser is generally unreliable, especially in IE; 'Save as' works better.</p>
<p>Consider replacing the cachebusting headers with an alternative method, such as add a '?randomstring' parameter to the URL. Also consider adding a "Content-Disposition: attachment; filename=..." header, which will stop a plug-in trying and failing to display the file in the browser UI.</p>
|
modelbinder with dropdownlist in asp.net mvc <p>Here's what I'm trying to do : </p>
<p>I have an entity <strong>Task</strong> with a TaskName property and a <strong>TaskPriority</strong> property.</p>
<p>Now, in the html I have :</p>
<pre><code><td><%=Html.TextBox("Task.TaskName") %></td>
<td><%=Html.DropDownList("Task.TaskPriority",new SelectList(ViewData.Model.TaskPriorities,"ID","PriorityName")) %></td>
</code></pre>
<p>The Controller action is like this : </p>
<pre><code>public ActionResult Create(Task task){
//task.TaskName has the correct value
//task.TaskPriority is null - how should the html look so this would work ?
}
</code></pre>
<p><strong>EDIT</strong>
In the example bellow (from Schotime) : </p>
<pre><code>public class Task
{
public int name { get; set; }
public string value { get; set; } // what if the type of the property were Dropdown ?
// in the example I gave the Task has a property of type: TaskPriority.
}
</code></pre>
| <p>This should work.</p>
<p>Three classes:</p>
<pre><code> public class Container
{
public string name { get; set; }
public List<Dropdown> drops { get; set; }
}
public class Dropdown
{
public int id { get; set; }
public string value { get; set; }
}
public class Task
{
public int name { get; set; }
public TaskPriority priority { get; set; }
}
public class TaskPriority
{
public string value { get; set; }
...
}
</code></pre>
<p>Controller:</p>
<pre><code> public ActionResult Tasks()
{
List<dropdown> ds = new List<Dropdown>();
ds.Add(new Dropdown() { id = 1, value = "first" });
ds.Add(new Dropdown() { id = 2, value = "second" });
ViewData.Model = new Container() { name = "name", drops = ds };
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Tasks(Task drops)
{
//drops return values for both name and value
return View();
}
</code></pre>
<p>View: Strongly typed <code>Viewpage<Container></code></p>
<pre><code><%= Html.BeginForm() %>
<%= Html.TextBox("drops.name") %>
<%= Html.DropDownList("drops.priority.value",new SelectList(ViewData.Model.drops,"id","value")) %>
<%= Html.SubmitButton() %>
<% Html.EndForm(); %>
</code></pre>
<p>When i debugged it worked as expected.
Not sure what you are doing wrong if you have something similar to this.
Cheers.</p>
|
Rounded Swing JButton using Java <p>Well, I have an image that I would like to put as a background to a button (or something clicable). The problem is that this image is round, so I need to show this image, without any borders, etc.</p>
<p>The JComponent that holds this button has a custom background, so the button really needs to only show the image.</p>
<p>After searching Google, I couldn't manage to do so. I have tried all the following, but with no luck:</p>
<pre><code>button.setBorderPainted(false);
button.setContentAreaFilled(false);
button.setOpaque(true);
</code></pre>
<p>And after I paint the icon at the background, the button paints it, but holds an ugly gray background with borders, etc. I have also tried to use a JLabel and a JButton. And to paint an ImageIcon at it, but if the user resizes or minimizes the window, the icons disappear!</p>
<p>How can I fix this?</p>
<p>I just need to paint and round an image to a JComponent and listen for clicks at it...</p>
| <p>Did you try the following?</p>
<pre><code>button.setOpaque(false);
button.setFocusPainted(false);
button.setBorderPainted(false);
button.setContentAreaFilled(false);
setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); // Especially important
</code></pre>
<p><code>setBorder(null)</code> might work, but there is <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4192869" rel="nofollow">a bug described at Sun</a> explaining it is by design that the UI sets a border on a component unless the client sets a non-null border which does not implement the <code>UIResource</code> interface.</p>
<p>Rather than the JDK itself setting the border to an <code>EmptyBorder</code> when null is passed in, the clients should set an <code>EmptyBorder</code> themselves (a very easy workaround). That way there is no confusion about who's doing what in the code.</p>
|
StringDictionary not saving as user setting <p>I've created a user scoped setting with the type "System.Collections.Specialized.StringDictionary". Whenever I open the local settings, I can see it in the config, but it's empty.</p>
<p>I have other user settings that save correctly, but this dictionary doesn't seem to be saving at all.</p>
<p>Is there something I need to do in order to get a dictionary to save?</p>
| <p>If you're setting it from code, are you remembering to call <code>Settings.Save()</code>?</p>
<p>Edit: Boy am I dumb, I just remembered I had the same problem myself and labored over it for hours. The problem is that the <code>Dictionary</code> doesn't serialize to XML (even though it really should). You have two options. You can specify your own serialization methods for the dictionary, or you can cheat.</p>
<p>If you don't care about being able to read/edit the values in the XML, you can add a <code>[SettingSerializeAs(SettingsSerializeAs.Binary)]</code> attribute to the setting. Gets the job done, but it's the quick-and-dirty approach.</p>
|
Grouping Regular expression BackReferences <p>I have the following RegEx</p>
<pre><code>id=(.*?) | id="(.*?)"
</code></pre>
<p>The reason for this is I am trying to replace Ids from the browsers DOM using JavaScript. IE, however strips quotes from element atributes as it appears not to require them in the DOM</p>
<p>The problem I have is that the backrefererences from each alternate statement are in separate groups ($1 and $2) as the match is only one OR the other can I return both the backreference as a single backreference?</p>
<p>EDIT:</p>
<pre><code><div id="test1" /><div id=test2 />
</code></pre>
<p>will match as follows</p>
<pre><code> match | $1 | $2
--------------------------------
id="test1" | test1 |
id=test2 | | test2
</code></pre>
<p>I just want both backreferences to be added to $1</p>
| <p>what about:</p>
<pre><code>id="?(.*?)"?
</code></pre>
<p><em>(possibly that . should be [^"] - I didn't test it)</em></p>
|
SQL Server 2000 intermittent connection exceptions on production server - specific environment problem? <p>We've been having intermittent problems causing users to be forcibly logged out of out application.</p>
<p>Our set-up is ASP.Net/C# web application on Windows Server 2003 Standard Edition with SQL Server 2000 on the back end. We've recently performed a major product upgrade on our client's VMWare server (we have a guest instance dedicated to us) and whereas we had none of these issues with the previous release the added complexity that the new upgrade brings to the product has caused a lot of issues. We are also running SQL Server 2000 (build 8.00.2039, or SP4) and the IIS/ASP.NET (.Net v2.0.50727) application on the same box and connecting to each other via a TCP/IP connection.</p>
<hr>
<p>Primarily, the exceptions being thrown are:</p>
<blockquote>
<p>System.IndexOutOfRangeException: Cannot find table 0.</p>
<p>System.ArgumentException: Column 'password' does not belong to table Table. </p>
</blockquote>
<p>[This exception occurs in the log in script, even though there is clearly a password column available]</p>
<blockquote>
<p>System.InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first. </p>
</blockquote>
<p>[This one is occurring very regularly]</p>
<blockquote>
<p>System.InvalidOperationException: This SqlTransaction has completed; it is no longer usable.</p>
<p>System.ApplicationException: ExecuteReader requires an open and available Connection. The connection's current state is connecting.</p>
<p>System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.</p>
</blockquote>
<p>And just today, for the first time:</p>
<blockquote>
<p>System.Web.UI.ViewStateException: Invalid viewstate.</p>
</blockquote>
<hr>
<p>We have load tested the app using the same number of concurrent users as the production server and cannot reproduce these errors. They are very intermittent and occur even when there are only 8/9/10 user connections. My gut is telling me its ASP.NET - SQL Server 2000 connection issues..</p>
<p>We've pretty much ruled out code-level Data Access Layer errors at this stage (we've a development team of 15 experienced developers working on this) so we think its a specific production server environment issue.</p>
| <p>The Invalid Viewstate error is pretty common in a high traffic web site. Though, if you recently moved to multiple web servers, make sure you're sharing the same machine key so Viewstate is signed with the same key on all servers. <a href="http://www.codinghorror.com/blog/archives/000132.html" rel="nofollow">http://www.codinghorror.com/blog/archives/000132.html</a></p>
<p>Based on the other errors I'd guess that you are using shared connections across multiple threads. Are your connections stored in static variables, Application state, Session state, or other object that's used across multiple requests? Maybe there's a hashtable somewhere containing connections, commands, or transactions. None of the ADO.Net objects are thread safe. So, make sure you only use them in a single threaded fashion.</p>
<p>Another possibility is you're passing around the ADO.NET objects and not consistently disposing of them and managing their scope. Maybe they're cached in the request context or some such?</p>
|
\\\\$ converted to \$ in jsp template data <p>I just stumbled unto a weirdness in my JSP code. It seems that a double backslash followed by a dollar or percent symbol gets converted to a single backslash (plus symbol).</p>
<p>That is, the following JSP:</p>
<pre><code><%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
\\#
\\$
\\%
\\^
</code></pre>
<p>gets rendered as:</p>
<pre><code>\\#
\$
\%
\\^
</code></pre>
<p>I'm using JDK 1.6.0_02 and Apache Tomcat 5.5.23 and 6.0.16 (two machines).</p>
<p>Is this a bug in Tomcat? JDK? Or is it conforming to some obscure option in the JSP spec? I tried looking at the spec but couldn't find anything useful.</p>
<p>Workarounds are fairly trivial, I just thought I'd file a bug in case it is one.</p>
<p><strong>EDIT</strong>: Heh, stackoverflow also mangles backslashes</p>
| <p>\$ is in the <a href="http://jcp.org/aboutJava/communityprocess/final/jsr152/index.html" rel="nofollow">spec</a> (Section JSP.1.6). "Only when EL is enabled for the page...., a literal $ can be quoted by \$.</p>
<p>\% will probably be because "A literal <% is quoted by <\%". I suspect that the parser isn't checking for the < before the \%.</p>
|
Preventing Brute Force Logins on Websites <p>As a response to the recent <a href="http://blog.wired.com/27bstroke6/2009/01/professed-twitt.html">Twitter hijackings</a> and <a href="http://www.codinghorror.com/blog/archives/001206.html">Jeff's post on Dictionary Attacks</a>, what is the best way to secure your website against brute force login attacks?</p>
<p>Jeff's post suggests putting in an increasing delay for each attempted login, and a suggestion in the comments is to add a captcha after the 2nd failed attempt.</p>
<p>Both these seem like good ideas, but how do you know what "attempt number" it is? You can't rely on a session ID (because an attacker could change it each time) or an IP address (better, but vulnerable to botnets). Simply logging it against the username could, using the delay method, lock out a legitimate user (or at least make the login process very slow for them).</p>
<p>Thoughts? Suggestions?</p>
| <p>I think database-persisted short lockout period for the given account (1-5 minutes) is the only way to handle this. Each userid in your database contains a TimeOfLastFailedLogin and numberOfFailedAttempts. When numbeOfFailedAttempts > X you lockout for some minutes.</p>
<p>This means you're locking the userid in question for some time, but not permanently.It also means you're updating the database for each login attempt (unless it is locked, of course), which may be causing other problems.</p>
<p>There is at least one whole country is NAT'ed in asia, so IP's cannot be used for anything.</p>
|
Determining "Owner" of Text Edited by Multiple Users <p>You may have noticed that we now show an edit summary on Community Wiki posts:</p>
<blockquote>
<p>community wiki<br />
220 revisions, 48 users</p>
</blockquote>
<p>I'd like to also show the user who "most owns" the final content displayed on the page, as a percentage of the remaining text:</p>
<blockquote>
<p>community wiki<br />
220 revisions, 48 users<br />
<strong>kronoz</strong> 87%</p>
</blockquote>
<p>Yes, there could be top (n) "owners", but for now I want the top 1.</p>
<p>Assume you have this data structure, a list of user/text pairs ordered chronologically by the time of the post:</p>
<pre>
User Id Post-Text
------- ---------
12 The quick brown fox jumps over the lazy dog.
27 The quick brown fox jumps, sometimes.
30 I always see the speedy brown fox jumping over the lazy dog.
</pre>
<p><strong>Which of these users most "owns" the final text?</strong></p>
<p>I'm looking for a reasonable algorithm -- it can be an approximation, it doesn't have to be perfect -- to determine the owner. Ideally expressed as a percentage score.</p>
<p>Note that we need to factor in edits, deletions, and insertions, so the final result feels reasonable and right. You can use any stackoverflow post with a decent revision history (not just retagging, but frequent post body changes) as a test corpus. Here's a good one, with 15 revisions from 14 different authors. Who is the "owner"?</p>
<p><a href="http://stackoverflow.com/revisions/327973/list">http://stackoverflow.com/revisions/327973/list</a></p>
<p>Click "view source" to get the raw text of each revision.</p>
<p>I should warn you that a pure algorithmic solution might end up being a form of the <a href="http://en.wikipedia.org/wiki/Longest_common_substring_problem" rel="nofollow">Longest Common Substring Problem</a>. But as I mentioned, approximations and estimates are fine too if they work well.</p>
<p><strong>Solutions in any language are welcome</strong>, but I prefer solutions that are</p>
<ol>
<li>Fairly easy to translate into c#.</li>
<li>Free of dependencies. </li>
<li>Put simplicity before efficiency.</li>
</ol>
<p>It is extraordinarily rare for a post on SO to have more than 25 revisions. But it should "feel" accurate, so if you eyeballed the edits you'd agree with the final decision. I encourage you to <strong>test your algorithm out on stack overflow posts with revision histories</strong> and see if you agree with the final output.</p>
<p><hr /></p>
<p>I have now deployed the following approximation, which you can see in action for every <em>new</em> saved revision on Community Wiki posts</p>
<ul>
<li>do a <a href="http://www.mathertel.de/Diff/" rel="nofollow">line based diff</a> of every revision where the body text changes</li>
<li>sum the insertion and deletion lines for each revision as "editcount"</li>
<li>each userid gets sum of "editcount" they contributed</li>
<li>first revision author gets 2x * "editcount" as initial score, as a primary authorship bonus</li>
<li>to determine final ownership percentage: each user's edited line count total divided by total number of edited lines in all revisions</li>
</ul>
<p>(There are also some guard clauses for common simple conditions like 1 revision, only 1 author, etcetera. The line-based diff makes it fairly speedy to recalc for all revisions; in a typical case of say 10 revisions it's ~50ms.)</p>
<p>This works fairly well in my testing. It does break down a little when you have small 1 or 2 line posts that several people edit, but I think that's unavoidable. Accepting Joel Neely's answer as closest in spirit to what I went with, and upvoted everything else that seemed workable.</p>
| <p>I think the idea is fundamentally flawed.</p>
<p>If someone writes a brilliant analysis with awful spelling and unclear examples, and I copy edit it extensively, have I created 60 % of the work? Clearly not; the result is a derivative where most of the value comes from the initial poster. A useful measure is not possible based on character or word counts, but requires strong AI-level semantic analysis.</p>
<p>Quite apart from that, seeking credit based on âownershipâ of articles would likely be entirely unhelpful and anti-wiki. On Wikipedia, for example, people who act as though they own articles are one of the most damaging influences.</p>
|
Is there a way to get rid of aspx placeholder files in a ASP.NET web deployment project? <p>I'm using a <strong>web deployment project</strong> in order to precompile my <strong>ASP.NET 3.5 web project</strong>. It creates a single extra DLL for the code in aspx and ascx files. And, for every aspx file there is a placeholder aspx file (empty) which needs to be copied to the server.</p>
<p>I'd like to simplify the deployment process. Is there a way (configuring the IIS site and adding some sort of http handlers etc.) to <strong>get rid of these aspx placeholders</strong>?</p>
<p>Also, I'd like to know if there is a way to get rid of the <strong>.compiled files</strong> in the bin folder. It would make the deployment process smoother.</p>
<p><em>Thanks!</em></p>
| <p>I discovered it by myself. It is much easier than I thought (IIS 6.0):</p>
<p>In Internet Information Manager go to the property page of the site, then chose the tab "Home Directory" and click on the button "Configuration...".</p>
<p>Click "Edit..." for the .aspx ISAPI extension and <strong>uncheck "Verify that file exists"</strong>. At this point, no aspx file is needed anymore.</p>
<p><img src="http://i.stack.imgur.com/7Rzne.png" alt="alt text"></p>
<p><strong>Update</strong> </p>
<p>One important thing: I had to create an empty "default.aspx" file in the root of the application in order to allow the default document for requests like "<a href="http://www.example.com/" rel="nofollow">http://www.example.com/</a>" (without calling an aspx).</p>
<p><strong>Update 2</strong></p>
<p>Another very important thing: if you're using ASP.NET Ajax PageMethods, then you have to keep the aspx placeholder of that page. If you're omitting the file, a javascript <em>'PageMethods is undefined'</em> error will be thrown on the browser.</p>
|
Where can I find information on code blocks? <p>Does anyone know a good website that summarises what you can do with code blocks (i.e. <% <%= <%# etc) in ASP.Net?</p>
<p>Thanks.</p>
| <p>Here is a MSDN page: <a href="http://msdn.microsoft.com/en-us/library/ms178135.aspx" rel="nofollow">MSDN Embedded Code Blocks</a></p>
<pre><code><% - any code
<%= - shortcut for Response.Write()
<%# - is for binding
<%-- - is for comments
</code></pre>
|
Converting letters to their greek equivalent in Javascript <p>I have some JSON data from a web service which gives me data like the following</p>
<pre><code>blah blah <greek>a</greek>
</code></pre>
<p>I need to be able to convert what is inside the greek tags into their symbol equivalent, using javascript.</p>
<p>Any ideas?</p>
| <p>There's no obvious generic way to do this, as there is no obvious relation. On the other hand, there is a finite set of greek characters. By extension that means there's a finite set of mappings. It should be trivial to find the ASCII character your JSON provider sends for each greek character. pre/postfix the tags forch each. Then, it's a simple search-and replace.</p>
|
When foo and bar is not enough <p>When you are using placeholder names when programming (not necessary variable names, but labels, mockup names, etc) and foo and bar is not enough, what do you use?</p>
<p>I guess <em>baz</em> is rather common as third name, and the <em>lorem ipsum</em> for longer texts. But then what?</p>
| <p>If an example is that complex, it would probably be easier to understand if you just used real variable names.</p>
|
Trying to find a simple way to do upload only modified files through FTP <p>Need to find a way to upload files to my server through FTP. But only the ones that have been modified.
Is there a simple way of doing that?
Command line ftp client or script is preferred.
Thanks, Jonas. </p>
| <p>The most reliable way would be to make md5 hashes of all the local files you care about and store it in a file. So the file will contain a list of filenames and their md5 hashes. Store that file on your ftp server. When you want to update the files on your ftp server, download the file containing the list, compare that against all your local files, and upload the files that have changed (or are new). That way you don't have to worry about archive bits, modified date, or looking at file sizes, the use of which can never be 100% reliable.</p>
<p>Using file sizes isn't reliable for the obvious reason - a file could change but have the same size. I'm not a fan of using the archive bit or modified date because either of those could be confused if you backup or restore your local directory with another backup program.</p>
|
What will be the lifespan of the .Net Framework? <p>Will it ever become obsolete?</p>
| <p>Yes, I'm sure it will become obsolete at some point. I think it's safe to assume our descendants won't be using it in 1000 years. Now, the more interesting question is <em>when</em> it becomes obsolete.</p>
<ul>
<li>5 years? Unlikely IMO.</li>
<li>10 years? Almost certainly still in use, but <em>possibly</em> not for new development; MS in "support but no new versions mode"? I <em>suspect</em> it will still be very much alive at that point, but I wouldn't be <em>totally</em> surprised if it had been eclipsed by something else. It partly depends on how Windows itself fares as a platform, I suspect.</li>
<li>20 years? I'd hope we've got better tools by then, but wouldn't be surprised to see significant maintenance development (including new versions of existing products) using the latest version of .NET at that point.</li>
</ul>
|
Display a map in a Windows Form app <p>I built a Winform app several months ago that schedules appointments for repair techs. I'd like to update the app by adding a map for the customer's address on the customer form, and then print that map on the report the techs take when they leave the office.</p>
<p>I've been looking around but I haven't found a good solution for this yet.</p>
<p>I currently have an address for the customer. What I'd like to do is submit the address to one of the popular online map sites and get a minimap of the locale. I can <em>almost</em> do this with Google maps using their embedded link feature. I can get the following HTML after adding an address to their website:</p>
<pre><code><iframe width="300" height="300" frameborder="0" scrolling="no"
marginheight="0" marginwidth="0"
src="http://maps.google.com/maps?hl=en&amp;ie=UTF8&amp;t=h&amp;g=1193+Presque+Isle+Dr,+Port+Charlotte,+FL+33952&amp;s=AARTsJqsWtjYwJ7ucpVS6UU2EInkRk6JLA&amp;ll=27.012108,-82.087955&amp;spn=0.005735,0.006437&amp;z=16&amp;output=embed">
</iframe>
</code></pre>
<p>My first plan was to simply parse this HTML and insert whichever customer's address was needed in place this address, then show the result in a browser object on the form. However, if I change the address in the above iframe Google gives me a "Your client does not have permission to get URL ..." message.</p>
<p>I have no preference on which map service I ultimately use, the important thing is that the solution can't have an associated expenses and its usable from Windows forms.</p>
<p>Anyone got an ideas/recommendations/resources on how to tackle this?</p>
<p><strong>Results</strong>:</p>
<p>I ended up using the control found <a href="http://www.codeplex.com/VEarthControl">here</a>. I find it an "okay" solution... it's tedious to get working as the code does not work as-is. I'm pretty stunned to find that none of the popular map APIs support winforms.</p>
| <p>There is <a href="http://www.koushikdutta.com/2008/07/virtual-earth-and-google-maps-tiled-map.html" rel="nofollow">some example code</a> for developing a map viewer control (NB: I doubt this is strictly within their licence)</p>
<p>Otherwise, depending on your budget, you could use the <a href="http://msdn.microsoft.com/en-us/cc905749.aspx" rel="nofollow">MapPoint ActiveX control</a></p>
|
What is the best way to get the minimum or maximum value from an Array of numbers? <p>Let's say I have an Array of numbers: <code>[2,3,3,4,2,2,5,6,7,2]</code></p>
<p>What is the best way to find the minimum or maximum value in that Array?</p>
<p>Right now, to get the maximum, I am looping through the Array, and resetting a variable to the value if it is greater than the existing value:</p>
<pre><code>var myArray:Array /* of Number */ = [2,3,3,4,2,2,5,6,7,2];
var maxValue:Number = 0;
for each (var num:Number in myArray)
{
if (num > maxValue)
maxValue = num;
}
</code></pre>
<p>This just doesn't seem like the best performing way to do this (I try to avoid loops whenever possible).</p>
| <p>The theoretical answers from everyone else are all neat, but let's be pragmatic. ActionScript provides the tools you need so that you don't even have to write a loop in this case!</p>
<p>First, note that <code>Math.min()</code> and <code>Math.max()</code> can take any number of arguments. Also, it's important to understand the <code>apply()</code> method available to <code>Function</code> objects. It allows you to pass arguments to the function using an <code>Array</code>. Let's take advantage of both:</p>
<pre><code>var myArray:Array = [2,3,3,4,2,2,5,6,7,2];
var maxValue:Number = Math.max.apply(null, myArray);
var minValue:Number = Math.min.apply(null, myArray);
</code></pre>
<p>Here's the best part: the "loop" is actually run using native code (inside Flash Player), so it's faster than searching for the minimum or maximum value using a pure ActionScript loop.</p>
|
Detecting whether a file is locked by another process (or indeed the same process) <p>This is how I do it at the moment. I try to open the file with the FileShare set to none. So I want exclusive accesss to the file. If I can't get that then its a good bet somebody else has the file locked.</p>
<p>There's got to be a better and faster way. Any ideas?</p>
<pre><code> try
{
using (FileStream fs = File.Open(GetLockFilename(), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fs.Close();
}
// The file is not locked
}
catch (Exception)
{
// The file is locked
}
</code></pre>
| <p>There is no need first to check if the file is locked and then access it, as between the check and the access some other process may still get a lock on the file. So, what you do is correct, if you succeed, do your work with the file.</p>
|
Is it possible for native class to consume .NET event? <p>Any idea how to initialize .NET delegate that points to method from 'mixed' class instance?</p>
<p>I have 'mixed' C++ class like this:</p>
<pre><code>class CppMixClass
{
public:
CppMixClass(void){
dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
}
~CppMixClass(void);
void UpdateState(System::Object^ sender, DotNetClass::StateEventArgs^ e){
//doSmth
}
}
</code></pre>
<p>DotNetClass is implemented in C#, and Method declaration is OK with delegate.
This line generates error:</p>
<pre><code>dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
error C2276: '&' : illegal operation on bound member function expression
</code></pre>
<p>Anyone have a clue about a problem?
Maybe coz CppMixClass class is not a pure .NET (ref) class?</p>
<p>I got this to work when UpdateHealthState is static method, but I need pointer to instance method.</p>
<p>I tried smth like:</p>
<pre><code>dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(this, &UpdateHealthState);
</code></pre>
<p>But this obviously doesn't work coz this is not pointer (handle) to .NET (ref) class, (System::Object).</p>
<p>ServiceStateEventHandler is defined in C# as:</p>
<pre><code>public delegate void ServiceStateEventHandler(object sender, ServiceStateEventArgs e);
</code></pre>
<p>Thanx for reading this :)</p>
| <p>I just found answer to this(of course by Nishant Sivakumar, man seems to have answers to all my C++/CLI interop related problems):</p>
<p><a href="http://www.codeproject.com/KB/mcpp/CppCliSupportLib.aspx?display=Print" rel="nofollow">http://www.codeproject.com/KB/mcpp/CppCliSupportLib.aspx?display=Print</a></p>
<p>Answer is located in "msclr/event.h" header, where macros for delegates in native classes are defined.</p>
<p>Nish's code is following:</p>
<pre><code>class Demo5
{
msclr::auto_gcroot<FileSystemWatcher^> m_fsw;
public:
// Step (1)
// Declare the delegate map where you map
// native method to specific event handlers
BEGIN_DELEGATE_MAP(Demo5)
EVENT_DELEGATE_ENTRY(OnRenamed, Object^, RenamedEventArgs^)
END_DELEGATE_MAP()
Demo5()
{
m_fsw = gcnew FileSystemWatcher("d:\\tmp");
// Step (2)
// Setup event handlers using MAKE_DELEGATE
m_fsw->Renamed += MAKE_DELEGATE(RenamedEventHandler, OnRenamed);
m_fsw->EnableRaisingEvents = true;
}
// Step (3)
// Implement the event handler method
void OnRenamed(Object^, RenamedEventArgs^ e)
{
Console::WriteLine("{0} -> {1}",e->OldName, e->Name);
}
};
</code></pre>
|
Is there a way to make "destructive" string methods a-la Ruby? <p>In Ruby, methods which change the object have a bang on the end: <code>string.downcase!</code></p>
<p>In c# you have to do: <code>foo = foo.ToLower()</code></p>
<p>Is there a way to make an extension method like:</p>
<p><code>foo.ConvertToLower()</code></p>
<p>that would manipulate <code>foo</code>?</p>
<p>(I think the answer is no since strings are immutable and you can't do a <code>ref this</code> in an extension method.)</p>
| <p>There are two ways of mutating a string instance:</p>
<ul>
<li>Reflection</li>
<li>Unsafe code</li>
</ul>
<p>I wouldn't recommend using either of them. Your fellow developers will hate you forever - particularly if the method is ever used to change a string which happens to be a literal...</p>
|
SQL Distinct by ID and Latest By Date <p>I have the following SQL Statement. I need to select the latest record for each System.Id using the System.RevisedDate</p>
<pre><code>SELECT [System.Id],[System.RevisedDate], [System.Title], [System.State], [System.Reason], [System.CreatedDate], [System.WorkItemType], [System.TeamProject],
[Microsoft.VSTS.Scheduling.RemainingWork], [Microsoft.VSTS.Scheduling.CompletedWork], [Microsoft.VSTS.CMMI.Estimate]
FROM WorkItems
WHERE ([System.WorkItemType] = 'Change Request') AND ([System.CreatedDate] >= '09/30/2008') AND ([System.TeamProject] NOT LIKE '%Deleted%') AND
([System.TeamProject] NOT LIKE '%Sandbox%')
</code></pre>
<p>Can you please help?</p>
| <p>Try this:</p>
<pre><code>SELECT * FROM WorkItems w
JOIN (
SELECT [System.Id],MAX([System.RevisedDate])
FROM WorkItems
WHERE ([System.WorkItemType] = 'Change Request')
AND ([System.CreatedDate] >= '09/30/2008')
AND ([System.TeamProject] NOT LIKE '%Deleted%')
AND ([System.TeamProject] NOT LIKE '%Sandbox%')
GROUP BY {System.Id]
) x ON w.[System.Id] = x.[System.Id] AND w.[System.DateRevised] = x.[System.DateRevised]
</code></pre>
|
Losing ODBC connection with SQL Server 2005 Database <p>One of our clients has an application (FoxPro 9) running on top of a SQL Server 2005 backend. Intermittently, they are losing their ODBC connection with the SQL Server database. Below is the initial error information:</p>
<blockquote>
<p>Err Msg: Connectivity error: [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionRead (recv()). </p>
<p>ODBC Err Msg: [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionRead (recv()). </p>
<p>SQL State: 01000 </p>
<p>ODBC Err No: 10054 </p>
<p>ODBC Handle: 1 </p>
<p>FoxPro Error No: 1526 </p>
</blockquote>
<p>We cannot duplicate this error on command. We have tried any number of solutions to no avail. One such hardware base solution which we found was described in: <a href="http://support.microsoft.com/kb/942861/en-us" rel="nofollow">http://support.microsoft.com/kb/942861/en-us</a> </p>
<p>I mention this because it almost perfectly matches what we have been seeing. However, we have implemented all the workarounds listed in that posting (and in this one <a href="http://support.microsoft.com/kb/948496" rel="nofollow">http://support.microsoft.com/kb/948496</a> ) - and the problem still continues. </p>
<p>This issue seems to show itself after the execution of long running queries, but we are not receiving any timeout errors, either from the application, or from SQL Server. I do not believe that this is the result of an idle timeout, because it sometimes occurs in the middle of an executing program.</p>
<p>I am not a hardware guy, but both the network, and the server (Windows Server 2003), appear to be fast and well designed. There are times however, when the database server is under significant stress.</p>
<p>If anyone has any suggestions on things we could try...please let us know!</p>
| <p>Just a shot in the dark, but have you tried running a trace and trying to capture error events as well as any tsql. This might provide some clues or help you to see a pattern.</p>
|
Abstracted References Between Entities <p>An upcoming project of mine is considering a design that involves (what I'm calling) "abstract entity references". It's quite a departure from a more common data model design, but it may be necessary to achieve the flexibility we want. I'm wondering if other architects have experience with systems like this and where the caveats are.</p>
<p>The project has a requirement for a to control access to various entities (logically: business objects; physically: database rows) by various people. For example, we might want to create rules like:</p>
<ul>
<li>User Alice is a member of Company Z</li>
<li>User Bob is the manager of Group Y, which has users Charlie, Dave, and Eve.</li>
<li>User Frank may enter data for [critical business object] X, and also the [critical business objects] in [critical business object group] U.</li>
<li>User George is not a member of Company T but may view the reports for Company T.</li>
</ul>
<p>The idea is that we have a lot of different securable objects, roles, groups, and permissions, and we want a system to handle this. Ideally this system would require little to no coding for new situations once it's launched; it should be very flexible.</p>
<p>In a "traditional" data design, we might have entities/tables like this:</p>
<ul>
<li>User</li>
<li>Company</li>
<li>User/Company Cross-Reference</li>
<li>UserGroup</li>
<li>User/UserGroup Cross-Reference</li>
<li>CBO ("Critical Business Object")</li>
<li>User/CBO Cross-Reference</li>
<li>CBOGroup</li>
<li>User/CBOGroup Cross-Reference</li>
<li>CBO/CBOGroup Cross-Reference</li>
<li>ReportAccess, which is a cross-reference between User and Company specifically for access to reports</li>
</ul>
<p>Note the big number of cross-reference tables. This system isn't terribly flexible as any time we want to add a new means of access we'd need to introduce a new cross-reference table; that, in turn, means additional coding.</p>
<p>The proposed system has all of the major entities (User, Company, CBO) reference a value in a new table called Entity. (In the code we'd probably make all of these entities subclasses of an Entity superclass). Then there's two additional tables that reference Entity
* Group, which is also an Entity "subclass".
* EntityRelation, which is a relation between two entities of any type (including Group). This will probably also have some sort of "Relationship Type" field to explain/qualify the relationship.</p>
<p>This system, at least at first glance, looks like it would meet a lot of our requirements. We might introduce new Entities down the road, but we'd never need to do additional tables to handle the grouping and relationships between these entities, because Group and EntityRelation can already handle that.</p>
<p>I'm concerned, however, whether this might not work very well in practice. The relationships between entities would become very complex and might be very hard for people (users and developers alike) to understand them. Also, they'd be very recursive; this would make things more difficult for our SQL-dependent report writing staff.</p>
<p>Does anyone have experiences with a similar system?</p>
| <p>I have a weird experience with this; which is as follows:</p>
<p>Architect/programmer designs extermely symmetrical, generic model that looks really really neat and is very tree-ish and recursive.</p>
<p>When it comes to user interface design the <em>customer</em> or <em>user</em> insists that real usage is much simpler and would be satisfied with these two simple screens (user/customer draws these on a blackboard for you as you listen).</p>
<p>At this stage I consistently find that the <em>solution</em> tends to get very bloated when the underlying model supports very general use cases that no-one really wants or needs. So my basic advice is to always listen very closesly to the customer and stick very close to what the real requirements are. Make sure your personal desires for neat structures are not the driving force here.</p>
<p>And yes, I have experienced this a multitude of times: In my most recent experience all the developers were absolutely sure that we were talking about a hierarchical tree structure. But the customer decidedly wanted this to be flat list-like structure in all regards. We had to go full circle (implement tree first, then list) before we caved in.</p>
<p>I'm not entirely sure about the generic model you suggest, but it has all the <em>smells</em> that set me off talking about overly generic models. I would in the least <em>always</em> be very sure to model <strong>both</strong> alternatives in full detail before selecting. </p>
|
C++ DLL: Not exposing the entire class <p>How can I "hide" parts of a class so that whoever is using the libary does not have to include headers for all the types used in my class. Ie take the MainWindow class below, ho can I have it so when compiled in a static/dynamic libary, whoever is useing the libary does NOT have to include windows.h, ie HWND, CRITICAL_SECTION, LRESULT, etc do not have to be defined.</p>
<p>I know I could split it into two classes, an abstract class with just the public interface, and an implementation class which is hidden that contains the members that require windows.h.</p>
<p>The problem here is that the visible class can no longer be created itsself, and an additional create function (eg CreateMainWindow) is required. That is fine in this case since it is most likly that just a single instance created on the heap is wanted but for other classes this is not.</p>
<pre><code>class MainWindow
{
HWND hwnd;
int width, height;
std::string caption;
bool started,exited;
bool closeRequest;
unsigned loopThread;
CRITICAL_SECTION inputLock;
Input *input;
public:
static void init_type();
Py::Object getattr(const char *name);
MainWindow(int width, int height, std::string caption);
~MainWindow();
bool CloseRequest(const Py::Tuple &args);
bool CloseRequestReset(const Py::Tuple &args);
HWND GetHwnd();
int GetWidth();
int GetHeight();
Input* GetInput();
protected:
unsigned static __stdcall loopThreadWrap(void *arg);
unsigned LoopThreadMain();
LRESULT WndProc(UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT static CALLBACK WndProcWrapper(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
};
</code></pre>
| <p>You can hide parts of a class using the so-called "cheshire cat", "letter/envelope", or "pimpl" technique (which are, all, different names for the same technique):</p>
<pre><code>class MainWindow
{
private:
//opaque data
class ImplementationDetails;
ImplementationDetails* m_data;
public:
... declare your public methods here ...
}
</code></pre>
<p>The best way is probably the abstract class mentioned in your 2nd paragraph (however I failed to understand your last sentence, in which you (tried/failed to) explain what your counter-argument to that is).</p>
|
How do you return a vector iterator from a variable in a templated class? <p>I'm trying to return an iterator for a vector in a templated class (I'm not sure if that makes a difference, but I've read that may, so I thought I'd mention it). The problem is that I get an error about C++ not supporting default-int when I try this. I've looked online and from what I can see in forums and explanaions, I don't think I'm <em>that</em> far off, it just won't compile.</p>
<pre><code>template<class T>
class Table
{
public:
...
vector<shared_ptr<vector<T>>>::iterator GetRowIterator();
//vector<shared_ptr<vector<CellValueType> > >::const_iterator GetRowIterator();
...
protected:
vector<shared_ptr<vector<CellValueType> > > data; //outside vector is rows, inside vector is columns
...
};
vector<shared_ptr<vector<T> > >::const_iterator Table<T>::GetRowIterator()
{
return data.begin();
}
</code></pre>
<p>The errors that I get are: </p>
<pre><code>error C2146: syntax error : missing ';' before identifier 'GetRowIterator'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
</code></pre>
<p><em>Edit:</em><br/>
Changed the end angle brackets so they are not as close together - same error.<br/><br/>
Any thoughts as to why this is occurring?<br/>
As always, thanks for advice/help in advance!</p>
| <p>Also remember to use typename when declaring the template-dependent return type:</p>
<pre><code>typename vector< shared_ptr< vector< T > > >::iterator GetRowIterator();
</code></pre>
<p>and the method definition</p>
<pre><code>typename vector< shared_ptr< vector< T > > >::const_iterator Table<T>::GetRowIterator()
{
return data.begin();
}
</code></pre>
<p>Notice also that when defining a template class method outside the class definition, you have to use the template keyword:</p>
<pre><code>template <class T> typename vector< shared_ptr< vector< T > > >::const_iterator Table<T>::GetRowIterator()
{
return data.begin();
}
</code></pre>
<p>So that the compiler can know what the T is about.</p>
|
How do I paint Swing Components to a PDF file with iText? <p>I would like to print my Swing JComponent via iText to pdf. </p>
<pre><code>JComponent com = new JPanel();
com.add( new JLabel("hello") );
PdfWriter writer = PdfWriter.getInstance( document, new FileOutputStream( dFile ) );
document.open( );
PdfContentByte cb = writer.getDirectContent( );
PdfTemplate tp = cb.createTemplate( pageImageableWidth, pageImageableHeight );
Graphics2D g2d = tp.createGraphics( pageImageableWidth, pageImageableHeight, new DefaultFontMapper( ) );
g2d.translate( pf.getImageableX( ), pf.getImageableY( ) );
g2d.scale( 0.4d, 0.4d );
com.paint( g2d );
cb.addTemplate( tp, 25, 200 );
g2d.dispose( );
</code></pre>
<p>Unfortunately nothing is shown in the PDF file.
Do you know how to solve this problem?</p>
| <p>I have figured it out adding addNotify and validate helps.</p>
<pre>
com.addNotify( );
com.validate( );
</pre>
|
PageMethod Not Updating - Requires Project Rebuild to be Updated <p>I am using the AJAX Toolkit:</p>
<pre><code> <ajaxToolkit:CascadingDropDown ID="CategoryDDL_C" runat="server" TargetControlID="CategoryDDL"
Category="Main" PromptText="Please select a category" LoadingText="[Loading...]"
ServiceMethod="MainDDL" />
</code></pre>
<p>And for the Service Method:</p>
<pre><code>[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] MainDDL(string knownCategoryValues, string category)
{
CascadingDropDownNameValue[] CDDNV = new CascadingDropDownNameValue[1] ;
CDDNV[0] = new CascadingDropDownNameValue(knownCategoryValues + "NO", "1");
return CDDNV;
}
</code></pre>
<p>However, if I make code changes in the MainDDL method, it is not reflected on the page until I do a Website Rebuild.</p>
<p>Any clues how I can update the Page Method without doing a full rebuild?</p>
| <p>Web <em>application</em> projects need to be recompiled when codebehind files change, web <em>site</em> projects do not. Which is yours?</p>
|
Is there a MVC pattern for C# in WPF <p>Is there a pattern where in WPF, I can build a simple UI form from an XML like definition file pulled from a database? </p>
<p>It would allow the user to enter data into this form, and submit it back. The data would be sent back in an XML structure that would closely/exactly mimic the UI definition. </p>
<p>The definition should include the data-type, and if it was a required value or not. I would then like to map these data-types and required values to Data Validation Rules, so the form could not be submitted unless it passes the check. </p>
<p>It should also handle the ability to have lists of repeating data.</p>
<p>I am in the planning stages of this project and have fairly good flexibility in the design at this point, though I am pretty sure I need to stick to the desktop, not web since I may be doing some Office Inter-op stuff as well.</p>
<p>What technology stack would you recommend? I think XMAL and WPF may be close to the answer. </p>
<p>I have also looked at <a href="http://www.mozilla.org/projects/xul" rel="nofollow">XUL</a>, but it doesn't seem ready or useful for C#. (Found this <a href="http://msdn.microsoft.com/en-us/magazine/cc188912.aspx" rel="nofollow">article</a> from MSDN in 2002)</p>
<p>Thank you,<br />
Keith</p>
| <p>Model View Presenter seems to suit WPF quite well, if you've not heard of it before check out the <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html" rel="nofollow">Supervisor Controller</a> pattern, which is a subset of MVP (the author has renamed it to <a href="http://martinfowler.com/eaaDev/SupervisingPresenter.html" rel="nofollow">Supervisor Controller</a> and <a href="http://martinfowler.com/eaaDev/PassiveScreen.html" rel="nofollow">Passive View</a> as two different flavours of MVP). It is a design principal that will help you promote the separation of concerns and works much better than MVC when you don't have a framework to physically enforce it.</p>
<p>You could always try to create a view engine for ASP.NET MVC that works with WPF though, that would be nice.</p>
|
Is there a DesignMode property in WPF? <p>In Winforms you can say </p>
<pre><code>if ( DesignMode )
{
// Do something that only happens on Design mode
}
</code></pre>
<p>is there something like this in WPF?</p>
| <p><strong>Indeed there is</strong>:</p>
<p><strong><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.designerproperties.getisindesignmode.aspx">System.ComponentModel.DesignerProperties.GetIsInDesignMode</a></strong></p>
<p>Example:</p>
<pre><code>using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
public class MyUserControl : UserControl
{
public MyUserControl()
{
if (DesignerProperties.GetIsInDesignMode(this))
{
// Design-mode specific functionality
}
}
}
</code></pre>
|
Using DateTime in a SqlParameter for Stored Procedure, format error <p>I'm trying to call a stored procedure (on a SQL 2005 server) from C#, .NET 2.0 using <code>DateTime</code> as a value to a <code>SqlParameter</code>. The SQL type in the stored procedure is 'datetime'.</p>
<p>Executing the sproc from SQL Management Studio works fine. But everytime I call it from C# I get an error about the date format. </p>
<p>When I run SQL Profiler to watch the calls, I then copy paste the <code>exec</code> call to see what's going on. These are my observations and notes about what I've attempted:</p>
<p>1) If I pass the <code>DateTime</code> in directly as a <code>DateTime</code> or converted to <code>SqlDateTime</code>, the field is surrounding by a PAIR of single quotes, such as</p>
<pre><code>@Date_Of_Birth=N''1/8/2009 8:06:17 PM''
</code></pre>
<p>2) If I pass the <code>DateTime</code> in as a string, I only get the single quotes</p>
<p>3) Using <code>SqlDateTime.ToSqlString()</code> does not result in a UTC formatted datetime string (even after converting to universal time)</p>
<p>4) Using <code>DateTime.ToString()</code> does not result in a UTC formatted datetime string.</p>
<p>5) Manually setting the <code>DbType</code> for the <code>SqlParameter</code> to <code>DateTime</code> does not change the above observations.</p>
<p>So, my questions then, is how on earth do I get C# to pass the properly formatted time in the <code>SqlParameter</code>? Surely this is a common use case, why is it so difficult to get working? I can't seem to convert <code>DateTime</code> to a string that is SQL compatable (e.g. '2009-01-08T08:22:45')</p>
<p><strong>EDIT</strong></p>
<p>RE: BFree, the code to actually execute the sproc is as follows:</p>
<pre><code>using (SqlCommand sprocCommand = new SqlCommand(sprocName))
{
sprocCommand.Connection = transaction.Connection;
sprocCommand.Transaction = transaction;
sprocCommand.CommandType = System.Data.CommandType.StoredProcedure;
sprocCommand.Parameters.AddRange(parameters.ToArray());
sprocCommand.ExecuteNonQuery();
}
</code></pre>
<p>To go into more detail about what I have tried:</p>
<pre><code>parameters.Add(new SqlParameter("@Date_Of_Birth", DOB));
parameters.Add(new SqlParameter("@Date_Of_Birth", DOB.ToUniversalTime()));
parameters.Add(new SqlParameter("@Date_Of_Birth",
DOB.ToUniversalTime().ToString()));
SqlParameter param = new SqlParameter("@Date_Of_Birth",
System.Data.SqlDbType.DateTime);
param.Value = DOB.ToUniversalTime();
parameters.Add(param);
SqlParameter param = new SqlParameter("@Date_Of_Birth",
SqlDbType.DateTime);
param.Value = new SqlDateTime(DOB.ToUniversalTime());
parameters.Add(param);
parameters.Add(new SqlParameter("@Date_Of_Birth",
new SqlDateTime(DOB.ToUniversalTime()).ToSqlString()));
</code></pre>
<p><strong>Additional EDIT</strong></p>
<p>The one I thought most likely to work:</p>
<pre><code>SqlParameter param = new SqlParameter("@Date_Of_Birth",
System.Data.SqlDbType.DateTime);
param.Value = DOB;
</code></pre>
<p>Results in this value in the exec call as seen in the SQL Profiler</p>
<pre><code>@Date_Of_Birth=''2009-01-08 15:08:21:813''
</code></pre>
<p>If I modify this to be:</p>
<pre><code>@Date_Of_Birth='2009-01-08T15:08:21'
</code></pre>
<p>It works, but it won't parse with pair of single quotes, and it wont convert to a <code>DateTime</code> correctly with the space between the date and time and with the milliseconds on the end.</p>
<p><strong>Update and Success</strong></p>
<p>I had copy/pasted the code above after the request from below. I trimmed things here and there to be concise. Turns out my problem was in the code I left out, which I'm sure any one of you would have spotted in an instant. I had wrapped my sproc calls inside a transaction. Turns out that I was simply not doing <code>transaction.Commit()</code>!!!!! I'm ashamed to say it, but there you have it.</p>
<p>I still don't know what's going on with the syntax I get back from the profiler. A coworker watched with his own instance of the profiler from his computer, and it returned proper syntax. Watching the very SAME executions from my profiler showed the incorrect syntax. It acted as a red-herring, making me believe there was a query syntax problem instead of the much more simple and true answer, which was that I need to commit the transaction! </p>
<p>I marked an answer below as correct, and threw in some up-votes on others because they did, after all, answer the question, even if they didn't fix my specific (brain lapse) issue.</p>
| <p>How are you setting up the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx"><code>SqlParameter</code></a>? You should set the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.sqldbtype.aspx"><code>SqlDbType</code> property</a> to <a href="http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx"><code>SqlDbType.DateTime</code></a> and then pass the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx"><code>DateTime</code></a> directly to the parameter (do NOT convert to a string, you are asking for a bunch of problems then).</p>
<p>You should be able to get the value into the DB. If not, here is a very simple example of how to do it:</p>
<pre><code>static void Main(string[] args)
{
// Create the connection.
using (SqlConnection connection = new SqlConnection(@"Data Source=..."))
{
// Open the connection.
connection.Open();
// Create the command.
using (SqlCommand command = new SqlCommand("xsp_Test", connection))
{
// Set the command type.
command.CommandType = System.Data.CommandType.StoredProcedure;
// Add the parameter.
SqlParameter parameter = command.Parameters.Add("@dt",
System.Data.SqlDbType.DateTime);
// Set the value.
parameter.Value = DateTime.Now;
// Make the call.
command.ExecuteNonQuery();
}
}
}
</code></pre>
<p>I think part of the issue here is that you are worried that the fact that the time is in UTC is not being conveyed to SQL Server. To that end, you shouldn't, because SQL Server doesn't know that a particular time is in a particular locale/time zone.</p>
<p>If you want to store the UTC value, then convert it to UTC before passing it to SQL Server (unless your server has the same time zone as the client code generating the <code>DateTime</code>, and even then, that's a risk, IMO). SQL Server will store this value and when you get it back, if you want to display it in local time, you have to do it yourself (which the <code>DateTime</code> struct will easily do).</p>
<p>All that being said, if you perform the conversion and then pass the converted UTC date (the date that is obtained by calling the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.touniversaltime.aspx"><code>ToUniversalTime</code> method</a>, not by converting to a string) to the stored procedure.</p>
<p>And when you get the value back, call the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.tolocaltime.aspx"><code>ToLocalTime</code> method</a> to get the time in the local time zone.</p>
|
Numbers of ways of Rendering in Qt <p>Can anyone please tell me how many ways are there to render a screen in Qt.Like Show() , QDirectPainter etc...</p>
| <p>Qt is double buffered. So, you would use update() to request a screen redraw. Another perspective would be to enumerate the backends in Qt - and this varies on different platforms. E.g. for Windows you can use raster, OpenGL or Direct3D. In Qt 4.5 a new graphics system is introduced, where you can specify that <em>all</em> rendering should be done using one of native, raster, opengl. See also <a href="http://labs.trolltech.com/blogs/2008/10/22/so-long-and-thanks-for-the-blit/" rel="nofollow">So Long and Thanks for the Blit!</a></p>
|
Django on IronPython <p>I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success? </p>
<p>If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?</p>
| <p>Besides the Jeff Hardy blog post on <a href="http://jdhardy.blogspot.com/2008/12/django-ironpython.html">Django + IronPython</a> mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy_install and zlib. The first is <a href="http://jdhardy.blogspot.com/2008/12/solving-zlib-problem-ironpythonzlib.html">Solving the zlib problem</a> which discusses the absence of zlib for IronPython; hence, no easyinstall. Jeff reimplemented zlib based on ComponentAce's zlib.net. And finally, in <a href="http://jdhardy.blogspot.com/2008/12/easyinstall-on-ironpython-part-deux.html">easy_install on IronPython, Part Deux</a> Jeff discusses some final tweaks that are needed before easy_install can be used with IronPython.</p>
|
ASP.NET Controller Base Class User.Identity.Name <p>As described in <a href="http://www.asp.net/Learn/mvc/tutorial-13-cs.aspx" rel="nofollow">this post</a>, I created an abstract base controller class in order to be able to pass data from a controller to master.page. In this case, I want to lookup a user in my db, querying for User.Identity.Name (only if he is logged in).</p>
<p>However, I noticed that in this abstract base class the <code>User</code> property is always <code>null</code>. What do I have to do to get this working?</p>
<p>Thanks a lot</p>
| <p>As Paco suggested, the viewdata isn't initialized till after you are trying to use it.</p>
<p>Try overriding Controller.Initialize() instead:</p>
<pre><code>public abstract class ApplicationController : Controller
{
private IUserRepository _repUser;
public ApplicationController()
{
}
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
_repUser = RepositoryFactory.getUserRepository();
var loggedInUser = _repUser.FindById(User.Identity.Name);
ViewData["LoggedInUser"] = loggedInUser;
}
}
</code></pre>
|
Is it advantageous to use threads in windows? <p>Some of the fellows in the office think that when they've added threads to their code that windows will assign these threads to run on different processors of a multi-core or multi-processor machine. Then when this doesn't happen everything gets blamed on the existence of these threads colliding with one another on said multi-core or multi-processor machine. </p>
<p>Could someone debunk or confirm this notion?</p>
| <p>When an application spawns multiple threads, it is indeed possible for them to get assigned to different processors. In fact, it is not uncommon for incorrect multi-threaded code to run ok on a single-processor machine but then display problems on a multi-processor machine. (This happens if the code is safe in the face of time slicing but broken in the face of true concurrency.)</p>
|
IIS6 is not finding .asp files <p>Hoping someone can provide an answer with this, although it's not 100% programming related. All of a sudden my IIS6 install on Server 2003 will give me a "404 Not Found" error when I try to load any file ending in .asp. </p>
<p>I can see the file there if I turn on directory browsing, but clicking on it immediately gives me a 404. Regular HTML pages load just fine, it's only the ASP files that it cannot find, although they're right in the directory alongside the HTML file.</p>
<p>I'm probably forgetting something stupid - can someone remind me what I need to do in order to get it to load properly?</p>
| <p>In the Web Service Extensions area, make sure Active Server Pages is enabled</p>
|
Visual Studio Shortcut for Automatically Creating Constructors from an Inherited Class <p>Say I am inheriting from a class with several "overloaded" constructors.</p>
<p>By any chance is there a short cut in Visual Studio which writes the constructors in the derived class with the same signatures as in the default class for me, with boilerplate code which calls MyBase.New(...) and plugs in the arguments for me?</p>
<p>EDIT: As far as I can find there is no such shortcut built-in, however there is one in resharper as suggested by Raymond.</p>
| <p>I don't know about a shortcut in a standard Visual Studio installation, but if you install the excellent Resharper plugin from jetBrains, it is Alt-Insert, C. I don't develop without it.</p>
|
What is the LD_PRELOAD trick? <p>I came across a reference to it recently on <a href="http://www.reddit.com/r/programming/comments/7o8d9/tcmalloca_faster_malloc_than_glibcs_open_sourced/c06wjka">proggit</a> and (as of now) it is not explained.</p>
<p>I suspect <a href="http://stackoverflow.com/questions/335108/hide-symbols-in-shared-object-from-ld#335253">this</a> might be it, but I don't know for sure.</p>
| <p>If you set <code>LD_PRELOAD</code> to the path of a shared object, that file will be loaded <strong>before</strong> any other library (including the C runtime, <code>libc.so</code>). So to run <code>ls</code> with your special <code>malloc()</code> implementation, do this:</p>
<pre><code>$ LD_PRELOAD=/path/to/my/malloc.so /bin/ls
</code></pre>
|
How do you post data with a link <p>I have a database which holds the residents of each house in a certain street. I have a 'house view' php web page which can display an individual house and residents when given the house number using 'post'. I also have a 'street view' web page which gives a list of houses. What I want to know is if you can have links on the street view which will link to the house view and post the house number at the same time without setting up a form for each?</p>
<p>Regards</p>
| <p>If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:</p>
<pre><code>function formSubmit(house_number)
{
document.forms[0].house_number.value = house_number;
document.forms[0].submit();
}
</code></pre>
<p>Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:</p>
<pre><code><form action="house.php" method="POST">
<input type="hidden" name="house_number" value="-1">
<?php
foreach ($houses as $id => name)
{
echo "<a href=\"javascript:formSubmit($id);\">$name</a>\n";
}
?>
</form>
</code></pre>
<p>That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavasScript submits the form.</p>
|
Seeding java.util.Random with consecutive numbers <p>I've simplified a bug I'm experiencing down to the following lines of code:</p>
<pre><code> int[] vals = new int[8];
for (int i = 0; i < 1500; i++)
vals[new Random(i).nextInt(8)]++;
System.out.println(Arrays.toString(vals));
</code></pre>
<p>The output is: [0, 0, 0, 0, 0, 1310, 190, 0]</p>
<p>Is this just an artifact of choosing consecutive numbers to seed Random and then using nextInt with a power of 2? If so, are there other pitfalls like this I should be aware of, and if not, what am I doing wrong? (I'm not looking for a solution to the above problem, just some understanding about what else could go wrong)</p>
<p><hr /></p>
<p>Dan, well-written analysis. As the javadoc is pretty explicit about how numbers are calculated, it's not a mystery as to why this happened as much as if there are other anomalies like this to watch out for-- I didn't see any documentation about consecutive seeds, and I'm hoping someone with some experience with java.util.Random can point out other common pitfalls.</p>
<p>As for the code, the need is for several parallel agents to have repeatably random behavior who happen to choose from an enum 8 elements long as their first step. Once I discovered this behavior, the seeds all come from a master Random object created from a known seed. In the former (sequentially-seeded) version of the program, all behavior quickly diverged after that first call to nextInt, so it took quite a while for me to narrow the program's behavior down to the RNG library, and I'd like to avoid that situation in the future.</p>
| <p>As much as possible, the seed for an RNG should itself be random. The seeds that you are using are only going to differ in one or two bits.</p>
<p>There's very rarely a good reason to create two separate RNGs in the one program. Your code is not one of those situations where it makes sense.</p>
<p>Just create one RNG and reuse it, then you won't have this problem.</p>
<p><strong>In response to comment from <a href="http://stackoverflow.com/users/13531/mmyers">mmyers</a>:</strong></p>
<blockquote>
<p>Do you happen to know java.util.Random
well enough to explain why it picks 5
and 6 in this case?</p>
</blockquote>
<p>The answer is in the source code for java.util.Random, which is a <a href="http://en.wikipedia.org/wiki/Linear_congruential_generator">linear congruential RNG</a>. When you specify a seed in the constructor, it is manipulated as follows.</p>
<pre><code>seed = (seed ^ 0x5DEECE66DL) & mask;
</code></pre>
<p>Where the mask simply retains the lower 48 bits and discards the others.</p>
<p>When generating the actual random bits, this seed is manipulated as follows:</p>
<pre><code>randomBits = (seed * 0x5DEECE66DL + 0xBL) & mask;
</code></pre>
<p>Now if you consider that the seeds used by <a href="http://stackoverflow.com/users/42562/parker">Parker</a> were sequential (0 -1499), and they were used once then discarded, the first four seeds generated the following four sets of random bits:</p>
<pre><code>101110110010000010110100011000000000101001110100
101110110001101011010101011100110010010000000111
101110110010110001110010001110011101011101001110
101110110010011010010011010011001111000011100001
</code></pre>
<p>Note that the top 10 bits are indentical in each case. This is a problem because he only wants to generate values in the range 0-7 (which only requires a few bits) and the RNG implementation does this by shifting the higher bits to the right and discarding the low bits. It does this because in the general case the high bits are more random than the low bits. In this case they are not because the seed data was poor.</p>
<p>Finally, to see how these bits convert into the decimal values that we get, you need to know that java.util.Random makes a special case when n is a power of 2. It requests 31 random bits (the top 31 bits from the above 48), multiplies that value by n and then shifts it 31 bits to the right.</p>
<p>Multiplying by 8 (the value of n in this example) is the same as shifting left 3 places. So the net effect of this procedure is to shift the 31 bits 28 places to the right. In each of the 4 examples above, this leaves the bit pattern 101 (or 5 in decimal).</p>
<p>If we didn't discard the RNGs after just one value, we would see the sequences diverge. While the four sequences above all start with 5, the second values of each are 6, 0, 2 and 4 respectively. The small differences in the initial seeds start to have an influence.</p>
<p><strong>In response to the updated question:</strong> <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html">java.util.Random</a> is thread-safe, you can share one instance across multiple threads, so there is still no need to have multiple instances. If you <em>really</em> have to have multiple RNG instances, make sure that they are seeded <em>completely independently</em> of each other, otherwise you can't trust the outputs to be independent.</p>
<p>As to why you get these kind of effects, java.util.Random is not the best RNG. It's simple, pretty fast and, if you don't look too closely, reasonably random. However, if you run some <a href="http://stat.fsu.edu/~geo/">serious tests</a> on its output, you'll see that it's flawed. You can see that visually <a href="http://www.alife.co.uk/nonrandom/">here</a>.</p>
<p>If you need a more random RNG, you can use <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/security/SecureRandom.html">java.security.SecureRandom</a>. It's a fair bit slower, but it works properly. One thing that might be a problem for you though is that it is not repeatable. Two SecureRandom instances with the same seed won't give the same output. This is by design.</p>
<p>So what other options are there? This is where I plug <a href="https://uncommons-maths.dev.java.net/">my own library</a>. It includes 3 repeatable pseudo-RNGs that are faster than SecureRandom and more random than java.util.Random. I didn't invent them, I just ported them from the original C versions. They are all thread-safe.</p>
<p>I implemented these RNGs because I needed something better for <a href="https://watchmaker.dev.java.net/">my evolutionary computation code</a>. In line with my original brief answer, this code is multi-threaded but it only uses a single RNG instance, shared between all threads.</p>
|
What is the best way to call a .net webservice using jquery? <p>I'd like to call a .net webservice from another domain using only jquery.</p>
<p>What is the best way to do this? and are there any configuration changes I need to be aware of on the web site hosting the web page?</p>
<p>The reason I ask this, is that I am only marginally in control of that area.
So I can only make limited changes.</p>
| <p>The browser does not allow XMLHTTPRequest calls across domains in its default configuration. You can change browser settings to make certain calls succeed, but this is considered bad practice.</p>
<p>In order to perform cross-domain requests, you can </p>
<ul>
<li><p><a href="http://dotnetslackers.com/columns/ajax/MashitUpwithASPNETAJAX.aspx" rel="nofollow">Use the local server as a proxy to
a remote server</a></p>
<p>This example uses a local ASP.NET Web Service to make a call to the Yahoo! Geocode service </p></li>
<li><p><a href="http://www.codeproject.com/KB/ajax/FlickrSpell.aspx" rel="nofollow">Use a bridge</a></p>
<p>This example demonstrates how to create a bridge to <a href="http://www.flickr.com/" rel="nofollow">flickr</a> through the flickr API.</p></li>
</ul>
|
How do I mock the Python method OptionParser.error(), which does a sys.exit()? <p>I'm trying to unit test some code that looks like this:</p>
<pre><code>def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
</code></pre>
<p>With code that looks like this:</p>
<pre><code>@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
</code></pre>
<p>I'm using <a href="http://www.voidspace.org.uk/python/mock.html">Michael Foord's Mock</a>, and nose to run the tests.</p>
<p>When I run the test, I get:</p>
<pre><code> File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
</code></pre>
<p>The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.</p>
<p>I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?</p>
<p><strong>Update</strong>: <a href="http://stackoverflow.com/users/3002/df">df</a>'s answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".</p>
<p>Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?</p>
<p>BTW, the test is more robust if I add:</p>
<pre><code>self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
</code></pre>
<p>at the end.</p>
<p><strong>Update 2</strong>: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:</p>
<pre><code>try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
</code></pre>
| <p>Will this work instead of <code>assertEquals</code>?</p>
<pre><code>self.assertRaises(SystemExit, sut.main, 2)
</code></pre>
<p>This should catch the <code>SystemExit</code> exception and prevent the script from terminating.</p>
|
How to create custom MouseEvent.CLICK event in AS3 (pass parameters to function)? <p>This question doesn't relate only to MouseEvent.CLICK event type but to all event types that already exist in AS3. I read a lot about custom events but until now I couldn't figure it out how to do what I want to do. I'm going to try to explain, I hope you understand:</p>
<p>Here is a illustration of my situation:</p>
<pre><code>for(var i:Number; i < 10; i++){
var someVar = i;
myClips[i].addEventListener(MouseEvent.CLICK, doSomething);
}
function doSomething(e:MouseEvent){ /* */ }
</code></pre>
<p>But I want to be able to pass <em>someVar</em> as a parameter to <em>doSomething</em>. So I tried this:</p>
<pre><code>for(var i:Number; i < 10; i++){
var someVar = i;
myClips[i].addEventListener(MouseEvent.CLICK, function(){
doSomething(someVar);
});
}
function doSomething(index){ trace(index); }
</code></pre>
<p>This kind of works but not as I expect. Due to the function closures, when the MouseEvent.CLICK events are actually fired the <em>for</em> loop is already over and <em>someVar</em> is holding the last value, the number <em>9</em> in the example. So every click in each movie clip will call <em>doSomething</em> passing <em>9</em> as the parameter. And it's not what I want.</p>
<p>I thought that creating a custom event should work, but then I couldn't find a way to fire a custom event when the MouseEvent.CLICK event is fired and pass the parameter to it. Now I don't know if it is the right answer.</p>
<p>What should I do and how?</p>
| <p>You really need to extend the event class to create your own event with extra parameters. Placing functions inside the addEventListener (anonymous functions) is a recipe for memory leaks, which is not good.
Take a look at the following.</p>
<pre><code>import flash.events.Event;
//custom event class to enable the passing of strings along with the actual event
public class TestEvent extends Event
{
public static const TYPE1 :String = "type1";
public static const TYPE2 :String = "type2";
public static const TYPE3 :String = "type3";
public var parameterText:String;
public function TestEvent (type:String, searchText:String)
{
this.parameterText = searchText;
super(type);
}
}
</code></pre>
<p>when you create a new event such as</p>
<pre><code>dispatchEvent(new TestEvent(TestEvent.TYPE1, 'thisIsTheParameterText'))" ;
</code></pre>
<p>you can then listen for that event like this</p>
<pre><code>someComponent.addEventListener(TestEvent.TYPE1, listenerFunction, true , 0, true);
</code></pre>
<p>and inside the function 'listenerFunction' event.parameterText will contain your parameter.</p>
<p>so inside your myClips component you would fire off the custom event and listen for that event and not the Click event.</p>
|
Curing the "Back Button Blues" <p>Ever stumbled on a tutorial that you feel is of great value but not quite explained properly? That's my dilemma. I know <a href="http://www.tonymarston.net/php-mysql/backbuttonblues.html" rel="nofollow">THIS TUTORIAL</a> has some value but I just can't get it. </p>
<ol>
<li>Where do you call each function?</li>
<li>Which function should be called
first and which next, and which
third?</li>
<li>Will all functions be called in all files in an application?</li>
<li>Does anyone know of a better way cure the "Back Button Blues"?</li>
</ol>
<p>I'm wondering if this will stir some good conversation that includes the author of the article. The part I'm particularly interested in is controlling the back button in order to prevent form duplicate entries into a database when the back button is pressed. Basically, you want to control the back button by calling the following three functions during the execution of the scripts in your application. In what order exactly to call the functions (see questions above) is not clear from the tutorial.</p>
<blockquote>
<p>All forwards movement is performed by
using my scriptNext function. This is
called within the current script in
order to activate the new script.</p>
<pre><code>function scriptNext($script_id)
// proceed forwards to a new script
{
if (empty($script_id)) {
trigger_error("script id is not defined", E_USER_ERROR);
} // if
// get list of screens used in this session
$page_stack = $_SESSION['page_stack'];
if (in_array($script_id, $page_stack)) {
// remove this item and any following items from the stack array
do {
$last = array_pop($page_stack);
} while ($last != $script_id);
} // if
// add next script to end of array and update session data
$page_stack[] = $script_id;
$_SESSION['page_stack'] = $page_stack;
// now pass control to the designated script
$location = 'http://' .$_SERVER['HTTP_HOST'] .$script_id;
header('Location: ' .$location);
exit;
} // scriptNext
</code></pre>
<p>When any script has finished its
processing it terminates by calling my
scriptPrevious function. This will
drop the current script from the end
of the stack array and reactivate the
previous script in the array.</p>
<pre><code>function scriptPrevious()
// go back to the previous script (as defined in PAGE_STACK)
{
// get id of current script
$script_id = $_SERVER['PHP_SELF'];
// get list of screens used in this session
$page_stack = $_SESSION['page_stack'];
if (in_array($script_id, $page_stack)) {
// remove this item and any following items from the stack array
do {
$last = array_pop($page_stack);
} while ($last != $script_id);
// update session data
$_SESSION['page_stack'] = $page_stack;
} // if
if (count($page_stack) > 0) {
$previous = array_pop($page_stack);
// reactivate previous script
$location = 'http://' .$_SERVER['HTTP_HOST'] .$previous;
} else {
// no previous scripts, so terminate session
session_unset();
session_destroy();
// revert to default start page
$location = 'http://' .$_SERVER['HTTP_HOST'] .'/index.php';
} // if
header('Location: ' .$location);
exit;
} // scriptPrevious
</code></pre>
<p>Whenever a script is activated, which
can be either through the scriptNext
or scriptPrevious functions, or
because of the BACK button in the
browser, it will call the following
function to verify that it is the
current script according to the
contents of the program stack and take
appropriate action if it is not.</p>
<pre><code>function initSession()
// initialise session data
{
// get program stack
if (isset($_SESSION['page_stack'])) {
// use existing stack
$page_stack = $_SESSION['page_stack'];
} else {
// create new stack which starts with current script
$page_stack[] = $_SERVER['PHP_SELF'];
$_SESSION['page_stack'] = $page_stack;
} // if
// check that this script is at the end of the current stack
$actual = $_SERVER['PHP_SELF'];
$expected = $page_stack[count($page_stack)-1];
if ($expected != $actual) {
if (in_array($actual, $page_stack)) {// script is within current stack, so remove anything which follows
while ($page_stack[count($page_stack)-1] != $actual ) {
$null = array_pop($page_stack);
} // while
$_SESSION['page_stack'] = $page_stack;
} // if
// set script id to last entry in program stack
$actual = $page_stack[count($page_stack)-1];
$location = 'http://' .$_SERVER['HTTP_HOST'] .$actual;
header('Location: ' .$location);
exit;
} // if
... // continue processing
} // initSession
</code></pre>
<p>The action taken depends on whether
the current script exists within the
program stack or not. There are three
possibilities:</p>
<ul>
<li>The current script is not in the $page_stack array, in which case it is
not allowed to continue. Instead it is
replaced by the script which is at the
end of the array.</li>
<li>The current script is in the
$page_stack array, but it is not the
last entry. In this case all
following entries in the array are
removed.</li>
<li>The current script is the last entry
in the $page_stack array. This is
the expected situation. Drinks all
round!</li>
</ul>
</blockquote>
| <p>That is a good discussion but more to the point you should be looking into Post Redirect Get (PRG) also known as "Get after Post."</p>
<p><a href="http://www.theserverside.com/patterns/thread.tss?thread_id=20936" rel="nofollow">http://www.theserverside.com/patterns/thread.tss?thread_id=20936</a></p>
|
Where do you edit the constructor template on resharper 4.1? <p>When I create a constructor with parameters using Resharper's 'Generate code' feature, I get something like this:</p>
<pre><code>public class Example{
private int _x;
private int _y;
public Example(int _x, int _y){
this._x = _x;
this._y = _y;
}
}
</code></pre>
<p>I would like to use this naming convention instead:</p>
<pre><code>public class Example{
private int _x;
private int _y;
public Example(int x, int y){
_x = x;
_y = y;
}
}
</code></pre>
<p>but I don't know if it's possible to edit this constructor template and where.</p>
| <p>Options / Languages / Common / Naming Style
You should set your field prefix to underscore.</p>
|
How do I start a Storyboard in a Data Template in a Content Control in a User Control from codebehind? <p>PHEW.</p>
<p>I'm serious. I'll spell it out as follows...</p>
<p>The Storyboard has a Key "myStoryboard". It's held in a DataTemplate with a key "myDataTemplate".</p>
<p>This data template is used in a ContentControl with the name "myContentControl" by this tag:</p>
<pre><code><ContentControl Name="myContentControl"
ContentTemplate="{DynamicResource myDataTemplate}"/>
</code></pre>
<p>The content control is used in my UserControl. In the UserControl codebehind I've made a keyboard gesture that supposed to start "myStoryBoard" but i'm having no such luck getting to it. </p>
<pre><code>private void StartSB(object sender, ExecutedRoutedEventArgs e)
{
Storyboard sb = (Storyboard) this.TryFindResource("myStoryboard");
sb.Begin(this);
}
</code></pre>
<p>sb is always null here. How can i get the Storyboard?</p>
<p>UPDATE:</p>
<p>so playing with TryFindResource() I've managed to get to myDataTemplate</p>
<pre><code>private void StartSB(object sender, ExecutedRoutedEventArgs e)
{
object sb = this.myContentControl.TryFindResource("myDataTemplate");
}
</code></pre>
<p>in the Locals viewer I can see sb is myDataTemplate. I can see in the tree sb.base.Resources.Keys which is an array of resources in which "myStoryboard" is inside. Oh so close! </p>
<p>UPDATE2:</p>
<p>More code complete here. I realize now this may be too spaghettified to explain with words. </p>
<pre><code><UserControl >
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources\myUCResources.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<ContentControl Name="myContentControl"
ContentTemplate="{DynamicResource myDataTemplate}"
Content="{Binding}" />
...
</UserControl>
</code></pre>
<p>now the codebehind for this User control</p>
<pre><code>namespace myclass
{
public partial class myUserControl: UserControl, System.ComponentModel.INotifyPropertyChanged
{
...
public myUserControl()
{
InitializeComponent();
<!--setup keybinding-->
}
public void KeyBindExecuted(object sender, ExecutedRoutedEventArgs e)
{
Object sb = this.myContentControl.TryFindResource("myDataTemplate");
//sb returns the DataTemplate
}
}
}
</code></pre>
<p>And finally the resource dictionary containing the UI stuff and the animation I ultimately want to trigger. (myUCResources.xaml)</p>
<pre><code><ResourceDictionary>
<DataTemplate x:Key="myDataTemplate" >
<Grid>
<!-- elements like buttons -->
</Grid>
<DataTemplate.Resources>
<Storyboard x:Key="myStoryBoard">
<DoubleAnimation>
<!-- animation stuff-->
</DoubleAnimation>
</Storyboard>
</DataTemplate.Resources>
<DataTemplate.Triggers>
<EventTrigger SourceName="aButton" RoutedEvent="Button.Click">
<BeginStoryboard Storyboard="{StaticResource myStoryBoard}" />
</EventTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ResourceDictionary>
</code></pre>
<p>Update 3: </p>
<p>ok different approach. Can I use the EventTrigger in the DataTemplate from the codebehind to start the animation?</p>
| <p>AH HAH!</p>
<p>So I found a roundabout way to solving this. My third update where I entertained the thought of just firing an event seemed more fruitful. All can be found here.</p>
<p><a href="http://www.codeproject.com/script/Forums/View.aspx?fid=1004114&msg=2827455" rel="nofollow">http://www.codeproject.com/script/Forums/View.aspx?fid=1004114&msg=2827455</a></p>
<p>In a nutshell I used FindResource to get the DataTemplate, then FindName of the button in the DataTemplate used to normally trigger the animation. Then I raised a button click on that button.</p>
|
Data structure or algorithm for second degree lookups in sub-linear time? <p>Is there any way to select a subset from a large set based on a property or predicate in less than <code>O(n)</code> time?</p>
<p>For a simple example, say I have a large set of authors. Each author has a one-to-many relationship with a set of books, and a one-to-one relationship with a city of birth.</p>
<p>Is there a way to efficiently do a query like "get all books by authors who were born in Chicago"? The only way I can think of is to first select all authors from the city (fast with a good index), then iterate through them and accumulate all their books (<code>O(n)</code> where <code>n</code> is the number of authors from Chicago).</p>
<p>I know databases do something like this in certain joins, and Endeca claims to be able to do this "fast" using what they call "Record Relationship Navigation", but I haven't been able to find anything about the actual algorithms used or even their computational complexity.</p>
<p>I'm not particularly concerned with the exact data structure... I'd be jazzed to learn about how to do this in a <a href="https://en.wikipedia.org/wiki/Relational_database_management_system" rel="nofollow">RDBMS</a>, or a key/value repository, or just about anything.</p>
<p>Also, what about third or fourth degree requests of this nature? (Get me all the books written by authors living in cities with immigrant populations greater than 10,000...) Is there a generalized n-degree algorithm, and what is its performance characteristics?</p>
<p><strong>Edit:</strong></p>
<p>I am probably just really dense, but I don't see how the inverted index suggestion helps. For example, say I had the following data:</p>
<pre><code>DATA
1. Milton England
2. Shakespeare England
3. Twain USA
4. Milton Paridise Lost
5. Shakespeare Hamlet
6. Shakespeare Othello
7. Twain Tom Sawyer
8. Twain Huck Finn
INDEX
"Milton" (1, 4)
"Shakespeare" (2, 5, 6)
"Twain" (3, 7, 8)
"Paridise Lost" (4)
"Hamlet" (5)
"Othello" (6)
"Tom Sawyer" (7)
"Huck Finn" (8)
"England" (1, 2)
"USA" (3)
</code></pre>
<p>Say I did my query on "books by authors from England". Very quickly, in <code>O(1)</code> time via a hashtable, I could get my list of authors from England: <code>(1, 2)</code>. But then, for the next step, in order retrieve the books, I'd have to, for EACH of the set <code>{1, 2}</code>, do ANOTHER <code>O(1)</code> lookup: <code>1 -> {4}, 2 -> {5, 6}</code> then do a union of the results <code>{4, 5, 6}</code>.</p>
<p>Or am I missing something? Perhaps you meant I should explicitly store an index entry linking Book to Country. That works for very small data sets. But for a large data set, the number of indexes required to match any possible combination of queries would make the index grow exponentially. </p>
| <p>For joins like this on large data sets, a modern RDBMS will often use an algorithm called a <strong>list merge</strong>. Using your example:</p>
<ol>
<li>Prepare a list, A, of all authors who live in Chicago and sort them by author in O(Nlog(N)) time.*</li>
<li>Prepare a list, B, of all (author, book name) pairs and sort them by author in O(Mlog(M)) time.*</li>
<li>Place these two lists "side by side", and compare the authors from the "top" (lexicographically minimum) element in each pile.
<ul>
<li>Are they the same? If so:
<ul>
<li>Output the (author, book name) pair from <code>top(B)</code></li>
<li>Remove the top element of the B pile</li>
<li>Goto 3.</li>
</ul></li>
<li>Otherwise, is <code>top(A).author</code> < <code>top(B).author</code>? If so:
<ul>
<li>Remove the top element of the A pile</li>
<li>Goto 3.</li>
</ul></li>
<li>Otherwise, it must be that <code>top(A).author</code> > <code>top(B).author</code>:
<ul>
<li>Remove the top element of the B pile</li>
<li>Goto 3.</li>
</ul></li>
</ul></li>
</ol>
<p>* (Or O(0) time if the table is already sorted by author, or has an index which is.)</p>
<p>The loop continues removing one item at a time until both piles are empty, thus taking O(N + M) steps, where N and M are the sizes of piles A and B respectively. Because the two "piles" are sorted by author, this algorithm will discover every matching pair. It does not require an index (although the presence of indexes may remove the need for one or both sort operations at the start).</p>
<p>Note that the RDBMS may well choose a different algorithm (e.g. the simple one you mentioned) if it estimates that it would be faster to do so. The RDBMS's query analyser generally estimates the costs in terms of disk accesses and CPU time for many thousands of different approaches, possibly taking into account such information as the statistical distributions of values in the relevant tables, and selects the best.</p>
|
What is the easiest way to export data from a live google app engine application? <p>I'm especially interested in solutions with source code available (django independency is a plus, but I'm willing to hack my way through)</p>
| <p>You can, of course, write your own handler. Other than that, your options currently are limited to:</p>
<ul>
<li><a href="http://github.com/fczuardi/gae-rest/tree/master">gae-rest</a>, which provides a RESTful interface to the datastore.</li>
<li><a href="http://code.google.com/p/approcket/">approcket</a>, a tool for replicating between MySQL and App Engine.</li>
<li>The amusingly named <a href="http://aralbalkan.com/1784">GAEBAR</a> - Google App Engine Backup and Restore.</li>
</ul>
|
Is Drupal ready for the enterprise? <p>Is anyone out there using Drupal for large scale, business critical enterprise applications?</p>
<p>Does Drupal's lack of database transaction support dissuade potential users?</p>
<p>Are there any other lightweight web-frameworks based on dynamic languages that people are using for these types of apps? What about Java portals such as JBossPortal or Jetspeed as an alternative or a Drupal + J2EE hybrid architecture?</p>
| <p><strong>Answer One: Yes</strong></p>
<ul>
<li>internet_search://"drupal in the enterprise" <- use this exact phrase</li>
<li><a href="http://drupal.org/success-stories">Drupal "Success Stories"</a></li>
<li><a href="http://drupal.org/node/314624">Student Activities Supports 170 Drupal 6 Sites at Texas A&M</a></li>
</ul>
<p><strong>Answer Two: It depends</strong></p>
<p>There are surely some who have concerns about this issue. Drupal's database support and schema have been subject to some scrutiny and criticism over its evolution. That is likely to diminish if some or all of the planned enhancements make it into Drupal 7. This is the one out of your three questions that cannot be easily and definitively answered by searching the internet.</p>
<ul>
<li><a href="http://www.garfieldtech.com/blog/drupal-7-database-plans">Drupal 7 Database Plans</a></li>
<li><a href="http://www.garfieldtech.com/blog/database-7-update">Drupal 7 Database Update</a></li>
</ul>
<p><strong>Answer Three:</strong></p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Category%3aOpen_source_content_management_systems">Open Source Content Management Systems</a></li>
</ul>
<p><strong>Answer Four: (Update: 2010-02-03 11:25:04)</strong></p>
<ul>
<li>see also: <a href="http://stackoverflow.com/questions/1715811">http://stackoverflow.com/questions/1715811</a></li>
</ul>
|
Viewing include dependencies <p>Does anyone know of a tool that will analyse a C++ codebase and display a graphical representation of which files include which header files and highlight redundant includes? I've used Understand C++ but it's expensive and became very unwieldy very quickly on a large (and poorly encapsulated) codebase.</p>
| <p>There's always the <em>"-H"</em> option to gcc/g++...</p>
<p>Eg.: % <strong>g++ -H foo.C</strong></p>
<pre><code>'-H'
Print the name of each header file used, in addition to other
normal activities. Each name is indented to show how deep in the
'#include' stack it is. Precompiled header files are also
printed, even if they are found to be invalid; an invalid
precompiled header file is printed with '...x' and a valid one
with '...!' .
</code></pre>
<p>Then:</p>
<ul>
<li>'sed' or 'awk' to remove the leading '...'.</li>
<li>'sort to make same names adjacent.</li>
<li>'uniq -c' to count names.</li>
<li>'grep -v' to remove singletons.</li>
</ul>
<p>As in:</p>
<pre><code>% g++ -H foo.C |& awk '{print $2}' | sort | uniq -c | grep -v ' 1 '
</code></pre>
<p>Or is that too linux'y / unix'y for you?</p>
<p>(Under windows, there's always cygwin.)</p>
|
Any reason I couldn't create a language supporting infix, postfix, and prefix functions, and more? <p>I've been mulling over creating a language that would be extremely well suited to creation of DSLs, by allowing definitions of functions that are infix, postfix, prefix, or even consist of multiple words. For example, you could define an infix multiplication operator as follows (where multiply(X,Y) is already defined):</p>
<pre><code>a * b => multiply(a,b)
</code></pre>
<p>Or a postfix "squared" operator:</p>
<pre><code>a squared => a * a
</code></pre>
<p>Or a C or Java-style ternary operator, which involves two keywords interspersed with variables:</p>
<pre><code>a ? b : c => if a==true then b else c
</code></pre>
<p>Clearly there is plenty of scope for ambiguities in such a language, but if it is statically typed (with type inference), then most ambiguities could be eliminated, and those that remain could be considered a syntax error (to be corrected by adding brackets where appropriate).</p>
<p>Is there some reason I'm not seeing that would make this extremely difficult, impossible, or just a plain bad idea?</p>
<p><em>Edit:</em> A number of people have pointed me to languages that may do this or something like this, but I'm actually interested in pointers to how I could implement my own parser for it, or problems I might encounter if doing so. </p>
| <p>This is not too hard to do. You'll want to assign each operator a <em>fixity</em> (infix, prefix, or postfix) and a <em>precedence</em>. Make the precedence a real number; you'll thank me later. Operators of higher precedence bind more tightly than operators of lower precedence; at equal levels of precedence, you can require disambiguation with parentheses, but you'll probably prefer to permit some operators to be <em>associative</em> so you can write</p>
<pre><code>x + y + z
</code></pre>
<p>without parentheses. Once you have a fixity, a precedence, and an associativity for each operator, you'll want to write an <strong>operator-precedence parser</strong>. This kind of parser is fairly simply to write; it scans tokens from left to right and uses one auxiliary stack. There is an explanation in the dragon book but I have never found it very clear, in part because the dragon book describes a very general case of operator-precedence parsing. But I don't think you'll find it difficult.</p>
<p>Another case you'll want to be careful of is when you have</p>
<pre><code>prefix (e) postfix
</code></pre>
<p>where <code>prefix</code> and <code>postfix</code> have the same precedence. This case also requires parentheses for disambiguation.</p>
<p>My paper <a href="http://www.cs.tufts.edu/~nr/pubs/unparse-abstract.html">Unparsing Expressions with Prefix and Postfix Operators</a> has an example parser in the back, and you can download the code, but it's written in ML, so its workings may not be obvious to the amateur. But the whole business of fixity and so on is explained in great detail.</p>
|
How to format a string of HTML programatically <p>I've got unformatted html in a string.</p>
<p>I am trying to format it nicely and output the formatted html back into a string.
I've been trying to use The System.Web.UI.HtmlTextWriter to no avail:</p>
<pre><code>System.IO.StringWriter wString = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter wHtml = new System.Web.UI.HtmlTextWriter(wString);
wHtml.Write(sMyUnformattedHtml);
string sMyFormattedHtml = wString.ToString();
</code></pre>
<p>All I get is the unformatted html, is it possible to achieve what I'm trying to do here?</p>
| <p>You can pass it to <a href="http://tidy.sourceforge.net/" rel="nofollow">tidy</a> externally or use <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx" rel="nofollow">XmlTextWriter</a> if you are willing to use XHTML instead of HTML.</p>
|
Does each row in a silverlight dataGrid have to have the same "RowDetailsTemplate"? <p>I'm defining a datagrid's RowDetailsTemplate in the following way:</p>
<p>RowDetailsTemplate="{StaticResource defaultTemplate}"</p>
<p>where</p>
<pre><code><UserControl.Resources>
<DataTemplate x:Key="defaultTemplate">
<StackPanel>
<TextBlock Text="default" x:Name="_txt" />
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="otherTemplate">
<StackPanel>
<TextBlock Text="other" x:Name="_txt" />
</StackPanel>
</DataTemplate>
</UserControl.Resources>
</code></pre>
<p>Is there a way to programatically define which of the two above DataTemplates a given row is to use (perhaps in the LoadingRowDetails() event)?</p>
| <p>You can add the following code in your LoadingRowDetails event, obviously replacing my useless If condition with your own:</p>
<pre><code> If 1 = 1 Then
e.Row.DetailsTemplate = CType(Resources("defaultTemplate"), DataTemplate)
Else
e.Row.DetailsTemplate = CType(Resources("otherTemplate"), DataTemplate)
End If
</code></pre>
|
How to create a GUID/UUID using the iPhone SDK <p>I want to be able to create a GUID/UUID on the iPhone and iPad. </p>
<p>The intention is to be able to create keys for distributed data that are all unique. Is there a way to do this with the iOS SDK?</p>
| <pre><code>[[UIDevice currentDevice] uniqueIdentifier]
</code></pre>
<p>Returns the Unique ID of your iPhone.</p>
<blockquote>
<p>EDIT: <code>-[UIDevice uniqueIdentifier]</code> is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.</p>
</blockquote>
<p>If you need to create several UUID, just use this method (with ARC):</p>
<pre><code>+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (__bridge NSString *)string;
}
</code></pre>
<p>EDIT: Jan, 29 2014:
If you're targeting iOS 6 or later, you can now use the much simpler method:</p>
<pre><code>NSString *UUID = [[NSUUID UUID] UUIDString];
</code></pre>
|
Is there a good reference for Joomla 1.5 development? <p>I've been hacking together some basic Joomla 1.5 components and modules recently and always every time I get into it, I end up tearing my hair out because I simply do not understand how the MVC pattern works. Some examples of the problems I run into:</p>
<ul>
<li>How does the view get access the model?</li>
<li>How do you switch to a different view?</li>
<li>How do you even include the correct file which defines the model?</li>
<li>etc.</li>
</ul>
<p>I'm sure that there are very simple answers to all my questions: my main problem is that overall I don't feel the "documentation" is useful at all and definitely doesn't provide enough information about how to develop components/modules in the new MVC style. The API website is almost worse-than-useless since all it provides are class trees of the functions with virtually no comments at all. The docs website is targetted to administrators and core developers only.</p>
<p><strong>Is there any useful source of information for web developers using Joomla 1.5?</strong></p>
| <p>Although there are some articles about the core team mixed in, here is a link to the development category where you can get the most out of the docs site: <a href="http://docs.joomla.org/Category:Development" rel="nofollow">http://docs.joomla.org/Category:Development</a> And yes, the Joomla! Framework could use a LOT more in the way of documentation.</p>
<p>When you are using the controller class, the <code>display()</code> function is called by default if your task doesn't match any of the functions. This in turn checks the HTTP request for the <code>view</code> variable and displays the view with the same name. If no value for <code>view</code> is specified, you will get an error. The way to get around this is to define a <code>display()</code> function in your controller, then have it check the value of <code>view</code>, set it to a default value if unset, then call <code>parent::display()</code>. Here's one I've used in a recent project to display the <code>mylist</code> view:</p>
<pre><code>function display()
{
$view = JRequest::getVar('view', '');
if ($view == '') {
JRequest::setVar('view', 'mylist');
}
parent::display();
}
</code></pre>
<p>When your view is loaded, the model with the same name is also loaded. You can then access the model functions in your view class through <code>$this->get()</code>. For instance, if you have a function in your model named <code>getPreferences()</code>, you can call <code>$this->get('preferences')</code> to call that function.</p>
|
NSNumberFormatter for rounding up float values <p>I have a CGFloat value which I want to round to 3 digits after the decimal point. How should I do this?</p>
<p>Thanks.</p>
| <pre><code>NSString *value = [NSString stringWithFormat:@"%.3f", theFloat];
</code></pre>
|
Can you nest C preprocessor directives? <p>For instance, is the following possible:</p>
<pre><code>#define definer(x) #define #x?
</code></pre>
| <p>No, you can't do that.<br />
The pound (<code>#</code>) symbol has a different meaning while in a definition. it means - if this is an argument, make it a string by quoting it.</p>
|
Javascript Drag and Drop Grid <p>I'm looking for a script that would allow me to have a grid of draggable divs (used to organize <a href="http://imgfave.com/?view=thumb">image thumbnails</a>). So when one div is dragged over another, the divs would shift to create an empty spot to drop the div.</p>
<p>I know jQuery has a drag and drop lib, but it doesn't seem to allow for the functionality I need (snapping to a grid and moving of surrounding divs).</p>
<p>Anyone know of a script or framework that has what I need?</p>
<p>Thanks!</p>
| <p>Have a look at the <a href="http://www.jquery.com">JQuery</a> and more specifically, <a href="http://ui.jquery.com/">JQuery UI</a> since it has "draggable", "droppable", "sortable", and a variety of other complex components.</p>
<p>Here is the specific example of a <a href="http://ui.jquery.com/demos/sortable#floating">drag and drop grid</a> you're looking for.</p>
|
How Do I Get External LIbrary Like Html Agility To Work In My C# Project? <p>How do I use a free library, such as Html Agility in my Visual Studio Express C# programs? Obviously I have downloaded it. What I need to know is how do I set it up so I can simply use a "using" statement to link up with the classes. Html Agility does not come with any .dll's so do I need to compile it to dll, and then reference to that dll?</p>
<p>If so, how do you compile to dll in Visual Studio Express?</p>
| <p>Since you don't have any binaries with the downloaded thing, this means that what you have got is the source code. So, you should know that which type of code is this. Is this a .NET code? (if it is so, it should have a .csproj or a .vbproj etc file with it.) Then again it depends that with which development environment it was built with. If it is a project of Visusl Studio Express than you can build the project in your Visual Studio Express edition, otherwise, I am afraid that you would not be able to do so. </p>
<p>The best thing is that you should download the binaries (dlls etc) and use them in your project by adding reference as you mentioned. Otherwise, you are left with two options. Either to build the code and make a binary or to use the code directly but for that you need to have a thorough understanding of the code.</p>
|
Unit testing and mocking email sender in Python with Google AppEngine <p>I'm a newbie to python and the app engine.</p>
<p>I have this code that sends an email based on request params after some auth logic. in my Unit tests (i'm using <a href="http://code.google.com/p/gaeunit/" rel="nofollow">GAEUnit</a>), how do I confirm an email with specific contents were sent? - i.e. how do I mock the emailer with a fake emailer to verify send was called?</p>
<pre><code>class EmailHandler(webapp.RequestHandler):
def bad_input(self):
self.response.set_status(400)
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>bad input </body></html>")
def get(self):
to_addr = self.request.get("to")
subj = self.request.get("subject")
msg = self.request.get("body")
if not mail.is_email_valid(to_addr):
# Return an error message...
# self.bad_input()
pass
# authenticate here
message = mail.EmailMessage()
message.sender = "my.company@gmail.com"
message.to = to_addr
message.subject = subj
message.body = msg
message.send()
self.response.headers['Content-Type'] = 'text/plain'
self.response.out.write("<html><body>success!</body></html>")
</code></pre>
<p>And the unit tests,</p>
<pre><code>import unittest
from webtest import TestApp
from google.appengine.ext import webapp
from email import EmailHandler
class SendingEmails(unittest.TestCase):
def setUp(self):
self.application = webapp.WSGIApplication([('/', EmailHandler)], debug=True)
def test_success(self):
app = TestApp(self.application)
response = app.get('http://localhost:8080/send?to=vijay.santhanam@gmail.com&body=blah_blah_blah&subject=mySubject')
self.assertEqual('200 OK', response.status)
self.assertTrue('success' in response)
# somehow, assert email was sent
</code></pre>
| <p>You could also override the <code>_GenerateLog</code> method in the <code>mail_stub</code> inside AppEngine.</p>
<p>Here is a parent TestCase class that I use as a mixin when testing that e-mails are sent:</p>
<pre><code>from google.appengine.api import apiproxy_stub_map, mail_stub
__all__ = ['MailTestCase']
class MailTestCase(object):
def setUp(self):
super(MailTestCase, self).setUp()
self.set_mail_stub()
self.clear_sent_messages()
def set_mail_stub(self):
test_case = self
class MailStub(mail_stub.MailServiceStub):
def _GenerateLog(self, method, message, log, *args, **kwargs):
test_case._sent_messages.append(message)
return super(MailStub, self)._GenerateLog(method, message, log, *args, **kwargs)
if 'mail' in apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map:
del apiproxy_stub_map.apiproxy._APIProxyStubMap__stub_map['mail']
apiproxy_stub_map.apiproxy.RegisterStub('mail', MailStub())
def clear_sent_messages(self):
self._sent_messages = []
def get_sent_messages(self):
return self._sent_messages
def assertEmailSent(self, to=None, sender=None, subject=None, body=None):
for message in self.get_sent_messages():
if to and to not in message.to_list(): continue
if sender and sender != message.sender(): continue
if subject and subject != message.subject(): continue
if body and body not in message.textbody(): continue
return
failure_message = "Expected e-mail message sent."
args = []
if to: args.append('To: %s' % to)
if sender: args.append('From: %s' % sender)
if subject: args.append('Subject: %s' % subject)
if body: args.append('Body (contains): %s' % body)
if args:
failure_message += ' Arguments expected: ' + ', '.join(args)
self.fail(failure_message)
</code></pre>
<p>After that, a sample test case might look like:</p>
<pre><code>import unittest, MailTestCase
class MyTestCase(unittest.TestCase, MailTestCase):
def test_email_sent(self):
send_email_to('test@example.org') # Some method that would send an e-mail.
self.assertEmailSent(to='test@example.org')
self.assertEqual(len(self.get_sent_messages()), 1)
</code></pre>
|
Can Window application continue to run despite computer going to standby mode? <p>I am developing a Windows application using C#.net. This will accept the login details, validate the login and then keep running unattended till the time the computer is on.</p>
<p>This computer won't do anything else and go to standby mode after a few minutes as per the security policy.</p>
<p>Is there a way to <strong>configure my application to avoid going to sleep when the computer goes to standby mode</strong> and keep the app running? I know we can do this by installing this application as a service. However a service cannot print my data without throwing up a print dialog and therefore, I cannot configure the app as a service.</p>
| <p>I'm not sure I understand completely - you want your app to carry on running WHILE the computer is asleep? If so then there's no way you can do that, it's asleep :) Services don't carry on running when the machine is sleeping either.</p>
<p>It should still be running when the machine wakes back up again though.</p>
|
Regarding Home page <p>I hava a web application. In that i have a link called "Home". When the user clicks the starting page of the web application that is index.jsp should be displayed in the same page. How can i do that. It should work in internet explorer. </p>
<p>I have the following html page.</p>
<pre><code><html>
<body bgcolor="#FFF8DC">
<a href="index.jsp" target="parent" >HOME</a>
</body>
</html>
</code></pre>
<p>But it is not working.</p>
| <p>< a href="url">home< /a > </p>
|
Overwrite executable in C:\Program\MyProg on Windows Vista <p>I would like my program to update itself (downloading a new exe and/or some other files from ftp) and I used the recipe in the accepted answer to <a href="http://stackoverflow.com/questions/264788/can-i-update-a-exe-that-is-running-closed">this question</a>.
Recap:</p>
<ol>
<li>Rename running program to old-mp.exe</li>
<li>Download the update as mp.exe directly</li>
<li>Restart the program</li>
</ol>
<p>This works great for windows XP. On vista there is a problem, as the user must run the program as administrator for this to work. Rightclicking and selecting "Run as administrator" might be over my users heads... Does anyone know a way around this? I like the simple update method very much. </p>
| <p>The simple option is to include a manifest that specifies that the application needs administrator rights. Then Vista will automatically prompt for the rights elevation. The manifest should look something like this:</p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="ApplicationName" type="win32"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level="requireAdministrator"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
</code></pre>
<p>You can use the mt.exe tool to add it to an existing application.</p>
<p>Alternatively you can restart the program with administrative rights just before the actual update. That way the user won't need to run with administrative rights always - just when updating.</p>
|
How to limit RDLC report for one page in a PDF ? <p>I have a RDLC report and I am displaying it on the Report Viewer Control in my front end application. I am able to view the report perfectly.</p>
<p>But the problem arises when I try to export the report to a PDF (using the built-in option).</p>
<p>I print the report in 3 pages whereas my client wants it to be in a single page. I can't figure out the reason for it as in my report viewer I see only one page but in a PDF there are 3 pages.</p>
<p>Can something be done about it so that I can control the size of the report?</p>
| <p>The answer is pretty similar to what Dugan said, but it's not always just the margins.
It is pretty simple though:</p>
<p>When you are editing the rdlc file in design mode, firstly click on an empty part of the BODY area of your design. Hit F4 to see the properties tab. Here, you will see a "Size" property. This can be expanded for the width and height. The width you see here represents the width that the body of your report requires as printable area. Even if you have white space all over, the page knows that it needs to keep it as a printable area. It reserves the space, in some sense. As for the height, the system generally knows that it can grow or shrink as necessary, unless you have specified otherwise within your controls therein. So the width is what will, usually, play the most important role.</p>
<p>Next, click on an empty area of the report (outside the header, body, and footer; basically the gray area around the design), then hit F4 to view the properties panel. Under the "Layout" category of the properties, you will see 3 different options:
InteractiveSize,
Margins,
PageSize.
Each of those Size attributes can be expanded to show the Width and Height. The Margins attribute can be expanded for the left/right/top/bottom.</p>
<p>Basically, the pdf export works out of the PageSize (though I generally try to keep Interactive and Page size equal). When the pdf file is rendered via the ReportViewer's built-in export function, the width and height of each "page" within the pdf will be determined by the width and height in the report's PageSize attribute (you could override this if you used your own custom code for the pdf rendering).
As for the margins, they specify how much space MUST be left blank and unprintable between the printable area reserved for your report and the edge of the page. </p>
<p>In other words:
Your report's Body's Width, Plus the Report's Left Margin, Plus the Report's Right Margin, MUST be smaller than or equal to the Report's PageSize's Width!</p>
<p>So...if your margins are too wide, or if your report's body is too wide, or if the PageSize's width is too narrow, the rendered result is forced to be broken down to multiple pages in order to fit!</p>
<p>For example: If my report's body has width 7.75", my Left margin is 0.5", my right margin is 0.5", and the width specified in the PageSize is 8.5", my report will always use 2 pages for each 1 page of data. The 7.75" width of the body, plus 0.5"+0.5" for the margins add up to 8.75", which is larger than the 8.5" available in my page. So the first 7.5" (or so) of each page of my report's body will be shown in the first page, and the rest will be split down to the next page. This will not be done inside the report viewer, as it allows for the report to grow beyond the page size by just adding a scrollbar, but it will be annoyingly noticeable in the pdf export.
In order to make my example report fit in 1 page, I can either try and reduce the body of my report to 7.5" or less, or I can reduce the left and right margins by a total of 0.25" or more (for example, set them to 0.3" for a total reduction of 0.4"), or I can increase the PageSize to something larger than 8.75".
Note: Acrobat Reader is pretty smart and knows about various paper sizes. Therefore, while arbitrary PageSizes will work, it is typically best to use real page sizes. As such, in my last example I would rather set the PageSize to have Width = 11" and Height = 8.5", which is a real letter-size in landscape! Adobe will typically understand this and print properly.
Also Note: Some printers, especially older ones, have trouble printing with less than 0.3" margins. If you want to be nice to your users, you should best keep the margins large enough for those older printers ;)</p>
<p>I hope this helps.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.