instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>How would you solve this problem?</p>
<p>You're scraping HTML of blogs. Some of the HTML of a blog is blog posts, some of it is formatting, sidebars, etc. You want to be able to tell what text in the HTML belongs to which post (i.e. a permalink) if any.</p>
<p>I know what you're thinking: You could just look at the RSS and ignore the HTML altogether! However, RSS very often contains only very short excerpts or strips away links that you might be interested in. You want to essentially defeat the excerptedness of the RSS by using the HTML and RSS of the same page together.</p>
<p>An RSS entry looks like:</p>
<pre>
title
excerpt of post body
permalink
</pre>
<p>A blog post in HTML looks like:</p>
<pre>
title (surrounded by permalink, maybe)
...
permalink, maybe
...
post body
...
permalink, maybe</pre>
<p>So the HTML page contains the same fields but the placement of the permalink is not known in advance, and the fields will be separated by some noise text that is mostly HTML and white space but also could contain some additional metadata such as "posted by Johnny" or the date or something like that. The text may also be represented slightly different in HTML vs. RSS, as described below.</p>
<p>Additional rules/caveats:</p>
<ul>
<li>Titles may not be unique. This happens more often than you might think. Examples I've seen: "Monday roundup", "TGIF", etc..</li>
<li>Titles may even be left blank.</li>
<li>Excerpts in RSS are also optional, but assume there must be at least either a non-blank excerpt or a non-blank title</li>
<li>The RSS excerpt may contain the full post content but more likely contains a short excerpt of the start of the post body</li>
<li>Assume that permalinks must be unique and must be the same in both HTML and RSS.</li>
<li>The title and the excerpt and post body may be formatted slightly differently in RSS and in HTML. For example:
<ul>
<li>RSS may have HTML inside of title or body stripped, or on the HTML page more HTML could be added (such as surrounding the first letter of the post body with something) or could be formatted slightly differently</li>
<li>Text may be encoded slightly differently, such as being utf8 in RSS while non-ascii characters in HTML are always encoded using ampersand encoding. However, assume that this is English text where non-ascii characters are rare.</li>
<li>There could be badly encoded Windows-1252 horribleness. This happens a lot for symbol characters like curly quotes. However, it is safe to assume that most of the text is ascii.</li>
<li>There could be case-folding in either direction, especially in the title. So, they could all-uppercase the title in the HTML page but not in RSS.</li>
</ul></li>
<li>The number of entries in the RSS feed and the HTML page is not assumed to be the same. Either could have more or fewer older entries. We can only expect to get only those posts that appear in both.</li>
<li>RSS could be lagged. There may be a new entry in the HTML page that does not appear in the RSS feed yet. This can happen if the RSS is syndicated through Feedburner. Again, we can only expect to resolve those posts that appear in both RSS and HTML.</li>
<li>The body of a post can be very short or very long.</li>
</ul>
<p>100% accuracy is <em>not</em> a constraint. However, the more accurate the better.</p>
<p>Well, what would you do?</p>
|
<p>I would create a scraper for each of the major blogging engines. Start with the main text for a single post per page.</p>
<p>If you're lucky then the engine will provide reasonable XHTML, so you can come up with a number of useful XPath expressions to get the node which corresponds to the article. If not, then I'm afraid it's <a href="http://home.ccil.org/~cowan/XML/tagsoup/" rel="nofollow noreferrer">TagSoup</a> or <a href="http://tidy.sourceforge.net/" rel="nofollow noreferrer">Tidy</a> to coerce it into well formed XML.</p>
<p>From there, you can look for the metadata and the full text. This should safely remove the headers/footers/sidebars/widgets/ads, though may leave embedded objects etc.</p>
<p>It should also be fairly easy (TM) to segment the page into article metadata, text, comments, etc etc and put it into fairly sensible RSS/Atom item.</p>
<p>This would be the basis of taking an RSS feed (non-full text) and turning it into a full text one (by following the permalinks given in the official RSS).</p>
<p>Once you have a scraper for a blog engine, you can start looking at writing a detector - something that will be the basis of the "given a page, what blog engine was it published with".</p>
<p>With enough scrapers and detectors, it should be possible to point a given RSS/Atom feed out and convert it into a full text feed.</p>
<p>However, this approach has a number of issues:</p>
<ul>
<li>while you may be able to target the big 5 blog engines, there may be some blogs which you just have to have that aren't covered by them: e.g. there are <a href="http://en.wikipedia.org/wiki/Category:Blog_software" rel="nofollow noreferrer">61 engines listed on Wikipedia</a>; people who write their <a href="http://www.glasshalfempty.co.uk/" rel="nofollow noreferrer">own</a> blogging engines each need their own scraper.</li>
<li>each time a blog engine changes versions, you need to change your detectors and scrapers. More accurately, you need to add a new scraper and detector. The detectors have to become increasing more fussy to distinguish between one version of the same engine and the next (e.g. everytime <a href="http://www.slashcode.com/" rel="nofollow noreferrer">slashcode</a> changes, it usually changes the HTML, but <a href="http://slashdot.org" rel="nofollow noreferrer">different</a> <a href="http://kuro5hin.org" rel="nofollow noreferrer">sites</a> use different versions of slash).</li>
</ul>
<p>I'm trying to think of a decent fallback, but I'll edit once I have.</p>
|
<p><strong>RSS</strong> is actually quite simple to parse using XPath any XML parser (or regexes, but that's not recpmmended), you're going through the <item> tags, looking for <title>, <link>, <description> .</p>
<p>You can then post them as different fields in a database, or direcrtly merge them into HTML. In case the <description> is missing, you could scrape the link (one way would be to compare multiple pages to weed-out the layout parts of the HTML).</p>
| 47,723
|
<p>If I have an issue with my FLSUN printer how can I contact customer support?</p>
|
<p>They have a webpage by now <a href="http://www.flsun3d.com" rel="noreferrer">www.flsun3d.com</a></p>
|
<p>I have had good luck contacting them via AliExpress <a href="https://flsun.aliexpress.com/store/2383013" rel="nofollow noreferrer">https://flsun.aliexpress.com/store/2383013</a> even though I bought my printer on Amazon. </p>
| 1,681
|
<p>The following code says that passing the map as <code>const</code> into the <code>operator[]</code> method discards qualifiers:</p>
<pre><code>#include <iostream>
#include <map>
#include <string>
using namespace std;
class MapWrapper {
public:
const int &get_value(const int &key) const {
return _map[key];
}
private:
map<int, int> _map;
};
int main() {
MapWrapper mw;
cout << mw.get_value(42) << endl;
return 0;
}
</code></pre>
<p>Is this because of the possible allocation that occurs on the map access? Can no functions with map accesses be declared const?</p>
<pre><code>MapWrapper.cpp:10: error: passing const std::map<int, int, std::less<int>,
std::allocator<std::pair<const int, int> > > as this argument of
_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&)
[with _Key = int, _Tp = int, _Compare = std::less<int>,
_Alloc = std::allocator<std::pair<const int, int> >] discards qualifiers
</code></pre>
|
<p><a href="http://en.cppreference.com/w/cpp/container/map/operator_at" rel="noreferrer"><code>std::map</code>'s <code>operator []</code> is not declared as <code>const</code>, and cannot be due to its behavior:</a></p>
<blockquote>
<p>T& operator[] (const Key& key)</p>
<p>Returns a reference to the value that is mapped to a key equivalent to key, performing insertion if such key does not already exist. </p>
</blockquote>
<p>As a result, your function cannot be declared <code>const</code>, and use the map's <code>operator[]</code>. </p>
<p><a href="http://en.cppreference.com/w/cpp/container/map/find" rel="noreferrer"><code>std::map</code>'s <code>find()</code></a> function allows you to look up a key without modifying the map.</p>
<p><a href="http://en.cppreference.com/w/cpp/container/map/find" rel="noreferrer"><code>find()</code></a> returns an <code>iterator</code>, or <code>const_iterator</code> to an <a href="http://en.cppreference.com/w/cpp/utility/pair" rel="noreferrer"><code>std::pair</code></a> containing both the key (<code>.first</code>) and the value (<code>.second</code>).</p>
<p>In C++11, you could also use <a href="http://en.cppreference.com/w/cpp/container/map/at" rel="noreferrer"><code>at()</code></a> for <code>std::map</code>. If element doesn't exist the function throws a <code>std::out_of_range</code> exception, in contrast to <code>operator []</code>.</p>
|
<p>First, you should not be using symbols beginning with _ because they are reserved to the language implementation/compiler writer. It would be very easy for _map to be a syntax error on someone's compiler, and you would have no one to blame but yourself.</p>
<p>If you want to use an underscore, put it at the end, not the beginning. You probably made this mistake because you saw some Microsoft code doing it. Remember, they write their own compiler, so they may be able to get away with it. Even so, it's a bad idea.</p>
<p>the operator [] not only returns a reference, it actually creates the entry in the map. So you aren't just getting a mapping, if there is none, you are creating one. That's not what you intended.</p>
| 32,904
|
<p>Can I load an stand alone aspx page in another stand alone aspx page using System.Reflection? </p>
<p>I am using the ASP.NET 2.0 Web site project model.</p>
|
<p>Try using <a href="http://msdn.microsoft.com/en-us/library/system.web.compilation.buildmanager.createinstancefromvirtualpath.aspx" rel="noreferrer">BuildManager.CreateInstanceFromVirtualPath</a>. Sample usage:</p>
<pre><code>Page p = BuildManager.CreateInstanceFromVirtualPath("~/Default.aspx", typeof(Page))
</code></pre>
<p>This answers this specific question, although, based on your comments, I'm not sure that this is what you really want.</p>
|
<p>Don't know about doing it using Reflection, which may well be possible, but you can capture the output of an aspx or asp page to a string writer using HttpContext.Server.Execute().<br>
I have used this for rendering some complex email templates, but don't know if that is quite what you are after.</p>
| 49,274
|
<p>I might be missing something really obvious. I'm trying to write a custom Panel where the contents are laid out according to a couple of dependency properties (I'm assuming they <em>have</em> to be DPs because I want to be able to animate them.)</p>
<p>However, when I try to run a storyboard to animate both of these properties, Silverlight throws a Catastophic Error. But if I try to animate just one of them, it works fine. And if I try to animate one of my properties and a 'built-in' property (like Opacity) it also works. But if I try to animate both my custom properties I get the Catastrophic error.</p>
<p>Anyone else come across this?</p>
<p>edit:</p>
<p>The two DPs are ScaleX and ScaleY - both doubles. They scale the X and Y position of children in the panel. Here's how one of them is defined:</p>
<pre><code> public double ScaleX
{
get { return (double)GetValue(ScaleXProperty); }
set { SetValue(ScaleXProperty, value); }
}
/// <summary>
/// Identifies the ScaleX dependency property.
/// </summary>
public static readonly DependencyProperty ScaleXProperty =
DependencyProperty.Register(
"ScaleX",
typeof(double),
typeof(MyPanel),
new PropertyMetadata(OnScaleXPropertyChanged));
/// <summary>
/// ScaleXProperty property changed handler.
/// </summary>
/// <param name="d">MyPanel that changed its ScaleX.</param>
/// <param name="e">DependencyPropertyChangedEventArgs.</param>
private static void OnScaleXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyPanel _MyPanel = d as MyPanel;
if (_MyPanel != null)
{
_MyPanel.InvalidateArrange();
}
}
public static void SetScaleX(DependencyObject obj, double val)
{
obj.SetValue(ScaleXProperty, val);
}
public static double GetScaleX(DependencyObject obj)
{
return (double)obj.GetValue(ScaleXProperty);
}
</code></pre>
<p>Edit: I've tried it with and without the call to InvalidateArrange (which is absolutely necessary in any case) and the result is the same. The event handler doesn't even get called before the Catastrophic error kicks off.</p>
|
<p>It's a documented bug with Silverlight 2 Beta 2. You can't animate two custom dependancy properties on the same object.</p>
|
<p>I would try commenting out the InvalidateArrange in the OnPropertyChanged and see what happens.</p>
| 8,776
|
<p>How do I compare two dates in Lingo? To be specific, I want to know if today's date is after some fixed date. I know I can create the fixed date by using:</p>
<pre><code>date("20090101")
</code></pre>
<p>and I can get the current date using:</p>
<pre><code>_system.date()
</code></pre>
<p>but I can't seem to directly compare the two. Do I have to parse the _system.date() to determine if it's after my fixed date? I tried:</p>
<pre><code>if(_system.date() > date("20090101") then
--do something
end if
</code></pre>
<p>but that doesn't seem to work. Any ideas?</p>
|
<p>Instead of _system.date(), try _movie.systemDate(), it will return a date object that you can safely compare with another one.</p>
<p>if _movie.systemDate() > date("20090101") then</p>
<pre><code>--do something
</code></pre>
<p>end if</p>
<p>regards</p>
|
<p>I ended up doing the following. Inelegant, but it works:</p>
<pre><code> if (_system.date().char[1..2] >= 01 and _system.date().char[4..5] >= 01 and _system.date().char[7..10] >= 2010) then
alert("Your license has expired. Please contact the Company to renew your license.")
_player.quit()
end if
</code></pre>
<p>It does the trick, but I would still be interested in alternative methods of doing this.</p>
| 45,368
|
<p>I am using a class <code>Foo</code> that provides these methods:</p>
<pre><code>String overloadedMethod(Object)
String overloadedMethod(Goo)
</code></pre>
<p>Since Java statically dispatches on the non-receiver argument, I cannot just pass my <code>value</code> (which is an <code>Object</code>, but might have dynamic type <code>Goo</code>) and rely on the JVM to dynamically choose the "correct" method.</p>
<p>This is my current (ugly) work-around:</p>
<pre><code>Object value = ...;
Foo foo = new Foo();
if (value instanceof Goo) {
Goo gooValue = (Goo) value;
return foo.overloadedMethod(gooValue); // -> overloadedMethod(Goo)
} else {
return foo.overloadedMethod(value); // -> overloadedMethod(Object)
}
</code></pre>
<p>Is there a better way of doing this <em>without modifying the code in <code>Foo</code></em> (the class containing the overloaded method)?</p>
|
<p>Of course you could always use reflection to find the most specific version of the method that applies, but that could get hairy real quick.</p>
<p>But if those two calls result in entirely different behaviour, then Foo is either designed to be used in a visitor pattern (i.e. with double dispatch) or it is broken.</p>
|
<p>You could take a look at <a href="http://www-igm.univ-mlv.fr/~forax/works/jmmf/index.html" rel="nofollow noreferrer">the Java MultiMethod Framework</a>. It's pretty much a layer around what you're proposing, but atleast it's abstracted into a logical module that's not your responsibility?</p>
<p>(As far as I'm aware, there's no clean way to do this without resorting to reflection/instanceof hacking)</p>
| 48,450
|
<p>Lets say on my page I have this function:</p>
<pre><code> function ReturnFoo(bar)
{
return bar.toString() + "foo";
}
</code></pre>
<p>Now, I would like to have this called from ASP .NET, hopefully with the ASP .NET AJAX framework, as I am already using it in this codebase (I have already spent the 100k, might as well use it).</p>
<p>Also, I would like to get back the output that is returned from this function and then assign it to a variable created on the server side. And this is restricted to ASP .NET 2.0</p>
|
<p>Yeah, this is a difficult one. Using MS Ajax will help you out a bit. You'll need to push in code from the server to call this function upon page load and assign the return value to a hidden field that can be accessed by the server on post back.</p>
<p>I must say that this solution sucks, but I don't know another way. Hopefully, someone will have a better solution.</p>
|
<p>I don't see how you expect server-side code to call a client-side function???</p>
<p>AJAX calls are from the client-side to the server-side!</p>
| 21,689
|
<p>Normally, in Delphi one would declare a function with a variable number of arguments using the 'array of const' method. However, for compatibility with code written in C, there's an much-unknown 'varargs' directive that can be added to a function declaration (I learned this while reading Rudy's excellent '<a href="http://rvelthuis.de/articles/articles-convert.html#varargs" rel="noreferrer">Pitfalls of convering</a>' document).</p>
<p>As an example, one could have a function in C, declared like this :</p>
<pre><code>void printf(const char *fmt, ...)
</code></pre>
<p>In Delphi, this would become :</p>
<pre><code>procedure printf(const fmt: PChar); varargs;
</code></pre>
<p>My question is : How can I get to the contents of the stack when implementing a method which is defined with the 'varargs' directive?</p>
<p>I would expect that some tooling for this exists, like Dephi translations of the va_start(), va_arg() and va_end() functions, but I can't find this anywhere.</p>
<p>Please help!</p>
<p>PS: Please don't drift off in discussions about the 'why' or the 'array of const' alternative - I need this to write C-like patches for functions inside Xbox games (see the Delphi Xbox emulator project 'Dxbx' on sourceforge for details).</p>
|
<p>OK, I see the clarification in your question to mean that you need to implement a C import in Delphi. In that case, you need to implement varargs yourself.</p>
<p>The basic knowledge needed is the C calling convention on the x86: the stack grows downwards, and C pushes arguments from right to left. Thus, a pointer to the last declared argument, after it is incremented by the size of the last declared argument, will point to the tail argument list. From then, it's simply a matter of reading the argument out and incrementing the pointer by an appropriate size to move deeper into the stack. The x86 stack in 32-bit mode is 4-byte aligned generally, and this also means that bytes and words are passed as 32-bit integers.</p>
<p>Anyhow, here's a helper record in a demo program that shows how to read out data. Note that Delphi seems to be passing Extended types in a very odd way; however, you likely won't have to worry about that, as 10-byte floats aren't generally widely used in C, and aren't even implemented in the latest MS C, IIRC.</p>
<pre><code>{$apptype console}
type
TArgPtr = record
private
FArgPtr: PByte;
class function Align(Ptr: Pointer; Align: Integer): Pointer; static;
public
constructor Create(LastArg: Pointer; Size: Integer);
// Read bytes, signed words etc. using Int32
// Make an unsigned version if necessary.
function ReadInt32: Integer;
// Exact floating-point semantics depend on C compiler.
// Delphi compiler passes Extended as 10-byte float; most C
// compilers pass all floating-point values as 8-byte floats.
function ReadDouble: Double;
function ReadExtended: Extended;
function ReadPChar: PChar;
procedure ReadArg(var Arg; Size: Integer);
end;
constructor TArgPtr.Create(LastArg: Pointer; Size: Integer);
begin
FArgPtr := LastArg;
// 32-bit x86 stack is generally 4-byte aligned
FArgPtr := Align(FArgPtr + Size, 4);
end;
class function TArgPtr.Align(Ptr: Pointer; Align: Integer): Pointer;
begin
Integer(Result) := (Integer(Ptr) + Align - 1) and not (Align - 1);
end;
function TArgPtr.ReadInt32: Integer;
begin
ReadArg(Result, SizeOf(Integer));
end;
function TArgPtr.ReadDouble: Double;
begin
ReadArg(Result, SizeOf(Double));
end;
function TArgPtr.ReadExtended: Extended;
begin
ReadArg(Result, SizeOf(Extended));
end;
function TArgPtr.ReadPChar: PChar;
begin
ReadArg(Result, SizeOf(PChar));
end;
procedure TArgPtr.ReadArg(var Arg; Size: Integer);
begin
Move(FArgPtr^, Arg, Size);
FArgPtr := Align(FArgPtr + Size, 4);
end;
procedure Dump(const types: string); cdecl;
var
ap: TArgPtr;
cp: PChar;
begin
cp := PChar(types);
ap := TArgPtr.Create(@types, SizeOf(string));
while True do
begin
case cp^ of
#0:
begin
Writeln;
Exit;
end;
'i': Write(ap.ReadInt32, ' ');
'd': Write(ap.ReadDouble, ' ');
'e': Write(ap.ReadExtended, ' ');
's': Write(ap.ReadPChar, ' ');
else
Writeln('Unknown format');
Exit;
end;
Inc(cp);
end;
end;
type
PDump = procedure(const types: string) cdecl varargs;
var
MyDump: PDump;
function AsDouble(e: Extended): Double;
begin
Result := e;
end;
function AsSingle(e: Extended): Single;
begin
Result := e;
end;
procedure Go;
begin
MyDump := @Dump;
MyDump('iii', 10, 20, 30);
MyDump('sss', 'foo', 'bar', 'baz');
// Looks like Delphi passes Extended in byte-aligned
// stack offset, very strange; thus this doesn't work.
MyDump('e', 2.0);
// These two are more reliable.
MyDump('d', AsDouble(2));
// Singles passed as 8-byte floats.
MyDump('d', AsSingle(2));
end;
begin
Go;
end.
</code></pre>
|
<p>Delphi doesn't let you implement a varargs routine. It only works for importing external cdecl functions that use this.</p>
<p>Since varargs is based on the cdecl calling convention, you basically need to reimplement it yourself in Delphi, using assembly and/or various kinds of pointer manipulation.</p>
| 38,194
|
<p>I use <a href="http://docs.jquery.com/Plugins/Treeview" rel="nofollow noreferrer">jquery tree plugin</a> to render hierarchical data. </p>
<p>I have coded additional functions which would allow user to interact with this data (like adding/deleting nodes, swapping nodes, etc...)</p>
<p>Currently this plugin supports that whenever you want to add any node, you can call following method,</p>
<pre><code>$("#browser").treeview({
add: branches
});
</code></pre>
<p>here <code>branches</code> is <code>jQuery object</code> created with the HTML block, which would represent a particular node.</p>
<p>However, for delete and swapping of nodes, I use common JQuery functions like,</p>
<p><strong>for delete,</strong></p>
<pre><code>$("#topnd2").remove();
</code></pre>
<p><strong>for swapping,</strong></p>
<pre><code>var next = $("#topnd2").next();
$("#topnd2").insertAfter(next);
</code></pre>
<p><code>topnd2</code> is an <code>id</code> of any particular tree node.</p>
<p>The nodes get deleted / swapped properly but the problem is the tree does not get rendered and therefore the tree images (mainly vertical lines denoting branches) are not set properly.</p>
<p>For example, if I delete the last node then that node will be removed from rendered treeview but the remaining sibling node should get L as branch line image but not | .</p>
<p>I tried calling </p>
<p><code>$("#browser").treeview();</code> </p>
<p>Please let me know your ideas.</p>
<p>Thanks,
Jatan</p>
|
<p>I found some workaround as given below,</p>
<p>Once the node is swapped up, virtually add its previous node to its child,</p>
<p>$("#browser").treeview({add:$("#topnd2").insertBefore(previous).next()});</p>
<p>If node is swapped down, virtuall add the current node to its next node.</p>
<p>$("#browser").treeview({add:$("#topnd2").insertAfter(next)});</p>
<p>currently it's working fine, will update this post, if I find any problems in this approach. Also please validate this approach if you know.</p>
<p>Regards,
Jatan</p>
|
<p>If you try to refresh the treeview again after node removal, the link will work but not the [+] or [-] icon. Tried this on several browsers..</p>
| 34,121
|
<p>I read everywhere that business logic belongs in the models and not in controller but where is the limit?
I am toying with a personnal accounting application. </p>
<pre><code>Account
Entry
Operation
</code></pre>
<p>When creating an operation it is only valid if the corresponding entries are created and linked to accounts so that the operation is balanced for exemple buy a 6-pack :</p>
<pre><code>o=Operation.new({:description=>"b33r", :user=>current_user, :date=>"2008/09/15"})
o.entries.build({:account_id=>1, :amount=>15})
o.valid? #=>false
o.entries.build({:account_id=>2, :amount=>-15})
o.valid? #=>true
</code></pre>
<p>Now the form shown to the user in the case of <em>basic operations</em> is simplified to hide away the entries details, the accounts are selected among 5 default by the kind of operation requested by the user (intialise account -> equity to accout, spend assets->expenses, earn revenues->assets, borrow liabilities->assets, pay debt assets->liabilities ...) I want the entries created from default values.</p>
<p>I also want to be able to create more complex operations (more than 2 entries). For this second use case I will have a different form where the additional complexity is exposed.This second use case prevents me from including a debit and credit field on the Operation and getting rid of the Entry link. </p>
<p>Which is the best form ? Using the above code in a SimpleOperationController as I do for the moment, or defining a new method on the Operation class so I can call Operation.new_simple_operation(params[:operation])</p>
<p>Isn't it breaking the separation of concerns to actually create and manipulate Entry objects from the Operation class ?</p>
<p>I am not looking for advice on my twisted accounting principles :)</p>
<p>edit -- It seems I didn't express myself too clearly.
I am not so concerned about the validation. I am more concerned about where the creation logic code should go : </p>
<p>assuming the operation on the controller is called spend, when using spend, the params hash would contain : amount, date, description. Debit and credit accounts would be derived from the action which is called, but then I have to create all the objects. Would it be better to have </p>
<pre><code>#error and transaction handling is left out for the sake of clarity
def spend
amount=params[:operation].delete(:amount)#remove non existent Operation attribute
op=Operation.new(params[:operation])
#select accounts in some way
...
#build entries
op.entries.build(...)
op.entries.build(...)
op.save
end
</code></pre>
<p>or to create a method on Operation that would make the above look like </p>
<pre><code>def spend
op=Operation.new_simple_operation(params)
op.save
end
</code></pre>
<p>this definitely give a much thinner controller and a fatter model, but then the model will create and store instances of other models which is where my problem is.</p>
|
<blockquote>
<p>but then the model will create and store instances of other models which is where my problem is.</p>
</blockquote>
<p>What is wrong with this? </p>
<p>If your 'business logic' states that an Operation must have a valid set of Entries, then surely there is nothing wrong for the Operation class to know about, and deal with your Entry objects.</p>
<p>You'll only get problems if you take this too far, and have your models manipulating things they <em>don't</em> need to know about, like an EntryHtmlFormBuilder or whatever :-)</p>
|
<p>It's easier to think in terms of each entity validating itself, and entities which depend on one another delegating their state to the state of their associated entries. In your case, for instance:</p>
<pre><code>class Operation < ActiveRecord::Base
has_many :entries
validates_associated :entries
end
</code></pre>
<p>validates_associated will check whether each associated entity is valid (in this case, all entries should if the operation is to be valid).</p>
<p>It is very tempting to try to validate entire hierarchies of models as a whole, but as you said, the place where that would be most easily done is the controller, which should act more as a router of requests and responses than in dealing with business logic.</p>
| 8,974
|
<p>I have an old C library with a function that takes a void**:</p>
<pre><code>oldFunction(void** pStuff);
</code></pre>
<p>I'm trying to call this function from managed C++ (m_pStuff is a member of the parent ref class of type void*):</p>
<pre><code>oldFunction( static_cast<sqlite3**>( &m_pStuff ) );
</code></pre>
<p>This gives me the following error from Visual Studio:</p>
<blockquote>
<p>error C2440: 'static_cast' : cannot convert from 'cli::interior_ptr' to 'void **'</p>
</blockquote>
<p>I'm guessing the compiler is converting the void* member pointer to a cli::interior_ptr behind my back.</p>
<p>Any advice on how to do this?</p>
|
<p>EDIT: Fixed answer, see below.</p>
<p>Really you need to know what oldFunction is going to be doing with pStuff. If pStuff is a pointer to some unmanaged data you can try wrapping the definition of m_pStuff with:</p>
<pre><code>#pragma unmanaged
void* m_pStuff
#pragma managed
</code></pre>
<p>This will make the pointer unmanaged which can then be passed into unmanaged functions. Of course you will not be able to assign any managed objects to this pointer directly. </p>
<p>Fundamentally unmanaged and managed pointers are not the same and can't be converted without some sort of glue code that copies the underlying data. Basically managed pointers point to the managed heap and since this is garbage collected the actual memory address they point to can change over time. Unmanaged pointers do not change the memory address without you explicitly doing so. </p>
<p>Scratch that, you can't define unmanaged / managed inside a class definition. But this test code seems to work just fine:</p>
<pre><code>// TestSol.cpp : main project file.
#include "stdafx.h"
using namespace System;
#pragma unmanaged
void oldFunction(void** pStuff)
{
return;
}
#pragma managed
ref class Test
{
public:
void* m_test;
};
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Hello World");
Test^ test = gcnew Test();
void* pStuff = test->m_test;
oldFunction(&pStuff);
test->m_test = pStuff;
return 0;
}
</code></pre>
<p>Here I copy the pointer out of the managed object first and then pass that in by to the oldFunction. Then I copy the result (probably updated by oldFunction) back into the managed object. Since the managed object is on the managed heap, the compiler won't let you pass a reference to the pointer contained in that object as it may move when the garbage collector runs.</p>
|
<p>Thanks for the advice, the pointer is to an C style abstract structure which I think if I leave that structure exposed to the managed code is going to cause further pain due to its lack of defined structure. So what I think I will do is wrap the C library in C++ and then wrap the C++ wrapper with managed C++, which will prevent exposing those C structures to managed code.</p>
| 4,672
|
<p>I bought an ASP.NET script about a year ago to retrieve FedEx shipping values. It builds an XML string that passes to the FedEx server using an HttpWebRequest, then parses the raw XML. The average response time for the script is about 900 milliseconds. </p>
<p>So the other day I was poking around in the FedEx developer center and discovered that they provide some C# code samples for using their web service. I built a little project using their code and WSDL file, and was surprised to find that the average response time is about 2.5 seconds. </p>
<p>Can someone help me understand the difference in speed? And is there a way to make it faster? I have zero experience using web services.</p>
<p>Thanks.</p>
|
<p>You can find a good article and a library to start with here: <a href="http://www.codeproject.com/KB/COM/opcdotnet.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/COM/opcdotnet.aspx</a></p>
|
<p>If buying a comercial toolkit is an option I've used the Northern Dynamics <a href="http://www.nordyn.com/Main/Products/Main.htm" rel="nofollow noreferrer">server toolkit</a> and it worked fine. A toolkit will take away a lot of the issues mentioned in the other questions (or at least you should get support if there's a problem).</p>
<p>They've wrapped the OPC protocol up nicely so it makes it easy to use. See one of my questions here for a <a href="https://stackoverflow.com/questions/1649264/how-to-make-a-type-safe-wrapper-around-variant-values">type-safe Variant wrapper</a> that I wrote to help with this.</p>
| 9,234
|
<p>When an <code>AutoCompleteExtender</code> is displayed in IE6 it seems to ignore z-index and renders below any select controls (like <strong>dropdownlists</strong>) in IE6.</p>
<pre><code><asp:TextBox ID="TextBox1" runat="server" />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="TextBox1" EnableCaching="true" CompletionSetCount="5"
FirstRowSelected="true" ServicePath="~/Services/Service1.asmx" ServiceMethod="GetSuggestion" />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:DropDownList>
</code></pre>
<p>How do I make it render above <strong>dropdownlists</strong>?</p>
|
<p>Nothing renders below select controls in IE6. It's one of the many "features" microsoft bestowed upon us when they gifted IE to the world</p>
<p>You have to hide them, then re-show them.</p>
<p>Observe the <a href="http://code.google.com/p/nucleus-plugins/source/browse/lightbox2/trunk/lightbox2/js/lightbox.js#205" rel="nofollow noreferrer">standard lightbox script</a> - which does exactly this</p>
<p>(note that link is just to the first thing I found on google which had the source to lightbox.js as a demonstration. It's got nothing to do with anything else)</p>
|
<p>Nothing renders below select controls in IE6. It's one of the many "features" microsoft bestowed upon us when they gifted IE to the world</p>
<p>You have to hide them, then re-show them.</p>
<p>Observe the <a href="http://code.google.com/p/nucleus-plugins/source/browse/lightbox2/trunk/lightbox2/js/lightbox.js#205" rel="nofollow noreferrer">standard lightbox script</a> - which does exactly this</p>
<p>(note that link is just to the first thing I found on google which had the source to lightbox.js as a demonstration. It's got nothing to do with anything else)</p>
| 6,711
|
<p>First, a couple operating parameters:</p>
<ul>
<li>.NET development using Visual Studio 2005/2008</li>
<li>TortoiseSVN client</li>
</ul>
<p>I've only primarily worked with Visual Source Safe and SourceGear Vault source control systems. In each, I map the root of the repository to a local working directory. For example:</p>
<pre><code>$/ --> C:\source
</code></pre>
<p>As long as the local directory exists, I've got my "working copy" (svn) or "working folder" (VSS) set up.</p>
<p>To work on a new project that is already in the source code repository I need to "get the latest" (VSS) version of that project's directory.</p>
<p>When I go into any child directory in the repository and "Get Latest" (i.e. svn checkout) the client will automatically create the complete directory hierarchy for me, mirroring the structure on my local disk. Thus when I get latest of</p>
<pre><code>$/foo/bar/project1
</code></pre>
<p>it is created on the drive at</p>
<pre><code>C:\source\foo\bar\project1
</code></pre>
<p>In subversion, when I check out a directory, I must specify the working copy directory location. If I want to properly mirror my working copy directory structure to match the repository I have to either manually construct every child directory in the path or do a checkout of the repository root to the working copy root, getting everything in the repository.</p>
<p><strong>Is there a way to get a repository directory down in the hierarchy such that it will be created in a matching local working copy directory structure without all the manual intervention?</strong></p>
<p>This isn't a problem with a small repository, but in most cases, I don't need a large percentage of the source repository. It's imperative that the physical structure is maintained in order for file references to projects and resources not to break. Plus the disk cost of SVN is twice the actual source size given all the working base copies of the files.</p>
<p>I'm currently using Tortoise. Is it possible there are other SVN clients that will do what I'm looking for?</p>
|
<p>The Subversion "check out" operation creates a <em>new</em> working copy. What you probably want to do is check out your whole project (which automatically creates the proper directory structure as it is in the repository), then use the Subversion "update" operation. The update will update everything in the specified directory and in subdirectories.</p>
<p>This is perhaps due to a difference in terminology between VSS and Subversion. The <a href="http://svnbook.red-bean.com" rel="nofollow noreferrer">Subversion Book</a> is a worthwhile read, particularly the chapter on <a href="http://svnbook.red-bean.com/en/1.5/svn.tour.html" rel="nofollow noreferrer">Basic Usage</a>.</p>
<p>Update: I suppose I'm not quite understanding what your expected use-case is. It sounds like one of the new Subversion 1.5 features you might need is <a href="http://subversion.tigris.org/svn_1.5_releasenotes.html#sparse-checkouts" rel="nofollow noreferrer">sparse checkouts</a>. This lets you selectively fetch a portion of a repository without necessarily getting the whole thing. It's quite flexible in the options it gives you for managing how much you need to get.</p>
<p><strike>Since sparse checkouts are relatively new, I don't think the SVN book has been updated to include information on this feature.</strike> It has been updated, see comments.</p>
<p>Update 2: It sounds like you can construct what you want by checking out the top level of your repository into c:\source with the --depth=empty option. Then, for each subdirectory that you want, update that subdirectory with --depth=empty or --depth=infinity as appropriate.</p>
<p>I believe that all this is rooted in the Subversion design goal of being able to have multiple independent source trees on your system at the same time. With VSS, $/ is configured globally to refer to a specific directory (c:\source) so you can only have one checkout (without a bunch of messing around with the global configuration every time you want to switch).</p>
|
<p>Not sure why you want to do what you are asking. Most people just create a working local copy, and work on whatever directory they want. That's because of the way Subversion works. It doesn't lock the source code. I started source control by using SourceSafe, so I have a little bit of an idea of what you are going through. </p>
<p>What you probably want is to use the svn:externals property. There are several posts here that talk about this. Here is one of them:</p>
<p><a href="https://stackoverflow.com/questions/125468/how-to-make-svn-only-update-files-but-not-add-new-ones">How to make SVN only update files but not add new ones</a></p>
| 30,968
|
<p>What is the difference between </p>
<pre><code>if(null==object)
</code></pre>
<p>and </p>
<pre><code>if(object==null)
</code></pre>
<p>Please give the advantage for using the above.</p>
|
<p>The difference comes if you accidentally type <code>=</code> instead of <code>==</code>:</p>
<p><code>if (null = object)</code> - Compiler error<br>
<code>if (object = null)</code> - Bug!</p>
|
<p>In many languages == is the comparison operator = is the assignment operator.</p>
<p>It very easy to type = when you really mean ==.</p>
<p>Therefore the convention of typing constant==variable is preferred.</p>
<p>constant=variable will not compile thus showing you, your error.</p>
<p>variable=constant will compile and will do the wrong thing at runtime.</p>
| 38,883
|
<p>I have a simple, real life problem I want to solve using an OO approach. <strong>My harddrive is a mess.</strong> I have 1.500.000 files, duplicates, complete duplicate folders, and so on...</p>
<p>The first step, of course, is parsing all the files into my database. No problems so far, now I got a lot of nice entries which are kind of "naturaly grouped". Examples for this simple grouping can be obtained using simple queries like:</p>
<ol>
<li>Give me all files bigger than 100MB</li>
<li>Show all files older than 3 days</li>
<li>Get me all files ending with docx</li>
</ol>
<p>But now assume I want to find groups with a little more natural meaning. There are different strategies for this, depending on the "use case".</p>
<p>Assume I have a bad habit of putting all my downloaded files first on the desktop. Then I extract them to the appropriate folder, without deleting the ZIP file always. The I move them into a "attic" folder. For the system, to find this group of files a <strong>time oriented</strong> search approach, perhaps combined with a "check if ZIP is same then folder X" would be suitable.</p>
<p>Assume another bad habit of duplicating files, having some folder where "the clean files" are located in a <strong>nice structure</strong>, and another <strong>messy folders</strong>. Now my clean folder has 20 picture galleries, my messy folder has 5 duplicated and 1 new gallery. A human user could easily identify this logic by seeing "Oh, thats all just duplicates, thats a new one, so I put the new one in the clean folder and trash all the duplicates".</p>
<p><strong>So, now to get to the point:</strong></p>
<p>Which combination of strategies or patterns would you use to tackle such a situation. If I chain filters the "hardest" would win, and I have no idea how to let the system "test" for suitable combination. And it seemes to me it is more then just filtering. Its dynamic grouping by combining multiple criteria to find the "best" groups.</p>
<p>One very rough approach would be this:</p>
<ol>
<li>In the beginning, all files are equal</li>
<li>The first, not so "good" group is the directory</li>
<li>If you are a big, clean directory, you earn points (evenly distributed names)</li>
<li>If all files have the same creation date, you may be "autocreated"</li>
<li>If you are a child of Program-Files, I don't care for you at all</li>
<li>If I move you, group A, into group C, would this improve the "entropy"</li>
</ol>
<p>What are the best patterns fitting this situation. Strategy, Filters and Pipes, "Grouping".. Any comments welcome!</p>
<p><strong>Edit in reacation to answers:</strong></p>
<p><strong>The tagging approach:</strong>
Of course, tagging crossed my mind. But where do I draw the line. I could create different tag types, like InDirTag, CreatedOnDayXTag, TopicZTag, AuthorPTag. These tags could be structured in a hirarchy, but the question how to group would remain. But I will give this some thought and add my insights here.. </p>
<p><strong>The procrastination comment:</strong>
Yes, it sounds like that. But the files are only the simplest example I could come up with (and the most relevant at the moment). Its actually part of the bigger picture of grouping related data in dynamic ways. Perhaps I should have kept it more abstract, to stress this: I am <strong>NOT searching for</strong> a file tagging <strong>tool</strong> or a search engine, <strong>but an algorithm or pattern</strong> to approach this problem... (or better, ideas, like tagging)</p>
<p>Chris</p>
|
<p>I don't have a solution (and would love to see one), but I might suggest extracting metadata from your files besides the obvious name, size and timestamps.</p>
<ul>
<li>in-band metadata such as MP3 ID3 tags, version information for EXEs / DLLs, HTML title and keywords, Summary information for Office documents etc. Even image files can have interesting metadata. A hash of the entire contents helps if looking for duplicates.</li>
<li>out-of-band metadata such as can be stored in NTFS alternate data streams - eg. what you can edit in the Summary tab for non-Office files</li>
<li>your browsers keep information on where you have downloaded files from (though Opera doesn't keep it for long), if you can read it.</li>
</ul>
|
<p>You've got a fever, and the only prescription is Tag Cloud! You're still going to have to clean things up, but with tools like <a href="http://www.taggtool.com/index.php" rel="nofollow noreferrer">TaggCloud</a> or <a href="http://www.tag2find.com" rel="nofollow noreferrer">Tag2Find</a> you can organize your files by meta data as opposed to location on the drive. Tag2Find will watch a share, and when anything is saved to the share a popup appears and asks you to tag the file. </p>
<p>You should also get Google Desktop too.</p>
| 20,726
|
<p>Suppose that I have a Java program within an IDE (Eclipse in this case).
Suppose now that I execute the program and at some point terminate it or it ends naturally.</p>
<p>Is there a <strong>convenient</strong> way to determine which lines executed at least once and which ones did not (e.g., exception handling or conditions that weren't reached?)</p>
<p>A manual way to collect this information would be to constantly step with the debugging and maintain a set of lines where we have passed at least once. However, is there some tool or profiler that already does that?</p>
<p>Edit: Just for clarification: I need to be able to access this information programmatically and not necessarily from a JUnit test.</p>
|
<p><a href="http://www.eclemma.org/" rel="nofollow noreferrer">eclemma</a> would be a good start: a code coverage tool would allow a coverage session to record the information you are looking for.</p>
<p><a href="https://i.stack.imgur.com/bWhQj.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bWhQj.gif" alt="alt text"></a><br>
<sub>(source: <a href="http://www.eclemma.org/images/smallscreen.gif" rel="nofollow noreferrer">eclemma.org</a>)</sub> </p>
|
<p>What you're asking about is called "coverage". There are several tools that measure that, some of which integrate into Eclipse. I've used <a href="http://java-source.net/open-source/code-coverage/jcoverage-gpl" rel="nofollow noreferrer">jcoverage</a> and it works (I believe it has a free trial period, after which you'd have to buy it). I've not used it, but you might also try <a href="http://coverlipse.sourceforge.net/" rel="nofollow noreferrer">Coverlipse</a>.</p>
| 36,829
|
<p>I'm trying to store an xml serialized object in a cookie, but i get an error like this:</p>
<pre><code>A potentially dangerous Request.Cookies value was detected from the client (KundeContextCookie="<?xml version="1.0" ...")
</code></pre>
<p>I know the problem from similiar cases when you try to store something that looks like javascript code in a form input field.</p>
<p>What is the best practise here? Is there a way (like the form problem i described) to supress this warning from the asp.net framework, or should i JSON serialize instead or perhaps should i binary serialize it? What is common practise when storing serialized data in a cookie?</p>
<p>EDIT:
Thanks for the feedback. The reason i want to store more data in the cookie than the ID is because the object i really need takes about 2 seconds to retreive from a service i have no control over. I made a lightweight object 'KundeContext' to hold a few of the properties from the full object, but these are used 90% of the time. This way i only have to call the slow service on 10% of my pages. If i only stored the Id i would still have to call the service on almost all my pages.</p>
<p>I could store all the strings and ints seperately but the object has other lightweight objects like 'contactinformation' and 'address' that would be tedious to manually store for each of their properties.</p>
|
<p>Storing serialized data in a cookie is a very, very bad idea. Since users have complete control over cookie data, it's just too easy for them to use this mechanism to feed you malicious data. In other words: <i>any</i> weakness in your deserialization code becomes instantly exploitable (or at least a way to crash something).</p>
<p>Instead, only keep the simplest identifier possible in your cookies, of a type of which the format can easily be validated (for example, a GUID). Then, store your serialized data server-side (in a database, XML file on the filesystem, or whatever) and retrieve it using that identifier.</p>
<p>Edit: also, in this scenario, make sure that your identifier is random enough to make it infeasible for users to guess each other's identifiers, and impersonate each other by simply changing their own identifier a bit. Again, GUIDs (or ASP.NET session identifiers) work very well for this purpose.</p>
<p>Second edit after scenario clarification by question owner: why use your own cookies at all in this case? If you keep a reference to either the original object or your lightweight object in the session state (Session object), ASP.NET will take care of all implementation details for you in a pretty efficient way.</p>
|
<p>You might look into using <a href="http://msdn.microsoft.com/en-us/library/ms972429.aspx" rel="nofollow noreferrer">Session State</a> to store the value. You can configure it to use a cookie to store the session id. This is also more secure, because the value is neither visible or changeable by the user-side.</p>
<p>Another alternative is to use a distributed caching mechanism to store the value. My current favorite is <a href="http://www.codeplex.com/memcachedproviders" rel="nofollow noreferrer">Memcached</a>.</p>
| 14,545
|
<p>I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException".</p>
<p>The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception."</p>
<p>Here is my app.xaml:</p>
<pre><code><Application x:Class="MyNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
</Application.Resources>
</Application>
</code></pre>
<p>And here is my app.xaml.cs (exception thrown at "public App()"):</p>
<pre><code>public partial class App : Application
{
public App()
{
Bootstrapper bootStrapper = new Bootstrapper();
bootStrapper.Run();
}
}
</code></pre>
<p>I have set the "App" class as the startup object in the project.</p>
<p>What is going astray?</p>
|
<p>Thanks @ima, your answer pointed me in the right direction. I was using an app.config file and it contained this:</p>
<pre><code><configuration>
<startup>
<supportedRuntime version="v2.0.50727" sku="Client"/>
</startup>
<configSections>
<section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
</configSections>
<modules>
<module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/>
</modules>
</configuration>
</code></pre>
<p>It seems the problem was the <startup> element because when I removed it the application ran fine. I was confused because Visual Studio 2008 added that when I checked the box to utilise the "Client Profile" available in 3.5 SP1.</p>
<p>After some mucking about checking and un-checking the box I ended up with a configuration file like this:</p>
<pre><code><configuration>
<configSections>
<section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
</configSections>
<modules>
<module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/>
</modules>
<startup>
<supportedRuntime version="v2.0.50727" sku="Client"/>
</startup>
</configuration>
</code></pre>
<p>Which works!</p>
<p>I'm not sure why the order of elements in the app.config is important - but it seems it is.</p>
|
<p>You have two sections named "modules". Place both module definitions in one section named "modules".</p>
| 8,276
|
<p>I'm currently writing a website that allows people to download Excel and text files. Is there a way to redirect to a different page when they click, so that we run javascript and do analytics (i.e. keep download count)? Currently, nothing prevents the user from simply right-clicking and saving. </p>
<p>Edit: </p>
<p>To be more specific, it would be nice for a single or double click of a file link to redirect to a temporary download page for analytics, then have the file be downloaded.</p>
|
<p>I started describing how you might do this in Grails but then remembered most analytics services (Google, Omniture, etc.) will let you track downloaded files by using the onclick event. If you have some custom javascript based tracking you're doing, you can do the same thing. The onclick will get called before the document starts downloading. For example:</p>
<pre><code><a href="/path-to-download-file" onclick="record_download('filename')">myfile.txt</a>
</code></pre>
<p>More specifically for Google Analytics, here's some javascript to do this automatically:
<a href="http://www.goodwebpractices.com/downloads/gatag.js" rel="nofollow noreferrer">http://www.goodwebpractices.com/downloads/gatag.js</a></p>
|
<p>I'm not sure what you are asking here, are you trying to figure out how to redirect in the controller or are you trying to override the right-click behavior in the browser?</p>
<p>To redirect in the controller you can do something like this documented <a href="http://grails.org/doc/1.0.x/" rel="nofollow noreferrer">here</a>.</p>
<pre><code>redirect(controller:"book",action:"list")
</code></pre>
<p>If you are trying to change button or link behavior that's client side and will require some Javascript most likely.</p>
<p>If you clarify I might be able to help more.</p>
| 20,296
|
<p>I have been reading lots of blog posts offering cause and solution to the "Operation Aborted" error in IE. I recently built an application that is getting this error for some of ther users, some of the time.</p>
<p>Let me explain in detail.</p>
<p>The application is .NET 2.0, ASP .NET and C# web application built in VS 2008. It uses ComponentOne web controls along with standard Visual Studio controls.</p>
<p>In one of the web pages I am letting users type input in a set of ComponentOne Web input controls which then get added to a collection. The collection is bound to repeater and everytime a new entry is made in collection, repeater is rebound. If users delete entry from repeater (using command button), collection is updated and rebound to repeater.</p>
<p>When the application was submitted to end users for testing, a couple of them complained that they were getting "Operation Aborted" error when viewing or working on this page. It will sometime occur the moment user tries to load the page and other times when they are adding/dropping items to the collection.</p>
<p>Those users have IE7 with no third party add-ons other than Adobe PDF and Google Toolbar. The error doesn't occur in FireFox or Google Chrome. It also doesn't occur in IE8 Beta 2.</p>
<p>When I or my fellow developer try to replicate the error using IE7 on our machines, we just can't do that. No matter what we try, we don't get that error.</p>
<p>I also tried IE6 and don't get the error.</p>
<p>The IE7 version are same all across.</p>
<p>Not sure how to go about solving this problem. All the blog posts, forum post talk about JavaScript and altering body elements but not sure how this applies to me and even if it does, why the behavior different in two IE7 browsers?</p>
<p>Any suggestions/help is welcome.</p>
|
<p>The intricacies of your collection and bindings have introduced a <strong>race condition</strong>.</p>
<p>The <strong>Operation Aborted</strong> error is an obscure IE bug, which occurs when the DOM is appended before the page is finished loading.</p>
<p><strong>The Operation Aborted Error</strong></p>
<p>Refer to this question:
<a href="https://stackoverflow.com/questions/267160/what-is-the-operation-aborted-error-in-internet-explorer">What is the Operation Aborted error in Internet Explorer?</a></p>
<p>This isn't intrinsically an asp.net problem, but, in your case, asp.net is failing to control the order of execution, due to the way you've written the databind. In other words, depending on the order in which resources load and execute (which current is not being controlled), the condition exists. </p>
<p>Incidentally, it may be <strong>harder to reproduce</strong> the condition in your development environment if you have some of these resources <strong>cached</strong> on the front end, or if they load more quickly (being available on a <strong>local network</strong>), which would explain why you're having trouble seeing the error.</p>
|
<p>See bug report here:</p>
<p><a href="http://webbugtrack.blogspot.com/2008/08/bug-404-operation-aborted-in-ie.html" rel="nofollow noreferrer">http://webbugtrack.blogspot.com/2008/08/bug-404-operation-aborted-in-ie.html</a></p>
<p>in short:</p>
<ol>
<li><p>The HTML file is being parsed</p></li>
<li><p>script is executing</p></li>
<li><p>The executing script attempts to (add or remove) an element from an unclosed ancestor in the markup tree (excluding immediate parent of the script element)</p></li>
</ol>
<p>The good news is that this is <strong>partially</strong> fixed in IE8.</p>
| 33,422
|
<p>I need to be able to insert/update objects at a consistent rate of at least 8000 objects every 5 seconds in an in-memory HSQL database.</p>
<p>I have done some comparison performance testing between Spring/Hibernate/JPA and pure JDBC. I have found a significant difference in performance using HSQL.. With Spring/Hib/JPA, I can insert 3000-4000 of my 1.5 KB objects (with a One-Many and a Many-Many relationship) in 5 seconds, while with direct JDBC calls I can insert 10,000-12,000 of those same objects. </p>
<p>I cannot figure out why there is such a huge discrepancy. I have tweaked the Spring/Hib/JPA settings a lot trying to get close in performance without luck. I want to use Spring/Hib/JPA for future purposes, expandability, and because the foreign key relationships (one-many and many-many) are difficult to maintain by hand; but the performance requirements seem to point towards using pure JDBC.</p>
<p>Any ideas of why there would be such a huge discrepancy? </p>
|
<p>We have similar experience comparing Hibernate with JDBC in batch mode (Statement#executeBatch()). Basically, it seems like Hibernate just doesn't do that well with bulk operations. In our case, the Hibernate implementation was fast enough on our production hardware.</p>
<p>What you may want to do, is to wrap your database calls in a DAO, giving your application a consistent way of accessing your data. Implement your DAOs with Hibernate where it's convenient, and with JDBC where the performance requirements call for it.</p>
|
<p>All that mapping ... it can get a little bit expensive, with all the arcane logic and all the reflection and consistency-checking that it has to do.</p>
<p>The point of mapping is not to boost performance, of course. Typically, you take a performance hit. But what you lose in performance, you (<em>can</em>) gain many times over in developer productivity, consistency, testability, reliability, and so many more coveted attributes. Typically, when you need the extra performance and you don't want to give up mapping, you drop in some more hardware.</p>
| 32,585
|
<p>OK so I'm looking a some code which looks roughly like this:</p>
<pre><code>void DoSomething(object o)
{
if (o is Sometype1) {
//cast o to Sometype and do something to it
}
else if (o is Sometype2) {
//cast o to Sometype2 and do something to it
}
...
else if (o is SometypeN) {
//cast o to SometypeN and do something to it
}
}
</code></pre>
<p>Now one approach would be to make all the objects <code>o</code> that are used as parameters implement an interface like </p>
<pre><code>interface ICanHaveSomethingDoneToMe
{
//expose various properties that the DoSomething method wants to access
}
</code></pre>
<p>But the problem with this is that I don't want all my objects to implement this interface - the logic for the do something method doesn't really belong with them. What pattern should I be using to deal with this?</p>
<p>I suspect something like a series of implementations of </p>
<pre><code>interface IPropertiesForDoingSomethingTo<T>
{
//expose various properties that the DoSomething method wants to access
}
</code></pre>
<p>might be better. I'd have an implementation for each of the object types that I want to do it to, but then I have this new problem. I would at point need to have a method like</p>
<pre><code>IPropertiesForDoingSomethingTo<T> GetPropsGeneric(T t);
</code></pre>
<p>but is this going to need to have a massive switch on it? Should I define a class with loads of methods like</p>
<pre><code>IPropertiesForDoingSomethingTo<Someobject1> GetProps(Someobject1 t);
...
IPropertiesForDoingSomethingTo<Someobject1> GetProps(SomeobjectN t);
</code></pre>
<p>This has the problem compared to the generic version that you wouldn't be able to add new types at runtime. Ts there something cunning one can do with a DI container in GetPropsGeneric to resolve the container? Thanks!</p>
|
<p>any time you see a switch statement (or a series of if-statements) that are checking the type of an object, this is a Big Red Flag for a missing base class or interface. In other words, the code should be relying on polymorphism, not testing the object type</p>
<p>if you cannot change the base class or implement an interface, you're probably left with a dictionary to simulate dynamic dispatching. In C# you could use an anonymous delegate for the method that included the cast</p>
<p>as for the property access, if the properties don't conform and accessing via reflection is not an option, you may need to extract the property values in the method/delegate above and pass them to a generic function instead</p>
|
<p>A real example would be more helpful. If you are simply changing the implementation of a method for a family of related classes then, as @Steven A. Lowe says, you're best off using polymorphism and using the subclass relationships for this. If the classes don't participate in "is a" relationships, then other patterns like <a href="http://en.wikipedia.org/wiki/Visitor_pattern" rel="nofollow noreferrer">Visitor</a> may be more appropriate.</p>
| 39,391
|
<p>I am new to asp and have a deadline in the next few days.
i receive the following xml from within a webservice response.</p>
<pre><code>print("<?xml version="1.0" encoding="UTF-8"?>
<user_data>
<execution_status>0</execution_status>
<row_count>1</row_count>
<txn_id>stuetd678</txn_id>
<person_info>
<attribute name="firstname">john</attribute>
<attribute name="lastname">doe</attribute>
<attribute name="emailaddress">john.doe@johnmail.com</attribute>
</person_info>
</user_data>");
</code></pre>
<p>How can i parse this xml into asp attributes?</p>
<p>Any help is greatly appreciated</p>
<p>Thanks
Damien</p>
<p>On more analysis, some soap stuff is also returned as the aboce response is from a web service call. can i still use lukes code below?</p>
|
<p>You need to read about MSXML parser. Here is a link to a good all-in-one example <a href="http://oreilly.com/pub/h/466" rel="nofollow noreferrer">http://oreilly.com/pub/h/466</a></p>
<p>Some reading on XPath will help as well. You could get all the information you need in MSDN.</p>
<p>Stealing the code from <a href="https://stackoverflow.com/users/17602/luke">Luke</a> excellent reply for aggregation purposes:</p>
<pre><code>Dim oXML, oNode, sKey, sValue
Set oXML = Server.CreateObject("MSXML2.DomDocument.6.0") 'creating the parser object
oXML.LoadXML(sXML) 'loading the XML from the string
For Each oNode In oXML.SelectNodes("/user_data/person_info/attribute")
sKey = oNode.GetAttribute("name")
sValue = oNode.Text
Select Case sKey
Case "execution_status"
... 'do something with the tag value
Case else
... 'unknown tag
End Select
Next
Set oXML = Nothing
</code></pre>
|
<p>You could try loading the xml into the xmldocument object and then parse it using it's methods.</p>
| 12,029
|
<p>I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from.</p>
<p>Is this possible?</p>
|
<p>Yes. This can be done using the DataGridViewComboBoxCell.</p>
<p>Here is an example method to add the items to just one cell, rather than the whole column.</p>
<pre><code>private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd)
{
DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex];
// You might pass a boolean to determine whether to clear or not.
dgvcbc.Items.Clear();
foreach (object itemToAdd in itemsToAdd)
{
dgvcbc.Items.Add(itemToAdd);
}
}
</code></pre>
|
<pre><code> //Populate the Datatable with the Lookup lists
private DataTable typeDataTable(DataGridView dataGridView, Lookup<string, Element> type_Lookup, Dictionary<Element, string> type_dictionary, string strNewStyle, string strOldStyle, string strID, string strCount)
{
int row = 0;
DataTable dt = new DataTable();
dt.Columns.Add(strOldStyle, typeof(string));
dt.Columns.Add(strID, typeof(string));
dt.Columns.Add(strCount, typeof(int));
dt.Columns.Add("combobox", typeof(DataGridViewComboBoxCell));
//Add All Doc Types to ComboBoxes
DataGridViewComboBoxCell CmBx = new DataGridViewComboBoxCell();
CmBx.DataSource = new BindingSource(type_dictionary, null);
CmBx.DisplayMember = "Value";
CmBx.ValueMember = "Key";
//Add Style Comboboxes
DataGridViewComboBoxColumn Data_CmBx_Col = new DataGridViewComboBoxColumn();
Data_CmBx_Col.HeaderText = strNewStyle;
dataGridView.Columns.Add(addDataGrdViewComboBox(Data_CmBx_Col, type_dictionary));
setCellComboBoxItems(dataGridView, 1, 3, CmBx);
//Add style Rows
foreach (IGrouping<string, Element> StyleGroup in type_Lookup)
{
row++;
//Iterate through each group in the Igrouping
//Add Style Rows
dt.Rows.Add(StyleGroup.Key, row, StyleGroup.Count().ToString());
}
return dt;
}
private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, DataGridViewComboBoxCell CmBx)
{
DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell)dataGrid.Rows[rowIndex].Cells[colIndex];
// You might pass a boolean to determine whether to clear or not.
dgvcbc.Items.Clear();
foreach (DataGridViewComboBoxCell itemToAdd in CmBx.Items)
{
dgvcbc.Items.Add(itemToAdd);
}
</code></pre>
| 11,717
|
<p>I could use some advice on tracking down the cause of memory leaks in C#. I understand what is a memory leak and I get why they occur in C# but I'm wondering what tools/strategies have you used in the past to resolve them?</p>
<p>I am using .NET Memory Profiler and I've found that one of my huge main objects is staying in memory after I close the window it manages but I'm not sure what to do to severe all links to it.</p>
<p>If I'm not being clear enough just post an answer with a question and I'll edit my question in response. Thanks!</p>
|
<p>Break into the debugger and then type this into the Immediate window:</p>
<pre><code>.load C:\Windows\Microsoft.NET\Framework\v2.0.50727\sos.dll
</code></pre>
<p>The path to sos.dll varies. The way to find out the correct path is to look for mscorwks.dll in the Modules pane. Wherever that is loaded from is the correct path for sos.dll.</p>
<p>Then type this:</p>
<pre><code>System.GC.Collect()
</code></pre>
<p>That will ensure anything not reachable is collected. Then type this:</p>
<pre><code>!DumpHeap -type <some-type-name>
</code></pre>
<p>This will show you a table of all existing instances, with addresses. You can find out what is keeping an instance alive like this:</p>
<pre><code>!gcroot <some-address>
</code></pre>
|
<p>.NET Memory Profiler is an excellent tool, and one that I use frequently to diagnose memory leaks in WPF applications.</p>
<p>As I'm sure you're aware, a good way to use it is to take a snapshot before using a particular feature, then take a second snapshot after using it, closing the window, etc. When comparing the two snapshots, you can see how many objects of a certain type are being allocated but not freed: this is a leak.</p>
<p>After double-clicking on a type, the profiler will show you the shortest root paths keeping objects of that type alive. There are many different ways that .NET objects can leak in WPF, so posting the root path that you are seeing should help identify the ultimate cause. In general, however, try to understand why those objects are holding onto your object, and see if there's some way you can detach your event handlers, bindings, etc. when the window is closed.</p>
<p>I recently posted a <a href="http://code.logos.com/blog/2008/10/detecting_bindings_that_should_be_onetime.html" rel="noreferrer">blog entry</a> about a particular <a href="http://support.microsoft.com/kb/938416" rel="noreferrer">memory leak</a> that can be caused by certain bindings; for that specific types of leak, the code there is useful for finding the Binding that's at fault. </p>
| 28,204
|
<p>In order to reference a member of a class in XML comments/documentation, you have to use the following tag:</p>
<pre><code><see cref="member"/>
</code></pre>
<p>It is better explained <a href="http://msdn.microsoft.com/en-us/library/acd0tfbe.aspx" rel="noreferrer">here</a>.</p>
<p><strong>How do you reference an <em>indexer</em>?</strong></p>
<p>I mean, a member like this one:</p>
<pre><code>internal object this[ int index ] {
...
}
</code></pre>
<p>Thanks in advance.</p>
|
<pre><code><see cref="P:System.Collections.ArrayList.Item(System.Int32)" />
</code></pre>
|
<p>In general, in order to find out, how to reference any member in your comments, find the member in your XML documentation file for the assembly. It is created on each build. With the only exception of generics the member reference can be taken from here: </p>
<pre><code></member>
<member name="P:My.Namespace.Class1.Item(System.String)">
<summary>
retrieve a single item of the given name from this instance
</summary>
<param name="name">name of the item</param>
<returns>the item</returns>
</member>
<member name="M:My.Namespace.Class1.Function1(System.Int32[])">
<summary>
...
</code></pre>
<p>Unfortunately, generic definition formats seem not to be compatible between the documentation file and the cref tags. While in the XML file, generics look like that: </p>
<pre><code><member name="M:My.Namespace.Class1.Get``1(System.String)">
<summary>
retrieve an named item of the given type
</summary>
<typeparam name="T">the type of the item to retrieve</typeparam>
...
</code></pre>
<p>The <code>cref</code> tag expects them in one of the following formats: </p>
<pre><code>/// <seealso cref="M:My.Namespace.Class1.Get{T}(System.String)"/>
/// <seealso cref="M:My.Namespace.Class1.Get&lt;T>(System.String)"/>
</code></pre>
| 44,325
|
<p>In SQL Server 2005, are there any disadvantages to making all character fields nvarchar(MAX) rather than specifying a length explicitly, e.g. nvarchar(255)? (Apart from the obvious one that you aren't able to limit the field length at the database level)</p>
|
<p>Same question was asked on MSDN Forums:</p>
<ul>
<li><a href="https://social.msdn.microsoft.com/Forums/sqlserver/en-US/4d9c6504-496e-45ba-a7a3-ed5bed731fcc/varcharmax-vs-varchar255" rel="noreferrer">Varchar(max) vs Varchar(255)</a></li>
</ul>
<p>From the original post (much more information there):</p>
<blockquote>
<p>When you store data to a VARCHAR(N) column, the values are physically stored in the same way. But when you store it to a VARCHAR(MAX) column, behind the screen the data is handled as a TEXT value. So there is some additional processing needed when dealing with a VARCHAR(MAX) value. (only if the size exceeds 8000)</p>
<p>VARCHAR(MAX) or NVARCHAR(MAX) is considered as a 'large value type'. Large value types are usually stored 'out of row'. It means that the data row will have a pointer to another location where the 'large value' is stored...</p>
</blockquote>
|
<p>This will cause a performance problem, although it may never cause any actual issues if your database is small. Each record will take up more space on the hard drive and the database will need to read more sectors of the disk if you're searching through a lot of records at once. For example, a small record could fit 50 to a sector and a large record could fit 5. You'd need to read 10 times as much data from the disk using the large record.</p>
| 17,882
|
<p>I want to make a WPF Window that behaves like a context menu.</p>
<p>So, for instance - when I show the wpf window, I want it to be the topmost window and from there on out, if the user clicks anything outside of that window I want the window to be hidden again.</p>
<p>So far I have tried quite a few techniques but the only one that I found that kinda works is shown here. It works the very first time but never again after that:</p>
<pre><code>public TheWindow()
{
InitializeComponent();
this.Topmost = true;
}
void ShowMe()
{
this.Show();
this.CaptureMouse();
}
void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
/// TODO: Check if they clicked outside the window here!
this.ReleaseMouseCapture();
this.Hide();
}
</code></pre>
<p>I also tried just handling the Deactivated event, but it also only works the first time for some reason.</p>
|
<p>Is <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.popup.aspx" rel="nofollow noreferrer">PopUp</a> not sufficient for your needs? It has a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.popup.staysopen.aspx" rel="nofollow noreferrer">StaysOpen</a> property that lets it act like you describe.</p>
|
<p>Don't know how helpful this will be, but if you don't necessarily need a Window, one technique I have used is placing a UserControl inside a Window.</p>
<p>Depending on whatever condition, you would show a context menu. Inside the menu I placed a menu item and inside that just place the user control. It will behave exactly like what you want. You can show the context menu anywhere on the screen and clicking outside its bounds will close it.</p>
<p>See: <a href="http://andyonwpf.blogspot.com/2006/10/dropdownbuttons-in-wpf.html" rel="nofollow noreferrer">http://andyonwpf.blogspot.com/2006/10/dropdownbuttons-in-wpf.html</a>
for an example of how one would show a context menu anywhere on the screen. Also, you would need to override the default template for MenuItem so that mousing over the menu item doesn't highlight it.</p>
| 47,115
|
<p>I have a public property set in my form of type <code>ListE<T></code> where:</p>
<pre><code>public class ListE<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
</code></pre>
<p>Yeah, it's a mouthful, but that's what the Designer requires for it to show up as an editable collection in the Properties window. Which it does! So, I click the little [..] button to edit the collection, and then click Add to add an item to the collection.</p>
<blockquote>
<p>Arithmetic operation resulted in an overflow.</p>
</blockquote>
<p>Now, this is a very basic List, little more than an expanding array. The only part that comes close to arithmetic in the whole thing is in the expand function, and even that uses a left shift rather than a multiplication, so that won't overflow. This all makes me think that this exception is being raised inside the Designer, perhaps caused by some small inattention to implementation detail on my part, but I can't find a way to test or debug that scenario. Does anyone have any smart ideas?</p>
<p>EDIT: Yes, I can use the property successfully, well even manually, ie. in the <code>OnLoad</code> handler, and I suppose that's what I'll have to resort to if I can't get this working, but that wouldn't be ideal. :(</p>
|
<p>I can't understand what's motivating you to attempt to reinvent the List<T> wheel in that way, but to answer your question: I would add a line "System.Diagnostics.Debugger.Break()" to the constructor of your class.</p>
<p>Then try to use it in the designer, and you'll get a popup asking you if you want to attach a debugger. Attach a second instance of Visual Studio as a debugger, and you'll be able to set some breakpoints in your code and start debugging.</p>
|
<p>One place to start would be that it may be doing math with your ListE`1::Count property. If that has some subtle flaw (i.e. it is more complicated than return this.innerList.Count) it could be causing the designer to arithmetic overflow on some operation. Normally arithmetic overflows do not occur unless specifically asked for using the</p>
<pre><code>checked
{
// ...
}
</code></pre>
<p>syntax.</p>
| 13,604
|
<p>I'm trying to use TJCLHashMap family of classes, but apparently this class has no useful public methods. All methods are "protected". How to use this class? Although JCL comes with some samples, I seem to miss something. A basic example would be great.</p>
|
<p>You should use the interfaces declared in JclContainerIntf.pas. The classes in JclHashMaps implement those interfaces.<br>
Take a look at jcl\examples\common\containers\hashing\HashingExample.dpr for a few examples (integer, strings, objects, etc.)</p>
|
<p>Extend it and add public methods that call the protected methods internally?</p>
| 30,762
|
<p>I have an OpenGL RGBA texture and I blit another RGBA texture onto it using a framebuffer object. The problem is that if I use the usual blend functions with
<code>glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA),</code>
the resulting blit causes the destination texture alpha to change, making it slightly transparent for places where alpha previously was 1. I would like the destination surface alpha never to change, but otherwise the effect on RGB values should be exactly like with <code>GL_SRC_ALPHA</code> and <code>GL_ONE_MINUS_SRC_ALPHA</code>. So the blend factor functions should be (As,As,As,0) and (1-As,1-As,1-As,1). How can I achieve that?</p>
|
<p>You can set the blend-modes for RGB and alpha to different equations:</p>
<pre><code>void glBlendFuncSeparate(
GLenum srcRGB,
GLenum dstRGB,
GLenum srcAlpha,
GLenum dstAlpha);
</code></pre>
<p>In your case you want to use the following enums:</p>
<pre><code> glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE);
</code></pre>
<p>Note that you may have to import the glBlendFuncSeparate function as an extension. It's safe to do so though. The function is around for a very long time. It's part of OpenGL 1.4</p>
<p>Another way to do the same is to disable writing to the alpha-channel using glColorMask:</p>
<pre><code>void glColorMask( GLboolean red,
GLboolean green,
GLboolean blue,
GLboolean alpha )
</code></pre>
<p>It <strong>could</strong> be a lot slower than glBlendFuncSeparate because OpenGL-drivers optimize the most commonly used functions and glColorMask is one of the rarely used OpenGL-functions. </p>
<p>If you're unlucky you may even end up with software-rendering emulation by calling oddball functions :-)</p>
|
<p>Maybe you could use <a href="http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/colormask.html" rel="nofollow noreferrer">glColorMask</a>()? It let's you enable/disable writing to each of the four color components.</p>
| 17,604
|
<p>Can anyone suggest a way of getting version information into a Web Service? (VB.NET)</p>
<p>I would like to dynamically use the assembly version in the title or description, but the attributes require constants. </p>
<p>Is manually writing the version info as a string the only way of displaying the information on the .asmx page?</p>
|
<p>I have been looking at this kind of functionality myself recently and have decided on using jQuery with the help of <a href="http://ui.jquery.com/" rel="noreferrer">jQuery UI</a>. I came across a large amount of information that also suggested <a href="http://developer.yahoo.com/yui/" rel="noreferrer">Yahoo UI</a> (YUI), I had already started learning <a href="http://jQuery.com" rel="noreferrer">jQuery</a> due to the AJAX support that it offers, so I stuck with it.</p>
<p><a href="http://ui.jquery.com/" rel="noreferrer">jQuery UI Site</a><br/>
<a href="http://docs.jquery.com/UI" rel="noreferrer">jQuery UI Documentation</a><br/>
<a href="http://ui.jquery.com/repository/real-world/layout/" rel="noreferrer">Example of a drag and drop screen layout with jQuery UI</a><br/>
<a href="http://www.learningjquery.com/2008/07/introduction-to-jquery-ui#" rel="noreferrer">Introduction to jQuery UI</a></p>
<p>If you decide to use the YUI javascript library, here is a link to a vast amount of videos to help get you started.</p>
<p><a href="http://developer.yahoo.com/yui/theater/" rel="noreferrer">http://developer.yahoo.com/yui/theater/</a></p>
|
<p>I used the Microsoft ASP.Net Ajax and AjaxControlToolkit to do something like this. They have a ResizeableControl and a DragPanel. I used these, then hosted an IFrame inside the panel to display the content.</p>
<p>Worked pretty well.</p>
<hr>
<p>This site:</p>
<p><a href="http://www.asp.net/learn/videos/default.aspx?tabid=63#ajax" rel="nofollow noreferrer">http://www.asp.net/learn/videos/default.aspx?tabid=63#ajax</a></p>
<p>Has lots of tutorial videos that show you how to get started using the controls.</p>
| 3,695
|
<p>I have written a program in C to parse large XML files and then create files with insert statements. Some other process would ingest the files into a MySQL database.
This data will serve as a indexing service so that users can find documents easily.</p>
<p>I have chosen InnoDB for the ability of row-level locking. The C program will be generating any where from 500 to 5 million insert statements on a given invocation.</p>
<p>What is the best way to get all this data into the database as quickly as possible? The other thing to note is that the DB is on a separate server. Is it worth moving the files over to that server to speed up inserts?</p>
<p>EDIT: This table won't really be updated, but rows will be deleted. </p>
|
<ul>
<li>Use the mysqlimport tool or the LOAD DATA INFILE command.</li>
<li>Temporarily disable indices that you don't need for data integrity</li>
</ul>
|
<p>MySQL with the standard table formats is wonderfully fast as long as it's a write-only table; so the first question is whether you are going to be updating or deleting. If not, don't go with innosys - there's no need for locking if you are just appending. You can truncate or rename the output file periodically to deal with table size.</p>
| 40,600
|
<p>I'm trying to call a 3rd party vendor's C DLL from vb.net 2005 and am getting <code>P/Invoke</code> errors. I'm successfully calling other methods but have hit a bottle-neck on one of the more complex. The structures involved are horrendous and in an attempt to simplify the troubleshooting I'd like to create a C++ DLL to replicate the problem. </p>
<p>Can somebody provide the smallest code snippet for a C++ DLL that can be called from .Net? I'm getting a <code>Unable to find entry point named XXX in DLL</code> error in my C++ dll. It should be simple to resolve but I'm not a C++ programmer.</p>
<p>I'd like to use a .net declaration for the DLL of</p>
<pre><code>Declare Function Multiply Lib "C:\MyDll\Debug\MyDLL.DLL" Alias "Multiply" (ByVal ParOne As Integer, ByVal byvalParTwo As Integer) As Integer
</code></pre>
|
<p>Try using the <a href="http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx" rel="nofollow noreferrer">__decspec(dllexport)</a> magic pixie dust in your C++ function declaration. This declaration sets up several things that you need to successfully export a function from a DLL. You may also need to use WINAPI or something similar:</p>
<pre><code>__declspec(dllexport) WINAPI int Multiply(int p1, int p2)
{
return p1 * p2;
}
</code></pre>
<p>The WINAPI sets up the function calling convention such that it's suitable for calling from a language such as VB.NET.</p>
|
<p>You can try to look at the exported functions (through DumpBin or Dependency Walker) and see if the names are mangled.</p>
| 6,009
|
<p>I'm familiar with object-oriented architecture, including use of design patterns and class diagrams for visualization, and I know of service-oriented architecture with its contracts and protocol bindings, but <strong>is there anything characteristic about a software architecture for a system written in a functional programming language?</strong></p>
<p>I know that FP has been used for medium-size to large scale projects. Paul Graham wrote the first incarnation of Yahoo! Store in Common Lisp. Some lisp development systems are complex. Artifical intelligence and financial systems written in functional languages can get pretty big. They all have at least some kind of inherent architecture, though, I'm wondering if they have anything in common?</p>
<p>What does an architecture based on the evaluation of expressions look like? Are FP architectures more composable?</p>
<p><strong>Update:</strong> Kyle reminded me that <a href="http://mitpress.mit.edu/sicp/" rel="noreferrer">SICP</a> is a good resource for this subject.</p>
<p><strong>Update 2:</strong> I found a good post on the subject: <em><a href="http://lorgonblog.spaces.live.com/Blog/cns!701679AD17B6D310!511.entry" rel="noreferrer">How does functional programming affect the structure of your code?</a></em></p>
|
<p>The common thread in the "architecture" of projects that use functional languages is that they tend to be separated into layers of algebras rather than subsystems in the traditional systems architecture sense.</p>
<p>For great examples of such projects, check out <a href="http://xmonad.org/" rel="noreferrer">XMonad</a>, <a href="http://www.haskell.org/haskellwiki/Yi" rel="noreferrer">Yi</a>, and <a href="http://happs.org/" rel="noreferrer">HappS</a>. If you examine how they are structured, you will find that they comprise layers of monadic structure with some combinator glue in between.</p>
<p>Also look at <a href="http://www.cs.princeton.edu/~dpw/popl/06/odersky.pdf" rel="noreferrer">The Scala Experiment</a> paper which outlines an architecture where a system is composed of components that abstract over their dependencies.</p>
|
<p>I think this may help; </p>
<blockquote>
<p>Some of the patterns disappear -- that
is, they are supported directly by
language features, some patterns are
simpler or have a different focus, and
some are essentially unchanged.</p>
</blockquote>
<p>[AIM-2002-005] Gregory T. Sullivan, <a href="http://dspace.mit.edu/handle/1721.1/6686" rel="nofollow noreferrer">Advanced Programming Language Features for Executable Design Patterns "Better Patterns Through Reflection</a></p>
<p>March 22, 2002</p>
<blockquote>
<p>The Design Patterns book [GOF95]
presents 24 time-tested patterns that
consistently appear in well-designed
software systems. Each pattern is
presented with a description of the
design problem the pattern addresses,
as well as sample implementation code
and design considerations. This paper
explores how the patterns from the
"Gang of Four'', or "GOF'' book, as it
is often called, appear when similar
problems are addressed using a
dynamic, higher-order, object-oriented
programming language. Some of the
patterns disappear -- that is, they
are supported directly by language
features, some patterns are simpler or
have a different focus, and some are
essentially unchanged.</p>
</blockquote>
| 11,479
|
<p><strong>Is there a YAML driver for the Java <a href="http://x-stream.github.io/" rel="nofollow noreferrer">XStream</a> package?</strong></p>
<p>I'm already using XStream to serialise/deserialise both XML and JSON. I'd like to be able to do the same with YAML.</p>
|
<p>To parse a YAML document you can use this chain:
YAML -> SnakeYAML -> Java -> Your Application (-> XStream -> XML)</p>
<p>Emitting YAML is simpler and there are a couple of options:
1) Your Application -> XStream with Custom Writer -> YAML
2) Your Application -> SnakeYAML -> YAML</p>
<p>The second option does not require any additional development.</p>
|
<p>I used JYAML and it worked great. I know it doesn't directly answer your question but it works well.</p>
| 45,292
|
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p>
<p>What I'm doing now:</p>
<pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def doGET
[...]
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)
server.serve_forever()
</code></pre>
|
<p>Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <a href="http://localhost:1111/" rel="noreferrer">http://localhost:1111/</a> and <a href="http://localhost:2222/" rel="noreferrer">http://localhost:2222/</a></p>
<pre><code>from threading import Thread
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write("Hello World!")
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
def serve_on_port(port):
server = ThreadingHTTPServer(("localhost",port), Handler)
server.serve_forever()
Thread(target=serve_on_port, args=[1111]).start()
serve_on_port(2222)
</code></pre>
<p><em>update:</em></p>
<p>This also works with Python 3 but three lines need to be slightly changed:</p>
<pre><code>from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
</code></pre>
<p>and</p>
<pre><code>self.wfile.write(bytes("Hello World!", "utf-8"))
</code></pre>
|
<p>Not easily. You could have two ThreadingHTTPServer instances, write your own serve_forever() function (don't worry it's not a complicated function).</p>
<p>The existing function:</p>
<pre><code>def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__serving = True
self.__is_shut_down.clear()
while self.__serving:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = select.select([self], [], [], poll_interval)
if r:
self._handle_request_noblock()
self.__is_shut_down.set()
</code></pre>
<p>So our replacement would be something like:</p>
<pre><code>def serve_forever(server1,server2):
while True:
r,w,e = select.select([server1,server2],[],[],0)
if server1 in r:
server1.handle_request()
if server2 in r:
server2.handle_request()
</code></pre>
| 8,566
|
<p>What is the maxiimum boost factor value for a word in Lucene.Net?
I believe default value is 1.0f</p>
<p>Thanks!</p>
|
<p>It can be any positive number. Of course, if you pick an unreasonable number, like Float.POSITIVE_INFINITY (or the .NET equivalent), you'll end up with some crazy scores. Generally, you want to look at your boosts as a percentage: 1.0F is 100%, meaning no boost up or down. 1.2F is 120%, a little boost up; 0.5 is 50%, a fairly significant boost down.</p>
|
<p>I've found evidence on Google that it's at least 4... but I can't find any further information as to what the ceiling is. Some of the document importance descriptions use 4 as an example which is where I drew my conclusion.</p>
<p>However the user documentation defines that it must be a positive number which may be less than 1 (presumably, given some of the examples it may also not be less than 1).</p>
<p>Draw from that as you will.</p>
| 44,581
|
<p>I am using jQuery to try and trigger a method when an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> (2.0) dropdown list's change event is handled by jQuery. The problem is that the drop down list is located inside a gridview and even then only when a user has decided to edit a row within that gridview.</p>
<p>I think I have it picking up the object using an ASP code block, but the problem with that is that when the page first loads the edit index of the row does not exist and it throws an error. Putting the block inside a <code>IF</code> statement also does not work.</p>
<pre><code>$(document).ready(function() //when DOM is ready, run containing code
{
<% if (grvTimeSheets.EditIndex > -1) {%>
$(#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>).change(function() {
$(#<%= grvTimeSheets.ClientID %>).block({ message: null }
});
}
);
<% } %>
</code></pre>
<p>It is one attempt I made, and I also tried putting the IF statement ASP code outside the JavaScript block. It doesn't work either.</p>
<p>How could I apply the jQuery event to the drop drop box? Ideally as concise as possible.</p>
<hr>
<p>Thanks for the answer but nope, it doesn't work :(. The JavaScript code seems not to be outputted... Confusing...</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.js"></script>
<script type="text/javascript" src="jquery.blockUI.js"></script>
<script type="text/javascript">
$(document).ready(function() //When DOM is ready, run the containing code
{
}
);
</script>
</code></pre>
<p>Is the output. Even though this is the code:</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.js"></script>
<script type="text/javascript" src="jquery.blockUI.js"></script>
<script type="text/javascript">
$(document).ready(function() //when DOM is ready, run containing code
{<% if (grvTimeSheets.EditIndex > -1) {%>
var id = '#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>';
$(id).change(function() {
$(id).block({ message: null }
});
<% } %>
}
);
</script>
</code></pre>
<p>It was doing that before as well, driving me CRAZY.</p>
<hr>
<p>Sorry, could you make that slightly clearer. I tried defining the entire thing in code behind like so:</p>
<pre><code>DropDownList ddl (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients");
if (ddl != null)
{
ClientScriptManager csm = Page.ClientScript;
Type cstype = this.GetType();
String csname1 = "PopupScript";
string script = @"
<script language='javascript' type='text/javascript'>
$(#" + ddl.ClientID + ").change(function() { $(" + grvTimeSheets.ClientID + ").blockUI({ message: null }});} </script>";
csm.RegisterStartupScript(cstype, csname1, script, true);
}
</code></pre>
<p>Is that what you meant?</p>
<p>BTW, the above didn't work. No errors, just no events worked.</p>
|
<p>A couple of things here.</p>
<ol>
<li>You need to wrap your selectors in quotes when you pass them to the <code>$()</code> function. The code snippet above generates something like <code>$(#some-generated-id)</code>, which won't work.</li>
<li>The closing curly brace for your server side if statement was outside the onready function. It needs to be nested at the same level as the opening if.</li>
</ol>
<p>Try this one:</p>
<pre><code>$(document).ready(function() //when DOM is ready, run containing code
{
<% if (grvTimeSheets.EditIndex > -1) {%>
var id = '#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>';
$(id).change(function() {
$(id).block({ message: null }
});
<% } %>
}
);
</code></pre>
<p>If it doesn't work, go ahead and paste the generated javascript as well.</p>
|
<p>The key can be anything you want, it should be unique though.</p>
| 34,232
|
<p>I'm using VB .NET 2005 and Exchange Server 2003 installed
I have found some code which gives me the ability to connect in an Exchange Server and create an appointment.
The thing is that I cannot find the CDO. Appointment.
Where can I find it and make the below code to work ?
I have tried all the examples with CDO and Outlook.
I believe that the below code need to be produced in an Exchange environment and use CDOEX.DLL ?
Appreciate any help or ideas you can give me.
Thank you</p>
<p>[Sample Code]</p>
<pre><code>sURL = "http://ExchangeServername/Exchange/testuser/calendar"
Dim oCn As ADODB.Connection = New ADODB.Connection()
'oCn.Provider = "exoledb.datasource";
'I am using the below provider because I am in the client side
oCn.Provider = "MSDAIPP.DSO"
oCn.Open(sURL, "testuser", "q1w2e3r4t5", 0)
If oCn.State = 1 Then
MsgBox("Good Connection")
Else
MsgBox("Bad Connection")
Return
End If
Dim iConfg As CDO.Configuration = New CDO.Configuration()
Dim oFields As ADODB.Fields
oFields = iConfg.Fields
oFields.Item(CDO.CdoCalendar.cdoTimeZoneIDURN).Value = CDO.CdoTimeZoneId.cdoAthens
'oFields.Item(CDO.CdoConfiguration.cdoSendEmailAddress).Value = "test@test.com"
oFields.Update()
Dim oApp As CDO.Appointment = New CDO.Appointment()
oApp.Configuration = iConfg
oApp.StartTime = Convert.ToDateTime("10/11/2001 10:00:00 AM")
oApp.EndTime = Convert.ToDateTime("10/11/2001 11:00:00 AM")
oApp.Location = "My Location"
oApp.Subject = "Test: Create Meeting in VB.NET"
oApp.TextBody = "Hello..."
'' Add recurring appointment
'' Every Thursday starting today, and repeat 3 times.
'' Save to the folder
oApp.DataSource.SaveToContainer(sURL, , _
ADODB.ConnectModeEnum.adModeReadWrite, _
ADODB.RecordCreateOptionsEnum.adCreateNonCollection, _
ADODB.RecordOpenOptionsEnum.adOpenSource, _
"", "")
oCn.Close()
oApp = Nothing
oCn = Nothing
oFields = Nothing
</code></pre>
|
<p>CDO.Appointment indeed is part of cdoex.dll (Collaboration Data Objects for Exchange) that comes with some versions of Exchange, SPS and Office. You can download and register cdoex.dll on your machine, and reference it in your VB.Net application.</p>
<p>These posts should be helpful:</p>
<ul>
<li><a href="http://support.microsoft.com/kb/310557" rel="nofollow noreferrer">http://support.microsoft.com/kb/310557</a></li>
<li><a href="http://mrspeaker.webeisteddfod.com/2005/05/02/cdoex/" rel="nofollow noreferrer">http://mrspeaker.webeisteddfod.com/2005/05/02/cdoex/</a></li>
</ul>
|
<p>If you cannot find a copy of <code>cdoex.dll</code> on your local PC or server, try these downloads:</p>
<p><a href="http://www.google.nl/search?q=download+CDOEX.DLL" rel="nofollow noreferrer">http://www.google.nl/search?q=download+CDOEX.DLL</a></p>
| 36,402
|
<p>I have a Rails application for project management where there are Project and Task models. A project can have many tasks, but a task can also have many tasks, ad infinitum.</p>
<p>Using nested resources, we can have /projects/1/tasks, /projects/1/tasks/new, /projects/1/tasks/3/edit etc.</p>
<p>However, how do you represent the recursive nature of tasks RESTfully? I don't want go another level deep, so perhaps the following would do:</p>
<pre><code>map.resources :tasks do |t|
t.resources :tasks
end
</code></pre>
<p>That would give me the following urls:</p>
<pre><code>/tasks/3/tasks/new
/tasks/3/tasks/45/edit
</code></pre>
<p>Or perhaps when it comes to an individual task I can just use /tasks/45/edit</p>
<p>Is this a reasonable design?</p>
<p>Cam</p>
|
<p>Going anywhere beyond a single nested route is generally considered a bad idea.</p>
<p>From page 108 of <strong>The Rails Way</strong>:</p>
<p><a href="http://weblog.jamisbuck.org/2007/2/5/nesting-resources" rel="noreferrer">"<em>Jamis Busk a very influential figure in the Rails community, almost as much as David himself. In February 2007, vis his blog, he basically told us that deep nesting was a _bad_ thing, and proposed the following rule of thumb: Resources <strong>should never</strong> be nested more than one level deep.</em>"</a></p>
<p>Now some would argue with this (which is discussed on page 109) but when you're talking about nesting tasks with tasks it just doesn't seem to make much sense.</p>
<p>I would approach your solution a different way and like it was mentioned above, a project should have many tasks but for a task to have many tasks doesn't seem correct and maybe those should be re-named as sub-tasks or something along those lines.</p>
|
<p>there's no reason they should have decendant URLS. </p>
<p>logically:</p>
<pre>
/projects/1 --> project 1
/projects/1/edit ( etc )
/tasks/1 --> task 1
/project/1/tasks --> task list for project 1
/project/1/tasks/new
/project/1/tasks/1/edit -> /tasks/5/edit ( redundancy )
/project/1/tasks/1 -> redirect to /tasks/1
/tasks/1/project -> redirect to /projects/1
/tasks/3/tasks --> list of tasks that are children tasks of task 3
/tasks/3/tasks/5 -> redirect /tasks/5/ ( because you don't really need to have a recursive URL )
/tasks/5/parents -> list of tasks that are parents of tasks 3
/tasks/5/parents/3 -> redirect /tasks/3/
</pre>
<p>there's no reason IMHO to require the URLs be associative, you're not going to need to know that task 5 is a child of task 3 to edit task 5. </p>
| 20,988
|
<p>I am using:</p>
<pre><code>set constraints all deferred;
(lots of deletes and inserts)
commit;
</code></pre>
<p>This works as expected. If there are any broken relationships then the commit fails and an error is raised listing ONE of the FKs that it fails on.</p>
<p>The user fixes the offending data and runs again. then hits another FK issue and repeats the process.</p>
<p>What I really want is a list of ALL FKs in one go that would cause the commit to fail.</p>
<p>I can of course write something to check every FK relationship through a select statement (one select per FK), but the beauty of using the deferred session is that this is all handled for me.</p>
|
<p>First option, you can look into <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_9014.htm#BGBEIACB" rel="nofollow noreferrer">DML error logging</a>. That way you leave your constraints active, then do the inserts, with the erroring rows going into error tables. You can find them there, fix them, re-insert the rows and delete them from the error table.</p>
<p>The second option is, rather than trying the commit, attempt to re-enable each deferred constraint dynamically, catching the errors. You'd be looking at a PL/SQL procedure that queries ALL_CONSTRAINTS for the deferrable ones, then does an EXECUTE IMMEDIATE to make that constraint immediate. That last bit would be in a block with an exception handler so you can catch the ones that fail, but continue on.</p>
<p>Personally, I'd go for option (1) as you do get the individual records that fail, plus you don't have to worry about deferrable constraints and remembering to make them immediate again after this script so it doesn't break something later.</p>
<p>I guess somewhere in memory Oracle must be maintaining a list, at least of constraints that failed if not the actual rows. I'm pretty confident it doesn't rescan the whole set of tables at commit time to check all the constraints. </p>
|
<p>Oracle's Error Mechanism is too primitive to return a collection of all errors that COULD occur. I mean, it's a cool thought but think about what you'd have to do if you wrote the code. Your standard error handling would need to be thwarted. Instead of returning an error as soon as you encounter it, you'd have to continue somehow to see if you could proceed if the first error you caught wasn't an error at all. And even if you did all of this you'd still face he possibility that the row you add that fixes the first error actually causes the second error. </p>
<p>For example:</p>
<p>A is the parent of B is the parent of C. I defer and I insert C. I get an error that there's no B record parent. I defer and I add B. Now I get another error that there's no A. </p>
<p>This is certainly possible and there's no way to tell in advance. </p>
<p>I think you're looking for the server to do some work that's really your responsibility. At the risk of mod -1, you're using a technique for firing an automatic weapon called "Spray and Pray" -- Fire as many rounds as possible and hope you kill the target. That approach just can't work here. You disable your RI and do a bunch of steps and hope that all the RI works out in the end when the database "grades" your DML.</p>
<p>I think you have to write the code.</p>
| 35,215
|
<p>How can i make my Java Swing GUI Components [Right To Left] for Arabic language from NetBeans Desktop Application?</p>
|
<p>Don't you just have to use:</p>
<pre><code>Component.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT )
</code></pre>
<p>I believe that the swing components all already have support for RTL, don't they?</p>
<p>Not sure how/where you'd do that in regards to netbeans, though.</p>
|
<p>you could use it if you have components inside panels inside contentPane</p>
<pre><code> Component[] component = contentPane.getComponents();
for(int i=0; i<component.length; i++){
component[i].applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
Component[] cp = ((Container) component[i]).getComponents();
for(int j=0; j<cp.length; j++){
try{
((Component) ((JComboBox) cp[j]).getRenderer()).applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}catch(Exception e){
continue;
}
}
}
</code></pre>
| 46,220
|
<p>What is the difference, if any, between these methods of indexing into a PHP array:</p>
<pre><code>$array[$index]
$array["$index"]
$array["{$index}"]
</code></pre>
<p>I'm interested in both the performance and functional differences.</p>
<h3>Update:</h3>
<p>(In response to @Jeremy) I'm not sure that's right. I ran this code:</p>
<pre><code> $array = array(100, 200, 300);
print_r($array);
$idx = 0;
$array[$idx] = 123;
print_r($array);
$array["$idx"] = 456;
print_r($array);
$array["{$idx}"] = 789;
print_r($array);
</code></pre>
<p>And got this output:</p>
<pre><code>Array
(
[0] => 100
[1] => 200
[2] => 300
)
Array
(
[0] => 123
[1] => 200
[2] => 300
)
Array
(
[0] => 456
[1] => 200
[2] => 300
)
Array
(
[0] => 789
[1] => 200
[2] => 300
)
</code></pre>
|
<p>see @svec and @jeremy above. All array indices are of type 'int' first, then type 'string', and will be cast to that as PHP sees fit.</p>
<p>Performance wise, $index should be faster than "$index" and "{$index}" (which are the same). </p>
<p>Once you start a double-quote string, PHP will go into interpolation mode and treat it as a string first, but looking for variable markers ($, {}, etc) to replace from the local scope. This is why in most discussions, true 'static' strings should always be single quotes unless you need the escape-shortcuts like "\n" or "\t", because PHP will not need to try to interpolate the string at runtime and the full string can be compiled statically.</p>
<p>In this case, doublequoting will first copy the $index into that string, then return the string, where directly using $index will just return the string.</p>
|
<p>I believe from a performance perspective that $array["$index"] is faster than $array[$index] See <a href="http://www.chazzuka.com/blog/?p=163" rel="nofollow noreferrer">Best practices to optimize PHP code performance</a></p>
<p>Another variation that I use sometimes when I have an array inside a string is:</p>
<pre><code>$str = "this is my string {$array["$index"]}";
</code></pre>
<p>Edit: What I meant to say is $row[’id’] is faster than $row[id]</p>
| 2,835
|
<p>I have a problem in regards to filament jam, however I don't think that my case is any related to the extruder nozzle.
After 30 to 40 minutes printing my filament bends and get stuck on the tube entrance.
To print a nut wheel which comes as a demo file, I had to repeat the operation 4 times, and I had to stop printing when it got stuck, and continue with the printing, which led to a small imperfection.
What's the problem? The filament? The printer? Myself?
I have a Voxelab Aquila (completely new) and the filament u just a generic PLA from Amazon.</p>
<p><a href="https://i.stack.imgur.com/SkWzF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SkWzF.jpg" alt="Filament jam" /></a>
<a href="https://i.stack.imgur.com/Hs1qY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hs1qY.jpg" alt="Filament jam from another angle" /></a></p>
|
<p>Something is stopping the filament from going down the tube 30 to 40 min. after you start printing. You are correct that this doesn't sound like a clogged nozzle. It could be deformed filament, but the closeness of the timing after the start sounds like heat creep. Other possibilities are also listed at the linked stackexchange article.</p>
<p>Note: with heat creep the filament will not jam in the tube. It will jam just above the nozzle on a Bowden tube extruder; thus the filament stops going down the tube. The tube entrance is probably the largest location the tube can kink, although not very large.</p>
<p><a href="https://3dprinting.stackexchange.com/questions/15629/what-are-ways-to-avoid-heat-creep">What are ways to avoid heat creep?</a></p>
|
<p>You need a better filament quality I have the same printer and I had switched to Overture. Know use PLA Plus or (PLA+)due to not sticking to the bed well enough and your issue. And this issue may be the way the entire module moves up and down the threads may need better positioning like tighten loosen or even level it out check for a bend.</p>
| 1,921
|
<p>I'm working on a visual studio 2005 vb.net windows forms project that's been around for several years. It's full of default textboxes, labels, dropdowns, datagrids, datetime pickers -- all the standard stuff. The end result is a very gray, old-looking project.</p>
<p>What would be the best approach to making this project look fresh and snazzy? I'd rather not rewrite the entire solution with all brand new forms objects, but would that be avoidable?</p>
|
<p>I was actually just sprucing up a dialog today. A lot of it depends on what kind of application you have, and what OS it is running on. A couple of these tips will certainly go a long way to jazzing things up.</p>
<ol>
<li><p>Ensure adequate spacing between controls — don't cram them all together. Space is appealing. You might also trying flowing the controls a little differently when you have more space.</p></li>
<li><p>Put in some new 3D and glossy images. You can put a big yellow exclamation mark on a custom warning dialog. Replace old toolbar buttons with new ones. Two libraries I have used and like are <a href="http://www.glyfx.com/" rel="noreferrer">GlyFX</a> and <a href="http://www.iconexperience.com/" rel="noreferrer">IconExperience</a>. You can find free ones too. Ideally get a graphic artist to make some custom ones for the specific actions your application does to fill in between the common ones you use (make sure they all go together). That will go a long way to making it look fancy.</p></li>
<li><p>Try a different font. Tahoma is a good one. Often times the default font is MS Sans Serif. You can do better. Avoid Times New Roman and Comic Sans though. Also avoid large blocks of bold — use it sparingly. Generally you want all your fonts the same, and only use different fonts sparingly to set certain bits of text apart. </p></li>
<li><p>Add subdued colors to certain controls. This is a tricky one. You always want to use subdued colors, nothing bright or stark usually, but the colors should indicate something, or if you have a grid you can use it to show logical grouping. This is a slippery slope. Be aware that users might change their system colors, which will change how your colors look. Ideally give them a few color themes, or the ability to change colors.</p></li>
<li><p>Instead of thinking eye-candy, think usability. Make the most common course of action obvious. Mark Miller of DevExpress has a great talk on the Science of User Interface Design. I actually have a video of it and might be able to post it online with a little clean-up.</p></li>
<li><p>Invest in a few good quality 3rd party controls. Replacing all your controls could be a pain, but if you are using the default grids for example, you would really jazz it up with a good grid from <a href="http://www.devexpress.com/" rel="noreferrer">DevExpress</a> or some other component vendor. Be aware that different vendors have different philosophies for how their components are used, so swapping them out can be a bit of a pain. Start small to test the waters, and then try something really complicated before you commit to replacing all of them. The only thing worse then ugly grids is ugly grids mixed with pretty grids. Consistency is golden! </p></li>
<li><p>You also might look at replacing your old tool bars and menus with a Ribbon Control like Microsoft did in Office 2007. Then everyone will think you are really uptown! Again only replacing key components and UI elements without thinking you need to revamp the whole UI.</p></li>
<li><p>Of course pay attention to the basics like tab order, etc. Consistency, consistency, consistency.</p></li>
</ol>
<p>Some apps lend themselves to full blown skinning, while others don't. Generally you don't want anything flashy that gets used a lot.</p>
|
<p>This depends on how the existing "gray old looking" project is structured in terms of code. For example, is data access code separated from the UI in a Data Access Layer, is the business logic in a Business Logic Layer? If yes, then cleaning the UI for a snazzy look should be relatively simple.</p>
<p>If everything is all there in the "Button Click" event, then a rewrite is the only way in my humble opinion as otherwise it will just be too time consuming trying to work with the existing code base.</p>
<p>Cheers</p>
| 5,376
|
<p>Does Stackoverflow create a new OpenID when a user registers with an email address (i.e. does not provide an existing OpenID)? How do you do that? Do you have code examples in C#? Java? Python?</p>
|
<p>You can find OpenID implementations <a href="http://wiki.openid.net/Libraries" rel="nofollow noreferrer">here</a>. If you just want more information, I would check out the <a href="http://openid.net/" rel="nofollow noreferrer">OpenID site</a>.</p>
|
<p>I think you are mis-understanding OpenID, the process of registering and OpenID is the responsibility of the user, you'll note that there is no place to signup here without an OpenID.</p>
| 6,386
|
<p>I recently was working with a subversion project that checked out code not only from the repository I was working with, but also from a separate repository on a different server.</p>
<p>How can I configure my repository to do this?</p>
<p>I'm using the subversion client version 1.3.2 on Linux, and I also have access to TortoiseSVN version 1.4.8 (built on svn version 1.4.6) in Windows.</p>
|
<p>See <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow noreferrer">svn:externals</a>:</p>
<blockquote>
<p>Sometimes it is useful to construct a working copy that is made out of a number of different checkouts. For example, you may want different subdirectories to come from different locations in a repository, or perhaps from different repositories altogether. You could certainly setup such a scenario by hand—using <code>svn checkout</code> to create the sort of nested working copy structure you are trying to achieve. But if this layout is important for everyone who uses your repository, every other user will need to perform the same checkout operations that you did.</p>
<p>Fortunately, Subversion provides support for <em>externals definitions</em>. An externals definition is a mapping of a local directory to the URL—and possibly a particular revision—of a versioned resource. In Subversion, you declare externals definitions in groups using the <code>svn:externals</code> property. You can create or modify this property using <code>svn propset</code> or <code>svn propedit</code> (see <a href="http://svnbook.red-bean.com/en/1.0/ch07s02.html#svn-ch-7-sect-2.1" rel="nofollow noreferrer">the section called “Why Properties?”</a>). It can be set on any versioned directory, and its value is a multi-line table of subdirectories (relative to the versioned directory on which the property is set) and fully qualified, absolute Subversion repository URLs...</p>
</blockquote>
|
<p>I think you should take a look at the <a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow noreferrer">svn:externals</a> property</p>
| 10,048
|
<p>Today I ran into a problem were I needed to remote-debug a program. The program was launched from another system, so I really don't have an opportunity to interact with it on the command line. I could change its source easily though.</p>
<p>What I needed to happen was for the program to start normally, and then wait for me to attach to it with a debugger. I couldn't come up with a way to do it that made me happy. I did find the bug, but without the help of the debugger.</p>
<pre><code>while(true) { }
</code></pre>
<p>Kept the process alive, and then I could "set next statement" with the debugger, but it seemed awkward and rude.</p>
<pre><code>Console.ReadLine();
</code></pre>
<p>Seemed odd to type since there wasn't actually a Console for me to press <strong>enter</strong> at. (It didn't work, either. Set next statement and then run takes you back into the ReadLine() wait.)</p>
<p>So what kind of code can I insert into a .NET/CLR/C# program that says "wait here until I can attach with a debugger"?</p>
|
<p>You can use the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached.aspx" rel="noreferrer">System.Diagnostics.Debugger.IsAttached</a> property to check if a debugger is attached to the process. This application will wait until a debugger has been attached:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Threading;
namespace DebugApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Waiting for debugger to attach");
while (!Debugger.IsAttached)
{
Thread.Sleep(100);
}
Console.WriteLine("Debugger attached");
}
}
}</code></pre>
|
<p>Set a timeout that gives you time to attach the debugger.</p>
<pre><code>Thread.Sleep(30000);
</code></pre>
| 47,122
|
<p>Did you ever use SQL Server auditing features on a production db?</p>
<p>How did that impact on performances, and are there differences you noticed between different versions of SQL Server.</p>
<p>Also how we need to enable the audit features.</p>
|
<p>The C2 audit mode suffers from a variety of problems, and your question touched on only one of them - performance. C2 auditing has a tremendous performance impact, very high.</p>
<p>Setting the performance issue aside, it's very difficult to manage. It's not a set-it-and-forget-it configuration switch. You have to spend quite a bit of time doing configuration, setting up the logging to go to files, and then when you're done, someone else can come behind you and get rid of the audit files pretty easily. There's no way to quickly poll all of your servers and make sure C2 auditing is working correctly, or that someone isn't dropping files.</p>
<p>SQL Server 2008 makes compliance much easier. I'd recommend taking a look at the <a href="http://www.microsoft.com/sqlserver/2008/en/us/compliance.aspx" rel="nofollow noreferrer">SQL Server 2008 Compliance portal</a>, which has an excellent whitepaper on how to configure 2008's new compliance features. 2008's new auditor uses the xEvent handling which has dramatically lower performance requirements and it's much easier to manage. You can use 2008's Policy-Based Management to check your servers, ensure you're auditing, and help get auditing configured again when things break.</p>
<p>Unfortunately, one weakness is still control of the audit output files - the bad guys can simply delete the files. Another weakness is a lack of reporting - just because you've got gigs of audit data doesn't mean you can do anything with it. You still have to write your own reports in order to analyze the audit data and find out who's doing what. It's not easy - but it's a lot easier and lower-impact than SQL 2005's C2 auditing.</p>
|
<p>I'm afraid there's no such a thing as "audit feature". Instead you need to build it yourself depending on what kind of requirements you have. There are many ways to do this, for example</p>
<ul>
<li>A trigger fires every time data in audited tables change. An example here: <a href="http://web.archive.org/web/20071006100909/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-audit-changes-to-sql-server-data.html" rel="nofollow noreferrer">http://web.archive.org/web/20071006100909/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-audit-changes-to-sql-server-data.html</a></li>
<li>using your ORM, with NHIbernate
ideas here:
<a href="https://stackoverflow.com/questions/15917/data-auditing-in-nhibernate-and-sqlserver">Data Auditing in NHibernate and SqlServer</a></li>
</ul>
| 39,189
|
<p>I've got a 44Khz audio stream from a CD, represented as an array of 16 bit PCM samples. I'd like to cut it down to an 11KHz stream. How do I do that? From my days of engineering class many years ago, I know that the stream won't be able to describe anything over 5500Hz accurately anymore, so I assume I want to cut everything above that out too. Any ideas? Thanks.</p>
<p>Update: There is some code on <a href="http://www.codeguru.com/forum/showthread.php?t=463186&page=1&pp=15" rel="noreferrer">this page</a> that converts from 48KHz to 8KHz using a simple algorithm and a coefficient array that looks like { 1, 4, 12, 12, 4, 1 }. I think that is what I need, but I need it for a factor of 4x rather than 6x. Any idea how those constants are calculated? Also, I end up converting the 16 byte samples to floats anyway, so I can do the downsampling with floats rather than shorts, if that helps the quality at all. </p>
|
<p>Read on FIR and IIR filters. These are the filters that use a coefficent array.</p>
<p>If you do a google search on "FIR or IIR filter designer" you will find lots of software and online-applets that does the hard job (getting the coefficients) for you. </p>
<p><strong>EDIT:</strong></p>
<p>This page here ( <a href="http://www-users.cs.york.ac.uk/~fisher/mkfilter/" rel="noreferrer">http://www-users.cs.york.ac.uk/~fisher/mkfilter/</a> ) lets you enter the parameters of your filter and will spit out ready to use C-Code...</p>
|
<p>I would try applying DFT, chopping 3/4 of the result and applying inverse DFT. I can't tell if it will sound good without actually trying tough.</p>
| 29,480
|
<p>I need to write a Delphi application that pulls entries up from various tables in a database, and different entries will be in different currencies. Thus, I need to show a different number of decimal places and a different currency character for every Currency data type ($, Pounds, Euros, etc) depending on the currency of the item I've loaded.</p>
<p>Is there a way to change the currency almost-globally, that is, for all Currency data shown in a form?</p>
|
<p>Even with the same currency, you may have to display values with a different format (separators for instance), so I would recommend that you associate a LOCALE instead of the currency only with your values.<br>
You can use a simple Integer to hold the LCID (locale ID).<br>
See the list here: <a href="http://msdn.microsoft.com/en-us/library/0h88fahh.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/0h88fahh.aspx</a> </p>
<p>Then to display the values, use something like:</p>
<pre><code>function CurrFormatFromLCID(const AValue: Currency; const LCID: Integer = LOCALE_SYSTEM_DEFAULT): string;
var
AFormatSettings: TFormatSettings;
begin
GetLocaleFormatSettings(LCID, AFormatSettings);
Result := CurrToStrF(AValue, ffCurrency, AFormatSettings.CurrencyDecimals, AFormatSettings);
end;
function USCurrFormat(const AValue: Currency): string;
begin
Result := CurrFormatFromLCID(AValue, 1033); //1033 = US_LCID
end;
function FrenchCurrFormat(const AValue: Currency): string;
begin
Result := CurrFormatFromLCID(AValue, 1036); //1036 = French_LCID
end;
procedure TestIt;
var
val: Currency;
begin
val:=1234.56;
ShowMessage('US: ' + USCurrFormat(val));
ShowMessage('FR: ' + FrenchCurrFormat(val));
ShowMessage('GB: ' + CurrFormatFromLCID(val, 2057)); // 2057 = GB_LCID
ShowMessage('def: ' + CurrFormatFromLCID(val));
end;
</code></pre>
|
<p>I'd use SysUtils.CurrToStr(Value: Currency; var FormatSettings: TFormatSettings): string;</p>
<p>I'd setup an array of TFormatSettings, each position configured to reflect each currency your application supports. You'll need to set the following fields of the TFormat Settings for each array position: CurrencyString, CurrencyFormat, NegCurrFormat, ThousandSeparator, DecimalSeparator and CurrencyDecimals.</p>
| 11,149
|
<p>I'm using .NET 3.5. I have two string arrays, which may share one or more values:</p>
<pre><code>string[] list1 = new string[] { "apple", "orange", "banana" };
string[] list2 = new string[] { "banana", "pear", "grape" };
</code></pre>
<p>I'd like a way to merge them into one array with no duplicate values:</p>
<pre><code>{ "apple", "orange", "banana", "pear", "grape" }
</code></pre>
<p>I can do this with LINQ:</p>
<pre><code>string[] result = list1.Concat(list2).Distinct().ToArray();
</code></pre>
<p>but I imagine that's not very efficient for large arrays.</p>
<p>Is there a better way?</p>
|
<pre><code>string[] result = list1.Union(list2).ToArray();
</code></pre>
<p>from <a href="http://msdn.microsoft.com/en-us/library/bb341731.aspx" rel="noreferrer">msdn</a>: "This method excludes duplicates from the return set. This is different behavior to the Concat(TSource) method, which returns all the elements in the input sequences including duplicates." </p>
|
<p>Probably creating a hashtable with your values as keys (only adding those not already present) and then converting the keys to an array could be a viable solution.</p>
| 17,624
|
<p>How do I access 'a' below?</p>
<pre><code>var test = function () {
return {
'a' : 1,
'b' : this.a + 1 //doesn't work
};
};
</code></pre>
|
<p>You can't do it this way. When you are in the process of constructing an object (that's what you actually do using the curly braces), there is no way to access it's properties before it is constructed.</p>
<pre><code>var test = function () {
var o = {};
o['a'] = 1;
o['b'] = o['a'] + 1;
return o;
};
</code></pre>
|
<pre><code>var test = function () {
//private members
var a = 1;
var b = a + 1;
//public interface
return {
geta : function () {
return a;
},
getb : function () {
return b;
}
}
}();
</code></pre>
| 44,800
|
<p>How can I implement ActiveX Document on C#/.NET? (ActiveX Document can draw itself in IE)<br>
<strong>Update:</strong> I need a solution for drawing my own document type in IE windows (like MS Word or MS Excel draw its documents in IE). </p>
|
<p>You need to dive into OLE for that purpose. </p>
<p>Things like IOleDocument, IOleInPlaceSite (see <a href="http://msdn.microsoft.com/en-us/library/ms687196.aspx" rel="nofollow noreferrer">MSDN</a> for that). Figure out which interfaces are needed for the client (as IE would be the container and will need to communicate with your interface implementations), and how the communication is going on, e.g. what gets called when.It's not rocket science, but I believe still a fair amount of work.</p>
|
<p>Look at <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.domdocument.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.domdocument.aspx</a>, it's .NET wrapper for DOM Document</p>
| 44,793
|
<p>I know there are some ways to get notified when the page body has loaded (before all the images and 3rd party resources load which fires the <strong>window.onload</strong> event), but it's different for every browser.</p>
<p>Is there a definitive way to do this on all the browsers?</p>
<p>So far I know of:</p>
<ul>
<li><p><strong>DOMContentLoaded</strong> : On Mozilla, Opera 9 and newest WebKits. This involves adding a listener to the event:</p>
<p>document.addEventListener( "DOMContentLoaded", [init function], false );</p></li>
<li><p><strong>Deferred script</strong>: On IE, you can emit a SCRIPT tag with a @defer attribute, which will reliably only load after the closing of the BODY tag.</p></li>
<li><p><strong>Polling</strong>: On other browsers, you can keep polling, but is there even a standard thing to poll for, or do you need to do different things on each browser?</p></li>
</ul>
<p>I'd like to be able to go without using document.write or external files.</p>
<p>This can be done simply via jQuery:</p>
<pre><code>$(document).ready(function() { ... })
</code></pre>
<p>but, I'm writing a JS library and can't count on jQuery always being there.</p>
|
<p>There's no cross-browser method for checking when the DOM is ready -- this is why libraries like jQuery exist, to abstract away nasty little bits of incompatibility.</p>
<p>Mozilla, Opera, and modern WebKit support the <code>DOMContentLoaded</code> event. IE and Safari need weird hacks like scrolling the window or checking stylesheets. The gory details are contained in jQuery's <code>bindReady()</code> function.</p>
|
<p>This works pretty well:</p>
<pre><code>setTimeout(MyInitFunction, 0);
</code></pre>
| 9,115
|
<p>I have a class that has some properties. And I want something that calculates a Score out of these properties. Since this is a trivial task (some additions and divisions, but nothing spectacular).</p>
<p>So naturally, the question is: "When to use a Property with some code in the getter, and when to use a function?", and <a href="https://stackoverflow.com/questions/67063/">that question was already answered</a>.</p>
<p>Now, I wonder about one thing though: If - against all expectations - I ever needed to make this Getter so complicated that it should be a function (for example, because I need to put data in or because it can throw an exception or whatever), is it easy to change a Property into a Method?</p>
<p>Of course, it seems really trivial, just changing</p>
<pre><code>public double Score {
get {
return Math.Round(A + B / C * D,3);
}
}
</code></pre>
<p>to</p>
<pre><code>public double Score(){
return Math.Round(A + B / C * D,3);
}
</code></pre>
<p>But I wonder: Are there any side effects? Is anything going to break when changing stuff around like this? I can only ever see this as a possible problem when Reflection is involved, but what in situations where I have 2 Assemblies - one that defines the class and one that uses the class - and only change the one that contains the class without recompiling the consumer assembly. Is that a possible source of "weird bugs that are nearly impossible to track" or is it completely safe to change Properties to Methods?</p>
|
<p>Pull up reflector, you'll see that your properties already are methods :)</p>
|
<p>As others already pointed out - nothing to worry. I just post to clarify that according to the coding guidelines, a property name usually is noun (i.e. Score), but methods should describe actions (verb), so more proper name is GetScore() or CalculateScore() :)</p>
<p>Grammar Nazi in action :)</p>
| 37,951
|
<p>I'm trying to get a query working that takes the values (sometimes just the first part of a string) from a form control. The problem I have is that it only returns records when the full string is typed in.</p>
<p>i.e. in the surname box, I should be able to type gr, and it brings up </p>
<p>green
grey
graham</p>
<p>but at present it's not bringing up anything uless the full search string is used.</p>
<p>There are 4 search controls on the form in question, and they are only used in the query if the box is filled in.</p>
<p>The query is :</p>
<pre><code>SELECT TabCustomers.*,
TabCustomers.CustomerForname AS NameSearch,
TabCustomers.CustomerSurname AS SurnameSearch,
TabCustomers.CustomerDOB AS DOBSearch,
TabCustomers.CustomerID AS MemberSearch
FROM TabCustomers
WHERE IIf([Forms]![FrmSearchCustomer]![SearchMember] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchMember]=[customerid])=True
AND IIf([Forms]![FrmSearchCustomer].[SearchFore] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchFore] Like [customerforname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![SearchLast] Is Null
,True
,[Forms]![FrmSearchCustomer]![SearchLast] Like [customersurname] & "*")=True
AND IIf([Forms]![FrmSearchCustomer]![Searchdate] Is Null
,True
,[Forms]![FrmSearchCustomer]![Searchdate] Like [customerDOB] & "*")=True;
</code></pre>
|
<h2>There is an Access Method for that!</h2>
<p>If you have your "filter" controls on the form, why don't you use the Application.buildCriteria method, that will allow you to add your filtering criterias to a string, then make a filter out of this string, and build your WHERE clause on the fly?</p>
<pre><code>selectClause = "SELECT TabCustomers.* FROM TabCustomers"
if not isnull(Forms!FrmSearchCustomer!SearchMember) then
whereClause = whereClause & application.buildCriteria(your field name, your field type, your control value) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchFore) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchLast) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
if not isnull(Forms!FrmSearchCustomer!SearchDate) then
whereClause = whereClause & application.buildCriteria(...) & " AND "
endif
--get rid of the last "AND"
if len(whereClause) > 0 then
whereClause = left(whereClause,len(whereClause)-5)
selectClause = selectClause & " WHERE " & whereClause
endif
-- your SELECT instruction is ready ...
</code></pre>
<p>EDIT: the buildCriteria will return (for example):</p>
<ul>
<li><code>'field1 = "GR"'</code> when you type "GR" in the control</li>
<li><code>'field1 LIKE "GR*"'</code> when you type <code>"GR*"</code> in the control</li>
<li><code>'field1 LIKE "GR*" or field1 like "BR*"'</code> if you type <code>'LIKE "GR*" OR LIKE "BR*"'</code> in the control </li>
</ul>
<p>PS: if your "filter" controls on your form always have the same syntax (let's say "search_fieldName", where "fieldName" corresponds to the field in the underlying recordset) and are always located in the same zone (let's say formHeader), it is then possible to write a function that will automatically generate a filter for the current form. This filter can then be set as the form filter, or used for something else:</p>
<pre><code>For each ctl in myForm.section(acHeader).controls
if ctl.name like "search_"
fld = myForm.recordset.fields(mid(ctl.name,8))
if not isnull(ctl.value) then
whereClause = whereClause & buildCriteria(fld.name ,fld.type, ctl.value) & " AND "
endif
endif
next ctl
if len(whereClause)> 0 then ...
</code></pre>
|
<p>My only thoguht is that maybe a () is needed to group the like</p>
<p>For example a snippet on the first part</p>
<pre><code>,[Forms]![FrmSearchCustomer]![SearchFore] Like ([customerforname] & "*"))=True
</code></pre>
<p>It has been a while since I've used access, but it is the first thing that comes to mind</p>
| 27,614
|
<p>I'll be quick and honest: I'm currently trying to write a client/server for an online game. Since I'm poor and limited on resources, I'll be testing the bare basics of the server using a PHP backend, with the eventual goal being to rebuild the server end in C++.</p>
<p>I'm looking for a C++ library for Windows (XP and Vista preferably) that will let me use a finite number of threads, one dedicated to each piece of the networking problem. As an example, I want to use a thread to report the positional information of the player to the server (and to receive responses about positional information of the other players) but I want a different thread to background download in the 3D artwork for the area/players, and a different thread for the built in chat system, etc. These all need to be fairly independent of one another.</p>
<p>I know what I want to <em>do</em> with the library, I've got the design bit figured out, I just feel a bit silly re-inventing the wheel, since I know that a good library for this exact purpose probably already exists. So, what are your suggestions? I need to be able to send data to a server, and accept responses. Ideally, the request needs to trigger an Event when its done (so I can immediately grab the data and do something with it) and I need to be able to handle multiple transactions simultaneously. HTTP is a nice bonus, but I can handle HTTP protocol myself if necessary, especially considering that I plan on dropping it in the long run.</p>
<p>Thanks!</p>
|
<p><a href="http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio.html" rel="nofollow noreferrer">Boost.Asio</a></p>
<p>ASIO has simple web server examples.</p>
<p><a href="http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html" rel="nofollow noreferrer">Boost.Thread</a></p>
|
<p>You should just use <a href="http://curl.haxx.se/" rel="nofollow noreferrer">cUrl</a> with multihandles. It is better designed to do what you want than whatever it is that you have designed.</p>
| 44,579
|
<p>On a number of occasions I've broken small plastic parts that are nearly impossible to replace but could easily be 3-D printed. The latest such mishap is the volume knob on the factory-installed radio on my car. </p>
<p>I have little experience in 3D printing, and would like to be able to replace these parts with something very close to the original. Spending hours measuring and designing a replacement part that should be $5 isn't really an option. I need something to scan the broken pieces in 3D and somehow just seal up the seam where it's broken.</p>
<p>Is there a scanning/printing/software system to do this that doesn't require a lot of 3D design experience?</p>
|
<p>The easiest way is as you currently do: model the pieces by hand, using (digital) calipers to measure them.</p>
<p>Scanning technology isn't very good, and the models are not of printable quality. Usually, fixing a scan is more work than modeling an item from scratch.</p>
|
<p>There is scanning technology: either hardware or software (such software typically works from multiple 2D photographs). It has limitations, but is an active research area, and getting better all the time. "Autodesk 123D Catch" and "3-Sweep" are a couple examples.</p>
<p>One tradeoff between automatic and manual is the complexity of the shape you need to duplicate. Sometimes you can make a much simpler shape that still works, and/or thicken the part so it doesn't break the next time. That can make manual design much more attractive.</p>
| 97
|
<p>I'm using Chris Pederick's Firefox addon <a href="http://chrispederick.com/work/web-developer/" rel="nofollow noreferrer">"Web Developer 1.1.6"</a>. I get this warning when hitting a certain web page on my site: </p>
<blockquote>
<p>Unknown property 'MozOpacity'. Declaration dropped.</p>
</blockquote>
<p>What does this mean and how can I fix this on my site?</p>
|
<p>It's customary for browsers to prefix experimental or proprietary features with <em>-moz</em> (for Gecko-based browsers) or <em>-webkit</em> (for webkit) so they can be used but don't interfere with standard CSS rendering. In the case of <em>-moz-opacity</em>, it seems that they have finally removed the proprietary tag since the standard <em>opacity</em> tag is supported.</p>
<p>I don't think any equivalent convention is followed by the IE team, but then again IE is so behind the pack it probably never came up ;)</p>
|
<p>there is some proprietary css declaration :
- filter (from microsoft);
- -moz-corner-radius, -moz-opacity and other -moz prefixed from mozilla
- -khtml prefixed from safari</p>
<p>these are NOT standard and it works ONLY in that browser.
If you don't expect -moz properties to work on safari and filter on firefox, you can ignore that warnings :)</p>
| 28,999
|
<p>I want to create a class that, for example, extends HttpServlet? My compiler warns me that my class should have a serialVersionUID. If I know that this object will never be serialized, should I define it or add an annotation to suppress those warnings?</p>
<p>What would you do and why?</p>
|
<p>I don't know Java best practices, but it occurs to me that if you are claiming that serialization will never happen, you could add a writeObject method which throws. Then suppress the warning, safe in the knowledge that it cannot possibly apply to you.</p>
<p>Otherwise someone might in future serialize your object through the parent class, and end up with a default serialized form where:</p>
<ul>
<li>the form isn't compatible between different versions of your code.</li>
<li>you've suppressed the warning that this is the case.</li>
</ul>
<p>Adding an ID sounds like a bodge, since what you really want to do is not serialize. Expecting callers not to serialize your object means that you expect them to "know" when their HttpServlet is of your class. That breach of polymorphism is on your head for having a Serializable object which must not be serialized, and the least you can do is make sure unwary callers know about it.</p>
|
<p>Please follow this link to get detailed explanation: <a href="http://technologiquepanorama.wordpress.com/2009/02/13/what-is-use-of-serialversiouid/" rel="nofollow noreferrer">http://technologiquepanorama.wordpress.com/2009/02/13/what-is-use-of-serialversiouid/</a></p>
| 17,660
|
<p>I have some strings that I am pulling out of a database and I would like to use Template Toolkit on them, but I can't seem to figure out how to use strings as TT input. Any tips?</p>
<p>Thanks!</p>
<p>-fREW</p>
|
<p>The documentation explains:</p>
<blockquote>
<p>process($template, \%vars, $output, %options)</p>
<p>The process() method is called to process a template. The first parameter indicates the input template as one of: a filename relative to INCLUDE_PATH, if defined; <strong>a reference to a text string containing the template text</strong>; ...</p>
</blockquote>
<pre><code> # text reference
$tt->process(\$text)
|| die $tt->error(), "\n"
</code></pre>
|
<p>From the <a href="http://template-toolkit.org/docs/modules/Template.html#method_process" rel="nofollow noreferrer">docs</a>:</p>
<pre><code># text reference
$text = "[% INCLUDE header %]\nHello world!\n[% INCLUDE footer %]";
$tt->process(\$text)
|| die $tt->error(), "\n";
</code></pre>
<p>(Looks like I should have refreshed the page before posting.)</p>
| 40,624
|
<p>I am trying to coach some guys on building web applications. They understand and use MVC, but I am interested in other common patterns that you use in building web apps. </p>
<p>So, what patterns have you found to fit nicely into a properly MVC app. Perhaps something for Asynchronous processes, scheduled tasks, dealing with email, etc. What do you wish you knew to look for, or avoid? </p>
<p>Not that it matters for this question, but we are using ASP.NET and Rails for most of our applications.</p>
|
<p>Once you get into MVC, it can be worthwhile to explore patterns beyond the "Gang of Four" book, and get into Martin Fowler's "<a href="http://martinfowler.com/eaaCatalog/index.html" rel="noreferrer">Patterns of Enterprise Application Architecture</a>."</p>
<p>The <a href="http://martinfowler.com/eaaCatalog/registry.html" rel="noreferrer">Registry</a> pattern can be useful to make well-known objects available throughout the object hierarchy. Essentially a substitute for using global data.</p>
<p>Many MVC frameworks also employ the <a href="http://martinfowler.com/eaaCatalog/frontController.html" rel="noreferrer">Front Controller</a> and the <a href="http://martinfowler.com/eaaCatalog/twoStepView.html" rel="noreferrer">Two-Step View</a> patterns.</p>
<p>The "Model" in MVC is best designed as the <a href="http://martinfowler.com/eaaCatalog/domainModel.html" rel="noreferrer">Domain Model</a> pattern, although some frameworks (led by Rails) <a href="http://wiki.rubyonrails.org/rails/pages/Models" rel="noreferrer">conflate</a> the Model with the <a href="http://martinfowler.com/eaaCatalog/activeRecord.html" rel="noreferrer">ActiveRecord</a> pattern. I often <a href="http://karwin.blogspot.com/2008/05/activerecord-does-not-suck.html" rel="noreferrer">advise</a> that the relationship between a Model and ActiveRecord should be HAS-A, instead of IS-A.</p>
<p>Also read about <a href="http://c2.com/cgi/wiki?ModelViewController" rel="noreferrer">ModelViewController</a> at the Portland Pattern Repository wiki. There is some good discussion about MVC, object-orientation, and other patterns that complement MVC, such as <a href="http://c2.com/cgi/wiki?ObserverPattern" rel="noreferrer">Observer</a>.</p>
|
<p>I would most likely recommend some kind of Dependency Injection as well (Inversion of Control). Probably the single most important supplementary "pattern" to use.</p>
| 42,477
|
<p>A listbox is passed, the data placed in an array, the array is sort and then the data is placed back in the listbox. The part that does work is putting the data back in the listbox. Its like the listbox is being passed by value instead of by ref.</p>
<p>Here's the sub that does the sort and the line of code that calls the sort sub.</p>
<pre><code>Private Sub SortListBox(ByRef LB As MSForms.ListBox)
Dim First As Integer
Dim Last As Integer
Dim NumItems As Integer
Dim i As Integer
Dim j As Integer
Dim Temp As String
Dim TempArray() As Variant
ReDim TempArray(LB.ListCount)
First = LBound(TempArray) ' this works correctly
Last = UBound(TempArray) - 1 ' this works correctly
For i = First To Last
TempArray(i) = LB.List(i) ' this works correctly
Next i
For i = First To Last
For j = i + 1 To Last
If TempArray(i) > TempArray(j) Then
Temp = TempArray(j)
TempArray(j) = TempArray(i)
TempArray(i) = Temp
End If
Next j
Next i ! data is now sorted
LB.Clear ! this doesn't clear the items in the listbox
For i = First To Last
LB.AddItem TempArray(i) ! this doesn't work either
Next i
End Sub
Private Sub InitializeForm()
' There's code here to put data in the list box
Call SortListBox(FieldSelect.CompleteList)
End Sub
</code></pre>
<p>Thanks for your help.</p>
|
<p>This works for me on Excel 2003 on a very basic UserForm with a single ListBox called ListBox1:</p>
<pre><code>Private Sub UserForm_Initialize()
ListBox1.AddItem "john"
ListBox1.AddItem "paul"
ListBox1.AddItem "george"
ListBox1.AddItem "ringo"
SortListBox ListBox1
End Sub
</code></pre>
<p>and then your SortListBox as written apart from fixing the three comments which start with ! rather than '</p>
<p>The only difference to your initializer is the name (<code>UserForm_Initialize</code> vs <code>InitializeForm</code>). Make sure to use the object and event selectors at the top of the code page for the userform to ensure that the event handlers get named correctly</p>
|
<p>I dont know if this would work for you but try it this way. </p>
<p>First, make an array of all the items in the list box</p>
<p>Pass that array to your function</p>
<p>Sort that array</p>
<p>return the array to the main program</p>
<p>clear the listbox</p>
<p>overwrite the listbox items with the new array</p>
| 44,927
|
<p>Besides the sample applications featured in the books <em>Beginning Groovy and Grails</em> and <em>The Definitive Guide to Grails</em>, are there any applications out there written in Grails that are good examples from which to learn best practices? Such as real applications that are open-source? Thanks.</p>
|
<p>During my learning phase, I came across several good sample applications.</p>
<p>This sample web album app got me started on grails. It covers security, image upload / manipulation, basic crud etc.</p>
<p><a href="http://www.syger.it/Tutorials/GrailsWebAlbum.html" rel="noreferrer">http://www.syger.it/Tutorials/GrailsWebAlbum.html</a></p>
<p>Here's one from Glen Smith, author of the upcoming Grails in Action book. The source code to the groovy blog aggregator is located here:</p>
<p><a href="http://code.google.com/p/groovyblogs/" rel="noreferrer">http://code.google.com/p/groovyblogs/</a></p>
<p>Here's another one by Glen, a blog engine written with grails:</p>
<p><a href="http://code.google.com/p/gravl/" rel="noreferrer">http://code.google.com/p/gravl/</a></p>
<p>And finally, here's the code to the grails.org site which includes wiki functionality:</p>
<p><a href="http://github.com/grails/grails/tree/master/grails-samples/grails.org/" rel="noreferrer">http://github.com/grails/grails/tree/master/grails-samples/grails.org/</a></p>
|
<p>I second the IBM series Ray Tayek mentioned, and the energizedwork.com example j pimmel mentioned. The latter has been my reference manual for writing well-tested code and I can't live without it.</p>
| 34,935
|
<p>What is the difference between a pointer variable and a reference variable?</p>
|
<ol>
<li><p>A pointer can be re-assigned:</p>
<pre><code>int x = 5;
int y = 6;
int *p;
p = &x;
p = &y;
*p = 10;
assert(x == 5);
assert(y == 10);
</code></pre>
<p>A reference cannot be re-bound, and must be bound at initialization:</p>
<pre><code>int x = 5;
int y = 6;
int &q; // error
int &r = x;
</code></pre>
</li>
<li><p>A pointer variable has its own identity: a distinct, visible memory address that can be taken with the unary <code>&</code> operator and a certain amount of space that can be measured with the <code>sizeof</code> operator. Using those operators on a reference returns a value corresponding to whatever the reference is bound to; the reference’s own address and size are invisible. Since the reference assumes the identity of the original variable in this way, it is convenient to think of a reference as another name for the same variable.</p>
<pre><code>int x = 0;
int &r = x;
int *p = &x;
int *p2 = &r;
assert(p == p2); // &x == &r
assert(&p != &p2);
</code></pre>
</li>
<li><p>You can have arbitrarily nested pointers to pointers offering extra levels of indirection. References only offer one level of indirection.</p>
<pre><code>int x = 0;
int y = 0;
int *p = &x;
int *q = &y;
int **pp = &p;
**pp = 2;
pp = &q; // *pp is now q
**pp = 4;
assert(y == 4);
assert(x == 2);
</code></pre>
</li>
<li><p>A pointer can be assigned <code>nullptr</code>, whereas a reference must be bound to an existing object. If you try hard enough, you can bind a reference to <code>nullptr</code>, but this is <a href="https://stackoverflow.com/questions/2397984/">undefined</a> and will not behave consistently.</p>
<pre><code>/* the code below is undefined; your compiler may optimise it
* differently, emit warnings, or outright refuse to compile it */
int &r = *static_cast<int *>(nullptr);
// prints "null" under GCC 10
std::cout
<< (&r != nullptr
? "not null" : "null")
<< std::endl;
bool f(int &r) { return &r != nullptr; }
// prints "not null" under GCC 10
std::cout
<< (f(*static_cast<int *>(nullptr))
? "not null" : "null")
<< std::endl;
</code></pre>
<p>You can, however, have a reference to a pointer whose value is <code>nullptr</code>.</p>
</li>
<li><p>Pointers can iterate over an array; you can use <code>++</code> to go to the next item that a pointer is pointing to, and <code>+ 4</code> to go to the 5th element. This is no matter what size the object is that the pointer points to.</p>
</li>
<li><p>A pointer needs to be dereferenced with <code>*</code> to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses <code>-></code> to access its members whereas a reference uses a <code>.</code>.</p>
</li>
<li><p>References cannot be put into an array, whereas pointers can be (Mentioned by user @litb)</p>
</li>
<li><p>Const references can be bound to temporaries. Pointers cannot (not without some indirection):</p>
<pre><code>const int &x = int(12); // legal C++
int *y = &int(12); // illegal to take the address of a temporary.
</code></pre>
<p>This makes <code>const &</code> more convenient to use in argument lists and so forth.</p>
</li>
</ol>
|
<p>In short,</p>
<blockquote>
<p>Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. - Extracted from Geeks for Geeks</p>
</blockquote>
<blockquote>
<p>References: A reference variable is an alias, that is, another name for an already existing variable. A reference, like a pointer, is also implemented by storing the address of an object. - Extracted from Geeks for Geeks</p>
</blockquote>
<p>Another picture for more details:</p>
<p><a href="https://i.stack.imgur.com/PBfzi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PBfzi.png" alt="From the web." /></a></p>
| 8,172
|
<p>I have a classic 3-tier ASP.Net 3.5 web application with forms that display business objects and allow them to be edited. Controls on the form correspond to a property of the underlying business object. The user will have read/write, readonly, or no access to the various controls depending on his/her role. Very conventional stuff.</p>
<p>My question is: what is the object-oriented best practice for coding this? Is there anything more elegant than wrapping each control in a test for the user's role and setting its Visible and Enabled properties?</p>
<p>Thanks</p>
|
<p>To work properly, I have found that access levels should be in this increasing order:
NONE, VIEW, REQUIRED, EDIT.</p>
<p>Note that REQUIRED is NOT the top level as you may think it would be since EDIT (both populate & de-populate permission) is a greater privilege than REQUIRED (populate-only permission).</p>
<p>The enum would look like this:</p>
<pre><code>/** NO permissions.
* Presentation: "hidden"
* Database: "no access"
*/
NONE(0),
/** VIEW permissions.
* Presentation: "read-only"
* Database: "read access"
*/
VIEW(1),
/** VIEW and POPULATE permissions.
* Presentation: "required/highlighted"
* Database: "non-null"
*/
REQUIRED(2),
/** VIEW, POPULATE, and DEPOPULATE permissions.
* Presentation: "editable"
* Database: "nullable"
*/
EDIT(3);
</code></pre>
<p>From the bottom layer (database constraints), create a map of fields-to-access. This map then gets updated (further restrained) at the next layer up (business rules + user permissions). Finally, the top layer (presentation rules) can then further restrain the map again if desired.</p>
<p>Important: The map must be wrapped so that it only allows access to be <em>decreased</em> with any subsequent update. Updates which attempt to increase access should just be ignored without triggering any error. This is because it should act like a voting system on what the access should look like. In essence, the subsequent layering of access levels as mentioned above can happen in any order since it will result in an access-level low-water-mark for each field once all layers have voted.</p>
<p>Ramifications:</p>
<p>1) The presentation layer CAN hide a field (set access to NONE) for a database-specified read-only (VIEW) field.</p>
<p>2) The presentation layer CANNOT display a field when the business rules say that the user does not have at least VIEW access.</p>
<p>3) The presentation layer CANNOT move a field's access up to "editable" (nullable) if the database says it's only "required" (non-nullable).</p>
<p>Note: The presentation layer should be made (custom display tags) to render the fields by reading the access map without the need for any "if" statements.</p>
<p>The same access map that is used for setting up the display can also be using during the submit validations. A generic validator can be written to read any form and its access map to ensure that all the rules have been followed.</p>
|
<p>I have often found that this is really the only real easy and understandable way to do it, as your interface needs to modify based on the information and level of editing that they can complete. </p>
<p>I do find typically though that depending on the needs, you can interject the "cannot edit" information by passing role information to the business level if you have plans to move to different presentation levels. but this adds complexity, and if you are only building for one interface it would most likely be overkill</p>
| 48,164
|
<p>It seems safe to cast the result of my vector's <code>size()</code> function to an <code>unsigned int</code>. How can I tell for sure, though? My documentation isn't clear about how <code>size_type</code> is defined.</p>
|
<p>Do not assume the type of the container size (or anything else typed inside).</p>
<h3>Today?</h3>
<p>The best solution for now is to use:</p>
<pre><code>std::vector<T>::size_type
</code></pre>
<p>Where T is your type. For example:</p>
<pre><code>std::vector<std::string>::size_type i ;
std::vector<int>::size_type j ;
std::vector<std::vector<double> >::size_type k ;
</code></pre>
<p>(Using a typedef could help make this better to read)</p>
<p>The same goes for iterators, and all other types "inside" STL containers.</p>
<h3>After C++0x?</h3>
<p>When the compiler will be able to find the type of the variable, you'll be able to use the auto keyword. For example:</p>
<pre><code>void doSomething(const std::vector<double> & p_aData)
{
std::vector<double>::size_type i = p_aData.size() ; // Old/Current way
auto j = p_aData.size() ; // New C++0x way, definition
decltype(p_aData.size()) k; // New C++0x way, declaration
}
</code></pre>
<h3>Edit: Question from JF</h3>
<blockquote>
<blockquote>
<p>What if he needs to pass the size of the container to some existing code that uses, say, an unsigned int? – JF</p>
</blockquote>
</blockquote>
<p>This is a problem common to the use of the STL: You cannot do it without some work.</p>
<p>The first solution is to design the code to always use the STL type. For example:</p>
<pre><code>typedef std::vector<int>::size_type VIntSize ;
VIntSize getIndexOfSomeItem(const std::vector<int> p_aInt)
{
return /* the found value, or some kind of std::npos */
}
</code></pre>
<p>The second is to make the conversion yourself, using either a static_cast, using a function that will assert if the value goes out of bounds of the destination type (sometimes, I see code using "char" because, "<em>you know, the index will never go beyond 256</em>" [I quote from memory]).</p>
<p>I believe this could be a full question in itself.</p>
|
<p>I'm not sure how well this will work because I'm just thinking off the top of my head, but a compile-time assertion (such as <code>BOOST_STATIC_ASSERT()</code> or see <a href="https://stackoverflow.com/questions/174356/ways-to-assert-expressions-at-build-time-in-c">Ways to ASSERT expressions at build time in C</a>) might help. Something like:</p>
<pre><code>BOOST_STATIC_ASSERT( sizeof( unsigned int) >= sizeof( size_type));
</code></pre>
| 27,979
|
<p>I have heard a few developers recently say that they are simply polling stuff (databases, files, etc.) to determine when something has changed and then run a task, such as an import.</p>
<p>I'm really against this idea and feel that utilising available technology such as <a href="http://en.wikipedia.org/wiki/.NET_Remoting" rel="noreferrer">Remoting</a>, <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="noreferrer">WCF</a>, etc. would be far better than polling.</p>
<p>However, I'd like to identify the reasons why other people prefer one approach over the other and more importantly, how can I convince others that polling is wrong in this day and age?</p>
|
<p>Polling is not "wrong" as such.</p>
<p>A lot depends on how it is implemented and for what purpose. If you really care about immedatly notification of a change, it is very efficient. Your code sits in tight loop, constantly polling (asking) a resource whether it has changed / updated. This means you are notified as soon as you can be that something is different. But, your code is not doing anything else and there is overhead in terms of many many calls to the object in question.</p>
<p>If you are less concerned with immediate notification you can increase the interval between polls, and this can also work well, but picking the correct interval can be difficult. Too long and you might miss critical changes, too short and you are back to the problems of the first method.</p>
<p>Alternatives, such as interrupts or messages, etc. can provide a better compromise in these situations. You are notified of a change as soon as is practically possible, but this delay is not something you control, it depends on the component tself being timely about passing on changes in state.</p>
<p>What is "wrong" with polling?</p>
<ul>
<li>It can be resource hogging.</li>
<li>It can be limiting (especially if you have many things you want to know about / poll).</li>
<li>It can be overkill.</li>
</ul>
<p>But...</p>
<ul>
<li>It is not inherently wrong.</li>
<li>It can be very effective.</li>
<li>It is very simple.</li>
</ul>
|
<p>Here is a good summary of relative merits of push and pull:
<a href="https://stpeter.im/index.php/2007/12/14/push-and-pull-in-application-architectures/" rel="nofollow noreferrer">https://stpeter.im/index.php/2007/12/14/push-and-pull-in-application-architectures/</a></p>
<p>I wish I could summarize it further into this answer but some things are best left unabridged.</p>
| 41,428
|
<p>I would like to be able to detect what country a visitor is from on my website, using PHP. </p>
<p>Please note that I'm not trying to use this as a security measure or for anything important, just changing the spelling of some words <em>(Americans seems to believe that the word "enrolment" has 2 Ls.... crazy yanks)</em>, and perhaps to give a default option in a "Select your country" list.</p>
<p>As such, using a Geolocation database is a tad over-the-top and I really don't want to muck about with installing new PHP libraries just for this, so <strong>what's the easiest/simplest way to find what country a visitor is from?</strong></p>
|
<p>Not guaranteed, but most browsers submit an Accept-Language HTTP header that specifies en-us if they're from the US. Some older browsers only said they are en, though. And not all machines are set up correctly to indicate which locale they prefer. But it's a good first guess.</p>
<p>English-UK based-users usually set their system or user locale to English-UK, which in default browser configurations should result in en-gb as the Accept Language header. (An earlier version of this said en-uk; that was a typo, sorry.) Other countries also have en locales, such as en-za (south africa), and, primarily theoretically, combinations like en-jp are also possible.</p>
<p>Geo-IP based guesses will less likely be correct on the preferred language/locale, however. Google thinks that content-negotiation based on IP address geolocation makes sense, which really annoys me when I'm in Japan or Korea...</p>
|
<p>The <a href="http://countries.nerd.dk" rel="nofollow noreferrer">http://countries.nerd.dk</a> service is what I use for IP-to-country mapping. It works really well and being based on DNS, is cached well too.</p>
<p>You can also download the database for local use if you don't want to rely on an external service.</p>
| 38,077
|
<p>Like many people, I have burnt the pins in the micro-controller connected to the E0 motor - the E0 motor is not working anymore and I need to print tomorrow! I need to control the extruder motor with the working E1 pins. How do I change this in firmware? </p>
<p>I tried to change to the pins in `pins_RAMPS.h" but it was a complete fail, the motors that i tried to change didn't move. </p>
<p>I have a Arduino Mega + Ramps 1.3 in "Extruder Fan Bed" configuration, I use Repetier-Host as host and Marlin as firmware. </p>
|
<p>I would change the pin assignments by swapping E0 and E1 in <code>pins_RAMPS.h</code>.</p>
|
<p>As a quick and dirty solution you may try to enable two extruders in configuration file, re-upload firmware, and then edit your GCODE file to replace all E0 references with E1.</p>
| 447
|
<p>In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block.</p>
<p>The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware?</p>
<p>Thanks</p>
|
<p>As mentioned in other answers, you can use either the ifconfig command or the ip command. ip is a much more robust command, and I prefer to use it. A full script which loops through a full class C subnet adding the IP, doing stuff, then removing it follows. Note that it doesn't use .0 or .255, which are the network and broadcast addresses of the subnet. Also, when using the ip command to add or remove an address, it's good to include the mask width, as well (the /24 at the end of the address).</p>
<pre><code>#!/bin/bash
SUBNET=192.168.135.
ETH=eth0
for i in {1..254}
do
ip addr add ${SUBNET}${i}/24 dev ${ETH}
# do whatever you want here
ip addr del ${SUBNET}${i}/24 dev ${ETH}
done</code></pre>
|
<p>It should be something like: <code>ifconfig eth0 192.168.0.42 up</code></p>
<p>Replace eth0 by the network interface of your network card, obviously adapt the ip address to your needs and the up is only necessary once, but doesn't hurt if you run it each time. </p>
| 9,967
|
<p>How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it. </p>
|
<pre><code>if(doc.SelectSingleNode("//mynode")==null)....
</code></pre>
<p>Should do it (where doc is your XmlDocument object, obviously)</p>
<p>Alternatively you could use an XSD and validate against that</p>
|
<p>//I am finding childnode ERNO at 2nd but last place</p>
<pre><code>If StrComp(xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).Name.ToString(), "ERNO", CompareMethod.Text) = 0 Then
xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).InnerText = c
Else
elem = xmldoc.CreateElement("ERNo")
elem.InnerText = c.ToString
root.ChildNodes(i).AppendChild(elem)
End If
</code></pre>
| 12,650
|
<p>I am currently working on (or at least planning) a couple of projects that work with large amounts of repetitive data. The kind of data that works well in a spreadsheet or database, but is nasty in XML. :)</p>
<p>NetCDF seems like a great option for a file format. However, my work is in C# and there is no "official" NetCDF implementation available. There is an "official" Python version that I could potentially use with IronPython. Another option is the "NetCDF Library for .Net" on CodePlex but it seems pretty quiet (<a href="http://www.codeplex.com/netcdf" rel="noreferrer">http://www.codeplex.com/netcdf</a>).</p>
<p>Has anyone worked with either of these libraries? Can you provide any recommendations?</p>
|
<p>First, are you sure that NetCDF is the right choice? If you want to interact with other programs that need to read in large amounts of data and they already support NetCDF, then it's probably a great choice. There aren't that many standard and well-supported file formats that support large multidimensional arrays. But if you're only going to be reading and writing files from C#, it may not be such a good choice.</p>
<p>I'm a big fan of the "classic" NetCDF file format. It's compact and extremely simple, but flexible enough to support lots of common kinds of multidimensional well-structured data. It only took me one day to write a complete parser for classic NetCDF, and it only took an hour to write a program to output a well-formed special case of a classic NetCDF file. You could implement a pure C# NetCDF library yourself and it wouldn't be much trouble. You could easily start by implementing only the features you need. <a href="http://www.unidata.ucar.edu/software/netcdf/docs/netcdf/NetCDF-Classic-Format.html" rel="noreferrer">Here's the specification.</a></p>
<p>Unfortunately, NetCDF-4 chose to use HDF-5 as its data format. It adds a lot of complexity and makes it much more difficult to write a complete NetCDF parser in another language. HDF-5 is very general-purpose and in my opinion, it was overengineered - it tries to be too many things to too many people. I would not recommend trying to work with it directly unless you plan to spend a month writing unit tests. If you must use netCDF-4 / HDF-5 from C#, your only realistic option would be to wrap the C library using SWIG or something like that.</p>
<p>Note that NetCDF for Python is just a wrapper around the C code, so it's not really all that helpful; if you're going to use a wrapped C library you may as well just write a C# wrapper rather than use Python as a middle layer.</p>
|
<p>In a project we are using the ucar netcdf implementation in c# using ikvm. IKVM can be used to 'convert' java projects into .Net libraries without a use for java VM. I have not done any performance check but it is a simple way to get netcdf in c# :).</p>
<p><a href="http://www.unidata.ucar.edu/downloads/netcdf/netcdf-java-4/index.jsp" rel="nofollow noreferrer">http://www.ikvm.net/stories.html</a></p>
<p><a href="http://www.unidata.ucar.edu/downloads/netcdf/netcdf-java-4/index.jsp" rel="nofollow noreferrer">http://www.unidata.ucar.edu/downloads/netcdf/netcdf-java-4/index.jsp</a></p>
| 8,484
|
<p>I have a custom XML schema defined for page display that puts elements on the page by evaluating XML elements on the page. This is currently implemented using the preg regex functions, primarily the excellent preg_replace_callback function, eg:</p>
<pre><code>...
$s = preg_replace_callback("!<field>(.*?)</field>!", replace_field, $s);
...
function replace_field($groups) {
return isset($fields[$group[1]) ? $fields[$groups[1]] : "";
}
</code></pre>
<p>Just as an example.</p>
<p>Now this works pretty well... so long as the XML elements aren't nested. At this point it gets a whole lot more complicated, like if you have:</p>
<pre><code><field name="outer">
<field name="inner">
...
</field>
</field>
</code></pre>
<p>You want to make sure you replace the innermost field first. Judicious use of greedy/non-greedy regex patterns can go some of the way to handling these more complicated scenarios but the clear message is that I'm reaching the limits of what regex can reasonably do and really I need to be doing XML parsing.</p>
<p>What I'd like is an XML transformation package that:</p>
<p>allows me to conditionally evaluate/include the contained document tree or not based on a callback function ideally (analagous to preg_replace_callback);
can handle nested elements of the same or different types; and
handles attributes in a nice way (eg as an associative array).</p>
<p>What can help me along the way?</p>
|
<p>PHP's <a href="http://de2.php.net/manual/en/class.xsltprocessor.php" rel="nofollow noreferrer"><code>XSLTProcessor</code></a> class (<a href="http://de2.php.net/manual/en/book.xsl.php" rel="nofollow noreferrer">ext/xsl</a> - PHP 5 includes the XSL extension by default and can be enabled by adding the argument <code>--with-xsl[=DIR]</code> to your configure line) is quite sophisticated and allows among other things the use of PHP functions within your XSL document by using the <a href="http://de2.php.net/manual/en/xsltprocessor.registerphpfunctions.php" rel="nofollow noreferrer"><code>XSLTProcessor::registerPHPFunctions()</code></a> method.</p>
<p>The following example is shamelessly pinched from the <a href="http://de2.php.net/manual/en/xsltprocessor.registerphpfunctions.php" rel="nofollow noreferrer">PHP manual page</a>:</p>
<pre><code>$xml = '<allusers>
<user>
<uid>bob</uid>
</user>
<user>
<uid>joe</uid>
</user>
</allusers>';
$xsl = '<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:php="http://php.net/xsl">
<xsl:output method="html" encoding="utf-8" indent="yes"/>
<xsl:template match="allusers">
<html><body>
<h2>Users</h2>
<table>
<xsl:for-each select="user">
<tr><td>
<xsl:value-of
select="php:function(\'ucfirst\',string(uid))"/>
</td></tr>
</xsl:for-each>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>';
$xmldoc = DOMDocument::loadXML($xml);
$xsldoc = DOMDocument::loadXML($xsl);
$proc = new XSLTProcessor();
$proc->registerPHPFunctions();
$proc->importStyleSheet($xsldoc);
echo $proc->transformToXML($xmldoc);
</code></pre>
|
<p>Definitely not regexps. XML formats can change in ways that don't effect their content (in other words: that are invisible to XML-handling libraries), yet are significant to regexps. Such code becomes a maintenance nightmare quickly. </p>
<p>As to which parser to use (SAX, StAX, DOM, JDOM, dom4j, XOM, etc.), </p>
| 42,376
|
<p>I have a Monoprice Maker Select Plus, currently using Ultimaker Cura 3.6.0 with the default settings for a Wanhao Duplicator i3 Plus. Right now when a print finishes, the bed retreats towards the back of the machine. I'd rather present the bed forward for easier part removal.</p>
<p>Here is my ending G-Code:</p>
<pre>
M104 S0 ;extruder heater off
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 Y0 ;move X/Y to min endstops, so the head is out of the way
M84 ;steppers off
G90 ;absolute positioning
</pre>
<p>It looks like I need to change that <code>G28</code> line third from the bottom, but I'm not sure what to change it to. I've not yet done any g-code manipulation of my own. I don't know what units it's using, and it looks like it still has relative positioning, so even then I don't know it's a good idea to just set it for the max size of the bed. </p>
<p>So how can I change this code to move the bed as I want?</p>
|
<p>Note that <a href="https://reprap.org/wiki/G-code#G28:_Move_to_Origin_.28Home.29" rel="nofollow noreferrer">this reference</a> states that:</p>
<blockquote>
<p>Because the behavior of <code>G28</code> is unspecified, it is recommended <strong>not</strong> to automatically include <code>G28</code> in your <strong>ending GCode</strong>. On a Cartesian this will result in damaging the printed object. If you need to move the carriage at the completion of a print, use <code>G0</code> or <code>G1</code>.</p>
</blockquote>
<p>So you need to use a <a href="https://reprap.org/wiki/G-code#G0_.26_G1:_Move" rel="nofollow noreferrer"><code>G0</code> or <code>G1</code></a> move.</p>
<p>When using Ultimaker Cura (like many other slicers), there is built in functionality known as <a href="https://github.com/Ultimaker/Cura/issues/1131" rel="nofollow noreferrer">keywords</a> with a complete list found <a href="https://github.com/Ultimaker/Cura/blob/master/resources/definitions/fdmprinter.def.json" rel="nofollow noreferrer">here</a>.</p>
<p>The keyword <code>machine_depth</code> is the one that is of use to you, embed this in your end G-code in between curly brackets and it will expand to the bed size of your machine (replacing <code>G28 X0 Y0</code>):</p>
<p><code>G1 X0 Y{machine_depth}</code></p>
<p>For me this compiles to (e.g. for my coreXY printer):</p>
<p><code>G1 X0 Y300</code></p>
<p>To set the speed, just add the following command prior to the one above:</p>
<p><code>G1 F2500</code></p>
<p>Adding this line before the actual move ensures that the speed is constant, if <code>F2500</code> would have been included in the move command (like <code>G1 X0 Y{machine_depth} F2500</code>), this defines the end speed, it would start moving at the last speed value prior to the move.</p>
<p>This results in adding the following lines in your endscript:</p>
<pre>
G1 F2500
G1 X0 Y{machine_depth}
</pre>
|
<p>You're correct that the G28 line should be changed. What I would do is the following:</p>
<pre><code>M104 S0 ;extruder heater off
G91 ;relative positioning
G1 E-1 F300 ;retract the filament a bit before lifting the nozzle, to release some of the pressure
G1 Z+0.5 E-5 X-20 Y-20 F{travel_speed} ;move Z up a bit and retract filament even more
G28 X0 ;move X to min endstop, so the head is out of the way
G90 ;absolute positioning
G1 Y200 ;Move bed forward
M84 ;steppers off
</code></pre>
<p>This way your X axis still gets homed after the Z bumps up and before Y moves to present the print.</p>
<p>G28 is the command to home the print head. Your current settings homes the X and Y axes. G1 is a linear movement. One caveat to this change in G-Code is that there needs to be a home command at the start of your prints since you're not homing afterwards anymore. (I believe most slicers default to a G28 at the start AND end of prints so it's not a major concern, but one to be wary of now just in case.)</p>
| 1,210
|
<p>I ruined several unit tests some time ago when I went through and refactored them to make them more <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">DRY</a>--the intent of each test was no longer clear. It seems there is a trade-off between tests' readability and maintainability. If I leave duplicated code in unit tests, they're more readable, but then if I change the <a href="http://en.wikipedia.org/wiki/System_Under_Test" rel="noreferrer">SUT</a>, I'll have to track down and change each copy of the duplicated code.</p>
<p>Do you agree that this trade-off exists? If so, do you prefer your tests to be readable, or maintainable?</p>
|
<p>Readability is more important for tests. If a test fails, you want the problem to be obvious. The developer shouldn't have to wade through a lot of heavily factored test code to determine exactly what failed. You don't want your test code to become so complex that you need to write unit-test-tests.</p>
<p>However, eliminating duplication is usually a good thing, as long as it doesn't obscure anything, and eliminating the duplication in your tests may lead to a better API. Just make sure you don't go past the point of diminishing returns.</p>
|
<p>I don't think there is a relation between more duplicated and readable code. I think your test code should be as good as your other code. Non-repeating code is more readable then duplicated code when done well.</p>
| 15,761
|
<p>I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique.</p>
<p>The elements can occur multiple times in both lists and they are originally unsorted.</p>
<p>My function looks like this:</p>
<pre><code>(defun merge-lists (list-a list-b sort-fn)
"Merges two lists of (x, y) coordinates sorting them and removing dupes"
(let ((prev nil))
(remove-if
(lambda (point)
(let ((ret-val (equal point prev)))
(setf prev point)
ret-val))
(sort
(merge 'list list-a list-b sort-fn) ;'
sort-fn))))
</code></pre>
<p>Is there a better way to achieve the same?</p>
<p>Sample call:</p>
<pre><code>[CL]> (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'>)
==> (9 8 7 6 4 3 2 1)
</code></pre>
|
<p>Our neighbourhood friendly Lisp guru pointed out the <a href="http://www.lispworks.com/documentation/HyperSpec/Body/f_rm_dup.htm" rel="nofollow noreferrer">remove-duplicates function</a>.</p>
<p>He also provided the following snippet:</p>
<pre><code>(defun merge-lists (list-a list-b sort-fn test-fn)
(sort (remove-duplicates (append list-a list-b) :test test-fn) sort-fn))
</code></pre>
|
<p>Sounds like you need to be using Sets.</p>
| 12,523
|
<p>I have a Win32 TreeCtrl where the user can rename the tree labels. I process the TVN_ENDLABELEDIT message to do this.</p>
<p>In certain cases I need to change the text that the user entered. Basically the user can enter a short name during edit and I want to replace it with a longer text.</p>
<p>To do this I change the pszText member of the TVITEM struct I received during TVN_ENDLABELEDIT. I do a pointer replace here, as the original memory may be too small to do a simple strcpy like operation.</p>
<p>However I do not know how to deallocate the original pszText member. Basically because it's unknown if that was created with malloc() or new ... therefore I cannot call the appropriate deallocator. Obviously Win32 won't call the deallocator for the old pszText because the pointer has been replaced. So if I don't deallocate, there will be a memory leak.</p>
<p>Any idea how Win32 allocate these structs and what is the proper way to handle the above situation?</p>
|
<p>Unless you're using <code>LPSTR_TEXTCALLBACK</code>, the tree-view control is responsible for allocating the memory, not your code, so you shouldn't change the value of the <code>pszText</code> pointer.</p>
<p>To change the item's text in your <code>TVN_ENDLABELEDIT</code> handler, you can use <code>TreeView_SetItem</code>, then return 0 from the handler.</p>
|
<p>You don't want to directly edit the text in the TVITEM struct, the results are undefined. Instead, use the TVM_SETITEM message, or equivalently, use the TreeView_SetItem() macro defined in windowsx.h.</p>
| 12,638
|
<p>Is using SQL Express in a production environment a reasonable choice?</p>
<p>I looked at Microsoft's comparison chart:</p>
<p><a href="https://www.microsoft.com/en-us/sql-server/sql-server-2019-comparison" rel="nofollow noreferrer">https://www.microsoft.com/en-us/sql-server/sql-server-2019-comparison</a></p>
<p>I would be using SQL Express with a small to mid-sized web site. I don't believe I would exceed the 4GB database size limit. Is SQL Express typically supported in shared hosting environments? Is there something I'm missing that would make SQL Express an unreasonable choice?</p>
|
<p>I know many people using SQL Express for production and it works well, the biggest limiting factor is the absence of SQL Agent for automated backups. To automate backups you have to either take a VM image (if on a VPS) or use windows scheduler or some other technology.</p>
<p>The only other major limiting factor is the ram limitation, but for a small site I have not really noticed that being too much of an actual issue.</p>
|
<p>There's a maximum of 5 concurrent connections for SQL Express. If you have more than 5 concurrent connections performance will drop severely.
Alos, you have to consider that SQL Agent is not included so if you want to schedule backups or maintenance tasks you have to use windows scheduler.
Other that this, it's a perfect solution for small databases.</p>
| 21,783
|
<p>I'm trying to figure out how all these work together. I know that a DTO is basically just a container of data for the Domain Objects to pass back and forth to forms and such. Does the Domain object contain a DTO or do the DTO and the Domain Object happen to just have all of the same properties that will be mapped manually?</p>
<p>If I am exposing my DTO type in a service, how do I use the getters and setters without creating a round trip for each get/set operation on the client? I know that you can have one long constructor, but that can get ugly if you have more than 7 properties.</p>
<p>When implementing the Repository pattern, do I pass in the DTO or the Domain Object?</p>
|
<ul>
<li>The DTO's and the Domain objects should be separate.</li>
<li>There should be a mapper that maps a DTO to a domain object and a domain object to a DTO. This mapper should be an implementation of an interface, with the default mapper using reflection to map the objects to each other.</li>
<li>The repository should be a service that returns the domain objects, which themselves should services.</li>
<li>If the DTO is a class that is exposed by a web service, the WSDL that is created defines the property as an element, and the proxy that gets created on the other side just creates a getter / setter property that is run on the client itself, so the getters and setters do not cause a roundtrip.</li>
<li>Even if you just create a public variable in your DTO, the proxy will be implemented as a getter and setter.</li>
</ul>
|
<p>I think it's better to have the DTO contain a reference to the Domain object so that the DTO's consumers can begin using the Domain object. That said, if the DTO's consumers must not mutate the Domain object, you may need to have the DTO contain the values encapsulated in the Domain object. This can be difficult since you may need to do a deep copy of the Domain object.</p>
<p>I'm not sure why it's a problem that exposing a DTO type as a service would cause use of its getters/setters to do a round trip. If the service is a remote service, the returned DTO is serialized anyway and your getters/setters will get the copy of the values. If the service is not remote, it doesn't seem to be much of penalty to do a "round trip" since the client and the service are in the same process space.</p>
| 34,580
|
<p>I want to decode all the HTML entities in a complicated data structure. Basically I'm looking for a "super map()" function. Here's what I have so far:</p>
<pre><code>sub _html_decode {
my $self = shift;
my $ref = shift;
if (ref($ref) eq "HASH") {
$self->_html_decode_hash($ref)
}
if (ref($ref) eq "ARRAY") {
$self->_html_decode_array($ref);
}
}
sub _html_decode_array {
my $self = shift;
my $ref = shift;
unless (@$ref) {return;}
foreach (0 .. (scalar(@$ref) - 1)) {
if (ref($ref->[$_]) eq "HASH") {
$self->_html_decode_hash($ref->[$_]);
}
if (ref($ref->[$_]) eq "ARRAY") {
$self->_html_decode_array($ref->[$_]);
}
else {
$ref->[$_] = decode_entities($ref->[$_]);
}
}
}
sub _html_decode_hash {
my $self = shift;
my $ref = shift;
unless (%$ref) {return;}
while (my ($k, $v) = each %$ref) {
if (ref($v) eq "HASH") {
$self->_html_decode_hash($v);
}
if (ref($v) eq "ARRAY") {
$self->_html_decode_array($v)
}
else {
$ref->{$k} = decode_entities($v);
}
}
}
</code></pre>
|
<p><a href="http://search.cpan.org/~bowmanbs/Data-Rmap-0.62/lib/Data/Rmap.pm" rel="nofollow noreferrer">Data::Rmap</a> seems to do this as well. Does anyone have any experience with this module?</p>
|
<p>I think this should do, but I haven't tested it.</p>
<pre><code>sub _html_decode {
my ($self, $ref) = @_;
if (ref($ref) eq "HASH") {
for my $value (values %{$ref}) {
$self->_html_decode($value);
}
}
elsif (ref($ref) eq "ARRAY") {
for my $value (@{$ref}) {
$self->_html_decode($value);
}
}
else {
$_[1] = decode_entities($_[1]);
}
}
</code></pre>
<p>I admit the last part isn't pretty though.</p>
| 49,108
|
<p>I have a class that maintans a reference to a Hashtable and serializes/deserializes that Hashtable. After the call to SerializationInfo.GetValue, the Hashtable is not fully deserialized because the deserialization happens during the IDeserialization calback.</p>
<pre><code>Hashtable hashtable = (Hashtable) info.GetValue("hash", typeof(Hashtable));
</code></pre>
<p>I also implemented the IDeserialization callback in the parent class, but there too the Hashtable is not fully deserialized yet. I expected it to be if the deserialization is happening from the inside out.</p>
<p>My question is, is it safe to explicitely call Hashtable.OnDeserialization from the OnDeserialization method of my parent class, so that I can enumerate it at that point?</p>
<pre><code>public virtual void OnDeserialization(object sender)
{
hashtable.OnDeserialization(sender);
}
</code></pre>
|
<p>This is really an interesting issue. After checking the serialization code with Reflector, I think that there is no generally good soluiton if a referred class uses IDeserializationCallback. </p>
<p>Probably you have seen, that there are two other ways as well to run some code during deserialization, the [OnDeserializing] and the [OnDeserialized] attributes. Unfortuanately both runs before the IDeserializationCallback.OnDeserialization(). This is the run order of the methods if you have class1 that refers to a class2:</p>
<pre><code>Class1: [OnDeserializing]
Class2: [OnDeserializing]
Class2: [OnDeserialized]
Class1: [OnDeserialized]
Class1: IDeserializationCallback.OnDeserialization
Class2: IDeserializationCallback.OnDeserialization
</code></pre>
<p>As you can see, the [OnDeserializing] and the [OnDeserialized] attributes work consistent, but the IDeserializationCallback methods not really... :(</p>
<p>I have also checked the OnDeserialization implementation of Hashtable and Dictionary, and both seems to be safe for calling the OnDeserialization more than once (only the first call will perform the necessary operation, the subsequent calls will do nothing).</p>
<p>So finally you should call the OnDeserialization() of the Hashtable, as <a href="http://clevercoder.wordpress.com/2006/11/30/hashtable-serialization-and-the-ideserializationcallback-interface/" rel="noreferrer">Sean</a> and Brian suggested. </p>
|
<p>I suspect you have already googled, but I happened to across <a href="http://clevercoder.wordpress.com/2006/11/30/hashtable-serialization-and-the-ideserializationcallback-interface/" rel="nofollow noreferrer">this</a> pattern yesterday. </p>
<pre><code>public BoringClass(SerializationInfo info, StreamingContext context)
{
Hashtable hashtable = (Hashtable) info.GetValue("hash", typeof(Hashtable));
hashtable.OnDeserialization(this);
Console.WriteLine("Value is: " + hashtable["testItem"]);
}
</code></pre>
| 35,329
|
<p>I am looking for a method of reading emails using Pop3 in C# 2.0. Currently, I am using code found in <a href="http://www.codeproject.com/KB/IP/Pop3MimeClient.aspx?fid=341657" rel="noreferrer">CodeProject</a>. However, this solution is less than ideal. The biggest problem is that it doesn't support emails written in unicode.</p>
|
<p>I've successfully used <a href="http://sourceforge.net/projects/hpop/" rel="noreferrer">OpenPop.NET</a> to access emails via POP3. </p>
|
<p>call me old fashion but why use a 3rd party library for a simple protocol. I've implemented POP3 readers in web based ASP.NET application with System.Net.Sockets.TCPClient and System.Net.Security.SslStream for the encryption and authentication. As far as protocols go, once you open up communication with the POP3 server, there are only a handful of commands that you have to deal with. It is a very easy protocol to work with. </p>
| 6,614
|
<p>I have a compiled AppleScript application which I have moved to my windows server. I'd like to then insert a text file into the application (which looks like a zip file on windows):</p>
<pre><code>myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt
</code></pre>
<p>So, I've precompiled the AppleScript to try to read from this text file and get the contents as a string. This is what I do:</p>
<pre><code>set theFolder to POSIX path of (the path to me)
set theFile to theFolder & "Contents/Resources/MyNewDir/MyTxtFile.txt"
open for access theFile
set fileContents to (read theFile)
close access theFile
</code></pre>
<p>but this is the error I get:</p>
<blockquote>
<p>Can't make
"/Users/mike/Desktop/myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt"
into type file</p>
</blockquote>
|
<p>Ok, I figured it out, I changed the second line to this:</p>
<pre><code>set theFile to (POSIX file (theFolder & "Contents/Resources/MyNewDir/MyTxtFile.txt"))
</code></pre>
|
<p>Reading a file via a file path in a variable.</p>
<p>The 1st two work. The 3rd, which stores the file name in variable does not.</p>
<p>set myData to read file POSIX file ¬
"/Users/sww/Devel/afile.csv"</p>
<p>set myData to read file ¬
"Macintosh HD:Users:sww:Devel:afile.csv"</p>
<pre><code>set fRef to "Macintosh HD:Users:sww:Devel:afile.csv"
set myData to read file fRef -- No good
</code></pre>
<p>To fix? Give the file reference as a string. </p>
<pre><code>set myData to read file (fRef as string) -- OK
</code></pre>
| 35,561
|
<p>So lets say I'm using Python's <a href="http://www.python.org/doc/2.5.2/lib/module-ftplib.html" rel="nofollow noreferrer">ftplib</a> to retrieve a list of log files from an FTP server. How would I parse that list of files to get just the file names (the last column) inside a list? See the link above for example output.</p>
|
<p>Using retrlines() probably isn't the best idea there, since it just prints to the console and so you'd have to do tricky things to even get at that output. A likely better bet would be to use the nlst() method, which returns exactly what you want: a list of the file names.</p>
|
<p>I believe it should work for you.</p>
<pre><code>file_name_list = [' '.join(each_file.split()).split()[-1] for each_file_detail in file_list_from_log]
</code></pre>
<p>NOTES - </p>
<ol>
<li><p>Here I am making a assumption that you want the data in the program (as list), not on console.</p></li>
<li><p>each_file_detail is each line that is being produced by the program.</p></li>
<li><p>' '.join(each_file.split())</p></li>
</ol>
<p>To replace multiple spaces by 1 space.</p>
| 29,406
|
<p>I'm having trouble running a complex query against our company LDAP server. I'm using the following Perl script:</p>
<pre><code>use Data::Dumper;
use Net::LDAP;
die "Can't connect to LDAP-Server: $@\n"
unless $ldap = Net::LDAP->new( 'xLDAPx' );
foreach my $filter ( 'ou=Personal', 'ou=BAR', 'ou=Personal,ou=BAR', 'ou=Personal,ou=FOO,o=FOO,dc=foo,dc=com' )
{
$mesg = $ldap->search( base => "o=FOO,dc=foo,dc=com", filter => $filter );
print Dumper($mesg), "\n\n";
}
</code></pre>
<p>While the first two filters work (as in returning the expected values) the last and complex one doesn't. It returns an empty array. What really puzzles me is that exactly the same query string works when I use it with a tool like the Softerra LDAP Browser. </p>
<p>I have also tried the same query using PHP's <code>ldap_search</code> & co, no avail.</p>
<p>Can somebody shed some light on this?</p>
<p>Thanks for reading</p>
<p>holli</p>
<p>Edit:
This is the structure of the server:</p>
<pre><code>Server
ou=FOO
ou=...
ou=Personal
uid=something
</code></pre>
<p>I need a list of uids.</p>
|
<p>I think you want it to be more like <code>(&(ou=Personal)(ou=FOO)(o=FOO)(dc=foo)(dc=com))</code>.
But you are not clear at all on what you want exactly, so I can't make a filter for you.</p>
<p>Edited to add: I'm guessing this is what you want to do: <code>(|(ou=Personal)(ou=FOO))</code></p>
|
<p>The reason is that you are not providing syntactically correct filter strings, but parts of a DN. I can't imagine this works in Ldap Browser - I just tried myself without success.</p>
<p>The first two are correct filter strings. They filter on a single object attribute in a "({attribute}={value})" fashion. The first ("ou=Personal") would return any OU named "Personal" within your search base.</p>
<p>If you explain in more detail what you are trying to find I can probably tell you what filter expression you need.</p>
| 30,038
|
<p>I am attempting to determine prior art for the following idea:</p>
<p>1) user types in some code in a language called (insert_name_here);</p>
<p>2) user chooses a destination language from a list of well-known output candidates (javascript, ruby, perl, python);</p>
<p>3) the processor translates insert_name_here into runnable code in destination language;</p>
<p>4) the processor then runs the code using the relevant system call based on the chosen language</p>
<p>The reason this works is because there is a pre-established 1 to 1 mapping between all language constructs from insert_name_here to all supported destination languages.</p>
<p>(<strong>Disclaimer:</strong> This obviously does not produce "elegant" code that is well-tailored to the destination language. It simply does a rudimentary translation that is runnable. The purpose is to allow developers to get a quick-and-dirty implementation of algorithms in several different languages for those cases where they do not feel like re-inventing the wheel, but are required for whatever reason to work with a specific language on a specific project.)</p>
<p>Does this already exist?</p>
|
<p>The .NET CLR is designed such that C++.Net, C#.Net, and VB.Net all compile to the same machine language, and you can "decompile" that CLI back in to any one of those languages. </p>
<p>So yes, I would say it already exists though not exactly as you describe.</p>
|
<p>This seems a little bizarre. If you're using the term "prior art" in its most common form, you're discussing a potentially patentable idea. If that <strong>is</strong> the case, you have:</p>
<p>1/ Published the idea, starting the clock running on patent filing - I'm assuming, perhaps incorrectly, that you're based in the U.S. Other jurisdictions may have other rules.</p>
<p>2/ Told the entire planet your idea, which means it's pretty much useless to try and patent it, unless you act very fast.</p>
<p>If you're not thinking about patenting this and were just using the term "prior art" in a laypersons sense, I apologize. I work for a company that takes patents very seriously and it's drilled into us, in great detail, what we're allowed to do with information before filing.</p>
<p>Having said that, patentable ideas must be novel, useful and non-obvious. I would think that your idea would not pass on the third of these since you're describing a language translator which would have the prior art of the many pascal-to-c and fortran-to-c converters out there.</p>
<p>The one glimmer of hope would be the ability of your idea to generate one of multiple output languages (which p2c and f2c don't do) but I think even that would be covered by the likes of cross compilers (such as gcc) which turn source into one of many different object languages.</p>
<p>IBM has a product called Visual Age Generator in which you code in one (proprietary) language and it's converted into COBOL/C/Java/others to run on different target platforms from PCs to the big honkin' System z mainframes, so there's your first problem (thinking about patenting an idea that IBM, the biggest patenter in the world, is already using).</p>
| 43,997
|
<p>I tried GNUBOX which use bluetooth to connect to my computer then to the internet. It's very painful to set up (under windows more than under linux, but it's still painful, it works 1 time on 3).</p>
<p>I own a Nokia 6630 so there is no WLAN support. Is there any emulator? I'd need to know something like max width, max height etc... usability in general, any hint?</p>
|
<p>This may sound silly but you could consider getting a mobile tariff with unlimited data. In most European countries these are now available and are not too expensive.</p>
<p>I don't believe you would get a solid experience from any emulator.</p>
|
<p>Can you use a data cable and IP pass through? </p>
<p>Since the 6630 is a Symbian phone, you should be able to use GNUbox to handle the connection. See <a href="http://xan.dnsalias.org/gnubox/" rel="nofollow noreferrer">http://xan.dnsalias.org/gnubox/</a></p>
| 17,535
|
<p>I just saw this mentioned in Stack Overflow question <em><a href="http://web.archive.org/web/20090503103538/http://stackoverflow.com:80/questions/7975/best-css-editor" rel="nofollow noreferrer">Best WYSIWYG CSS editor</a></em> and didn't know it could be done. I'm a Visual Studio newbie, so how do you do it?</p>
<p>Is there a separate debugger for JavaScript? I know how to work the one for code-behind pages... I usually use Firebug to deal with debugging JavaScript code.</p>
<p>I'm using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005" rel="nofollow noreferrer">Visual Studio 2005</a>.</p>
|
<p>I prefer using <a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="nofollow noreferrer">Firebug</a> for projects I can't use <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="nofollow noreferrer">Visual Studio 2008</a> on.</p>
|
<p>In Internet Explorer, select <em>View</em> -> <em>Script Debugger</em> -> <em>Open</em>. That should do it.</p>
| 2,981
|
<p>I recently installed vim-enhanced , but I can't find any article/tutorial related to it.All I could find is a page that briefly describes it's new features , along with several RPM's to download .
What exactly does it have to offer to scripting languages that regular vi/vim can't ?</p>
<p>Thanks</p>
|
<p>According to <a href="http://linux.maruhn.com/sec/vim-enhanced.html" rel="noreferrer">this</a>, vim-enhanced is just vim "with the perl, python, tcl, and cscope options compiled in." You should be able to find everything you need to know about these compile options in <a href="http://vimdoc.sourceforge.net/htmldoc/help.html" rel="noreferrer">the documentation</a>.</p>
|
<p>If you're new to vim, then run vimtutor</p>
<p>You may also want to start out by reading :help and learning how to use the help system. In particular :help topic (control-D) and :help topic (more useful if you have :set wildmenu) will help you find topics in vim's built-in help (which is notably superior to trying to Google for things). If all else fails there's also :helpgrep topic and then use the quickfix buffer to see the hits (:cn, :cp, :cl, etc).</p>
<p>The #vim channel on Freenode IRC network is also a good place to get help.</p>
| 10,044
|
<p>I need a framework for generating charts for data visualization. I picked up Processing www.processing.org/ but at the moment i can not run that in the "headless" mode from a web server. Is there any other candidate for this domain? What are the options if you need more chart type than what is supported by out-of-the-box solutions</p>
<p>-Bharani</p>
|
<p><a href="http://www.jfree.org/jfreechart/" rel="nofollow noreferrer">JFreeChart</a> is a option, or a software reporting software tool that does all the footwork of data analysis for you. I can recommend <strong><a href="http://www.inetsoftware.de" rel="nofollow noreferrer">i-net Clear Reports</a></strong> seeing as how I work for i-net software and all... ;).</p>
|
<p>I am now using Graphics2D that comes with JDK. With this you are no longer limited to the chart types - simply concentrate of the data pattern and let Graphics2D do it's job. </p>
| 12,839
|
<p>I have a custom control that I created for my project. In this control there are several child controls like a Label, a PictureBox, and a LinkLabel. Other then the LinkLabel, I want the mouse over event currently on the parent control and have the control respond to the mouse over. The background color changes when you hover over the control, but the background color doesn't change when over a child control; this is because there is no MouseEnter and MouseLeave events on the child control. I solved this issue by added the parent controls delegate methods to the child controls. The problem remains that the click event also is ignored over the child controls when I've subscribed to the click event on my parent control. I can subscribe to each individual child control, but how do I force the click event of the parent control? The term I've found by searching is Event Bubbling, but this seems to only apply to ASP.NET technologies and frameworks. Any suggestions?</p>
|
<p>Your description leads me to believe that you want both your child and your parent controls to respond to a click on the child control.</p>
<p>If I understand your question correctly, I'd suggest subscribing to your child controls' click events and, in those event handlers, calling some common method that manipulates the state of the parent UserControl in the manner that you desire (e.g., changing the background color).</p>
|
<p>Peter Rilling over at CodeProject has some simple and effective code to do event bubbling/broadcasting in winforms (and C#). It's really easy to use.</p>
<p><a href="http://www.codeproject.com/KB/cs/event_broadcast.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/event_broadcast.aspx</a></p>
| 21,756
|
<p>I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations?</p>
<p>I was thinking a long the lines of having a display.php that just runs display() and from the Plone template to download that URL and output the content. Do you think it might work? What methods of hitting a URL, retrieve the content and outputting can I use from inside a Plone template?</p>
<p>One important and critical constraint is that the output should be directly on the HTML and not an an iframe. This is a constraint coming from the outside, nothing technical.</p>
|
<p>Another option is to run the PHP script on the server using os.popen, then just printing the output. Quick and dirty example:</p>
<pre><code>import os
print os.popen('php YourScript.php').read()</code></pre>
|
<p>Probably the easiest way: install <a href="http://plone.org/products/windowz" rel="nofollow noreferrer" title="windowz">windowz</a> inside your site. That way you get a page with an iframe in your plone layout. Make sure the php script outputs a regular html page and configure your windowz page with that url. Done.</p>
<p>Works great for existing in-company phonebook applications and so.</p>
| 41,526
|
<p>Does anyone have C# code handy for doing a ping and traceroute to a target computer? I am looking for a pure code solution, not what I'm doing now, which is invoking the ping.exe and tracert.exe program and parsing the output. I would like something more robust.</p>
|
<p>Given that I had to write a TraceRoute class today I figured I might as well share the source code.</p>
<pre><code>using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
using System.Net;
namespace Answer
{
public class TraceRoute
{
private const string Data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
public static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress)
{
return GetTraceRoute(hostNameOrAddress, 1);
}
private static IEnumerable<IPAddress> GetTraceRoute(string hostNameOrAddress, int ttl)
{
Ping pinger = new Ping();
PingOptions pingerOptions = new PingOptions(ttl, true);
int timeout = 10000;
byte[] buffer = Encoding.ASCII.GetBytes(Data);
PingReply reply = default(PingReply);
reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions);
List<IPAddress> result = new List<IPAddress>();
if (reply.Status == IPStatus.Success)
{
result.Add(reply.Address);
}
else if (reply.Status == IPStatus.TtlExpired || reply.Status == IPStatus.TimedOut)
{
//add the currently returned address if an address was found with this TTL
if (reply.Status == IPStatus.TtlExpired) result.Add(reply.Address);
//recurse to get the next address...
IEnumerable<IPAddress> tempResult = default(IEnumerable<IPAddress>);
tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1);
result.AddRange(tempResult);
}
else
{
//failure
}
return result;
}
}
}
</code></pre>
<p>And a VB version for anyone that wants/needs it</p>
<pre><code>Public Class TraceRoute
Private Const Data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Public Shared Function GetTraceRoute(ByVal hostNameOrAddress As String) As IEnumerable(Of IPAddress)
Return GetTraceRoute(hostNameOrAddress, 1)
End Function
Private Shared Function GetTraceRoute(ByVal hostNameOrAddress As String, ByVal ttl As Integer) As IEnumerable(Of IPAddress)
Dim pinger As Ping = New Ping
Dim pingerOptions As PingOptions = New PingOptions(ttl, True)
Dim timeout As Integer = 10000
Dim buffer() As Byte = Encoding.ASCII.GetBytes(Data)
Dim reply As PingReply
reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions)
Dim result As List(Of IPAddress) = New List(Of IPAddress)
If reply.Status = IPStatus.Success Then
result.Add(reply.Address)
ElseIf reply.Status = IPStatus.TtlExpired Then
'add the currently returned address
result.Add(reply.Address)
'recurse to get the next address...
Dim tempResult As IEnumerable(Of IPAddress)
tempResult = GetTraceRoute(hostNameOrAddress, ttl + 1)
result.AddRange(tempResult)
Else
'failure
End If
Return result
End Function
End Class
</code></pre>
|
<p>As am improvement to Scotts code answer above, I found that his solution doesn't work if the route tapers off into nothing before reaching the destination - it never returns. A better solution with at least a partial route could be this (which I've tested and it works well). You can change the '20' in the for loop to something bigger or smaller or try to detect if it's taking too long if you want to control the number of iterations some other way. Full credit to Scott for the original code - thanks.</p>
<pre><code> using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
using System.Net;
...
public static void TraceRoute(string hostNameOrAddress)
{
for (int i = 1; i < 20; i++)
{
IPAddress ip = GetTraceRoute(hostNameOrAddress, i);
if(ip == null)
{
break;
}
Console.WriteLine(ip.ToString());
}
}
private static IPAddress GetTraceRoute(string hostNameOrAddress, int ttl)
{
const string Data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
Ping pinger = new Ping();
PingOptions pingerOptions = new PingOptions(ttl, true);
int timeout = 10000;
byte[] buffer = Encoding.ASCII.GetBytes(Data);
PingReply reply = default(PingReply);
reply = pinger.Send(hostNameOrAddress, timeout, buffer, pingerOptions);
List<IPAddress> result = new List<IPAddress>();
if (reply.Status == IPStatus.Success || reply.Status == IPStatus.TtlExpired)
{
return reply.Address;
}
else
{
return null;
}
}
</code></pre>
| 17,233
|
<p>I'm porting a Java library to C#. I'm using Visual Studio 2008, so I don't have the discontinued Microsoft Java Language Conversion Assistant program (JLCA).</p>
<p>My approach is to create a new solution with a similar project structure to the Java library, and to then copy the java code into a c# file and convert it to valid c# line-by-line. Considering that I find Java easy to read, the subtle differences in the two languages have surprised me.</p>
<p>Some things are easy to port (namespaces, inheritance etc.) but some things have been unexpectedly different, such as visibility of private members in nested classes, overriding virtual methods and the behaviour of built-in types. I don't fully understand these things and I'm sure there are lots of other differences I haven't seen yet.</p>
<p>I've got a long way to go on this project. What rules-of-thumb I can apply during this conversion to manage the language differences correctly?</p>
|
<p>Your doing it in the only sane way you can...the biggest help will be this document from Dare Obasanjo that lists the differences between the two languages:</p>
<p><a href="http://www.25hoursaday.com/CsharpVsJava.html" rel="nofollow noreferrer">http://www.25hoursaday.com/CsharpVsJava.html</a></p>
<p>BTW, change all getter and setter methods into properties...No need to have the C# library function just the same as the java library unless you are going for perfect interface compatibility.</p>
|
<p>I'm not sure if it is really the best way to convert the code line by line especially if the obstacles become overwhelming. Of course the Java code gives you a guideline and the basic structure but I think at the end the most important thing is that the library does provide the same functionality like it does in Java.</p>
| 20,380
|
<p>Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction.</p>
<p>I am trying to develop an automation framework using <a href="http://en.wikipedia.org/wiki/HP_QuickTest_Professional" rel="nofollow noreferrer">QuickTest Professional</a>, a testing tool.</p>
<ul>
<li>There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets).</li>
<li>I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop.</li>
<li>I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call.</li>
</ul>
|
<p>Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the data within the main loop and make it stop there..</p>
<p>Now, I have not done VBScript for a LONG time so, to pseudo it:</p>
<pre><code>While Not EndOfExcelSheet
ReadDataFromExcel();
If errOccurred Then TakeScreenPrint();
'NOTE: We have caught the error and requested the screen print
'is taken, but we have NOT bubbled the exception up!
End While
</code></pre>
|
<p>It's hard to answer your question based on what you wrote, but the first thing that comes to my mind is to add a boolean parameter to your exception-handling function (let's call it ExceptionHandler). Say, if the parameter (let's call it ExitLoop) is true, you wll exit from the "entire loop", otherwise, continue. Now, it might be too tedius to change that for old calls to the function (calls without the new parameter) -- I'm not sure if VB supports function overloading. If this is the case, you can rename your ExceptionHandler to ExceptionHandler2, add the new parameter (ExitLoop) and logic to it and create a (now new) function ExceptionHandler that calls ExceptionHandler2 with its parameters plus true for ExitLoop.</p>
<p>Hope it helps.</p>
| 13,926
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.