input
stringlengths
51
42.3k
output
stringlengths
18
55k
When can't an object be converted to a reference? <p>I want to compile the following line of code from <a href="http://code.google.com/p/enhsim">http://code.google.com/p/enhsim</a>:</p> <pre><code>enh::eout &lt;&lt; enh::setw(26); </code></pre> <p>gcc gives the following error:</p> <pre><code>error: no match for 'operator&lt;&lt;' in 'enh::eout &lt;&lt; enh::setw(26)' </code></pre> <p>But the <code>EnhSimOutput</code> class (of which <code>enh::eout</code> is an instance) does declare:</p> <pre><code>EnhSimOutput&amp; operator&lt;&lt; (setw&amp; p); </code></pre> <p>This problem goes away if I implement a version of the operation that accepts the object by value:</p> <pre><code>EnhSimOutput&amp; operator&lt;&lt; (setw p); </code></pre> <p>or if I create the <code>enh::setw</code> object as a local, i.e.:</p> <pre><code>enh::setw wValue(26); enh::eout &lt;&lt; wValue; </code></pre> <p>My question is this: why does gcc not select the "by-reference" version of the operator to begin with?</p> <p>The developers who wrote this code clearly made it compile, yet default gcc refuses to do it. Why is there a difference between an object declared separately as a local variable and a local created inline?</p>
<p>The value <code>enh::setw(26);</code> is an <em>rvalue</em> . Actually, temporaries like that are rvalues. Rvalues have special properties. One of them is that their address can't be taken (<code>&amp;enh::setw(26);</code> is illegal), and they can't generally bind to references to non-const (some temporaries <em>can</em> bind to references to non-const, but these undergo special rules: Calling member functions on temporary objects and catching exception objects by reference to non-const. In the latter case, the temporary even is an <em>lvalue</em>). </p> <p>There are two kind of expressions: <strong>lvalues</strong> that denote objects (that in turn may store an value) or functions, and <strong>rvalues</strong> which are meant to represent values read out of an object or represented by temporaries, numeral literals and enumerator constants. In C++03, to be able to pass such values to a function that accepts its value by-reference, there is a rule that they can be accepted by reference-to-const: <code>setw const&amp; p</code> would accept it. That is, you would have to declare your operator like this:</p> <pre><code>EnhSimOutput&amp; operator&lt;&lt; (setw const&amp; p); </code></pre> <p>That's a bit unfortunate, because you can't disambiguate constant lvalues (objects you created on the stack using <code>const enh::setw e(26);</code> for example) and non-const or const rvalues (like <code>enh::setw(26);</code> which is a non-const temporary). Also, if you go by that, the parameter can't have called non-const member functions on it, because it's a reference-to-const. For that reason, C++1x, the next C++ version, introduce a new kind of reference, so-called <em>rvalue-references</em> which fixes that.</p> <p><hr /></p> <p>The <em>Microsoft Visual C++</em> compiler binds rvalues to references to non-const, but gives out a warning when doing that (you have to use at least warning level 4 for it to show up). That's unfortunate, because problems rise up when porting to other compilers that are more strict in Standard compliance. </p>
Is using a while block to do nothing a bad thing? <p>I'm currently working through the excercises in 'The C Programming Language'. Here's one of my solutions: </p> <pre><code>int c; while ((c=getchar()) != EOF) { if (c == ' ') { while ((c = getchar()) == ' ') {} // do nothing? putchar(' '); } putchar(c); } </code></pre> <p>I found some solutions <a href="http://users.powernet.co.uk/eton/kandr2/krx109.html">here</a> that are quite different to mine and use an extra variable to keep track of what's going on, whereas I just use a while loop to skip through all the spaces. My solution feels a bit messy, as it seems bit hackish to have a while loop with nothing between the curly braces. I was wondering if there are any good reasons not to do this? Thanks for any advice :-) </p>
<p>Not at all - I believe you'll find do-nothing loops like these in K&amp;R, so that's about as official as it gets.</p> <p>It's a matter of personal preference, but I prefer my do-nothing loops like this:</p> <pre><code>while(something()); </code></pre> <p>Others prefer the semicolon to go on a separate line, to reinforce the fact that it's a loop:</p> <pre><code>while(something()) ; </code></pre> <p>Still others prefer to use the brackets with nothing inside, as you have done:</p> <pre><code>while(something()) { } </code></pre> <p>It's all valid - you'll just have to pick the style you like and stick with it.</p>
How to keep code base and database schema in synch? <p>So recently on a project I'm working on, we've been struggling to keep a solution's code base and the associated database schema in synch (Database = SQL Server 2008). </p> <p>Database changes occur fairly regularly (adding columns, constraints, relationships, etc) and as a result it's not uncommon for people to do a 'Get Latest' from source control and find that they also need to rebuild the database as well (and sometimes they forget to do the latter). </p> <p>We're not using VSTS: Database Edition (DataDude) but the standard Visual Studio database project with a script (batch file) which tears down and recreates the database from T-SQL scripts. The solution is a .Net &amp; ASP.net solution with LINQ to SQL underlying as the ORM.</p> <p>Anyone have ideas on an approach to take (automated or not) which would keep everyone up to date with the latest database schema? </p> <p>Continuous integration with MSBuild is an option, but only helps pick up any breaking changes committed, it doesn't really help in the scenario I highlighted above.</p> <p>We are using Team Foundation Server, if that helps..</p>
<p>We try to work forward from the creation scripts.</p> <p>i.e a change to the database is not authorised unless the script has been tested and checked into source control.</p> <p>But this assumes that the database team is integrated with your app team which is usually not the case in a large project...</p> <p>(I was tempted to answer this "with great difficulty")</p> <p>EDIT: Tools won't help you if your process isn't right.</p>
jQuery form submit() is not working in IE6? <p>I want to submit a with using jquery as below;</p> <pre><code>$("#formid").submit(); </code></pre> <p>Its working perfect in all browsers except IE6.</p> <p>How to make it work in IE6 ??</p>
<p>You probably have an <code>&lt;input name="submit" /&gt;</code> somewhere in your form, which overwrites the function "submit" of the form in IE.</p> <p><strong>Edit:</strong> </p> <p>I have tested in some other browsers. The latest versions of all major browsers seem to be affected by this issue.</p> <ul> <li>IE - all versions</li> <li>Firefox 4+</li> <li>Chrome at least since version 12</li> <li>Opera at least since version 11</li> </ul> <p>Bottom line: Never name your inputs "submit", or any other default property or method of the form element (e.g. "action" or "reset") . See <a href="https://developer.mozilla.org/en/DOM/HTMLFormElement">MDC</a> for a complete overview.</p>
Create regex from glob expression <p>i write program that parse text with regular expression. Regular expression should be obtained from user. I deside to use glob syntax for user input, and convert glob string to the regular expression internally. For example: </p> <pre><code>"foo.? bar*" </code></pre> <p>should be converted to </p> <pre><code>"^.*foo\.\w\bar\w+.*" </code></pre> <p>Somehow, i need to escape all meaningful characters from the string, then i need to replace glob * and ? characters with apropriate regexp syntax. What is the most convinient way to do this? </p>
<p>no need for incomplete or unreliable hacks. there's a function included with python for this</p> <pre><code>&gt;&gt;&gt; import fnmatch &gt;&gt;&gt; fnmatch.translate( '*.foo' ) '.*\\.foo$' &gt;&gt;&gt; fnmatch.translate( '[a-z]*.txt' ) '[a-z].*\\.txt$' </code></pre>
Is SQL the assembly for databases? <p>Talking about hibernate and others ORMs, the ORMs evangelists talk about SQL like the assembly language for Databases.</p> <p>I think is soon to assert this, but I guess can be true on a near future, not sure.</p> <p><strong>UPDATE:</strong> The analogy I was referring means <em>SQL</em> is to <em>assembly</em> what <em>ORM</em> is to <em>C/Java/C#</em>. Of course, an exact analogy is not possible. The question is if in the future, with more powerful computers the developers are going to use only <em>ORM</em> (or ORM like) instead of <em>SQL</em>.</p>
<p>Absolutely not. </p> <p>Assembly language is a very low level language where you instruct the processor exactly what to do, including what registers you want to use etc. </p> <p>SQL is a very high level language where you describe the semantics of what you want, and then a query optimiser decides how to execute it, so you don't even control what gets executed. It's an extremely powerful and flexible language of which any ORM offers at most a (fairly small) subset.</p> <p>You'll notice that the .NET framework has introduced LINQ recently which is a way to introduce high level SQL-like constructs into languages like C# and VB. Rather than being like assembler, it's pretty easy to argue that SQL works at a higher level of abstraction than most mainstream programming languages.</p>
Is there an easy way to send SCSI passthrough on OSX using native python <p>On Windows I am able to sent SCSI passthrough to devices using win32file.DeviceIOControl(..), on UN*X I can do it using fnctl.ioctl(...).</p> <p>I have been searching for something equivalent in OSX that would allow me to send the IOCTL commands using only native python.</p> <p>I would to send commands to hard drives specifically, not USB devices.</p> <p>Is there anyway to do it without writing a Kernel Extension or any other code using only standard python libraries? </p>
<p>I saw <a href="http://wagerlabs.com/blog/2008/02/04/writing-a-mac-osx-usb-device-driver-that-implements-scsi-pass-through/" rel="nofollow">this blog post</a> recently talking about using SCSI passthrough under OS X. Looks like it isn't as easy as Windows or Unix</p>
Why is Long.valueOf(0).equals(Integer.valueOf(0)) false? <p>This questions is prompted by <a href="http://stackoverflow.com/questions/444638/strange-hashmap-put-behaviour#444757">http://stackoverflow.com/questions/444638/strange-hashmap-put-behaviour#444757</a></p> <p>I think I understand why <code>Map&lt;K,V&gt;.put</code> takes a <code>K</code> but <code>Map&lt;K,V&gt;.get</code> takes an <code>Object</code>, it seems not doing so will break too much existing code. </p> <p>Now we get into a very error-prone scenario:</p> <pre><code>java.util.HashMap&lt;Long, String&gt; m = new java.util.HashMap&lt;Long, String&gt;(); m.put(5L,"Five"); // compiler barfs on m.put(5, "Five") m.contains(5); // no complains from compiler, but returns false </code></pre> <p>Couldn't this have been solved by returning true if the <code>Long</code> value was withing <code>int</code> range and the values are equal?</p>
<p>Here is the source from Long.java</p> <pre><code>public boolean equals(Object obj) { if (obj instanceof Long) { return value == ((Long)obj).longValue(); } return false; } </code></pre> <p>I.e. it needs to be a Long type to be equal. I think the key difference between:</p> <pre><code>long l = 42L int i = 42; l == i </code></pre> <p>and your example above is that with primitives an implicit widening of the int value can occur, however with object types there are no rules for implicitly converting from Integer to a Long.</p> <p>Also check out <a href="http://www.javapuzzlers.com/">Java Puzzlers</a>, it has a lot of examples similar to this.</p>
Resizing a Webbrowser control hosted by an Explorer Bar in IE <p>I am very new to windows programming so bare with me.</p> <p>I have a custom explorer bar (a band object) that hosts a webbrowser control. I can initialize the WebBrowser control properly and have it display web pages.</p> <p>However, I've noticed that when I resize the explorer bar, <b>the webbrowser control doesn't resize appropriately</b> to the size of the bar:</p> <p><br> <b>Before Resize:</b></p> <p><img src="http://farm4.static.flickr.com/3347/3198030477_abd73d020b.jpg" alt="Before Resize" /></p> <p><b>After Resize:</b></p> <p><img src="http://farm4.static.flickr.com/3482/3198030475_952eceb19d.jpg" alt="After Resize" /></p> <p>I'm not sure what events I need to handle and what can resize the browser control. I have some experience in .NET programming, and none really in Windows programming.</p> <p>I've also included my source code <a href="http://rapidshare.com/files/183531789/ExplrBar.Cpp" rel="nofollow">here</a> if you would like to poke aorund it more.</p> <p>Thanks!</p>
<p>Typically, when a container hosting an OLE control is resized, it queries the embedded object for its IOleInPlaceObject interface, and uses the SetObjectRects() on that interface to tell the control its new size.</p>
CSS two divs next to each other <p>I want to put two <code>&lt;div&gt;</code>s next to each other. The right <code>&lt;div&gt;</code> is about 200px; and the left <code>&lt;div&gt;</code> must fill up the rest of the screen width? How can I do this?</p>
<p>You can use <strong><a href="https://devdocs.io/css/css_flexible_box_layout">flexbox</a></strong> to lay out your items:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#parent { display: flex; } #narrow { width: 200px; background: lightblue; /* Just so it's visible */ } #wide { flex: 1; /* Grow to rest of container */ background: lightgreen; /* Just so it's visible */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="parent"&gt; &lt;div id="wide"&gt;Wide (rest of width)&lt;/div&gt; &lt;div id="narrow"&gt;Narrow (200px)&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This is basically just scraping the surface of flexbox. Flexbox can do pretty amazing things.</p> <hr> <p>For older browser support, you can use CSS <strong>float</strong> and a <strong>width</strong> properties to solve it.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#narrow { float: right; width: 200px; background: lightblue; } #wide { float: left; width: calc(100% - 200px); background: lightgreen; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="parent"&gt; &lt;div id="wide"&gt;Wide (rest of width)&lt;/div&gt; &lt;div id="narrow"&gt;Narrow (200px)&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
Moving an arbitrary setting to a toolbar in Visual Studio <p>I want to be able to modify a certain setting of Visual Studio right from the toolbar. Specifically, the number of parallel builds (Tools | Options | Projects and Solutions | Build and Run | maximum number of parallel project builds). It can be either an edit box right on the toolbar or two buttons setting it to certain values.</p> <p>I use Visual Studio 2005.</p> <p>Any suggestions?</p>
<p>Write macros which will modify the two settings, then put macro on toolbar using "Cusomtize"</p>
multiple description coding <p>How can I encode an h264 video to be MDC (multiple description coding)</p>
<h1>You can't (but...)</h1> <p>It is not possible today to just check a box on existing software, stream video encoded as <a href="http://en.wikipedia.org/wiki/H264" rel="nofollow">h264</a> MDC, decode it and play it back in a browser. There is no h264 MDC profile. (Without more details of your intent, I am assuming general web-based streaming video.)</p> <p>Note that MDC is different from '<a href="http://en.wikipedia.org/wiki/Bitrate%5Fpeeling" rel="nofollow">bitrate peeling</a>', which can be found in Real's SureStream. That is basically packaging multiple, individual streams into a single media file for playback. The client and server negotiate which stream to send. This is fundamentally different from MDC.</p> <p>That said, it's early days for MDC, and it is still largely academic. There is no standard for it (yet), there is no production full source->encoder->decoder->target path implementation (yet, if ever). </p> <p>If you want to encode (and obviously stream and then decode) h264 MDC you'll have to jump into the world of academia and probably write it yourself. </p>
C# compiler and caching of local variables <p><strong>EDIT:</strong> Oops - as rightly pointed out, there'd be no way to know whether the constructor for the class in question is sensitive to when or how many times it is called, or whether the object's state is changed during the method, so it would have to be created from scratch each time. Ignore the Dictionary and just consider delegates created in-line during the course of a method :-)</p> <p><hr /></p> <p>Say I have the following method with Dictionary of Type to Action local variable.</p> <pre><code>void TakeAction(Type type) { // Random types chosen for example. var actions = new Dictionary&lt;Type, Action&gt;() { {typeof(StringBuilder), () =&gt; { // .. }}, {typeof(DateTime), () =&gt; { // .. }} }; actions[type].Invoke(); } </code></pre> <p>The Dictionary will always be the same when the method is called. Can the C# compiler notice this, only create it once and cache it somewhere for use in future calls to the method? Or will it simply be created from scratch each time? I know it could be a field of the containing class, but it seems neater to me for a thing like this to be contained in the method that uses it.</p>
<p>How should the C# compiler know that it's "the same" dictionary every time? You explicitly create a new dictionary every time. C# does not support static local variables, so you have to use a field. There's nothing wrong with that, even if no other method uses the field.</p> <p>It would be bad if the C# compiler did things like that. What if the constructor of the variable uses random input? :)</p>
What is the best way to add summary tags to a generated webservice proxy class? <p>Aloha</p> <p>I'm referencing an external webservice in my .NET 2.0 application. Adding a service reference generated a nice proxy class for me. I'd like to add <code>///&lt;summary&gt;</code> style documentation to this. If the service reference is updated, all my shiny comments are gone.</p> <p>Is there any solution to this?</p>
<p>You could create a wrapper class around the generated proxy class, and document the methods there. Then instead of using the generated proxy directly, you always use your wrapper class. E.g:</p> <pre><code>public class MyWebServiceWrapper { private MyWebService _service = null; public MyWebServiceWrapper() { _service = new MyWebService(); } ///&lt;summary&gt; /// doc goes here ///&lt;summary&gt; public int MethodOne() { return _service.MethodOne(); } } </code></pre> <p>This approach allows you to re-generate the proxy class whenever required.</p> <p>Of course this means, that you will have to (manually) update the wrapper class whenever the interface of the web service changes. On the other hand, the wrapper class also allows you to add some centralized error handling, etc.</p>
How do I replace the contents of an existing XML file in C#.NET? <p>When trying to replace the content of an XML file in C#.NET with a snippet like this:</p> <pre><code>string file = Path.GetTempFileName(); // pretend this is a real file string tmpFile = Path.GetTempFileName(); using (var writer = XmlWriter.Create(File.Create(tmpFile))) { writer.WriteStartElement("root"); for (int i = 0; i &lt; 100; i++) { writer.WriteElementString("test", null, "All work and no play makes Jack a dull boy"); } writer.WriteEndElement(); } File.Delete(file); File.Move(tmpFile, file); </code></pre> <p>... I get a System.IO.IOException claiming that the file is already opened by another process.</p>
<p>For some reason the XmlWriter class evidently does not dispose the underlying stream for the temporary file. Putting the stream in a "using" clause of its own makes sure the stream is closed correctly. Changing the code to</p> <pre><code>string file = Path.GetTempFileName(); // pretend this is a real file string tmpFile = Path.GetTempFileName(); using (var stream = File.Create(tmpFile)) using (var writer = XmlWriter.Create(stream)) { writer.WriteStartElement("root"); for (int i = 0; i &lt; 100; i++) { writer.WriteElementString("test", null, "All work and no play makes Jack a dull boy"); } writer.WriteEndElement(); } File.Delete(file); File.Move(tmpFile,file); </code></pre> <p>... makes the IOException disappear and it works as intended.</p>
How to detect IIS version using C#? <p>How to detect IIS version using C#?</p> <p>Update: I meant from a winapp (actually the scenario is developing a custom installer that wants to check the version of the installed IIS to call the appropriate api's)</p>
<p>Found the answer here: <a href="http://forums.iis.net/p/1162404/1923867.aspx#1923867">link text</a> The fileVersion method dosesn't work on Windows 2008, the inetserv exe is somewhere else I guess.</p> <pre><code>public Version GetIisVersion() { using (RegistryKey componentsKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\InetStp", false)) { if (componentsKey != null) { int majorVersion = (int)componentsKey.GetValue("MajorVersion", -1); int minorVersion = (int)componentsKey.GetValue("MinorVersion", -1); if (majorVersion != -1 &amp;&amp; minorVersion != -1) { return new Version(majorVersion, minorVersion); } } return new Version(0, 0); } } </code></pre> <p>I tested it, it works perfectly on Windows XP, 7 and 2008</p>
DataGridViewComboBoxColumn <p>I have two <code>DataGridViewComboBoxColumn</code> that I add at run time. I need the items of the first <code>DataGridViewComboBoxColumn</code> to stay the same in all the rows of the <code>GridView</code> but I want the items of the second <code>DataGridViewComboBoxColumn</code> to be different from row to another depending on the selected item of the first <code>DataGridViewComboBoxColumn</code>.</p> <p>If we say the first <code>DataGridViewComboBoxColumn</code> represents the locations and the second <code>DataGridViewComboBoxColumn</code> represents the sublocations. So, I want the second <code>DataGridViewComboBoxColumn</code> items to be the sublocations of the selected location from the first <code>DataGridViewComboBoxColumn</code>.</p> <p>Like this if <code>Canada</code> is selected</p> <pre class="lang-none prettyprint-override"><code>Country(comboBoxItems) | State/Province(ComboBox Items) USA Quebec CANADA(selected) Ontario ENGLAND Manitoba Alberta </code></pre> <p>Then if you select <code>USA</code></p> <pre class="lang-none prettyprint-override"><code>Country(comboBoxItems) | State/Province(ComboBox Items) USA (Selected) California CANADA New York ENGLAND Montana Ohio </code></pre>
<p>Recap of your problem:</p> <p>You have a collection of data and want to filter on it.</p> <p>This is a question with the <a href="http://stackoverflow.com/questions/13147049/how-to-apply-a-filter-on-linqtosql-results/13184592#13184592">same problem</a> that extends on this subject a bit more. (To be specific, filter a LINQtoSQL IQueriable object before it is fired to the database.)</p> <p>I found two solutions that might be interesting for our problem.</p> <p>I found a way to do it for data in DataSets (ADO.NET)</p> <pre><code>DataTable source { get; set; } String ValueMember { get; set; } String DisplayMember { get; set; } String FilterMember { get; set; } Object ADOSelect(Object criterium) { if ((source == null) || (criterium == null)) return null; return ( from r in source.AsEnumerable() where (r[FilterMember] == criterium) select new { Value = r[ValueMember], Display = r[DisplayMember] } ).ToList(); } </code></pre> <p>And a more generic solution.</p> <pre><code>class Record { public object Display { get; set; } public object Value { get; set; } } IEnumerable&lt;Object&gt; source { get; set; } String ValueMember { get; set; } String DisplayMember { get; set; } String FilterMember { get; set; } Object DataSelect(Object criterium) { List&lt;Record&gt; result = new List&lt;Record&gt;(); foreach (var record in source) Parse(sender, record, criterium, result); return result; } private void Parse(object record, Object criterium, List&lt;Record&gt; result) { MethodInfo DisplayGetter = null; MethodInfo ValueGetter = null; bool AddRecord = false; foreach (PropertyInfo property in record.GetType().GetProperties()) { if (property.Name == DisplayMember) DisplayGetter = property.GetGetMethod(); else if (property.Name == ValueMember) ValueGetter = property.GetGetMethod(); else if (property.Name == FilterMember) { MethodInfo ExternalGetter = property.GetGetMethod(); if (ExternalGetter == null) break; else { object external = ExternalGetter.Invoke(record, new object[] { }); AddRecord = external.Equals(criterium); if (!AddRecord) break; } } if (AddRecord &amp;&amp; (DisplayGetter != null) &amp;&amp; (ValueGetter != null)) break; } if (AddRecord &amp;&amp; (DisplayGetter != null) &amp;&amp; (ValueGetter != null)) { Record r = new Record(); r.Display = (DisplayGetter != null) ? DisplayGetter.Invoke(record, new object[] { }) : null; r.Value = (ValueGetter != null) ? ValueGetter.Invoke(record, new object[] { }) : null; result.Add(r); } } </code></pre>
Is it possible to define <configSections> in a dependent dll's application config <p>I have a custom .NET addin for an application and I am trying to create configSections for the addin's config file. The trouble is I am not able to read that section If load the configuration using the OpenMapperExeConfiguration/OpenExeConfiguration.</p> <p>Here is my config file(MyTest.dll.config)</p> <pre><code>&lt;configuration&gt; &lt;configSections&gt; &lt;section name="test" type="MyTest, Test.ConfigRead"/&gt; &lt;/configSections&gt; &lt;test&gt; ..Stuff here &lt;/test&gt; &lt;appSettings&gt; &lt;add key="uri" value="www.cnn.com"/&gt; &lt;/appSettings&gt; &lt;/configuration&gt; </code></pre> <p>Here is my code sample to access the test configSection</p> <pre><code>ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); fileMap.ExeConfigFilename = Assembly.GetExecutingAssembly().Location + "config"; Configuration applicationConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap,ConfigurationUserLevel.None); //Using OpenExeConfiguration doesnt help either. //Configuration applicationConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); //Accessing test section applicationConfig.GetSection("test"); //Accessing AppSettings works fine. AppSettingsSection appSettings = (AppSettingsSection)applicationConfig.GetSection("appSettings"); appSettings.Settings["uri"].Value; </code></pre> <p>As shown appsettings value can be read just fine. Is it possible to have configSections in any other config other than the main application's config file?</p>
<p>Configuration settings apply at application (app.config located in the application's root for .EXE, Web root for Web applications) and machine(machine.config located in [System Root]\Microsoft.NET\Framework[CLR Version]\CONFIG) level. </p> <p>The only other config file used is the policy config file which is used to create assembly versioning policies and is linked to the assembly by making of use of the AL tool. This is obviously what you do not want to do.</p> <p>Try to merge the add in's config sections into the current application's config section to create one app level config file or else put them in machine.config file.</p>
How to populate each DataGridViewComboBoxCell with different data? <p>i have two DataGridViewComboBoxColumn that i add at run time i need the items of the first DataGridViewComboBoxColumn to stay the same in all the rows of the gridview but i want the items of the second DataGridViewComboBoxColumn to be different from row to the other depending on the selected item of the first DataGridViewComboBoxColumn</p> <p>if we say the first DataGridViewComboBoxColumn represents the locations and the second DataGridViewComboBoxColumn to represent the sublocations. so i want the second DataGridViewComboBoxColumn items to be the sublocations of the selected location from the first DataGridViewComboBoxColumn </p>
<p>One option is to change the datasource at cell level for sublocations.</p> <p>Supposing the grid is named <code>grid</code> and the two grid columns were named <code>locationsColumn</code> respectively <code>subLocationsColumn</code>:</p> <pre><code>private void Form1_Load(object sender, EventArgs e) { locationsColumn.DataSource = new string[] { "Location A", "Location B" }; } </code></pre> <p>then, on grid's <code>CellEndEdit</code> event:</p> <pre><code>private void grid_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if(locationsColumn.Index == e.ColumnIndex) { DataGridViewComboBoxCell subLocationCell = (DataGridViewComboBoxCell)(grid.Rows[e.RowIndex].Cells["subLocationsColumn"]); string location = grid[e.ColumnIndex, e.RowIndex].Value as String; switch (location) { case "Location A": subLocationCell.DataSource = new string[] { "A sublocation 1", "A sublocation 2", "A sublocation 3" }; break; case "Location B": subLocationCell.DataSource = new string[] { "B sublocation 1", "B sublocation 2", "B sublocation 3" }; break; default: subLocationCell.DataSource = null; return; } } } </code></pre> <p>Some additional handling is necessary when the location changes for existing rows but this is the basic idea.</p>
Good way to make a repeating template for data in asp.net <p>I'm building a webpage on which I display the <em>n</em> newest newsposts on the front page, and this is the method that gets the posts and returns them to the .aspx-file. I use a asp:substitution-control to insert the string into the webpage.</p> <p>I think my way of doing this i kind of messy and ugly, and not very flexible if i want to do little changes on the template. Is there any way for me to achieve what i want while having the template itself in a separate .aspx or .ascx file? I've tried, but cant come up with a smart way of handing the data onto the template-file.</p> <p>Plus, when (if?) i've put the template in a separate file - how do i repeat it within another .aspx-file (within a contentplaceholder, if that matters. The layout is controlled by a master-page) with different values for each instance?</p> <pre><code>public static string getShortPosts(int postNumber) { DbConnection d = new DbConnection(); DataTable tbl = d.selectQuery("SELECT TOP (" + postNumber + ") news.id, news.title, news.newsContent, news.excerpt, news.date, news.userid, news.urlTitle, " + "news.isPublished, users.firstName, users.lastName FROM news INNER JOIN users ON news.userid = users.userid " + "ORDER BY id DESC;"); DataTableReader r = tbl.CreateDataReader(); StringBuilder s = new StringBuilder(""); while (r.Read()) { /* THIS */ s.Append( "&lt;div class=\"newsBox\"&gt;" + System.Environment.NewLine + "&lt;h2&gt;" + r["title"]+ "&lt;/h2&gt;" + System.Environment.NewLine + "&lt;p&gt;" + r["excerpt"] + "&lt;/p&gt;" + System.Environment.NewLine + "&lt;/div&gt;" +System.Environment.NewLine+System.Environment.NewLine ); } return s.ToString(); } </code></pre>
<p>If it were me, I would create a user control dedicated to creating a single entry in the listing. The user control would only need one parameter (the post number it's responsible for). The page itself need only maintain an array (or list or whatever structure you would prefer) of these user controls and add them to whatever panel they need to be displayed in dynamically.<br><br> The user control would contain a panel with class "newsBox", a label for the title, and another panel (or possibly just a regular HTML paragraph) for the content, so its output would be the same as what you're building in your example. The difference is it would be created using ASP and HTML objects instead of a string.<br><br> Also, if it were me, I wouldn't have a user control responsible for querying its own data from the database. A DAL would really be beneficial here, as you could have a function "GetNewsDetails(int postNumber)" that could cache news posts if they've been queried recently and could be reused by other user controls if necessary.</p>
Is there any defined atom syndication xml schema? <p>Is there any defined atom syndication xml schema?</p>
<p><a href="https://web.archive.org/web/20150307045002/http://www.kbcafe.com/rss/atom.xsd.xml" rel="nofollow">http://www.kbcafe.com/rss/atom.xsd.xml</a> (A Web Archive version since the original is no longer available)</p>
Having to set objectives for developers, even though objectives don't work <p>It is <a href="http://www.joelonsoftware.com/news/20020715.html">generally accepted</a> that <a href="http://www.inc.com/magazine/20081001/how-hard-could-it-be-sins-of-commissions.html">setting measurable objectives</a> for software developers <a href="http://stackoverflow.com/questions/324399/what-is-a-fair-productivity-measurement-technique-for-programmers#324441">doesn't work</a> , as too much focus on the objectives can lead to behaviour counter to the organisational goals (so-called "<a href="http://csdl.ics.hawaii.edu/techreports/96-16/96-16.html">measurement dysfunction</a>").</p> <p>However, in my company, we are required to set objectives for all staff, and are encouraged by Human Resources to make them <a href="http://en.wikipedia.org/wiki/SMART_(project_management)">SMART</a>. In the past, my fellow first-level managers (team leads) and I have tried a number of approaches:</p> <ol> <li>Set measurable objectives that are additional to the normal job, like "Do training on technology X", "Create documentation for piece of code Y that no-one understands" and so on. When it comes to the annual performance evaluation, rate developers not on the written objectives, but rather on my opinion of the unmeasurable value of their normal work, since that is actually what the company cares about.</li> <li>Set very specific objectives like "days' work done as recorded by the task management system", "number of bugs introduced", "number of production issued caused". This led to inflated estimates and incorrect classification of bugs, in order to achieve better "scores". Interestingly, even those developers scoring highly on this system didn't like it, as the intrinsic trust within the team was damaged and they didn't always feel they deserved their high position.</li> <li>Set vague objectives that are variants on "Do your normal job well". When it comes to the annual evaluation, their rating does reflect performance against the objectives, but the objectives themselves are not measurable or achievable, which is frowned upon.</li> </ol> <p>None of these is ideal. If you have been in a similar situation of having to create meaningful, measurable objectives for software developers in spite of the evidence against their effectiveness, <strong>what approach has worked best for you?</strong></p> <p><hr></p> <p>Related questions I found that don't quite address the same point:</p> <ul> <li><a href="http://stackoverflow.com/questions/51629/what-are-suitable-performance-indicators-for-programmers">What are some good performance goals for a software engineer?</a></li> <li><a href="http://stackoverflow.com/questions/210329/setting-performance-goals-for-developers">Setting Performance goals for Developers</a></li> <li><a href="http://stackoverflow.com/questions/51629/what-are-suitable-performance-indicators-for-programmers">What are suitable performance indicators for programmers?</a></li> <li><a href="http://stackoverflow.com/questions/324399/what-is-a-fair-productivity-measurement-technique-for-programmers#324441">What is a fair productivity measurement technique for programmers?</a></li> <li><a href="http://stackoverflow.com/questions/317836/i-need-some-career-goals-for-the-next-year">I need some career “Goals” for the next year</a></li> </ul> <p><hr></p> <p><strong>Update</strong> (18 November 2009): There are 10 upvotes for my question, and the highest-rated answers only have 4 upvotes (including one each from me). I think this tells us something: perhaps that Joel and the others are right, and that the combined wisdom of stackoverflow cannot come up with <em>any</em> compelling, measurable objectives for developers that could not be gamed without adversely affecting the true (unmeasurable) value of their work. Thanks for trying though!</p>
<blockquote> <p>what approach has worked best for you?</p> </blockquote> <p>Only one objective: <strong>pass a code inspection/peer review, with me as the reviewer, without me finding any bugs or having any other criticism, that has me asking you to redo something.</strong></p> <p>Notes:</p> <ul> <li>I wasn't measuring new hires' ability to finish quickly, and didn't encourage them to: I wanted people to learn how to finish well (because if it's not finished well, then it's not finished)</li> <li>People learned what I looked for in a code review: so it's a learning opportunity <strong>and</strong> a quality control measure, and not just a management objective</li> <li>My comments would have two categories: <ol> <li>This is a bug: you must fix this before you check in</li> <li>As a suggestion, I would have done such-and-such</li> </ol></li> <li>After a while, my reviews of a person's code would stop finding any "must fix" items (at which point I wouldn't need to review their work any more).</li> </ul>
How to submit multiple models on rails using flex? <p>I am trying to submit a create and update request to rails using flex with multiple models. For example, imagine that we have a blog post and multiple comments.</p> <p>The user comes and update the post and some comments, when he clicks on submit I want to send all updates.</p> <p>If I send something like:</p> <p>var params:Object = new Object();</p> <p>params["post[text]"] = myPostText;</p> <p>params["post[userid]"] = myPostUserId;</p> <p>Then I can send a array with the comments: var ar:Array = ["comment 1", "comment 2"]; params["post[comments]"] = ar;</p> <p>This work without problems (avoiding the problem with multiple attributes having the same name).</p> <p>But my problem is that for the comments I need to submit multiple attributes, lets suppose that for each comment I need to submit a rank, I tried to do (pseudo code):</p> <p>var ar:Array = new Array();</p> <p>for each comment c {</p> <p>ar.push({"text":c.text, "rank":c.rank});</p> <p>}</p> <p>params["post[comments]"] = ar;</p> <p>This does not work, because for each comment the hash parameters on rails side will contain the string "[object Object]".</p> <p>Does anyone know a way to submit multiple models on flex to rails?</p>
<p>Actually I have it. Forget using those parameters objects and use only XML, its easier than those parameters objects and you can have a single way to serialize your flex objects.</p> <p>Using XML you just need to build it with the objects nested (like rails does for you).</p> <p>The only issue is that you cannot use too much RESt with flex because flex does not support all HTTP operations, so for doing an update I did a workaround and created a flex_update method on application_controller that is called using POST during an update, this method simple calls the default update method and everything works fine.</p>
Dealing with variable category hierarchies <p>The issue I have is as follows: My company's supplier gives us an Access database (which I import into SQL Server) containing their product information (the alternative is to use XML), and I'm trying to massage this into a more usable format for use in an e-commerce website.</p> <p>The problem I run into, and maybe I'm just not thinking clearly, is that their category information can be anywhere from 3-6 subcategories deep; there are always at least 2 categories (a top-level Parent category and a more specific subcategory) but there can be up to 6 depending on the item.</p> <p>Their data is provided to me in the following table structure:</p> <pre><code>CREATE TABLE [dbo].[ECDB2_HIERARCHY]( [SEQ_ID] [int] NOT NULL, [PFX_NUM] [nvarchar](3) NOT NULL, [STK_NUM] [nvarchar](12) NOT NULL, [ECDB2_LVL_1] [nvarchar](max) NULL, [ECDB2_LVL_1_ID] [int] NULL, [ECDB2_LVL_2] [nvarchar](max) NULL, [ECDB2_LVL_2_ID] [int] NULL, [ECDB2_LVL_3] [nvarchar](max) NULL, [ECDB2_LVL_3_ID] [int] NULL, [ECDB2_LVL_4] [nvarchar](max) NULL, [ECDB2_LVL_4_ID] [int] NULL, [ECDB2_LVL_5] [nvarchar](max) NULL, [ECDB2_LVL_5_ID] [int] NULL, [ECDB2_LVL_6] [nvarchar](max) NULL, [ECDB2_LVL_6_ID] [int] NULL </code></pre> <p>For the most part I can ignore SEQ_ID as it's not used; PFX_NUM and STK_NUM get concatenated together to form the product's SKU, but that's not the issue. I need to be able to dynamically traverse categories from the site. For instance, given the following row:</p> <p><code>SEQ_ID: 364867 (ignored)</code></p> <p><code>PFX_NUM: AMP</code></p> <p><code>STK_NUM: 73121</code></p> <p><code>ECDB2_LVL_1: Office Supplies</code></p> <p><code>ECDB2_LVL_1_ID 11</code></p> <p><code>ECDB2_LVL_2: Envelopes, Mailers &amp; Shipping Supplies</code></p> <p><code>ECBD2_LVL_2_ID: 26</code></p> <p><code>ECDB2_LVL_3: Envelopes</code></p> <p><code>ECDB2_LVL_3_ID: 195</code></p> <p><code>ECDB2_LVL_4: Business Letter Envelopes</code></p> <p><code>ECDB2_LVL_4_ID: 795</code></p> <p><code>ECDB2_LVL_5: (empty)</code></p> <p><code>ECDB2_LVL_5_ID: 0</code></p> <p><code>ECDB2_LVL_6: (empty)</code></p> <p><code>ECDB2_LVL_6_ID: 0</code></p> <p>The user should be able to navigate through the levels, but what throws me off is the sample website provided with the data (see below) displays all items under a subcategory at random intervals... it looks like it's at the 3rd level (ecdb2_lvl_3) but for items that don't have the 3rd level it displays starting at the 2nd. As you can see from the schema, they have it all together in one table that lists the products AND all of the categories they belong to, instead of something like a self-referencing categories table and then a joining products table.</p> <p>The problem is that some items only have 2 levels, some like this one have up to 4, and there are a few that have all 6 - the vendor's sample website, available at <a href="http://www.biggestbook.com" rel="nofollow">http://www.biggestbook.com</a> does a good job of what I want, but I don't have access to their code so I'm left scratching my head as to how exactly they are pulling back categories and traversing them. I'm assuming they have some kind of global flag to indicate what level you're currently at (e.g. 1 for Office Supplies, 2 for Envelopes et all, and so on) so they can keep track of what your current depth is, and then check each sub-level to see if there are more subcategories to show, but I'm drawing a blank when I think of how to handle this efficiently. Their naming scheme leaves a lot to be desired, as well, but that's something I can tackle later if need be.</p> <p>Anyone have advice in how to tackle this issue? I'm planning the store in C#/ASP.NET (possibly MVC, possibly not) so C# examples would be most useful, but I can follow most languages easy enough to figure it out.</p>
<p>If you don't mind using recursive functions to traverse a self-referencing category table, definitely redesign the database to go that route. One would think a recursive function in SQL might be performance suicide, but with proper indexes set up it can complete extremely fast.</p> <p>As for the data set your are working with, you can see from the sample web site that they are storing current category in the URL query:</p> <p>Office Supplies > Envelopes, Mailers &amp; Shipping Supplies > Envelopes<br /> ?N=4294858589&amp;...</p> <p>Office Supplies > Envelopes, Mailers &amp; Shipping Supplies > Envelopes > Booklet &amp; Catalog Envelopes<br /> ?N=4294858588&amp;...</p> <p>Where N is the current category. I would think that their database has a lookup table to see what level N belongs to. Alternatively, they could be just doing a big WHERE/ORDER BY clause like:</p> <pre><code>WHERE (ECDB2_LVL_1_ID == @N) OR (ECDB2_LVL_2_ID == @N) OR (ECDB2_LVL_3_ID == @N) ... ORDER BY ECDB2_LVL_1_ID, ECDB2_LVL_2_ID, ECDB2_LVL_3_ID... </code></pre> <p>If N is a 2nd level category, products that don't have a 3rd level category will appear first since null comes to the top when sorted.</p> <p>On a side note, they keep track of what category you traversed to reach a product in the session. Follow a category down to a product till the URL says something like ?R=12345. The breadcrumbs will show the category used to find that product. Clear your cookies and refresh the page, the breadcrumbs will turn into Biggest Book > Product Detail. That isn't terribly useful for people who come upon the page from a search engine since they then cannot select a category easily to see what similar products are available.</p>
best way to show several images on a winform in c# <p>best way to show several images on a winform in c#? Datagrid? </p>
<p>Several <code>PictureBox</code>es :-)</p>
sql server bcp xml data <p>Hi I have a table which has a column which is of type xml. I have to extract data from this table and load the data into another environment. i am using bcp to extract and laod the target table but there are some special characters that is causing some issues when i bcp them into the target table. are there any workarounds</p> <p>thanks Ben</p>
<p>A custom CLR-SP provided me with the best solution. Now I can write XML-typed data directly to a file from TSQL, provided the SQL service account has permission to the file. This allows the simple syntax:</p> <pre><code>exec dbo.clr_xml2file @xml, @path, @bool_overwrite </code></pre> <p>The SP:</p> <pre><code>CREATE PROCEDURE [dbo].[clr_xml2file] @xml [xml], @file [nvarchar](max), @overwrite [bit] WITH EXECUTE AS CALLER AS EXTERNAL NAME [CLR_FileIO].[FreddyB.FileIO].[Xml2File] </code></pre> <p>The C# for the CLR DLL:</p> <pre><code>using System; using System.Data.SqlClient; using System.Data.SqlTypes; using System.IO; using System.Security.Principal; using System.Text; using System.Xml; using System.Xml.XPath; using Microsoft.SqlServer.Server; namespace FreddyB { public class FileIO { public static void Xml2File( SqlXml xml, SqlString sFile, SqlBoolean bOverwrite ) { SqlPipe sqlpipe = SqlContext.Pipe; try { if (xml == null || xml.IsNull || xml.Value.Length == 0) { sqlpipe.Send("Cannot write empty content to file : \n\t" +sFile.Value); return; } if (File.Exists(sFile.Value) &amp; bOverwrite.IsFalse) { sqlpipe.Send("File already exists : \n\t"+sFile.Value); return; } int iFileSize = 0; FileStream fs = null; try { byte[] ba = Encoding.UTF8.GetBytes(xml.Value); iFileSize = ba.Length; fs = new FileStream(sFile.Value, FileMode.Create, FileAccess.Write); fs.Write(ba, 0, ba.Length); sqlpipe.Send("Wrote " +String.Format("{0:0,0.0}",iFileSize/1024) +" KB to : \n\t" +sFile.Value); } catch (Exception ex) { sqlpipe.Send("Error as '" +WindowsIdentity.GetCurrent().Name +"' during file write : \n\t" +ex.Message); sqlpipe.Send("Stack trace : \n"+ex.StackTrace); } finally { if (fs != null) { fs.Close(); } } } catch (Exception ex) { sqlpipe.Send("Error writing to file : \n\t" +ex.Message); } } } } </code></pre>
Matching exact string with JavaScript <p>How can I test if a RegEx matches a string <em>exactly</em>?</p> <pre><code>var r = /a/; r.test("a"); // returns true r.test("ba"); // returns true testExact(r, "ba"); // should return false testExact(r, "a"); // should return true </code></pre>
<p>either</p> <pre><code>var r = /^a$/ </code></pre> <p>or</p> <pre><code>function matchExact(r, str) { var match = str.match(r); return match != null &amp;&amp; str == match[0]; } </code></pre>
VB6 ListBox Click and DblClick <p>I have a need to run different code when a user clicks or double-clicks an item in a VB6 ListBox control. When I click on the control, the Click event handler executes. However, I am finding that when I double-click on the control, both the Click and DblClick event handlers execute.</p> <p>Anyone have a good solution for getting just the DblClick event handler code to run without the Click code being executed first?</p> <p>Thanks in advance for any suggestions.</p>
<p>A slight hack, but you could use a Timer control and a boolean variable:</p> <ul> <li>Start the timer on the Click event, set the boolean variable to false</li> <li>Set the boolean variable to true on the DoubleClick event</li> <li>When the timer Tick event fires, check the boolean variable to see if the user did a Click or DoubleClick</li> </ul> <p>I'd recommend setting the timer interval to the Windows double click time setting, plus a bit (There should be a Windows API call that will give you this value).</p>
Can I change the input behaviour of a DateTimePicker control? <p>The default input behaviour of the DateTimePicker when entering a date is like this:</p> <p>YYYY(Right Arrow)MM(Right Arrow)DD</p> <p>The user want to enter the date like this:</p> <p>YYYYMMDD</p> <p>Is there any simple way of modifying the input behaviour of the DateTimePicker so that is does behave like the user want it to?</p> <p>TIA</p>
<p>I don't know how you use the DateTimePicker but what about using a simple editbox? (and validate date when a date is entered)</p> <p>DateTimePicker is mostly used to choose a date without entering any number.</p>
PHP If Date Is >13 Days Ago <p>I'm pulling a row from a database and there is a date field (y-m-d). I need to create an if statement so that I can do something IF that date is longer then 13 days ago. I've already found out how to display all results which are longer then 13 days ago if it is any help.</p> <pre><code>SELECT * FROM links WHERE (TO_DAYS(NOW()) - TO_DAYS(date))&gt;13 </code></pre> <p>Any help would be greatly appreciated.</p>
<p>In php you can use:</p> <pre><code>$date = '2008-11-05'; if (strtotime("now") &gt; strtotime("+13 days", strtotime($date))) { //Do something } </code></pre>
Rather difficult mySQL problem <p>A friend of mine is having an problem with an big mySQL database and quite a big number of repeating columns over multiple tables.</p> <p>To describe the problem better, the database serves multiple services like FTP, Postfix, webmail, pretty much all the common services you would be running on a general use Linux server and all of these services are using this database. The problem is that most of the services don't know how to read from multiple tables, so if you use multiple tables entries like username, pasword, switches must be repeated in those service specific tables. hing Ex. UserProfile Table conains all user relevant data. (Username, Password) ACL Table Contains Access related data (AccountEnabled, FTPEnabled, AccessType) FTP Table contains FTP related data (Quota, directories etc) I think you get the picture... So if i need the ftp service I must read the UserProfile Table, The ACL Table and the FTP Table, but since I can't read from multiple tables, I only read the ftp table where I've duplicate the fields I need such as UserName, Password and FTPEnabled. </p> <p>Now they are trying to create an application to administer all these services, you can imagine that this has been done by hand till now, and the server is serving more than a few hundred users. So, now they are trying to create a administrative interface that manages all those tables. The problem is that 30% of the that must be written is duplicate data. Ex. Username and Password must be written 6 times in different Tables.</p> <p>Is there a possibility to create a Table with "Symlink" or something similar? So that you have all the data in one Temp Table that is accessible to all services and dynamically updated. Or is there any other "smart" way, you can think of, to make all of this easier?</p> <p>Thank you in advance for your time, titel</p>
<p>What you are looking for is called a <a href="http://dev.mysql.com/doc/refman/5.0/en/create-view.html" rel="nofollow">VIEW</a>.</p> <p>That way you can have a central table with all the information an one view per app with the right structure.</p>
How can I modify multicast TCP/IP packets' TTL? <p>I'm supporting a 3rd party app that sends multicast packets with a TTL of 1. We cannot modify the app, but need a higher TTL to route the packets to another customer's network. Is there a network appliance or windows (server 2003) app that will let me modify this? </p> <p>Is there a better approach for connecting the sender and receiver in this scenario?</p>
<p>It is doable on the sending host (e.g. using ipfw and divert on FreeBSD; I don't know the equivalent for MS-Windows) but may be more effort than it is worth.</p> <p>An easy option might be to use a VPN (virtual private network) to make it appear to the application layer that the sending and receiving hosts are on the same (virtual) network.</p>
What's the recommended workaround if numeric_limits<double>::has_infinity is false? <p>I need to check a double value for infinity in a C++ app on Linux. On most platforms this works by comparing with <code>std::numeric_limits&lt;double&gt;::infinity()</code>. However, on some old platforms (RedHat 9 for example, with gcc 3.2.2) this is not available, and <code>std::numeric_limits&lt;double&gt;::has_infinity</code> is false there.</p> <p>What workaround would you recommend for those platforms?</p>
<p>If you're using IEEE 754 arithmetic, as you almost certainly are, infinities are well defined values and have defined outcomes for all arithmetic operations. In particular,</p> <pre><code>infinity - infinity = NaN </code></pre> <p>Positive and negative infinity and <code>NaN</code> values are the only values for which this is true. NaNs are special "not-a-number" values used to indicate domain errors of functions, e.g. <code>sqrt(-1)</code>. Also:</p> <pre><code>NaN != NaN </code></pre> <p><code>NaN</code>s are the only values for which this is true.</p> <p>Therefore:</p> <pre><code>bool is_infinite(double x) { double y = x - x; return x == x &amp;&amp; y != y; } </code></pre> <p>will return true if and only if <code>x</code> is either positive or negative infinity. Add a test for <code>x &gt; 0</code> if you only want to check for positive infinity.</p>
How can I find all tables cells which only contain a non breaking space with jQuery? <p>I need to only find the cells in the table which contain <code>&amp;nbsp;</code> using jQuery. </p> <pre><code> &lt;table&gt; &lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;Something&lt;/td&gt; &lt;td&gt;something else&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Any ideas?</p>
<p>Quick guess, maybe a better way</p> <p>updated - thanks to Tomalak</p> <pre><code>var x = $('table tr td').filter( function(){ return $(this).text() == String.fromCharCode(160); }) </code></pre>
PHP Mail Encodes Subject Line <p>When I try to send a HTML encoded email from PHP, if the subject line contains special chars like <code>"Here's the information you requested"</code>, PHP encodes it to read <code>"Here&amp;#039;s the information you requested."</code></p> <p>How do I fix this?</p> <hr> <p>Here's what the code looks like using PHP mail():</p> <pre><code>$headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'To: ' . $mod_params['name'] . '&lt;' . $mod_params['email'] . '&gt;' . "\r\n"; $headers .= 'From: &lt;do_not_reply@a4isp.com&gt;' . "\r\n"; $email_to = $mod_params['email']; $email_sub = "Here's the Information You Requested"; $body = html_entity_decode("&lt;html&gt;&lt;body&gt;" . $email_html_body . "&lt;/body&gt;&lt;/html&gt;"); mail($email_to,$email_sub,$body,$headers); </code></pre> <p>It gives the same error as running it through the SugarPHPMailer class.</p>
<p>Try this:</p> <pre><code> $newsubject='=?UTF-8?B?'.base64_encode($subject).'?='; </code></pre> <p>This way you don't rely on PHP or the MTA's encoding, you do the job, and the mail client should understand it. No special characters will be present in your new subject, so no problems should arise while delivering the email.</p>
decrypting pdf protected by aes-256bit using the right password <p>Is there any way to decrypting a pdf protected by an aes-256 bit key?</p> <p>I have the correct password and I need a command-line tool (or library - perhaps in python :P ) for decrypting the file and then doing some operation over it.</p> <p>The best thing could be if the file could be saved decrypted, then I elaborate it and then I can remove it...</p> <p>Does anyone know something about it?</p>
<pre><code>import pyPdf pdf = pyPdf.PdfFileReader(open("file.pdf")) pdf.decrypt("password") </code></pre> <p>You can then do whatever you want with the contents. This will work with either the user or owner passwords.</p>
PHP best design practices <p>Ok, have a bunch of questions that I have been thinking about the past few days. Currently I have a site that is just a bunch of PHP files with MySQL statements mixed in with PHP, HTML and CSS, basically a huge mess. I have been tasked with cleaning up the site and have made for myself, the following requirements:</p> <ul> <li>The site needs to be efficient and well laid out (the source code), I would like to be able to write as little code as possible.</li> <li>There has to be good separation between structure, presentation and logic.</li> <li>For whatever reason, I can't use a framework and need to keep the code maintainable and "simple" as there will be future developers working with it.</li> <li>There needs to be an admin section for at least a few pages.</li> </ul> <p>Saying that, this is what I know about the site as it is now:</p> <ul> <li>Consists of 10-12 pages, a few are completely static, most are dynamically driven via a database and there is a huge form for users to fill out (20-30 fields) that need to be validated and checked.</li> <li>The hierarchy of the site is basically 5-6 main pages and then sub-pages within those.</li> </ul> <p>So, knowing those things I wanted to know if anyone had any tips/suggestions as to how to go about doing this with the least amount of headaches. </p> <ul> <li>Would an OO approach be best in this situation?</li> <li>Since there are many static pages and the dynamic pages just need the content filled in would it be best to use some kind of basic template?</li> </ul> <p><strong>EDIT:</strong> Thanks for the answers, when I said no frameworks I basically meant anything that would require new syntax other than PHP, as whoever gets hired to work on this site after me will probably only know PHP.</p>
<p>Here's an article about how to organize your PHP project, from Rasmus Lerdorf, the architect who created the language:</p> <p><a href="http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html" rel="nofollow">http://toys.lerdorf.com/archives/38-The-no-framework-PHP-MVC-framework.html</a></p> <p>Despite the popularity of OO frameworks for PHP, Rasmus advocates a less OO approach. He knows more than anyone about PHP intended usage, and how to take advantage of its architecture for high-performance websites.</p> <p><strong>edit:</strong> In response to the comment by @theman, I'll concede the article isn't a fine work of writing, but I think the content is important. Using PHP as it was intended to be used is better than struggling against its weaknesses to make it fit an OO mold.</p>
Posting contents of a file using HttpClient? <p>I want to send the contents of a file as part of a http request using Apache HttpClient and I could not figure out how to pass on the file contents in the request body.</p>
<p>You didn't specify the format....</p> <p>Most likely, you want to send a POST request, the contents will be <em>multipart/form-data</em> MIME type. This emulates what a browser sends from an &lt;INPUT type="file" ...&gt; form element. This requires some pretty sophisticated parsing on the server side to extract the multiple parts from the body and correctly extract the file data from the other fields (if any). Fortunately, <a href="http://commons.apache.org/fileupload/" rel="nofollow">commons-fileupload</a> does this perfectly. The first answer regarding <a href="http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/methods/multipart/FilePart.html" rel="nofollow">FilePart</a> is exactly right.</p> <p>Alternatively, you could simply post the raw contents of a file as the body of the request by using an <a href="http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/methods/InputStreamRequestEntity.html" rel="nofollow">InputStreamRequestEntity</a>. This may be much simpler if you're writing your own server side to receive the data. The server side is as simple as streaming the request's InputStream to disk. I use this technique for uploads with Google Gears.</p>
How do I check the exit code in Test::More? <p>According to Test::More <a href="http://search.cpan.org/~mschwern/Test-Simple-0.86/lib/Test/More.pm#EXIT_CODES" rel="nofollow">documentation</a>, it will exit with certain exit codes depending on the out come of your tests. My question is, how do I check these exit codes?</p> <p>ps. I am trying to build a harness myself. Is there a simple harness I can use?</p> <p>ps2. Test::Harness did the trick for me. In particular execute_tests function. This function returns all the statistics I want. Thank you everyone who gave useful links.</p>
<p>Any decent harness program (such as <a href="http://search.cpan.org/~andya/Test-Harness-3.14/bin/prove" rel="nofollow">prove</a>) will do that for you, there is absolutely no reason for you to do that yourself.</p>
Debug multiple copies of a program from one VS instance <p>I have a pre-alpha GUI program that I'm <a href="http://en.wikipedia.org/wiki/Eat_one%27s_own_dog_food">dogfooding</a> and want to run under the debugger (for when things go wrong <code>;)</code> but I don't want to have to launch a new copy of VS for each instance of the App. Can this be done?</p> <p>I don't expect to actually be debugging more than one instance at a time, but still want the debugger in the look for all of them. Also I'm starting the app a few dozen time a day so it would have to be easy to do.</p>
<p>You can start an instance of the same, or different projects multiple times in one instance of visual studio. Here is how: Right click on any project in Solution Explorer, go to <strong>Debug</strong> context menu item, and click <strong>Start New Instance</strong>.</p> <p>You can view and manipulate all your running processes from the Processes window. (Debug -> Windows -> Processes)</p>
Is there a log4j equivalent for VBScript? <p>I need to instrument a series of .wsf and .vbs files with debug statements; before I go off and roll my own, does something like log4j exist for WSF/VBScript?</p>
<p>Not comparable to log4j, but something you could use to begin with:</p> <p><a href="http://www.naterice.com/blog/template_permalink.asp?id=43" rel="nofollow"><strong>Reusable Logging in VBScript - LogToFile.vbs</strong></a></p> <blockquote> <p>Anywhere you'd like to log a message within the script you'd simply add LogToFile "Your Message" to log the relevant information.</p> <p>With this script you can log the date and time you began the script, the date and time of any particular events, and generate unique filenames if you want to schedule script run times. It's also simple to turn off logging without editing the entire logging section out.</p> </blockquote> <p>If you want to write to the event log, you could do it using a <strong>WshShell object</strong>. It provides the LogEvent method for logging events to the Application event log. </p> <p>The LogEvent method enables you to write to the event log from within your scripts. LogEvent has two required parameters. The first parameter of the LogEvent method is an integer that specifies the type of event you would like your script to log.</p> <pre><code>Set objShell = WScript.CreateObject("Wscript.Shell") objShell.LogEvent 0,"Test Success Event" objShell.LogEvent 1,"Test Error Event" objShell.LogEvent 2,"Test Warning Event" objShell.LogEvent 4, "Test Information Event" objShell.LogEvent 8, "Test Success Audit Event" objShell.LogEvent 16, "Test Failure Audit Event" </code></pre> <p>See <a href="http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_xnbt.mspx?mfr=true" rel="nofollow">here on the Microsoft TechNet</a> site.</p>
Filtering models with ReferenceProperties <p>I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.</p> <p>eg.</p> <pre><code>class Group(db.Model): name = db.StringProperty(required=True) creator = db.ReferenceProperty(User) class GroupMember(db.Model): group = db.ReferenceProperty(Group) user = db.ReferenceProperty(User) </code></pre> <p>And I have tried writing something like this:</p> <pre><code>members = models.GroupMember.all().filter('group.name =', group_name) </code></pre> <p>and various other things that don't work. Hopefully someone can give me a prod in the right direction...</p>
<p>If your groups are uniquely named, then your "group.name" is a unique identifier of a Group entity.</p> <p>That means you can write:</p> <pre><code> members = models.GroupMember.all().filter( "group =",model.Group.gql("WHERE name=:1", group_name).get() ) </code></pre> <p>though you only need to do that if you don't already have the group entity lying around in the stack somewhere. </p> <p>Google's essay on many-to-many with appengine is <a href="http://code.google.com/appengine/articles/modeling.html">here</a>.</p>
How to Get a List of Assemblies in C#? <p>I need to get a list of assemblies in a directory. Is there another way than this?</p> <pre><code>System.IO.Directory.GetFiles(directory, "*.dll") </code></pre>
<p>Managed assemblies can also be EXEs. And your code just gets files with the extension "dll". Ntive DLLs, which are not assemblies, would also be returned.</p> <p>In the few occasions I needed to do this, I simply got a list of all files (similar to what you've done), and then used Assemby.LoadFrom to attempt to load each, trappig the exception in the event its native. The typical exception is a ReflectionTypeLoadException, though you also may get this if a reference can't be resolved.</p>
Represent a query string in JSON <p>I have this Javascript data:</p> <pre><code>[{id:123,type:"test"},{id:154,type:"another"}] </code></pre> <p>How would you transform that into something so that I can pass it as a HTTP post request?</p> <pre><code>menu[0][id] = 123 menu[0][type] = test menu[1][id] = 154 menu[1][type] = another </code></pre> <p>I dont want to pass the actual JSON data, I want to clean it up and pass it as formatted HTTP paramaters.</p> <p><strong>EDIT</strong></p> <p>Was able to parse the object on the client side using something like this, maybe you guys would suggest something better before I sign this as "answered"?</p> <pre><code>this.serialize = function(elem) { var childs = elem.childElements(); var str = ""; for(var i=0, item; i&lt;childs.length; i++) { item = childs[i]; str += ((i)?"&amp;":"")+"menu[" + i +"][id]=" + item.id.replace(/item_/,""); str += "&amp;menu[" + i +"][type]=" + item.className; str += "&amp;menu[" + i +"][section]=" + elem.id; str += "&amp;menu[" + i +"][position]=" + i; } return str; } </code></pre>
<pre><code>var data = [{id:123,type:"test"},{id:154,type:"another"}]; var params = new Array(); for(var x = 0; x &lt; data.length; x++) { params.push("id=[" + x + "]=" + escape(data[x].id)); params.push("type=[" + x + "]=" + escape(data[x].type)); } alert(params.join("&amp;")); // output: id=[0]=123&amp;type=[0]=test&amp;id=[1]=154&amp;type=[1]=another </code></pre> <p>Is that what you want?</p>
Good asp.net documentation tool? <p>Anyone know of a good asp.net website documentation tool? There are a ton of them out there for classes, assembly's, dependencies, etc... but seemingly nothing decent for interface and control documentation</p>
<p>Take a look at <a href="http://www.innovasys.com/products/dx2008/overview.aspx" rel="nofollow">DocumentX</a>. It may offer what you're looking for.</p>
ASP .NET and IIS <p>Most of the developers i work with test their web apps by running them from visual studio, and use the built in web server of VS to display the pages. My question is when these apps are deployed to a IIS server would they behave any differently?</p>
<p>One area where your app may behave differently is in the area of security. Because the built in web server is effectively running under your identity (i.e. you could be running as an admin user), when you deploy into a production environment life for your app may be very different.</p> <p>See this article by <a href="http://www.leastprivilege.com/default.aspx" rel="nofollow">Dominick Baier</a>:</p> <p><a href="http://www.leastprivilege.com/CassiniConsideredHarmful.aspx" rel="nofollow">http://www.leastprivilege.com/CassiniConsideredHarmful.aspx</a></p>
How do I append a newline character for all lines except the last one? <p>I'm iterating through a HashMap (see <a href="http://stackoverflow.com/questions/448122/how-do-i-use-a-foreach-loop-in-java-to-loop-through-the-values-in-a-hashmap">my earlier question</a> for more detail) and building a string consisting of the data contained in the Map. For each item, I will have a new line, but for the very last item, I don't want the new line. How can I achieve this? I was thinking I could so some kind of check to see if the entry is the last one or not, but I'm not sure how to actually do that.</p> <p>Thanks!</p>
<p>Change your thought process from "append a line break all but the last time" to "prepend a line break all but the first time":</p> <pre><code>boolean first = true; StringBuilder builder = new StringBuilder(); for (Map.Entry&lt;MyClass.Key,String&gt; entry : data.entrySet()) { if (first) { first = false; } else { builder.append("\n"); // Or whatever break you want } builder.append(entry.key()) .append(": ") .append(entry.value()); } </code></pre>
Are there any good examples on how to use Haskell monad functions? <p>Haskell monad functions are not easy to understand, where can I find usage examples?</p>
<p>You mean the functions with names like <code>fooM</code> and <code>fooM_</code>? You can understand them better possibly by reading their source code, or when you write a <code>do</code>-expression, you could think if that can be expressed with a relevant <code>fooM</code>-function.</p> <p>You could also take a look at <a href="http://stackoverflow.com/questions/412929/creative-uses-of-monads#412992">this question</a>.</p>
Valid binding root for VSS? <p>I'm trying to fix up my Visual Source Safe bindings for a project I have and when I select the location I believe a project should be bound to, i get a dialog that says:</p> <p><code> The folder you chose is not a valid binding root for the projects you have selected. You attempted to retarget a solution to a source control folder that is not within the solution's root. In the change source control dialog box, specify the root for the solution. Select the folder 5 levels higher in the tree to chagne the source control bindings correctly. </code></p> <p>What on earth does that mean? There are no folders 5 levels higher.</p>
<p>I think I figured this one out. I opened my vcproj file and searched for ..\..\.. and found a couple of references to files 5 directories "higher". I removed those references (the files weren't really there) and reopened the project. After doing this, I could rebind the project to SourceSafe.</p>
Generic Exception over webservices <p>I am integrating with MS Dynamics GP WebServices from C# and I am not sure how to handle exception.</p> <p>If I do a GetCustomer with a inexistant ID, the web services return me a "generic" SoapException and the message is "Business object not found." So the only way I see to be sure it's an invalid ID and not any other error, is by parsing the error message, I find this solution extremely fragile. My GP version is English, on customer site it's gonna be french and I have no idea in which language web services message gonna be. I am thinking about catching it, parsing the message and throw a more meaningful error type. </p> <p>Do you see a better option ?</p>
<p>Unfortunately both the eConnect API and the GP Web Services both return generic errors, just be glad you don't have to parse the eConnect ones.</p> <p>Good things is, the errors are generally static, so you can build parsers for them. Creating custom exceptions is definitely a good way to do it with this type of web service.</p>
Wordpress Category ID vs Eval Issue <p>Ok this is a little complex. I am creating a plugin, and want to find the category ID from the Post page.</p> <p>That's the easy part.</p> <p>What makes it complex is I am doing it within an ob_start (started in a 'template_redirect' action) as I want to edit the full page before it is returned to the browser. Again that is easy enough from the ob_start function.</p> <p>With the ID returned I want to evaluate some php stored in a sql field. I am trying to do this from within the ob_start function</p> <pre><code>$tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue); </code></pre> <p>This calls this</p> <pre><code>function tui_cifp_evaluate_html($string) { return preg_replace_callback("/(&lt;\?php|&lt;\?|&lt; \?php)(.*?)\?&gt;/si",'EvalBuffer', $string); } </code></pre> <p>Which in turn calls</p> <pre><code>function EvalBuffer($string) { ob_start(); eval("$string[2];"); $ret = ob_get_contents(); ob_end_clean(); return $ret; } </code></pre> <p>And the php I am trying to evaluate is.</p> <pre><code>&lt;?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?&gt; </code></pre> <p>This all works outside the ob_start routine, but here even simple php doesn't work. From within the ob_start routine the plugin breaks and a blank page returns.</p> <p>So I thought I could evaluate the php before the start of the ob_start and pass the result through a global variable. That works, but at the point this starts using the following, the category ID is not available.</p> <pre><code>if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin') === false ) { global $holdvalue; $tui_cifp_insertvalue = get_option('tui_cifp_insertvalue'); $categories = get_the_category(); $categoryID = $categories[0]-&gt;cat_ID; $tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue); $holdvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue); add_action('template_redirect','tui_cifp_ob_start'); // } </code></pre> <p>The ob_start function</p> <pre><code>function tui_cifp_ob_start() { ob_start('tui_cifp_templatefilter'); } </code></pre> <p>Ok I am stumped ... any ideas?</p> <p>I either need to find a hook that executes at the right time so that I have access to the category ID, or I need to work out how to evaluate the php during the ob_start.</p> <p>Oh ... I guess I should say. What I want to do is replace a tag on a wordpress page with some other information saved in a string, but need to be able to do this once the full page if drawn.</p> <p>Thanks Stephen</p> <p>PS I have asked this on the wordpress forums without a response. Sorry for the cross posting but I am a little desperate. </p>
<p>Im not partial to eval, but this seems to work, with or without the output buffering at the end ...</p> <pre><code>function tui_findPostThumbIMG() { echo "hey hey\n"; } ob_start(); $categoryID = 10; $tui_cifp_insertvalue = "&lt;?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?&gt;"; $tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue); $tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue); echo $tui_cifp_insertvalue; ob_end_flush(); </code></pre>
How to Handle Cancelled Recurring Payments <p>I'm using Paypal to handle automated recurring payments for my website. Users pay to subscribe to my website so they can get periodic newsletters.</p> <p>So let's say a customer cancels their membership a few months later. They do this by logging into Paypal and cancels future automated payments. How should I update my website to reflect this cancellation?</p> <p>The first solution I'm thinking of is to schedule a cronjob that executes a script every midnight to update my database with information from Paypal.</p> <p>The second solution is on newsletter mailout day, I execute a script to update my database with information from Paypal. The website will also execute the script every time a user "logs in" to my website.</p> <p>Are there better ways to do this?</p>
<p>If I understand correctly, Paypal's servers will update yours automatically when the status of a subscription changes, if you have this configured. This is called IPN (Instant Payment Notification) and does indeed include cancellation notification. Here's the <a href="https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&amp;content_ID=developer/e_howto_api_WPRecurringPayments#id086510570PN" rel="nofollow">Paypal documentation for recurring (subscription) payments</a>. Additionally you can poll their servers using their API for this information, so if you'd prefer to fetch it yourself, you can.</p>
C# - Locking issues with Mutex <p>I've got a web application that controls which web applications get served traffic from our load balancer. The web application runs on each individual server.</p> <p>It keeps track of the "in or out" state for each application in an object in the ASP.NET application state, and the object is serialized to a file on the disk whenever the state is changed. The state is deserialized from the file when the web application starts.</p> <p>While the site itself only gets a couple requests a second tops, and the file it rarely accessed, I've found that it was extremely easy for some reason to get collisions while attempting to read from or write to the file. This mechanism needs to be extremely reliable, because we have an automated system that regularly does rolling deployments to the server.</p> <p>Before anyone makes any comments questioning the prudence of any of the above, allow me to simply say that explaining the reasoning behind it would make this post much longer than it already is, so I'd like to avoid moving mountains.</p> <p>That said, the code that I use to control access to the file looks like this:</p> <pre><code> internal static Mutex _lock = null; /// &lt;summary&gt;Executes the specified &lt;see cref="Func{FileStream, Object}" /&gt; delegate on the filesystem copy of the &lt;see cref="ServerState" /&gt;. /// The work done on the file is wrapped in a lock statement to ensure there are no locking collisions caused by attempting to save and load /// the file simultaneously from separate requests. /// &lt;/summary&gt; /// &lt;param name="action"&gt;The logic to be executed on the &lt;see cref="ServerState" /&gt; file.&lt;/param&gt; /// &lt;returns&gt;An object containing any result data returned by &lt;param name="func" /&gt;.&lt;/returns&gt; private static Boolean InvokeOnFile(Func&lt;FileStream, Object&gt; func, out Object result) { var l = new Logger(); if (ServerState._lock.WaitOne(1500, false)) { l.LogInformation("Got lock to read/write file-based server state.", (Int32)VipEvent.GotStateLock); var fileStream = File.Open(ServerState.PATH, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); result = func.Invoke(fileStream); fileStream.Close(); fileStream.Dispose(); fileStream = null; ServerState._lock.ReleaseMutex(); l.LogInformation("Released state file lock.", (Int32)VipEvent.ReleasedStateLock); return true; } else { l.LogWarning("Could not get a lock to access the file-based server state.", (Int32)VipEvent.CouldNotGetStateLock); result = null; return false; } } </code></pre> <p>This <em>usually</em> works, but occasionally I cannot get access to the mutex (I see the "Could not get a lock" event in the log). I cannot reproduce this locally - it only happens on my production servers (Win Server 2k3/IIS 6). If I remove the timeout, the application hangs indefinitely (race condition??), including on subsequent requests.</p> <p>When I do get the errors, looking at the event log tells me that the mutex lock was achieved and released by the previous request <em>before</em> the error was logged.</p> <p>The mutex is instantiated in the Application_Start event. I get the same results when it is instantiated statically in the declaration.</p> <p>Excuses, excuses: threading/locking is not my forté, as I generally don't have to worry about it.</p> <p>Any suggestions as to why it randomly would fail to get a signal?</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>I've added proper error handling (how embarrassing!), but I am still getting the same errors - and for the record, unhandled exceptions were never the problem.</p> <p>Only one process would ever be accessing the file - I don't use a web garden for this application's web pool, and no other applications use the file. The only exception I can think of would be when the app pool recycles, and the old WP is still open when the new one is created - but I can tell from watching the task manager that the issue occurs while there is only one worker process.</p> <p>@mmr: How is using Monitor any different from using a Mutex? Based on the MSDN documentation, it looks like it is effectively doing the same thing - if and I can't get the lock with my Mutex, it <em>does</em> fail gracefully by just returning false.</p> <p>Another thing to note: The issues I'm having seem to be completely random - if it fails on one request, it might work fine on the next. There doesn't seem to be a pattern, either (certainly no every other, at least).</p> <p><hr /></p> <p><strong>Update 2:</strong></p> <p>This lock is not used for any other call. The only time _lock is referenced outside the InvokeOnFile method is when it is instantiated.</p> <p>The Func that is invoked is either reading from the file and deserializing into an object, or serializing an object and writing it to the file. Neither operation is done on a separate thread.</p> <p>ServerState.PATH is a static readonly field, which I don't expect would cause any concurrency problems.</p> <p>I'd also like to re-iterate my earlier point that I cannot reproduce this locally (in Cassini). <hr /></p> <p><strong>Lessons learned:</strong></p> <ul> <li>Use proper error handling (duh!)</li> <li>Use the right tool for the job (and have a basic understanding of what/how that tool does). As sambo points out, using a Mutex apparently has a lot of overhead, which was causing issues in my application, whereas Monitor is designed specifically for .NET.</li> </ul>
<p>You should only be using Mutexes if you need <a href="http://msdn.microsoft.com/en-us/library/ms173179(vs.80).aspx">cross-process synchronization</a>.</p> <blockquote> <p>Although a mutex can be used for intra-process thread synchronization, using Monitor is generally preferred, because monitors were designed specifically for the .NET Framework and therefore make better use of resources. In contrast, the Mutex class is a wrapper to a Win32 construct. While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by the Monitor class.</p> </blockquote> <p>If you need to support inter-process locking you need a <a href="http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c">Global mutex</a>.</p> <p>The pattern being used is incredibly fragile, there is no exception handling and you are not ensuring that your Mutex is released. That is really risky code and most likely the reason you see these hangs when there is no timeout.</p> <p>Also, if your file operation ever takes longer than 1.5 seconds then there is a chance concurrent Mutexes will not be able to grab it. I would recommend getting the locking right and avoiding the timeout. </p> <p>I think its best to re-write this to use a lock. Also, it looks like you are calling out to another method, if this take forever, the lock will be held forever. That's pretty risky.</p> <p>This is both shorter and much safer: </p> <pre><code> // if you want timeout support use // try{var success=Monitor.TryEnter(m_syncObj, 2000);} // finally{Monitor.Exit(m_syncObj)} lock(m_syncObj) { l.LogInformation("Got lock to read/write file-based server state.", (Int32)VipEvent.GotStateLock); using (var fileStream = File.Open(ServerState.PATH, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { // the line below is risky, what will happen if the call to invoke // never returns? result = func.Invoke(fileStream); } } l.LogInformation("Released state file lock.", (Int32)VipEvent.ReleasedStateLock); return true; // note exceptions may leak out of this method. either handle them here. // or in the calling method. // For example the file access may fail of func.Invoke may fail </code></pre>
Interpreting assembly code <p>Any assembly interpreters out there?</p> <p>What I'm looking for:</p> <ul> <li>I have some assembly firmware code I want to run, but not on the actual hardware. </li> <li>I would like to run the code and see what it is doing. </li> </ul> <p>So, is there some sort of free and easy to use assembly simulator out there? </p> <p>Any other pointers you can think of? </p>
<p>You should look into some processor emulator only that way you can "interpret" assembly, for example: <a href="http://bellard.org/qemu/" rel="nofollow">Qemu</a> or <a href="http://bochs.sourceforge.net/" rel="nofollow">Bochs</a></p>
Keep indentation of wrapped lines in Visual Studio 2008 <p>In Visual Studio 2008, is there a way to keep the indentation of automatically wrapped long lines? (Only need it for C#.)</p> <p>When word wrap is turned on, it looks like this:</p> <pre> var a = SomeFunctionOrWhateverWithSuperLongName(parameter1, parameter2); </pre> <p>I want it to look like this:</p> <pre> var a = SomeFunctionOrWhateverWithSuperLongName(parameter1, parameter2); </pre> <p>I know some text editor can do this.</p>
<p>Generally, code formatting settings can be changed at <code>Tools -&gt; Options -&gt; Text Editor -&gt; [Your Language] -&gt; Formatting</code>.</p> <p>I believe it's not supported under plain VS. However, some addins might provide this feature.</p>
Highlighting search terms in an MS Word document <p>We have a project where we need to provide search over a collection of Word documents through a web-based interface. The client would like for the search terms to be highlighted when a user opens a document.</p> <p>Is there a way to do this directly in Word when opening a document? The only alternative we can come up with is to convert the Word documents to HTML and display that.</p> <p>Just for background, we're currently using Windows SharePoint Services for document searching.</p>
<p>You could do that using Word's Highlight feature. However, to use the feature you will have to use Word automation on either server-side or client-side. </p> <p>A script in VBA for highlighting a search term could look like this:</p> <pre><code>Sub Highlight(oDoc As Word.Document, term As String) With oDoc.Range.Find .ClearFormatting .Replacement.ClearFormatting .Replacement.Highlight = True .Text = term .Replacement.Text = term .Forward = True .Wrap = wdFindContinue .Format = True .MatchCase = False .MatchWholeWord = False .MatchWildcards = False .MatchSoundsLike = False .MatchAllWordForms = False .Execute Replace:=wdReplaceAll End With End Sub </code></pre> <p>The script does a search-and-replace and applies highlighting to the found text. If you have any questions on how to automate Word best, e.g. in a server environment, don't hesitate to ask.</p>
Using Linq for ObjectDataSource: How to transform datetime using ToShortTimeString? <p>I am accessing a business class using an ObjectDataSource and trying to produce output that makes sense to the user. The return values describe a Class (as in Classroom and teaching, not software). I would like to show the time of the class as a range like this: "9:00 AM - 10:00 AM".</p> <p>This is the Linq Query I am using to pull the data:</p> <pre><code>return classQuery.Select(p =&gt; new SelectClassData { ClassID = p.ClassID, Title = p.Title, StartDate = p.StartDate.ToShortDateString(), EndDate = p.EndDate.ToShortDateString(), TimeOfClass = p.StartDate.ToShortTimeString() + " - " + p.EndDate.ToShortTimeString() }).ToList(); </code></pre> <p>As you can see, I encode the start and ending times in the starting and ending dates even though these could potentially be on different dates.</p> <p>When I execute this code I get:</p> <p><em>"Could not translate expression 'p.EndDate.ToShortTimeString()' into SQL and could not treat it as a local expression."</em></p> <p>I know that I am projecting the results but, being new to Linq, I had assumed that the C# call to ToShortTimeString happened after the projection. Can anyone help me figure out how to get the string I'm looking for?</p>
<p>The reason is the query is being used in LINQ to SQL. LINQ to SQL treats queries as expression trees. It has mappings defined for some methods (for instance, <code>Contains</code>) but since it doesn't really execute them, it can't work on arbitrary methods. It parses the query and submits it to SQL server. The equivalent of the query will be executed as a SQL statement on the database server and the result will come back. The problem is <code>ToShortTimeString()</code> does not have an equivalent SQL translation in LINQ to SQL. The trick used here is to fetch data from SQL server and call the method on the client side (<code>AsEnumerable</code> will do this).</p> <pre><code>return classQuery.Select(p =&gt; new { p.ClassID, p.Title, p.StartDate, p.EndDate }) .AsEnumerable() .Select(p =&gt; new SelectClassData { ClassID = p.ClassID, Title = p.Title, StartDate = p.StartDate.ToShortDateString(), EndDate = p.EndDate.ToShortDateString(), TimeOfClass = p.StartDate.ToShortTimeString() + " - " + p.EndDate.ToShortTimeString() }) .ToList(); </code></pre>
Makefile variable assignment <p>Can anybody give a clear explanation of how variable assignment really works in Makefiles. </p> <p>What is the difference between :</p> <pre><code> VARIABLE = value VARIABLE ?= value VARIABLE := value VARIABLE += value </code></pre> <p>I have read the <a href="http://www.gnu.org/software/make/manual/make.html#Reading-Makefiles">section</a> in GNU Make's manual, but it still doesn't make sense to me. </p>
<h3>Lazy Set</h3> <pre><code>VARIABLE = value </code></pre> <p>Normal setting of a variable - values within it are recursively expanded when the variable is used, not when it's declared</p> <h3>Immediate Set</h3> <pre><code>VARIABLE := value </code></pre> <p>Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.</p> <h3>Set If Absent</h3> <pre><code>VARIABLE ?= value </code></pre> <p>Setting of a variable only if it doesn't have a value</p> <h3>Append</h3> <pre><code>VARIABLE += value </code></pre> <p>Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)</p>
Winform Checklistbox Headers/Columns <p>Is there a way to implement a new column with a header in a checklistbox in vb.net? I've done a bit of searching, but didn't find much on the topic. Should I just abandon the quest and use a listview or some other control?</p> <p>Thanks for any/all help! JFV</p>
<p>I would suggest using a ListView with a checkbox column. You'll have better luck.</p>
How should a list be represented in XML? <p>In XML, how should a list be represented?</p> <p>With an enclosing list entity:</p> <pre><code>&lt;person&gt; &lt;firstname&gt;Joe&lt;/firstname&gt; &lt;lastname&gt;Bloggs&lt;/lastname&gt; &lt;children&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;/children&gt; &lt;/person&gt; </code></pre> <p>Or without:</p> <pre><code>&lt;person&gt; &lt;firstname&gt;Joe&lt;/firstname&gt; &lt;lastname&gt;Bloggs&lt;/lastname&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;child .../&gt; &lt;/person&gt; </code></pre>
<p>I would enclose it in an entity to distinguish it from the other elements.</p>
Reference generated primary key in SQL script <p>I'm trying to create a bunch of entries in a database with a single script and the problem I'm encountering is how to reference the generated primary key of the previous entry I created.</p> <p>For example if I created a customer, then tried to create an order for that customer, how do I get the primary key generated for the customer?</p> <p>I'm using SQLServer.</p>
<p>Like so:</p> <pre><code>DECLARE @customerid int; INSERT INTO customers(name) VALUES('Spencer'); SET @customerid = @@IDENTITY; </code></pre> <p><strong>EDIT:</strong></p> <p>Apparently it needs to be SCOPE_IDENTITY() in order to function as expected with triggers.</p> <pre><code>DECLARE @customerid int; INSERT INTO customers(name) VALUES('Spencer'); SET @customerid = SCOPE_IDENTITY(); </code></pre>
How do I project lines dynamically on to 3D terrain? <p>I'm working on a game in XNA for Xbox 360. The game has 3D terrain with a collection of static objects that are connected by a graph of links. I want to draw the links connecting the objects as lines projected on to the terrain. I also want to be able to change the colors etc. of links as players move their selection around, though I don't need the links to move. However, I'm running into issues making this work correctly and efficiently.</p> <p>Some ideas I've had are:</p> <p>1) Render quads to a separate render target, and use the texture as an overlay on top of the terrain. I currently have this working, generating the texture only for the area currently visible to the camera to minimize aliasing. However, I'm still getting aliasing issues -- the lines look jaggy, and the game chugs frequently <strike>when moving the camera</strike> EDIT: it chugs all the time, I just don't have a frame rate counter on Xbox so I only notice it when things move.</p> <p>2) Bake the lines into a texture ahead of time. This could increase performance, but makes the aliasing issue worse. Also, it doesn't let me dynamically change the properties of the lines without much munging.</p> <p>3) Make geometry that matches the shape of the terrain by tessellating the line-quads over the terrain. This option seems like it could help, but I'm unsure if I should spend time trying it out if there's an easier way.</p> <p>Is there some magical way to do this that I haven't thought of? Is one of these paths the best when done correctly?</p>
<p>Your 1) is a fairly good solution. You can reduce the jagginess by filtering -- first, make sure to use bilinear sampling when using the overlay. Then, try blurring the overlay after drawing it but before using it; if you choose a proper filter, it will remove the aliasing.</p> <p>If it's taking too much time to render the overlay, try reducing its resolution. Without the antialiasing filter, that would just make it jaggier, but with a good filter, it might even look better.</p> <p>I don't know why the game would chug only when moving the camera. Remember, you should have a separate camera for the overlay -- orthogonal, and pointing down onto the terrain.</p>
Is it "better" to have an update field or COUNT query? <p>In a Django App I'm working on I've got this going on:</p> <pre><code>class Parent(models.Model): name = models.CharField(...) def num_children(self): return Children.objects.filter(parent=self).count() def avg_child_rating(self): return Child.objects.filter(parent=self).aggregate(Avg('rating')) class Child(models.Model): name = models.CharField(...) parent = models.ForeignKey(Parent) rating = models.IntegerField(default=0) </code></pre> <p>I plan on accessing <strong>avg_child_rating</strong> often. Would it be <em>optimizing</em> if I did the following:</p> <pre><code>class Parent(models.Model): ... num_children = models.IntegerField(default=0) avg_child_rating = models.FloatField(default=0.0) def update_parent_child_stats(sender, instance, **kwargs): num_children = Child.objects.filter(parent=instance.parent) if instance.parent.num_children != num_children: instance.parent.num_children = num_children instance.parent.avg_child_rating = Child.objects.filter(instance.parent=self).aggregate(Avg('rating')) post_save.connect(update_parent_child_stats, sender=Child) post_delete.connect(update_parent_child_stats, sender=Child) </code></pre> <p>The difference now is that every time a child is created/rated/deleted, the Parent object is updated. I know that the created/rating will be done often.</p> <p>What's more <em>expensive</em>?</p>
<p>Depends on the scale of the problem. If you anticipate a lot of write traffic, this might be an issue. It's much harder to scale writes than reads (replicate, caching etc.) That said, you can probably going a long way without this extra query causing you any problems.</p> <p>Depending on how up-to-date your stats must be you could have some other process (non-web session) come through and update these stats nightly.</p>
How to programmatically set every other column in a worksheet in Interop <p>Using Excel Interop (.NET) how can we set programmatically two different Excel formulas for every other column. For instance, </p> <pre><code>Range r = _sheet.get_Range(_sheet.Cells[1, 1], _sheet.Cells[I, J]) r.Formula = "=something1" </code></pre> <p>will do it for every cell. </p> <p>But within <code>J</code> columns every other column has to have formula <code>=something2</code>. </p> <p>The size of the range is known only at run-time.</p>
<p>First, you create a function to define a range as every other column, a <a href="http://excel.bigresource.com/Track-excel-J1w0Pbug/" rel="nofollow">variant of this</a> (VBA):</p> <pre><code>Sub EveryOtherColumn() Dim rangeString As String Dim columnLetter As String Dim i As Long Dim firstCol, lastCol As Long firstCol = Selection.Column lastCol = Selection.Columns.Count + firstCol - 1 For i = firstCol To lastCol Step 2 columnLetter = Chr(i + 64) rangeString = rangeString &amp; "," &amp; columnLetter &amp; ":" &amp; columnLetter Next i rangeString = Mid(rangeString, 2) Range(rangeString).Select End Sub </code></pre> <p>Then, you just assign the formula to that Range.</p>
CSS Copy and paste problem <p>I've developed a system in my application where emails are picked up with a regex, and then reversed in the source (to thwart bots). I then add the span class 'obfuscate email'. I then use CSS to reverse the the text back to be displayed and Javascript make sure that <code>mailto:</code> links still work.</p> <p>I was pretty happy with my solution until I realised that copying and pasting the email puts it in the clipboard backwards. I was wondering if there was any way I could remedy this? I've been testing in Firefox 3 for OS X.</p> <p>The page in question is available here: <a href="http://www.leaklocations.com.au/contact-us/" rel="nofollow">http://www.leaklocations.com.au/contact-us/</a></p> <p>To see the problem, simply copy and paste the email on that site. </p>
<p>You can use the same Javascript to reverse the text as well as the mailto links. If the user doesn't have Javascript, then you can either settle for this problem or use an image.</p>
Most Efficient way to access schema with ODBC and OleDB <p>I am making a DAL template with C# and I am wondering what is the most efficient way to access schema information with ODBC and OleDB. I need the columns, column types, and primary key information.</p> <p>thanks</p>
<p>For OleDb, there is an OleDbConnection.GetoleDbSchemaTable() method. I've used it with Access.</p> <p>I have an example in this code on GitHub: <a href="http://github.com/rally25rs/storm/blob/053947d25ab5d789bf3f33302cf3e4aaf4ea08bf/StormOleDbSupport/DataBinders/OleDb/Validation/SchemaValidator.cs" rel="nofollow">SchemaValidator.cs</a></p> <p>There should be a .Schema() method on OdbcConnection too IIRC.</p> <p>I have noticed that the actual returned values may vary by database, so you'll want to do a fair amount of checking and debugging to see what he returned values may be.</p>
Programmatically binding List to ListBox <p>Lets say for instance i have the following extremely simple window:</p> <pre><code>&lt;Window x:Class="CalendarGenerator.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="447"&gt; &lt;Grid&gt; &lt;ListBox Margin="12,40,0,12" Name="eventList" HorizontalAlignment="Left" Width="134" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>And a simple list defined as:</p> <pre><code>List&lt;String&gt; ListOfNames = new List&lt;String&gt;(); </code></pre> <p>And lets assume that the list has several names in it. How would i go about binding the List to the ListBox using as much code-behind as possible?</p>
<p>First you'd need to give your ListBox a name so that it's accessible from your code behind (<em>edit</em> I note you've already done this, so I'll change my example ListBox's name to reflect yours):</p> <pre><code>&lt;ListBox x:Name="eventList" ... /&gt; </code></pre> <p>Then it's as simple as setting the ListBox's <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemssource.aspx">ItemsSource</a> property to your list:</p> <pre><code>eventList.ItemsSource = ListOfNames; </code></pre> <p>Since you've defined your "ListOfNames" object as a <code>List&lt;String&gt;</code>, the ListBox won't automatically reflect changes made to the list. To get WPF's databinding to react to changes within the list, define it as an <a href="http://msdn.microsoft.com/en-us/library/ms668604.aspx">ObservableCollection</a><code>&lt;String&gt;</code> instead.</p>
variable button vb.net <p>i declared a global variable button:</p> <p>Dim button1 As New Button()</p> <p>Now, i dont know how to add a click event in this button since it is a variable. Do you have any idea how do i do it?</p>
<p><code>AddHandler button1.click, AddressOf MyClickEventHandler</code> (<a href="http://msdn.microsoft.com/en-us/library/6yyk8z93(VS.71).aspx" rel="nofollow">MSDN Documentation</a>)</p> <p>You have to make sure <code>MyClickEventHandler</code> is defined with the same signature as any other Click event handler (i.e. <code>Sub MyClickEventHandler(ByVal sender as Object, ByVal e as EventArgs)</code>)</p>
How do I determine the size of an object in Python? <p>In C, we can find the size of an <code>int</code>, <code>char</code>, etc. I want to know how to get size of objects like a string, integer, etc. in Python.</p> <p>Related question: <a href="http://stackoverflow.com/questions/135664/how-many-bytes-per-element-are-there-in-a-python-list-tuple">How many bytes per element are there in a Python list (tuple)?</a></p> <p>I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.</p>
<p>Just use the <a href="http://docs.python.org/library/sys.html#sys.getsizeof">sys.getsizeof</a> function defined in the <code>sys</code> module.</p> <blockquote> <p><code>sys.getsizeof(object[, default])</code>:</p> <p>Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.</p> <p>The <code>default</code> argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a <code>TypeError</code>.</p> <p><code>getsizeof</code> calls the object’s <code>__sizeof__</code> method and adds an additional garbage collector overhead if the object is managed by the garbage collector.</p> </blockquote> <p>Usage example, in python 3.0:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; x = 2 &gt;&gt;&gt; sys.getsizeof(x) 14 &gt;&gt;&gt; sys.getsizeof(sys.getsizeof) 32 &gt;&gt;&gt; sys.getsizeof('this') 38 &gt;&gt;&gt; sys.getsizeof('this also') 48 </code></pre> <p>If you are in python &lt; 2.6 and don't have <code>sys.getsizeof</code> you can use <a href="http://code.activestate.com/recipes/546530/">this extensive module</a> instead. Never used it though.</p>
Webbased MySQL interface better that phpMyAdmin <p>Is there any webbased interface for MySQL better than phpMyAdmin? I use phpMyAdmin a lot but it is becoming a pain, especially it is slow sometimes. </p> <p>I'd like to have deep export functionality like phpMyAdmin but more design features</p>
<p>Why don't you just use a client? They are a lot nicer in my opinion.</p> <p>I love <a href="http://www.webyog.com" rel="nofollow">SQLyog</a> because it supports a lot of MySQL features (stored procedures) but I used to use HeidiSQL and it was nice as well.</p> <p>As for web based clients, I haven't got any suggestions unfortunately.</p>
What is the difference between DoS and Brute Force attacks? <p>I was reading about DoS attacks on Apache servers but the "Brute Force" word pops up sometimes I know DoS attacks but "Brute Force" seems to be similar, is there a difference or it is just another word of DoS?</p>
<p><strong>Brute force</strong> attacks use a technique of attempting to try every combination of passwords/keys to gain access to a particular system. What the hacker does when they gain entry to the system depends on the motivation of the hacker.</p> <p><strong>DoS (Denial of Service)</strong> attacks describe cases where the motivation of the hacker is to bring down the system, causing maximum inconvenience to the users of the system.</p> <p>They can't really be compared against each other, as brute force is a <em>technique</em> to gain entry, and DoS is a <em>type</em> of attack. It is possible that an attack could be <em>both</em> brute force and DoS.</p>
How can I monkey-patch an instance method in Perl? <p>I'm trying to monkey-patch (duck-punch :-) a <code>LWP::UserAgent</code> instance, like so:</p> <pre><code>sub _user_agent_get_basic_credentials_patch { return ($username, $password); } my $agent = LWP::UserAgent-&gt;new(); $agent-&gt;get_basic_credentials = _user_agent_get_basic_credentials_patch; </code></pre> <p>This isn't the right syntax -- it yields:</p> <blockquote> <p>Can't modify non-lvalue subroutine call at [module] line [lineno].</p> </blockquote> <p>As I recall (from <em>Programming Perl</em>), dispatch lookup is performed dynamically based on the blessed package (<code>ref($agent)</code>, I believe), so I'm not sure how instance monkey patching would even work without affecting the blessed package.</p> <p>I know that I can subclass the <code>UserAgent</code>, but I would prefer the more concise monkey-patched approach. Consenting adults and what have you. ;-)</p>
<p>As answered by <a href="http://stackoverflow.com/users/55276/fayland-lam">Fayland Lam</a>, the correct syntax is:</p> <pre><code> local *LWP::UserAgent::get_basic_credentials = sub { return ( $username, $password ); }; </code></pre> <p>But this is patching (dynamically scoped) the whole class and not just the instance. You can probably get away with this in your case.</p> <p>If you really want to affect just the instance, use the subclassing you described. This can be done 'on the fly' like this:</p> <pre><code>{ package My::LWP::UserAgent; our @ISA = qw/LWP::UserAgent/; sub get_basic_credentials { return ( $username, $password ); }; # ... and rebless $agent into current package $agent = bless $agent; } </code></pre>
Error: The object cannot be deleted because it was not found in the ObjectStateManager <p>Trying to get a handle on Entity Framework here and I am hitting some speed bumps... I have a Get() method that works fine and has been tested, but my Delete method is not working:</p> <pre><code> public static void Delete(string name) { J1Entities db = new J1Entities(); db.DeleteObject(Get(name)); db.SaveChanges(); } </code></pre> <p>But I get the following error: <strong>Error: The object cannot be deleted because it was not found in the ObjectStateManager.</strong></p> <p>I ran the debugger, and the object inside the DeleteObject is correct... what am I missing? Thank you.</p>
<p>Each EF object is tightly associated to the manager (for want of a better word) that created it. or to which it has been associated. Since you don't pass <code>db</code> to your <code>Get</code> method, I assume that <code>Get</code> has either used it's own <code>J1Entities</code>, or the object has been created standalone (perhaps deserialized).</p> <p>In order to delete it, it must know about it <em>first</em>. That might mean by <em>attaching</em> an object to the manager - but in this case, it seems like an easier option is just to pass <code>db</code> into <code>Get</code>, so that the <code>Get</code> is done in the same context (since <code>db</code> will automatically attach objects that it creates itself).</p>
Dividing workload on several threads <p>I was wondering if anyone knows about a good article which describes dividing workload on to several Threads? Preferebly it would be written for C# but it's really the concept I'm after, so it's not an issue if it's written for a different, similar, language.</p> <p>I have a problem where I would have to divide a large amount of computing into several threads and then Sum the generated data after one iteration completes (so I would need to know that all threads have finished) and then start a new iteration, supplying all the threads with the data generated in the last iteration (the data would be modified before the end of each iteration).</p> <p>I hope this makes sense, and is possible. Either way I would appreciate some advice on how to tackle the problem of computing large amounts of data divided on to several threads (so I can use more than one processor's core).</p> <p>Thank you for your answers!</p>
<p>You should look at Parallel FX (PFX), you can find the blog <a href="http://blogs.msdn.com/pfxteam/" rel="nofollow">here</a> and the download link <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3" rel="nofollow">here</a> (Thanks Marc).</p> <p>Unfortunately I don't know if this will be released for .NET 2.0/3.5 as it is currently slated for .NET 4.0.</p> <p>If you're looking at implementing it yourself, look into <a href="http://www.google.com/search?q=work+stealing+algorithms" rel="nofollow">Work Stealing Algorithms</a>.</p> <p>There is also a library named <a href="http://www.wintellect.com/PowerThreading.aspx" rel="nofollow">Power Threading</a>, by Jeffrey Richter from <a href="http://www.wintellect.com/Resources.aspx" rel="nofollow">Wintellect</a> which has some rather good classes available for you.</p>
About mobile game porting <p>I would like to ask a few questions regarding mobile game porting...</p> <p>Let say if I have a simple 2D C++ game engine and have a PC game based on that engine and I want to port it to different mobile platforms BREW, J2ME, iPhone, Android, Symbian, etc..</p> <p>Do I need to re-code the engine and the game for each platform? or is there an easier and more efficient way? I am sure the process is complicated since different phones have different graphic/processor/memory/etc. I am just curious about the overview of mobile game porting process. :)</p> <p>Thanks!</p>
<p>There are several ways of attacking mobile game porting. First of all, until very recently it was mostly BREW and J2ME. The iPhone, Android and BlackBerry are changing this landscape and making the impossible task of mobile game porting even more impossible. I worked in 3rd party mobile game development for many years until recently. I watched BREW vanish and saw publishers completely focus on J2ME as the cost of porting is strangling the industry. There are estimates to its cost, both time and money, and it seems to bell curve around 50-60% of the total development cost for each game is just porting.</p> <p>At our company, we handled porting by having two engines that paralleled each other, one in BREW, one in J2ME. We never supported Symbian as Symbian development does not make any money. It is mainly for high-end tech demos that might be on one or two devices, nothing that could reach the mass market. Plus, most Symbian phones supported J2ME. </p> <p>We would be required by publishers to provide any where from 7-23 reference builds of the game, targeting many different devices, in both BREW and J2ME. Just before moving on, publishers were also starting to require a J2ME touch screen reference version, and an iPhone SKU was being left as "to be determined" based on the final product and how cost effective an iPhone version would be at that time. The reference versions would then be passed on to a porting house to translate the different references to the thousands of other required SKUs.</p> <p>Companies like Gameloft still brute force their way through porting. That's why Gameloft's games are constantly at a higher quality than the rest of the industry. However, it is just not possible for smaller companies to attack the problem this way due to costs. Not everyone can afford an office in Beijing with 5000 developers.</p> <p>There are many companies out there developing engines to cut porting costs. <a href="http://www.mobile-distillery.com/home.htm" rel="nofollow">Mobile-Distillery</a> is one I was in contact with quite a lot, but we ended up never using it. So, I can't vouch for them. The problem here is that you will be at the mercy of another companies engine. Performance could be problematic due to the fact that it is being built to target thousands of SKUs. Plus, you really have little control over the low level implementation of your game in this instance. The end result seems to be a game that targets the lowest common denominator of phones.</p> <p>Finally, a lot of developers are just abandoning the idea of supporting all mobile platforms. There is a huge flood on games on the iPhone because 1) it requires only targeting one platform and 2) there is a 70 percent profit share through the AppStore for developers. Through carrier releases, the percentage is not even comparable.</p>
Recommended JavaScript HTML template library for JQuery? <p>Any suggestions on which HTML template library would go well with JQuery? Googling turns up quite a number of libraries but I'm not sure whether there is a well recognized library that would stand the test of time.</p>
<p>Well, to be frank, client-side templating is very hot nowadays, but quite a jungle.</p> <p>the most popular are, I believe: </p> <ul> <li><a href="http://beebole.com/pure/">pure</a>: It use only js, not his own "syntax"</li> <li><a href="http://mustache.github.com/">mustache</a>: quite stable and nice I heard.</li> <li><a href="http://aefxx.com/jquery-plugins/jqote2/">jqote2</a>: extremely fast according to jsperfs</li> <li>jquery templates (deprecated): </li> </ul> <p>there are <em>plenty</em> others, but you have to test them to see what suits you, and your project style, best.</p> <p>Personally, I have a hard time with adding a new syntax and set of logic (<em>mixing logic and template, hello??</em>), and went pure js. Every single one of my templates is stored in it's own html file (./usersTable.row.html). I use templates only when ajaxing content, and I have few "logic" js files, one for tables, one for div, one for lists. and not even one for select's options (where i use another method).</p> <p>Each time I tried to do something more complex, I found out the code was less clear and taking me more time to stabilize than doing it the "old" way. Logic in the template is an utter non-sense in my opinion, and adding it's own syntax adds only very-hard-to-trace bugs.</p>
How do i combine a list and a form in the same page using django? <p>Am building a Q&amp;A page, sort of stackoverflow kinda page! Am having a bit of a problem trying to render the form. Am pasing 3 objects to the template that renders the page i.e. Question object, Answers related to the question and Answer form object.</p> <p>In the first part of the page i want to display the Question, then the answers list follows, then at the bottom i display my form to enter the new answer.</p> <p>On my template when i use the {{ extends "base_site.html" }} tag then only the form get rendered, When i remove that tag then only the Question section get displayed minus the form!!</p> <p>How can i go round this problem?</p>
<p>Tricky to answer without seeing some code, but I suspect it's something to do with the way you are using {{ extends }} and inheriting/over-riding {{ block }} sections.</p> <p>I would check the names of all your {{ block }} sections, and that you are over-riding the blocks that you think you are. It may be that you have blocks in the inheriting page that aren't defined in the base page?</p>
Communicating with the web through a C# app? <p>Although i can grasp the concepts of the .Net framework and windows apps, i want to create an app that will involve me simulating website clicks and getting data/response times from that page. I have not had any experience with web yet as im only a junior, could someone explain to me (in english!!) the basic concepts or with examples, the different ways and classes that could help me communicate with a website?</p>
<p>what do you want to do?</p> <p>send a request and grab the response in a String so you can process?</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a> and <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx">HttpWebResponse</a> will work</p> <p>if you need to connect through TCP/IP, FTP or other than HTTP then you need to use a more generic method</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx">WebRequest</a> and <a href="http://msdn.microsoft.com/en-us/library/system.net.webresponse.aspx">WebResponse</a></p> <p>All the 4 methods above are in System.Net Namespace</p> <p>If you want to build a Service in the web side that you can consume, then today and in .NET please choose and work with <a href="http://channel9.msdn.com/pdc2008/TL35/">WCF (RESTfull style)</a>.</p> <p>hope it helps you finding your way :)</p> <p>as an example using the HttpWebRequest and HttpWebResponse, maybe some code will help you understand better.</p> <p><strong>case:</strong> send a response to a URL and get the response, it's like clicking in the URL and grab all the HTML code that will be there after the click:</p> <pre><code>private void btnSendRequest_Click(object sender, EventArgs e) { textBox1.Text = ""; try { String queryString = "user=myUser&amp;pwd=myPassword&amp;tel=+123456798&amp;msg=My message"; byte[] requestByte = Encoding.Default.GetBytes(queryString); // build our request WebRequest webRequest = WebRequest.Create("http://www.sendFreeSMS.com/"); webRequest.Method = "POST"; webRequest.ContentType = "application/xml"; webRequest.ContentLength = requestByte.Length; // create our stram to send Stream webDataStream = webRequest.GetRequestStream(); webDataStream.Write(requestByte, 0, requestByte.Length); // get the response from our stream WebResponse webResponse = webRequest.GetResponse(); webDataStream = webResponse.GetResponseStream(); // convert the result into a String StreamReader webResponseSReader = new StreamReader(webDataStream); String responseFromServer = webResponseSReader.ReadToEnd().Replace("\n", "").Replace("\t", ""); // close everything webResponseSReader.Close(); webResponse.Close(); webDataStream.Close(); // You now have the HTML in the responseFromServer variable, use it :) textBox1.Text = responseFromServer; } catch (Exception ex) { textBox1.Text = ex.Message; } } </code></pre> <p>The code does not work cause the URL is fictitious, but you get the idea. :)</p>
Is there already some std::vector based set/map implementation? <p>For small sets or maps, it's usually much faster to just use a sorted vector, instead of the tree-based <code>set</code>/<code>map</code> - especially for something like 5-10 elements. LLVM has some classes <a href="http://llvm.org/docs/ProgrammersManual.html#ds_sequential">in that spirit</a>, but no real adapter that would provide a <code>std::map</code> like interface backed up with a <code>std::vector</code>.</p> <p>Any (free) implementation of this out there?</p> <p><strong>Edit</strong>: Thanks for all the alternative ideas, but I'm really interested in a vector based set/map. I do have specific cases where I tend to create huge amounts of sets/maps which contain usually less than 10 elements, and I do really want to have less memory pressure. Think about for example neighbor edges for a vertex in a triangle mesh, you easily wind up with 100k sets of 3-4 elements each.</p>
<p>I just stumbled upon your question, hope its not too late.</p> <p>I recommend a great (open source) library named <a href="http://loki-lib.sourceforge.net/" rel="nofollow">Loki</a>. It has a vector based implementation of an associative container that is a drop-in replacement for std::map, called <a href="https://github.com/snaewe/loki-lib/blob/master/include/loki/AssocVector.h" rel="nofollow">AssocVector</a>.</p> <p>It offers better performance for accessing elements (and worst performance for insertions/deletions).</p> <p>The library was written by <a href="http://en.wikipedia.org/wiki/Andrei_Alexandrescu" rel="nofollow">Andrei Alexandrescu</a> author of <a href="http://en.wikipedia.org/wiki/Modern_C%2B%2B_Design" rel="nofollow">Modern C++ Design</a>.</p> <p>It also contains some other really nifty stuff.</p>
Running Cruise Control .NET as a Service <p>I've been configuring and testing CCNet for a little while now using Virtual PC to host it. Everything went well and it was decided to transfer the configuration to a server location - which went as well as could be expected. A few tweaks and kicks and i had it running as before.</p> <p>The problem is that we now need to run CCNet as a service which is proving problematic.</p> <p>I have configured a domain level user with the same access rights as myself (after all, the console application has been running as me for about 3 months now) and configured the service to run under that user. </p> <p>I started the service and it hung! [I'll not bore you with the details of forcing the service to stop and closing the sockets that were held open]. When I was eventually able to run the console again I did a 'Run As' and entered the 'cruisecontrol' user details, click OK and saw that there was a problem accessing SVN via https. I've sorted that by running IE as 'cruisecontrol', navigating to the repository and accepting/installing the certificate. Next when I ran the console application as 'cruisecontrol' it hangs after the following lines:</p> <p><code> 2009-01-15 16:55:50,994 [Pepsi Webservices:DEBUG] Running Subversion with arguments : log --xml --limit 1 https://ash-dev-005.[path to trunk]</p> <p>2009-01-15 16:55:51,478 [Pepsi Webservices:DEBUG] Authentication realm: https://ash-dev-005.[path to repository] Subversion Repositories </code></p> <p>After it times out I can close the console, run it as normal (i.e. as me) and it runs fine. I have tried logging into the server as the 'cruisecontrol' user and tried running the console but with the same result.</p> <p>Now, heres the thing: This morning I logged into the server as the 'cruisecontrol' user and opened a command window. I navigated to the trunk of my project and typed 'svn update' and was prompted for a password. </p> <p>This is not surprising but the line above that prompt was the 'Authentication realm:...' line above! Looking at the log file, sure enough right after the process is killed by CCNet there is a prompt for a password. Is CCNet/SVN waiting for a password entry and then timing out? If so, why it is not using the one in the config file?</p> <p>I entered the password and the update proceeded without any problems (so the cruisecontrol user does have permissions to access the repository from the server). I entered the command again and was not prompted a second time so i tried opening a new command window and rerunning the command - still not prompted for a password so i logged out and back in (as cruisecontrol) and tried again but was still not prompted.</p> <p>The good news is that when I run the console application as the cruisecontrol user (whether logged in as cruisecontrol or just using Run As) everything appears to be OK.</p> <p>So what's my question? Well, why is CCNet not using the password in the config file? How has entering the password in the command prompt resolved the problem (and will it persist)?</p> <p>Any suggestions/insight appreciated.</p>
<p>Hmmm - I may have answered my own question here (or not, only time will tell).</p> <p>For some reason CCNet does not appear to be using the credential in the config file (don't know why). When it calls SVN it waits for a password to be entered, even if the user cannot see it, and then times out when it doesn't get one.</p> <p>By accessing SVN from the command line the password prompt is visible and can be entered, moreover the password is cached in %app_data%\Subversion\auth\svn.simple inside an encrypted file for that user. This is why subsequent commands do not prompt for a password and why the console application will run without any problems.</p> <p>I'm going to configure the CCService now so hopefully this will work as well as the console application does now.</p> <p>If you have had any similar experiences please let me know. In the meantime I may raise the issue with ThoughtWorks.</p>
How to copy a recursive directory structure in TFS Team Build? <p>Is it possible to copy a directory in a team build target?</p>
<pre><code>&lt;Copy SourceFiles="@(SourceItemGroup)" DestinationFolder="$(YourDir\SubDir\%(RecursiveDir)" /&gt; </code></pre>
How do you achieve field level security in ASP.Net? <p>I have an .aspx form with 20 fields that must be disable based on a users role and a status of a order record. Currently the application has 5 roles and 3 status, so I have 300 different possible conditions that I have to account for. </p> <p>My first thought is to store each permutation in a table, then set the fields when the page loads by looping through the fields. Is there a better way? Please note, I am using .Net 2.0 and NOT MVC.</p>
<p>I'd probably store the details of each field, and then the roles and status that can edit them, and do it that way.</p> <p>What are the rules for the system? Basically, are there really 300 possible conditions? Or is that really certain fields are only editable for certain status, and then only certain roles can edit those fields? Or is it that certain fields are available for certain roles as well?</p> <p>If it's more of the former I'd probably have something like this:</p> <p>Three primary tables (makes it easy to extend if you add a field, role or status):</p> <ul> <li>Fields</li> <li>Roles</li> <li>Status</li> </ul> <p>Then two link tables:</p> <ul> <li>Field.Id and Role.Id</li> <li>Field.Id and Status.Id</li> </ul> <p>Then for any given order and user you can then find which Fields are editable for the order's current status, and the users role, and as you work through the fields set the access rights appropriately - however you set the controls - either dynamically generating them based on the collection you get back, or statically on the page.</p> <p>If you have an issue where the Role can override the Status, you could also store a boolean in the Field/Role table, indicating whether the Field should be avaiable regardless of status.</p>
A priority queue which allows efficient priority update? <p><strong>UPDATE</strong>: Here's <a href="http://tinyurl.com/7zgwb4">my implementation of Hashed Timing Wheels</a>. Please let me know if you have an idea to improve the performance and concurrency. (20-Jan-2009)</p> <pre><code>// Sample usage: public static void main(String[] args) throws Exception { Timer timer = new HashedWheelTimer(); for (int i = 0; i &lt; 100000; i ++) { timer.newTimeout(new TimerTask() { public void run(Timeout timeout) throws Exception { // Extend another second. timeout.extend(); } }, 1000, TimeUnit.MILLISECONDS); } } </code></pre> <p><strong>UPDATE</strong>: I solved this problem by using <a href="http://www.cse.wustl.edu/~cdgill/courses/cs6874/TimingWheels.ppt">Hierarchical and Hashed Timing Wheels</a>. (19-Jan-2009)</p> <p>I'm trying to implement a special purpose timer in Java which is optimized for timeout handling. For example, a user can register a task with a dead line and the timer could notify a user's callback method when the dead line is over. In most cases, a registered task will be done within a very short amount of time, so most tasks will be canceled (e.g. task.cancel()) or rescheduled to the future (e.g. task.rescheduleToLater(1, TimeUnit.SECOND)).</p> <p>I want to use this timer to detect an idle socket connection (e.g. close the connection when no message is received in 10 seconds) and write timeout (e.g. raise an exception when the write operation is not finished in 30 seconds.) In most cases, the timeout will not occur, client will send a message and the response will be sent unless there's a weird network issue.. </p> <p>I can't use java.util.Timer or java.util.concurrent.ScheduledThreadPoolExecutor because they assume most tasks are supposed to be timed out. If a task is cancelled, the cancelled task is stored in its internal heap until ScheduledThreadPoolExecutor.purge() is called, and it's a very expensive operation. (O(NlogN) perhaps?)</p> <p>In traditional heaps or priority queues I've learned in my CS classes, updating the priority of an element was an expensive operation (O(logN) in many cases because it can only be achieved by removing the element and re-inserting it with a new priority value. Some heaps like Fibonacci heap has O(1) time of decreaseKey() and min() operation, but what I need at least is fast increaseKey() and min() (or decreaseKey() and max()).</p> <p>Do you know any data structure which is highly optimized for this particular use case? One strategy I'm thinking of is just storing all tasks in a hash table and iterating all tasks every second or so, but it's not that beautiful.</p>
<p>How about trying to separate the handing of the normal case where things complete quickly from the error cases?</p> <p>Use both a hash table and a priority queue. When a task is started it gets put in the hash table and if it finishes quickly it gets removed in O(1) time.</p> <p>Every one second you scan the hash table and any tasks that have been a long time, say .75 seconds, get moved to the priority queue. The priority queue should always be small and easy to handle. This assumes that one second is much less than the timeout times you are looking for.</p> <p>If scanning the hash table is too slow, you could use two hash tables, essentially one for even-numbered seconds and one for odd-numbered seconds. When a task gets started it is put in the current hash table. Every second move all the tasks from the non-current hash table into the priority queue and swap the hash tables so that the current hash table is now empty and the non-current table contains the tasks started between one and two seconds ago.</p> <p>There options are a lot more complicated than just using a priority queue, but are pretty easily implemented should be stable.</p>
How to check if a file can be created inside given directory on MS XP/Vista? <p>I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.</p> <p>I have created directory for test purposes, let's call it <code>C:\foo</code>. </p> <p>I have following permissions to <code>C:\foo</code>: </p> <ul> <li>Traversing directory/Execute file </li> <li>Removing subfolders and files</li> <li>Removing</li> <li>Read permissions</li> <li>Change permissions</li> <li>Take ownership</li> </ul> <p>I don't have any of the following permissions to <code>C:\foo</code>: </p> <ul> <li>Full Control </li> <li>File creation </li> <li>Folder creation </li> </ul> <p>I have tried following approaches, so far:</p> <p><code><br /> os.access('C:\foo', os.W_OK) == True </p> <p>st = os.stat('C:\foo')<br /> mode = st[stat.ST_MODE]<br /> mode &amp; stat.S_IWRITE == True </code> </p> <p>I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not. </p> <p>Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?</p> <p>In brief - I want to check if current user has <strong>File creation</strong> and <strong>Folder creation</strong> permissions for given folder name.</p> <p>EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states: </p> <blockquote> <ol> <li>The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case. </li> </ol> </blockquote> <p>Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?' </p> <p>Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%? </p>
<p>I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file.</p> <p>So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails.</p>
Python Path <p>I am installing active python, django. I really dont know how to set the python path in vista environment system. first of all will it work in vista.</p>
<h1>Temporary Change</h1> <p>To change the python path temporarily (i.e., for one interactive session), just append to <code>sys.path</code> like this:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.path ['', 'C:\\Program Files\\PyScripter\\Lib\\rpyc.zip', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] &gt;&gt;&gt; sys.path.append(directory_to_be_added) </code></pre> <h1>Permanent (More or Less) Change</h1> <p>Go to <code>Computer -&gt; System Properties (Either by the big button near the title bar or in the context-menu by right-clicking) -&gt; Advanced Settings (in the right-hand nav bar) -&gt; Environment Variables</code>. In the <code>System Variables</code>, either add a variable called <code>PYTHONPATH</code> (if it's not already there, i.e., if you haven't done this before) or edit the existing variable.</p> <p>You should enter the directories normally (take care to use backslashes, not the normal ones) separated by a semicolon (<code>;</code>) w/o a space. Be careful not to end with a semicolon. </p> <p>The directories that you just entered now will be <em>added</em> to <code>sys.path</code> whenever you open a interpreter, they won't replace it. Also, the changes will take place only after you've restarted the interpreter.</p> <p><hr> <sup>Source: <a href="http://greeennotebook.com/2010/06/how-to-change-pythonpath-in-windows-and-ubuntu/" rel="nofollow">http://greeennotebook.com/2010/06/how-to-change-pythonpath-in-windows-and-ubuntu/</a></sup></p>
How to unit-test a file writing method with Visual Studio's built-in automated tests? <ol> <li><p>I use Visual Studio 2008 Professional automated tests. I have a function that writes to a file. I want to unit test the file writing function. I have read somewhere that I would have to mock a file somehow. I don't know how to do it. Can you help?</p></li> <li><p>How to unit-test a method that downloads a page from the Internet?</p></li> </ol>
<p>If the method has to open the file stream itself, then that's hard to mock. However, if you can pass a stream into the method, and make it write to that, then you can pass in a MemoryStream instead. An alternative overload can take fewer parameters, open the file and pass a FileStream to the other method.</p> <p>This way you don't get complete coverage (unless you write a test or two which really does hit the disk) but most of your logic is in fully tested code, within the method taking a Stream parameter.</p>
Login to the page with HttpWebRequest <p>How can I login to the this page <a href="http://www.bhmobile.ba/portal/index">http://www.bhmobile.ba/portal/index</a> by using HttpWebRequest? </p> <p>Login button is "Pošalji" (upper left corner).</p> <h3>HTML source of login page:</h3> <pre><code>&lt;table id="maintable" border="0" cellspacing="0" cellpadding="0" style="height:100%; width:100%"&gt; &lt;tr&gt; &lt;td width="367" style="vertical-align:top;padding:3px"&gt;&lt;script type="text/javascript"&gt; function checkUserid(){ if (document &amp;&amp; document.getElementById){ var f = document.getElementById('userid'); if (f){ if (f.value.length &lt; 8){ alert('Korisničko ime treba biti u formatu 061/062 xxxxxx !'); return false; } } } return true; } &lt;/script&gt; &lt;div style="margin-bottom:12px"&gt;&lt;table class="leftbox" style="height:184px; background-image:url(/web/2007/slike/okvir.jpg);" cellspacing="0" cellpadding="0"&gt; &lt;tr&gt; &lt;th style="vertical-align:middle"&gt;&lt;form action="http://sso.bhmobile.ba/sso/login" method="post" onSubmit="return checkUserid();"&gt; &lt;input type="hidden" name="realm" value="sso"&gt; &lt;input type="hidden" name="application" value="portal"&gt; &lt;input type="hidden" name="url" value="http://www.bhmobile.ba/portal/redirect?type=ssologin&amp;amp;url=/portal/show?idc=1111"&gt; &lt;table class="formbox" align="center" cellspacing="0" cellpadding="0"&gt; &lt;tr&gt; &lt;th style="vertical-align:middle; text-align:right;padding-right:4px;"&gt;Korisnik:&lt;/th&gt; &lt;td&gt;&lt;input type="text" size="20" id="userid" name="userid"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th style="text-align:right;padding-right:4px;"&gt;Lozinka:&lt;/th&gt; &lt;td&gt;&lt;input type="password" size="20" name="password" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th colspan="2"&gt; &lt;input class="dugmic" type="image" id="prijava1" alt="Prijava" src="/web/2007/dugmici/posalji_1.jpg" onmouseover="ChangeImage('prijava1','/web/2007/dugmici/posalji_2.jpg')" onmouseout="ChangeImage('prijava1','/web/2007/dugmici/posalji_1.jpg')"&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div style="padding:12px;"&gt; &lt;a href="/portal/show?idc=1121"&gt;Da li ste novi BH Mobile korisnik?&lt;/a&gt;&lt;br /&gt; &lt;a href="/portal/show?idc=1121"&gt;Da li ste zaboravili lozinku(šifru)?&lt;/a&gt;&lt;br /&gt; &lt;/div&gt; &lt;/form&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt;&lt;/div&gt; </code></pre> <p>Form action is <a href="http://sso.bhmobile.ba/sso/login">http://sso.bhmobile.ba/sso/login</a>. How can I use this with HttpWebRequest to get a cookie and use some date from this page?</p>
<p>Make a new default.aspx, and put this in the code behind: I cant test any further based on your current question, because you didn't include a valid username/password.</p> <pre><code> using System; using System.Web; using System.Net; using System.IO; using System.Web.UI; using System.Web.UI.WebControls; namespace Foo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://sso.bhmobile.ba/sso/login"); req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)"; req.Method = "POST"; req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; req.Headers.Add("Accept-Language: en-us,en;q=0.5"); req.Headers.Add("Accept-Encoding: gzip,deflate"); req.Headers.Add("Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"); req.KeepAlive = true; req.Headers.Add("Keep-Alive: 300"); req.Referer ="http://sso.bhmobile.ba/sso/login"; req.ContentType = "application/x-www-form-urlencoded"; String Username = "username"; String PassWord = "Password"; StreamWriter sw = new StreamWriter(req.GetRequestStream()); sw.Write("application=portal&amp;url=http%3A%2F%2Fwww.bhmobile.ba%2Fportal%2Fredirect%3Bjsessionid%3D1C568AAA1FB8B5C757CF5F68BE6ECE65%3Ftype%3Dssologin%26url%3D%2Fportal%2Fshow%3Bjsessionid%3D1C568AAA1FB8B5C757CF5F68BE6ECE65%3Fidc%3D1023278&amp;realm=sso&amp;userid=" + Username + "&amp;password=" + password + "&amp;x=16&amp;y=11"); sw.Close(); HttpWebResponse response = (HttpWebResponse)req.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string tmp = reader.ReadToEnd(); foreach (Cookie cook in response.Cookies) { tmp += "\n" + cook.Name + ": " + cook.Value; } Response.Write(tmp); Response.End(); } } } </code></pre>
Why is modulus different in different programming languages? <p>Perl</p> <pre><code>print 2 % -18; </code></pre> <p>--></p> <pre><code>-16 </code></pre> <p>Tcl</p> <pre><code>puts [expr {2 % -18}] </code></pre> <p>--></p> <pre><code>-16 </code></pre> <p>but VBScript</p> <pre><code>wscript.echo 2 mod -18 </code></pre> <p>--></p> <pre><code>2 </code></pre> <p>Why the difference?</p>
<p>The <a href="http://en.wikipedia.org/wiki/Modulo_operation">wikipedia answer</a> is fairly helpful here.</p> <p>A short summary is that any integer can be defined as </p> <p>a = qn + r </p> <p>where all of these letters are integers, and </p> <p>0 &lt;= |r| &lt; |n|. </p> <p>Almost every programming language will require that (a/n) * n + (a%n) = a. So the definition of modulus will nearly always depend on the definition of integer division. There are two choices for integer division by negative numbers 2/-18 = 0 or 2/-18 = -1. Depending on which one is true for your language will usually change the % operator.</p> <p>This is because 2 = (-1) * -18 + (-16) and 2 = 0 * -18 + 2. </p> <p>For Perl the situation is complicated. <a href="http://perldoc.perl.org/perlop.html#Multiplicative-Operators">The manual page</a> says: "Note that when use integer is in scope, "%" gives you direct access to the modulus operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster. " So it can choose either option for Perl (like C) if use integer is in scope. If use integer is not in scope, the manual says " If $b is negative, then $a % $b is $a minus the smallest multiple of $b that is not less than $a (i.e. the result will be less than or equal to zero). "</p>
Best way to build a search function <p>I have a website that has over 400,000 items. Some similar, some vastly different. We want to provide a way to search these items the best way possible. After being delivered the website it was using full text indexing. The solution is basic at best, woefully inadequate at worst. </p> <p>So what is the best way to search these items? They are stored in a SQL Server Database (2005). Our website is designed in C# 2.0. </p> <p>Currently here is the process:</p> <ol> <li>User enters value into text box.</li> <li>We 'clean' this entry. Removing 'scary' characters that could be an attempted hack. Remove key words (and, or, etc..)</li> <li>Pass value into a stored procedure to return results.</li> <li>Return results.</li> </ol>
<p>Look at <a href="http://lucenenet.apache.org/" rel="nofollow">Lucene.NET</a>. I think it's a vast improvement over full-text search in SQL Server.</p>
What do < and > mean such as implements Comparable<BigInteger>? <p>In Java 1.4.2, class <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigInteger.html" rel="nofollow">java.math.BigInteger</a> implements interfaces Comparable, Serializable.</p> <p>In Java 1.5.0, class <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html" rel="nofollow">java.math.BigInteger</a> implements interfaces Serializable, Comparable&lt;BigInteger&gt;.</p> <p>This is just an example to help me ask about &lt; and &gt;. What I am really wondering about is the &lt; and &gt; stuff.</p> <p>My question is threefold: What does the &lt;BigInteger&gt; part of the implements statement mean, what is that syntax called, and what does it do?</p> <p>P.S. It's really hard to google for &lt; and &gt; and impossible to search SO for &lt; and &gt; in the first place.</p> <p>Thanks!</p>
<p>Read the <a href="http://java.sun.com/docs/books/tutorial/java/generics/index.html" rel="nofollow">Java Generics Tutorial</a>. The thing between the angle brackets is a type parameter - Comparable is a generic class, and in this case the angle brackets mean that the class is comparable to other BigIntegers.</p> <p>For a little more clarification in this case, have a look at the <a href="http://java.sun.com/j2se/1.5.0/docs/api/" rel="nofollow">Javadocs for Comparable</a> in 1.5. Note that it is declared as <code>Comparable&lt;T&gt;</code>, and that the <code>compareTo</code> method takes an argument of type <code>T</code>. The T is a type parameter that is "filled in" when the interface is used. Thus in this case, declaring you implement <code>Comparable&lt;BigInteger&gt;</code> implies that you must have a <code>compareTo(BigInteger o)</code> method. Another class might implement <code>Comparable&lt;String&gt;</code> meaning that it would have to implement a <code>compareTo(String o)</code> method.</p> <p>Hopefully you can see the benefit from the above snippet. In 1.4, the signature of <code>compareTo</code> could only ever take an <code>Object</code> since all kinds of classes implemented Comparable and there was no way to know exactly what was needed. With generics, however, you can specify that you are comparable with respect to a particular class, and then write a more specific compareTo method that only takes that class as a parameter.</p> <p>The benefits here are two-fold. Firstly, you don't need to do an <code>instanceof</code> check and a cast in your method's implementation. Secondly, the compiler can do a lot more type checking at compile time - you can't accidentally pass a String into something that implements <code>Comparable&lt;BigInteger&gt;</code>, since the types don't match. It's much better for the compiler to be able to point this out to you, rather than have this cause a runtime exception as would have generally happened in non-generic code.</p>
Only create a TFS work item on a new failed build <p>I've seen the post about disabling work item creation on all failed builds, but I'd like to have TFS only create a work item on the first failure. We have a very complicated legacy system that involves VB6 COM components and frequently have build failures on the build server that track back to some funkiness VB6 does with binary files (frx, ctl, etc. -- if you haven't had to deal with that in a while, you don't want to). The only way to resolve those issues is to try to make updates on a developer machine, then check in the files and run the build again (since the build doesn't fail on the dev machine). So we may have three or four (or more) failed builds before we get a success, which means we'll have three or four work items to close out.</p> <p>Ideally, I'd like to have the following:</p> <ol> <li>Joe checks in a change that causes the build to fail</li> <li>A work item gets created and assigned to Joe</li> <li>Joe checks in another change and the build still fails</li> <li>No additional work item creation</li> <li>Joe checks in a change the build succeeds</li> <li>The work item assigned to Joe in step 2 above gets marked as Closed</li> </ol> <p>But I'd be happy with just steps 1 through 4.</p>
<p>How would you determine that the second failed build was related to the first one, since there's an additional check-in involved? What happens if the next check-in is actually additional code committed by another developer - you'd want them to know their code broke the build, or that it's still broken, even though according to your steps, nothing would be triggered.</p> <p>You'd either need to find a way to link the builds - for example, track who the auto-work-item is assigned to and then not create another work-item for checkins from that developer until there's a successful build, and maybe you could somehow queue up the builds for the other developers. I'm not really sure how you'd do it.</p> <p>Does this move you in the right direction?</p>
Change the ruby process name in top <p>I would like to change the name of the ruby process that gets displayed in the linux/unix top command. I have tried the </p> <pre><code>$0='miname' </code></pre> <p>approach but it only works with the ps command and in top the process keeps getting displayed as "ruby"</p>
<p>Dave Thomas had an interesting <a href="http://pragdave.blogs.pragprog.com/pragdave/2008/11/trivial-request-logging-for-rails.html">post</a> on doing this in rails. There's nothing rails specific about the actual process name change code. He uses the <code>$0='name'</code> approach. When I followed his steps the name was changed in <code>ps</code> and <code>top</code>. </p> <p>In the post he suggests using the <code>c</code> keyboard command if your version of top doesn't show the short version of the command by default.</p>
Visual C++ 2005 hangs during qt builds <p>At my shop, the main product app is a mongrel built on MFC, QT and other random things devs have thrown in over the years. In the current stack, Qt toolkit is on the way out, but still features heavily.</p> <p>If I have SQL 2005 Management studio open and have to do a full build, it usually hangs a CPU (even after the offending process is taken out back and shot...) during the qt specific parts of the build (Moc'ing and UIC'ing)</p> <p>has anyone seen anything like this? any ideas what the problem could be?</p>
<p>In my experience, some of these tools are capable of looping forever (qt4: lupdate/lrelease for sure).</p>
ASP.NET MVC Standard Link/Href As Save Button And Model IS NUll <p>Okay so, i am totally new to MVC and I'm trying to wrap my head around a few of the concepts. I've created a small application...</p> <p>This application has a view for creating a new Individual record. The view is bound to a model <strong>ViewPage</strong>... And I have a associated <strong>IndividualController</strong> which has a <strong>New</strong> method...</p> <p>The <strong>New</strong> method of the IndividualController looks like this...</p> <pre><code>public ActionResult New() { var i = new Individual(); this.Title = "Create new individual..."; i.Id = Guid.NewGuid(); this.ViewData.Model = new Individual(); return View(); } </code></pre> <p>Now, the above all seems to be working. When the view loads I am able to retrieve the data from the Individual object. The issue comes into play when I try and save the data back through the controller...</p> <p>In my <strong>IndividualController</strong> I also have a <strong>Save</strong> method which accepts an incoming parameter of type <strong>Individual</strong>. The method looks like...</p> <pre><code> public ActionResult Save(IndividualService.Individual Individual) { return RedirectToAction("New"); } </code></pre> <p>Now, on my view I wanted to use a standard html link/href to be used as the "Save" button so I defined an ActionLink like so...</p> <pre><code> &lt;%=Html.ActionLink("Save", "Save") %&gt; </code></pre> <p>Also, defined in my view I have created a single textbox to hold the first name as a test like so...</p> <pre><code> &lt;% using (Html.BeginForm()) { %&gt; &lt;%=Html.TextBox("FirstName", ViewData.Model.FirstName)%&gt; &lt;% } %&gt; </code></pre> <p>So, if I put a break point in the <strong>Save</strong> method and click the "Save" link in my view the break point is hit within my controller. The issue is that the input parameter of the Save method is null; even if I type a value into the first name textbox...</p> <p>Obviously I am doing something completely wrong. Can someone set me straight...</p> <p>Thanks in advance...</p>
<p>Your New controller method doesn't need to create an individual, you probably just want it to set the title and return the view, although you may need to do some authorization processing. Here's an example from one of my projects:</p> <pre><code> [AcceptVerbs( HttpVerbs.Get )] [Authorization( Roles = "SuperUser, EditEvent, EditMasterEvent")] public ActionResult New() { ViewData["Title"] = "New Event"; if (this.IsMasterEditAllowed()) { ViewData["ShowNewMaster"] = "true"; } return View(); } </code></pre> <p>Your Save action should take the inputs from the form and create a new model instance and persist it. My example is a little more complex than what I'd like to post here so I'll try and simplify it. Note that I'm using a FormCollection rather than using model binding, but you should be able to get that to work, too.</p> <pre><code> [AcceptVerbs( HttpVerbs.Post )] [Authorization( Roles = "SuperUser, EditEvent, EditMasterEvent")] public ActionResult Save( FormCollection form ) { using (DataContext context = ...) { Event evt = new Event(); if (!TryUpdateModel( evt, new [] { "EventName", "CategoryID", ... })) { this.ModelState.AddModelError( "Could not update model..." ); return View("New"); // back to display errors... } context.InsertOnSubmit( evt ); context.SubmitChanges(); return RedirectToAction( "Show", "Event", new { id = evt.EventID } ); } } </code></pre>
Can the DllMain of an .exe be called? <p>My question is not exactly the same as <a href="http://stackoverflow.com/questions/186502/dllmain-in-an-exe">this one</a> (it's not theoretical, there is only a main thread without message loop, InitInstance and ExitInstance are no fitting calls).</p> <p>I'm using a console app without message loop; this app loads an exe with the LoadLibrary function, so that it can use its exported functions. Bad news: the DllMain function of the exe is not called (and I verified the symbols tables, using a def file, DllMain appears correctly); <a href="http://msdn.microsoft.com/en-us/library/ms682583.aspx" rel="nofollow">the doc says</a> it's called if the loaded module is a DLL (too bad).</p> <p>What are the conditions (if they exist) which could lead to the execution of the exe's DllMain function when LoadLibrary is called (and maybe again when FreeLibrary is called)?</p> <p>Best regards</p>
<p>The most obvious condition is that the process calling LoadLibrary() explicitly gets GetProcAddress("DllMain") and then calls it.</p>
PHP Get Source and Search for Word <p>I need help i want to code a program that search for a word inside the source code. </p> <p>Here a Example in Python: </p> <pre><code>import urllib2, re site = "http://stackoverflow.com/" tosearch = "Questions" source = urllib2.urlopen(site).read() if re.search(tosearch,source): print "Found The Word", tosearch </code></pre>
<pre><code>&lt;?php $site = "http://stackoverflow.com/"; $tosearch = "Questions"; $source = file_get_contents($site); if(preg_match("/{$tosearch}/", $source)): // fixed, thanks meouw echo "Found the the word {$tosearch}"; endif; ?&gt; </code></pre>
C#: Generic sorted container that can return the sorted position of a newly added object? <p>I need a generic container that keeps its elements sorted and can be asked where (at which position) it would insert a new element, without actually inserting it.</p> <p>Does such a container exist in the .NET libraries? The best illustration is an example (container sorts characters by ASCII value, let's assume unicode does not exist):</p> <pre><code>sortedContainer.Add('d'); sortedContainer.Add('b'); sortedContainer.Add('g'); //container contains elements ordered like 'b' 'd' 'g' //index --------------------------------&gt; 0 1 2 sortedContainer.GetSortedIndex('a'); //returns 0 sortedContainer.GetSortedIndex('b'); //returns 0 sortedContainer.GetSortedIndex('c'); //returns 1 sortedContainer.GetSortedIndex('d'); //returns 1 sortedContainer.GetSortedIndex('e'); //returns 2 sortedContainer.GetSortedIndex('f'); //returns 2 sortedContainer.GetSortedIndex('g'); //returns 2 sortedContainer.GetSortedIndex('h'); //returns 3 [...] </code></pre> <p>The search for the position should take advantage of the fact that the elements are sorted.</p>
<p>If you sort a <a href="http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx" rel="nofollow"><code>List&lt;T&gt;</code></a> and then use <a href="http://msdn.microsoft.com/en-us/library/3f90y839.aspx" rel="nofollow"><code>List&lt;T&gt;.BinarySearch</code></a> it will give you the index of the entry if it exists, or the bitwise complement of the index of where it <em>would</em> be inserted if you inserted then sorted. From that, you should easily be able to build your method.</p> <p>Sample code matching your example, but not the results - if you look at your sample, you've only got 3 entries, so it doesn't make sense for 'h' to return 4 or 'g' to return 3. I hope that's your example which is slightly off, rather than me misunderstanding the problem :) Note that the sorting isn't automatic - you'd have to sort the list explicitly before calling GetSortedIndex.</p> <pre><code>using System; using System.Collections.Generic; static class Test { static int GetSortedIndex&lt;T&gt;(this List&lt;T&gt; list, T entry) { int index = list.BinarySearch(entry); return index &gt;= 0 ? index : ~index; } static void Main() { List&lt;char&gt; container = new List&lt;char&gt; { 'b', 'd', 'g' }; Console.WriteLine(container.GetSortedIndex('a')); Console.WriteLine(container.GetSortedIndex('b')); Console.WriteLine(container.GetSortedIndex('c')); Console.WriteLine(container.GetSortedIndex('d')); Console.WriteLine(container.GetSortedIndex('e')); Console.WriteLine(container.GetSortedIndex('f')); Console.WriteLine(container.GetSortedIndex('g')); Console.WriteLine(container.GetSortedIndex('h')); } } </code></pre>
Going beyond the iframe <p>Hey! I am trying to get an iframe B communicate with site A. I've searched and searched and every thing I read says it's impossible if they are of different domain (the iframe src is coming from a sub domain).</p> <p>I want to communicate because my company has ads on its page and it needs to refresh them every X minutes. This is ok if it's a normal add, but some adds extend. Like I have adds that start with 300x250 and then get to 800x300. I wanted to communicate to the iframe to know when the add was going to expand but it just doesn't seem to be a way. Is there any way to let the add go beyond the initial size of the iframe? </p> <p>If the add is 300x250 the iframe will also have 300x250, but when the add expands it get's cut off, so I really need to either get the iframe to expand also or have the add go beyond the size of the iframe.</p> <p>Anyone know how to do this or have some tutorial that shows how to have some basic communication to an iframe.</p> <p>Note: There are some websites that also serve adds that have a totally different domain, so it would be great if someone knew how to make it go beyond the iframe.</p> <p>Thanks</p>
<p>If you want the two iframes to communicate and you say one is on a different subdomain but the <strong>same top-level domain</strong>, you can do inter-frame scripting. See <a href="http://ajaxian.com/archives/how-to-make-xmlhttprequest-calls-to-another-server-in-your-domain" rel="nofollow">http://ajaxian.com/archives/how-to-make-xmlhttprequest-calls-to-another-server-in-your-domain</a>.</p> <p>The trick is to get page A and B to both set</p> <pre><code>document.domain = 'SameTopLevelDomain.com'; </code></pre> <p>and the browser will then let the pages communicate (eg grab data from the other, call functions, etc).</p> <p>However if the two pages are on different domains altogether, you'd have to take the server-side proxy approach as answered earlier.</p>
SQL nvl equivalent - without if/case statements & isnull & coalesce <p>Are there any nvl() equivalent functions in SQL?</p> <p>Or something close enough to be used in the same way in certain scenarios?</p> <p><hr> UPDATE: <br>no if statements<br>no case statements<br>no isnull<br>no coalesce<hr><br></p> <pre><code>select nvl (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581; (expression) SODIUFOSDIUFSDOIFUDSF 1 row(s) retrieved. select isnull (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581; 674: Routine (isnull) can not be resolved. Error in line 1 Near character position 8 select coalesce (purge_date,"SODIUFOSDIUFSDOIFUDSF") from id_rec where id=36581; 674: Routine (coalesce) can not be resolved. Error in line 1 Near character position 8 select decode(purge_date, NULL, "01/01/2009", purge_date) from id_rec where id=74115; 800: Corresponding types must be compatible in CASE expression. Error in line 1 Near character position 57 </code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/ms184325.aspx">ISNULL</a> (for a single replace)</p> <p>or</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms190349.aspx">COALESCE</a> (Returns the first nonnull expression among its arguments.)</p>
Can I fill in an encypted PDF with iTextSharp? <p>I have a fillable, saveable PDF file that has an owner password (that I don't have access to). I can fill it out in Adobe reader, export the FDF file, modify the FDF file, and then import it. </p> <p>Then I tried to do it with iText(Sharp). I can't create a PdfStamper from my PdfReader because I didn't provide the owner password to the reader. Is there any way to do this programmatically or must I recreate the document? Even using FdfReader requires a PdfStamper. Am I missing anything? Anything legal that is - I'm pretty sure I could hack the document, but I can't. Ironically, recreating it would probably be ok. </p>
<p>[I found this question several months after it was posted and I'm posting this solution now for anyone who comes across this question in a search.]</p> <p>I was in the exact same situation: my customer had a PDF with fillable fields that I needed to programmatically access. Unfortunately the PDF was password protected and they didn't have the password so I found couldn't work with their file.</p> <p>What I discovered was that iTextSharp version 4.0.4 (and later) enforces password restrictions, earlier versions did not. Check out <a href="http://www.opensubscriber.com/message/itext-questions@lists.sourceforge.net/7709373.html" rel="nofollow">this iText mailing list archive thread</a>, and the response from Paulo Soares (one of the iTextSharp developers).</p> <p>So I downloaded version 4.0.3 and sure enough it worked. In my case I didn't even have to change my code to use this older version.</p> <p>You can <a href="http://sourceforge.net/projects/itextsharp/files/itextsharp/" rel="nofollow">download 4.0.3 (and all other versions) at SourceForge</a>.</p>