instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I have a requirement to make a large amount of code MISRA compliant.<br>
First question: Can somebody to give an <strong>estimation</strong> for passing well written code for embedded system based on experience. I understand that "well written" is poorly defined and vague so i ask for raw estimation.<br>
Second question: Any recommendation for tool that can be customizable (i.e allowing suppress specific warnings) and used in automatic build environment (i.e command line interface)<br>
Any other useful suggestions that can help with this task.<br>
Thanks Ilya. </p>
|
<p>I also highly recommend PC-Lint. If you happen to be compiling your code with Visual Studio I recommend a plug-in 'Visual Lint' from Riverblade. If you cannot compile the code in Visual Studio, you can still run PC-Lint from the command line to good effect.</p>
<p>Some embedded system compilers provide MISRA compliance testing as compiler warnings. I use the IAR compiler for Arm7/Arm9 development. It provides an easy to configure MISRA compliance checklist right in the compiler setup.</p>
<p>It is difficult to come up with a rule of thumb for estimating the time it would take you to make some well written code MISRA compliant. A lot depends on the existing coding habits of the programmers and how closely they follow the MISRA rules in the first place.</p>
<p>Rough estimates:<br>
2 - 3 days to become adept at PC-Lint usage.<br>
Initial pass at making existing code MISRA compliant: 10 to 25 percent of the time spent writing the code in the first place.<br>
Keeping code MISRA compliant: 5 to 10 percent added to code development. Half of this cost is changing the habits of your coders to follow the 'MISRA way' of doing things. The other half is the extra cost of code testing and inspection to ensure MISRA compliance.</p>
|
<p>I appreciate that this is an old question, but for the benefit of any other Archaeologists (or searchers), it is important to remember that MISRA provides <strong>guidelines</strong> that should not always be blindly followed.</p>
<p>I commend writing new code with MISRA in mind; therefore it will be a lot easier to stay compliant.</p>
<p>However, this is not always possible - and in particular, when trying to reverse engineer code to meet the guidelines. In this case I suggest that you focus on the Required rules, and treat the Advisories as a bonus... cost v benefit applies here too!</p>
<p>Also, bear in mind that there is a deviation process - it is better to keep clean and maintainable code with a deviation, than to contrive some compliant but illegible spaghetti.</p>
| 8,848
|
<p>I am creating a new build process for a DotNet project which is to be held in Subversion.</p>
<p>For each dll/exe that I compile (via Nant) I would like to include 2 additional attibutes in the dlls that are built.</p>
<p>I already understand the workings of the 'asminfo' nant task. But I need help retrieving the information which I hope to embed in my binaries.</p>
<p>The build will always happen from a full working copy (checked out by the build process itself.) and will therefore always have an .svn directory available.</p>
<p>The attributes I want to add are RepositoryVersion and RepositoryPath. (I understand that these are not the names this information goes by in svn)</p>
<p>In order to do this I will need to extract the RepositoryVersion and RepositoryPath represented by the working copy folder that the BuildFile sits within.</p>
<p><strong>How do I extract this information from any given .svn folder into the 2 nant variables?</strong> </p>
|
<p>Firstly, you can use "svn info --xml >out.xml" to get the svn information to a text file. You can then use a Nant xml-peek to get a value out of the file into a variable.</p>
<pre><code><xmlpeek file="out.xml" xpath="/info/entry/url" property="svn.url" />
</code></pre>
|
<p>The entries in the .svn directory are not really meant to be accessed directly. I don't know much about what you're doing but I'd suggest you use the mechanism you use to checkout the project to find the HEAD version and path. (I'd actually assume that becuase you are checking out the project you already know the path but maybe that is not so).</p>
<p>Sorry I can't give more information than this.</p>
| 23,211
|
<p>I'm looking for a plugin for jQuery that can validate as a key is pressed and after it loses focus (text boxes). </p>
<p>I'm currently using <a href="http://www.overset.com/2008/07/31/jval-jquery-form-field-validation-plugin/" rel="nofollow noreferrer">jVal - jQuery Form Field Validation Plugin</a>. It works pretty good. The only issue I have is that I can only use a generic error message.</p>
<p>For example:
I need a string to between 2 and 5 characters. If its too short I would like to display an error message that indicates it to short, equally if its too long. I know I could display an error message that requires the string to between 2 and 5 characters. <strong>The validation that is being done is more complicated.</strong> </p>
<p>Any ideas of other validators or how I could use this plug-in to display unique error messages.</p>
<hr>
<p>Edit:</p>
<p>The validation tool needs to prevent particular letters or numbers and not require a form. </p>
<p>Thanks</p>
|
<p>This one looks like it would fit your description:</p>
<ul>
<li><a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="nofollow noreferrer">jQuery plugin:validation (Homepage)</a></li>
<li><a href="http://jquery.bassistance.de/validate/demo/" rel="nofollow noreferrer">demo</a></li>
<li><a href="http://docs.jquery.com/Plugins/Validation" rel="nofollow noreferrer">API docs</a></li>
</ul>
<p>Here's a snippet of code copied from the source of the demo:</p>
<pre><code>// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true,
email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above"
},
email: "Please enter a valid email address",
agree: "Please accept our policy"
}
});
</code></pre>
|
<p>I've use jQuery plugin:validation. it works pretty with creating DOM elements on the fly. When creating them on the fly make sure the attributes name and ID are included. I'm pretty sure the plugin uses the name attribute to find them in the html. If the name is missing they can't be found. </p>
<p>Also this might be another good validation tool.
<a href="http://www.livevalidation.com" rel="nofollow noreferrer">http://www.livevalidation.com</a></p>
| 25,655
|
<p>Can you package up the .Net framework in an installer created in Visual Studio? If so how?</p>
<p>I've seen this done with Install4J packaging a JVM but I think that was the JVM to run Install4J.</p>
|
<p>I just learned this lesson about deployment projects: the .MSI file delivers the application to the target machine, but that SETUP.EXE is the bootstrapper that installs prerequisites, such as the .NET Framework, MDAC, or Windows Installer. I specified the .NET Framework as a prerequisite but, because I only distributed the .MSI, no checks were run and the app crashed when starting up without the framework. </p>
<p>To ensure your prerequisites are on the target machine, you need to distribute the setup.exe too.</p>
|
<p>Sucky, yeah - I created an installer just recently before realizing that the .Net Framework (which was one of the things I needed to install) was required. I ended up making a c++ program that installed .Net before my installer was launched.</p>
<p>Seems kind of odd to me to offer the ability to create an installer and not have it offer to install what it needs to run. Kinda pointless at that point, eh? Unless you know that every machine you give the installer to will have the necessary components...</p>
<p>Oh well, live and learn</p>
| 19,690
|
<p>In some asp tutorials, like <a href="https://web.archive.org/web/20211020111619/https://www.4guysfromrolla.com/webtech/050900-1.shtml" rel="nofollow noreferrer">this</a>, i observe the following pattern:</p>
<blockquote>
<p>Application.Lock</p>
<p>'do some things with the application object</p>
<p>Application.Unlock</p>
</blockquote>
<p>However, since web pages can have multiple instances, there is an obvious concurrency problem. So my questions are the following:</p>
<p>What if one page tries to lock while the object is already locked?</p>
<p>Is there a way to detect whether the application object is locked?</p>
<p>Is it better to just work on an unlocked application object or does that have other consequences?</p>
<p>What if there is only one action involving the application object? ~Is there a reason to lock/unlock in that case?</p>
|
<p>From the <a href="http://msdn.microsoft.com/en-us/library/ms525184.aspx" rel="nofollow noreferrer">MSDN documentation</a>:</p>
<p>The <code>Lock</code> method <strong>blocks other clients</strong> from modifying the variables stored in the Application object, ensuring that <strong>only one client at a time</strong> can alter or access the Application variables.</p>
<p>If you <strong>do not call</strong> the <code>Application.Unlock</code> method explicitly, the server unlocks the locked Application object when the .asp file <strong>ends or times out</strong>.</p>
<p>A lock on the Application object persists for a very short time because the application object is unlocked when the page completes processing or times out.</p>
<p>If one page locks the application object and a second page tries to do the same while the first page still has it locked, the second page will wait for the first to finish, or until the <code>Server.ScriptTimeout</code> limit is reached.</p>
<p>An example:</p>
<pre><code><%@ Language="VBScript" %>
<%
Application.Lock
Application("PageCalls") = Application("PageCalls") + 1
Application("LastCall") = Now()
Application.Unlock
%>
This page has been called <%= Application("PageCalls") %> times.
</code></pre>
<p>In the example above, the <code>Lock</code> method <strong>prevents more than one client at a time from accessing the variable PageCalls</strong>. If the application had not been locked, two clients could simultaneously try to increment the variable PageCalls. </p>
|
<p>If one page tries to lock the Application object while it is already locked, it will wait until the page holding the lock has released it. This will normally be quick (ASP code should only generally hold the lock for long enough to access the shared object that's stored in Application).</p>
| 20,566
|
<p>I am working on a program which manipulates images of different sizes. Many of these manipulations read pixel data from an input and write to a separate output (e.g. blur). This is done on a per-pixel basis.</p>
<p>Such image mapulations are very stressful on the CPU. I would like to use multithreading to speed things up. How would I do this? I was thinking of creating one thread per row of pixels.</p>
<p>I have several requirements:</p>
<ul>
<li>Executable size must be minimized. In other words, I can't use massive libraries. What's the most light-weight, portable threading library for C/C++?</li>
<li>Executable size must be minimized. I was thinking of having a function forEachRow(fp* ) which runs a thread for each row, or even a forEachPixel(fp* ) where fp operates on a single pixel in its own thread. Which is best?
<ul>
<li>Should I use normal functions or functors or functionoids or some lambda functions or ... something else?</li>
<li>Some operations use optimizations which require information from the previous pixel processed. This makes forEachRow favorable. Would using forEachPixel be better even considering this?</li>
</ul></li>
<li>Would I need to lock my read-only and write-only arrays?
<ul>
<li>The input is only read from, but many operations require input from more than one pixel in the array.</li>
<li>The ouput is only written once per pixel.</li>
</ul></li>
<li>Speed is also important (of course), but optimize executable size takes precedence.</li>
</ul>
<p>Thanks.</p>
<p><strong>More information on this topic for the curious: <a href="https://stackoverflow.com/questions/615264/c-parallelization-libraries-openmp-vs-thread-building-blocks">C++ Parallelization Libraries: OpenMP vs. Thread Building Blocks</a></strong></p>
|
<p>If your compiler supports <a href="http://openmp.org/wp/" rel="noreferrer">OpenMP</a> (I know <a href="http://msdn.microsoft.com/en-us/library/tt15eb9t(VS.80).aspx" rel="noreferrer">VC++ 8.0 and 9.0</a> do, as does gcc), it can make things like this much easier to do. </p>
<p>You don't just want to make a lot of threads - there's a point of diminishing returns where adding new threads slows things down as you start getting more and more context switches. At some point, using too many threads can actually make the parallel version slower than just using a linear algorithm. The optimal number of threads is a function of the number of cpus/cores available, and the percentage of time each thread spends blocked on things like I/O. Take a look at <a href="http://www.ddj.com/cpp/211800538" rel="noreferrer">this article</a> by Herb Sutter for some discussion on parallel performance gains. </p>
<p>OpenMP lets you easily adapt the number of threads created to the number of CPUs available. Using it (especially in data-processing cases) often involves simply putting in a few <code>#pragma omp</code>s in existing code, and letting the compiler handle creating threads and synchronization.</p>
<p>In general - as long as data isn't changing, you won't have to lock read-only data. If you can be sure that each pixel slot will only be written once and you can guarantee that all the writing has been completed before you start reading from the result, you won't have to lock that either. </p>
<p>For OpenMP, there's no need to do anything special as far as functors / function objects. Write it whichever way makes the most sense to you. Here's an image-processing example from <a href="http://software.intel.com/en-us/articles/getting-started-with-openmp" rel="noreferrer">Intel</a> (converts rgb to grayscale):</p>
<pre><code>#pragma omp parallel for
for (i=0; i < numPixels; i++)
{
pGrayScaleBitmap[i] = (unsigned BYTE)
(pRGBBitmap[i].red * 0.299 +
pRGBBitmap[i].green * 0.587 +
pRGBBitmap[i].blue * 0.114);
}
</code></pre>
<p>This automatically splits up into as many threads as you have CPUs, and assigns a section of the array to each thread.</p>
|
<p>There's another option of using assembly for optimization. Now, one exciting project for dynamic code generation is <a href="https://gna.org/svn/?group=softwire" rel="nofollow noreferrer">softwire</a> (which dates back awhile - <a href="http://softwire.sourceforge.net/" rel="nofollow noreferrer">here</a> is the original project's site). It has been developed by Nick Capens and grew into now commercially available <a href="http://www.transgaming.com/products/swiftshader/" rel="nofollow noreferrer">swiftshader</a>. But the spin-off of the original softwire is still available on gna.org.
<p><a href="http://www.flipcode.com/archives/Pure_Run-Time_Assembler.shtml" rel="nofollow noreferrer">This</a> could serve as an introduction to his solution.
<p>Personally, I don't believe you can gain significant performance by utilizing multiple threads for your problem.</p>
| 42,308
|
<p>It's easy to wrap optional memcached caching around your existing database queries. For example:</p>
<p>Old (DB-only):</p>
<pre><code>function getX
x = get from db
return x
end
</code></pre>
<p>New (DB with memcache):</p>
<pre><code>function getX
x = get from memcache
if found
return x
endif
x = get from db
set x in memcache
return x
end
</code></pre>
<p>The thing is though, that's not always how you want to cache. For instance take the following two queries:</p>
<pre><code>-- get all items (recordset)
SELECT * FROM items;
-- get one item (record)
SELECT * FROM items WHERE pkid = 42;
</code></pre>
<p>If I was to use the above pseudo-code to handle the caching, I would be storing all fields of item 42 twice. Once in the big record set and once on its own. Whereas I'd rather do something like this:</p>
<pre><code>SELECT pkid FROM items;
</code></pre>
<p>and cache that index of PK's. Then cache each record individually as well.</p>
<p>So in summary, the data access strategy that will work best for the DB doesn't neatly fit the memcache strategy. Since I want the memcache layer to be optional (i.e. if memcache is down, the site still works) I kind of want to have the best of both worlds, but to do so, I'm pretty sure I'll need to maintain a lot of the queries in 2 different forms (1. fetch index, then records; and 2. fetch recordset in one query). It gets more complicated with pagination. With the DB you'd do LIMIT/OFFSET SQL queries, but with memcache you'd just fetch the index of PK's and then batch-get the relevant slice of the array.</p>
<p>I'm not sure how to neatly design this, does anyone have any suggestions?</p>
<p>Better yet, if you've come up against this yourself. How do you handle it?</p>
|
<p>Read about the <a href="http://martinfowler.com/eaaCatalog/identityMap.html" rel="nofollow noreferrer">Identity Map</a> pattern. This is a way to make sure you only keep one copy of a given row in your application space. Whether you store it in memcached or just plain objects, this is a way to handle what you want. I would guess that Identity Map is best used when you typically fetch one row at a time. </p>
<p>When you fetch whole subsets of a table, then you have to process each row individually. You might frequently have the dilemma of whether you're getting the best use out of your cache, because if 99% of your rows are in the cache but one requires fetching from the database, you have to run the SQL query anyway (at least once). </p>
<p>You could transform the SQL query to fetch only rows that aren't in the cache, but it's nontrivial to perform this transformation automatically without making the SQL query more costly.</p>
|
<p>Well, I guess that's something you'll have to live with. Memcahced will work the best if you don't really do stuff in batches. For example it's great for stuff like "where are the things for this user? Here is a bunch of things for this user." This doesn't really mean that this query doesn't do batches. Of course it will - if some of the user stuff is stuff like his/her posts.</p>
<p>I guess the problem you'll have is cases where you are mixing queries that need to get an item from the DB on its own and some that get bunch of the same kind of the previous items.</p>
<p>There is always a flip side to the situation. If you really want to get hairy with your implementation you can change your batch queries to not include the items already present in memcached.Very very ugly...</p>
<p>In my opinion it always comes down to "which queries do I <strong>really</strong> want to cache?"</p>
<p>EDIT:</p>
<p>The way I would go about this is:</p>
<ul>
<li>Single-item query - if in memcached, use that one, otherwise fetch from DB and update memcached.</li>
<li>Batch query - don't worry about which items are in memcached, just get everything and update memcached.</li>
</ul>
<p>This of course assumes that the batch queries already take hell a lot more time to complete and so it I'm already spending so much time I can live with external lookups to already cached items.</p>
<p>However, eventually, your cache will contain a lot of the items if you use the batch queries a lot. Therefore you'll have to strike the balance for determining at which point you still want to perform the database lookups. Good thing is if the batch query is earlier in the life cycle of your applications, then everything will be cached earlier. After the first batch query you can tell yourself that you don't need to fetch from DB anymore unless the data in the cache is invalidated by updates or deletes.</p>
| 34,898
|
<p>I'm building a fairly large website and my .htaccess is starting to feel a bit bloated, is there a way of replacing my current system of - one rule for each of the possibile number of vars that could be passed, to one catch all expression that can account for varying numbers of inputs ?</p>
<p>for example I currently have:</p>
<pre><code>RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4&$5=$6
RewriteRule ^([a-z]+)/([^/]*)/([^/]*)/([^/]*)$ /index.php?mode=$1&id=$2&$3=$4
RewriteRule ^([a-z]+)/([^/]*)$ /index.php?mode=$1&id=$2
RewriteRule ^([a-z]+)$ /index.php?mode=$1
</code></pre>
<p>the first backreference is always the <em>mode</em> and (if any more exist) the second is always <em>id</em>, thereafter any further backreferences alternate between the name of the input and its value</p>
<pre><code>http://www.example.com/search
http://www.example.com/search/3039/sort_by/name_asc/page/23
</code></pre>
<p>I would love to be able to have one expression to gracefully handle all the inputs.</p>
|
<p>Do like Drupal:</p>
<pre><code> RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
</code></pre>
<p>And then handle all the stuff in your script using php code something like this</p>
<pre><code>$pathmap = ();
if ($_GET["q"]){
$path = split("/", $_GET["q"]);
for ($i=0; $i+1<count($path); $i++){
$pathmap[$path[$i]] = $path[$i+1];
$i++;
}
}
</code></pre>
|
<p>I don't believe that their is a way - but I'd say that your best bet would be to have the script "index.php" process a path instead of having to do so many back references.</p>
<p>So for example, your rewriterule would be </p>
<pre><code>RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</code></pre>
<p>Or similar... This would then make the $_SERVER['REQUEST_URI'] variable contain the path information, which you can split and parse.</p>
<pre><code>$path = split('/', $_SERVER['REQUEST_URI']);
array_shift($path); // We always have a first null value
$mode = array_shift($path);
</code></pre>
<p>This ends up with $mode containing the mode, and $path containing an array of elements that are the rest of your path, so</p>
<pre><code>http://example.com/foo/bar/baz
</code></pre>
<p>Would leave you with $mode being 'foo' and $path being an array containing 'bar' and 'baz'</p>
| 14,351
|
<p>I have a c# form (let's call it MainForm) with a number of custom controls on it. I'd like to have the MainForm.OnClick() method fire anytime someone clicks on the form regardless of whether the click happened on the form or if the click was on one of the custom controls. I'm looking for behavior similar to the KeyPreview feature of forms except for mouse clicks rather than key presses.</p>
|
<p>In the form's ControlAdded event, add a MouseClick handler to the control, with the Address of the form's click event. I haven't tested this, but it might work.</p>
<pre><code>Private Sub Example_ControlAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded
AddHandler e.Control.MouseClick, AddressOf Example_MouseClick
End Sub
Private Sub Example_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseClick
MessageBox.Show("Click")
End Sub
</code></pre>
|
<p>Catching a click on an open space on the form is easy, but to get a click that's actually on a control, you'll need the cooperation of that control to send it to the form.</p>
<p>One possibility is to place a transparent control over the entire form, and accept clicks onto that, deal with them, and then pass them onto the proper control underneath.</p>
| 21,773
|
<p>I have a single user java program that I would like to have store data in a light weight database such as Derby or Sqlite. I would like to use a data abstraction layer in my program. Hibernate appears to require a lot of configuration and is overkill for what I need. What are light weight alternatives to Hibernate?</p>
|
<p>Hibernate requires next to zero configuration if you use annotations. It even can auto-discover mapped beans in the classpath! I don't see any alternative to it from both simplicity <strong>and</strong> power point of view.</p>
<p>It can also expose itself as JPA, which is (IMHO) even simpler.</p>
|
<p>Kiteframework is also very light orm framework. It provides almost all db operation with minimal configurations.</p>
<p><a href="http://deipakgarg.github.com/Kite-ORM/" rel="nofollow">http://deipakgarg.github.com/Kite-ORM/</a></p>
<p><strong>Disclosure: I am the author of this project</strong></p>
| 37,924
|
<p>I would like to be able to Serialize a DateTime with a specific Time Zone that is not the server, nor is it client time. Basically, any time zone.
Is it possible to override the DateTime serialization, in .Net2.0 webservices?</p>
<p>I compile an xmlschema using xsd.exe, so I made an attempt using XmlSchemaImporter.</p>
<p>The OnSerialize examples show value changes, but not changes to the output format.</p>
<p>XmlSchemaImporter, loaded it into the gac, ran xsd.exe, and generated code that has the class I want... but that class is an attribute, which end up not being able to be reflected.</p>
<blockquote>
<p>[InvalidOperationException: Cannot
serialize member 'metadataDateTime' of
type Cuahsi.XmlOverrides.W3CDateTime.
XmlAttribute/XmlText cannot be used to
encode complex types.]</p>
</blockquote>
<p>Generated code</p>
<pre><code>[System.Xml.Serialization.XmlAttributeAttribute()]
public Cuahsi.XmlOverrides.W3CDateTime dateTime {
get {
return this.dateTimeField;
}
set {
this.dateTimeField = value;
}
}
</code></pre>
<p>XmlSchemaImporter</p>
<pre><code>public class ImportW3CTime :
System.Xml.Serialization.Advanced.SchemaImporterExtension
{
public override string ImportSchemaType(string name, string ns,
XmlSchemaObject context, XmlSchemas schemas,
XmlSchemaImporter importer, CodeCompileUnit compileUnit,
CodeNamespace mainNamespace, CodeGenerationOptions options,
CodeDomProvider codeProvider)
{
if (XmlSchema.Namespace == ns)
{
switch (name)
{
case "dateTime":
string codeTypeName = typeof(W3CDateTime).FullName;
CodeTypeDeclaration cls =
new CodeTypeDeclaration("W3CDateTime");
cls.IsStruct = true;
cls.Attributes = MemberAttributes.Public;
cls.BaseTypes.Add("dateTime");
mainNamespace.Types.Add(cls);
return codeTypeName;
default: return null;
}
}
else { return null; }
}
}
</code></pre>
<p><strong>Addendum 1:</strong>
I just tired DateTimeoffset, and that still causes an error when the class is tagged like:</p>
<pre><code>[System.Xml.Serialization.XmlAttributeAttribute(DataType = "dateTime")]
public System.DateTimeOffset metadataDateTime {
get {
return this.metadataDateTimeField;
}
set {
this.metadataDateTimeField = value;
}
}
</code></pre>
|
<p>Don't serialize the <code>DateTimeOffset</code> directly, but serialize a string instead:</p>
<pre><code>// Don't serialize this one
[System.Xml.Serialization.XmlIgnore]
public System.DateTimeOffset metadataDateTime
{
get { ... }
set { ... }
}
// Serialize this one instead
[System.Xml.Serialization.XmlAttribute("metadataDateTime")]
public string metadataDateTimeXml
{
get { /* format metadataDateTime to custom format */ }
set { /* parse metadataDateTime from custom format */ }
}
</code></pre>
|
<p>This was discussed 2 days ago. Does this do it for you?</p>
<p><a href="https://stackoverflow.com/questions/299387/c-serializing-class-to-xml-where-one-of-class-properties-is-datetime-how-to-mak#299418">C# serializing Class to XML where one of class properties is DateTime. How to make this property in ISO format?</a></p>
| 39,438
|
<p>I am trying to setup a WCF service with multiple endpoints with one of the endpoints using the enableWebScript endpoint behavior so that a Javascript proxy will be created on the client (jsdebug/js).</p>
<p>When adding the Service Reference to my AJAX ScriptManager, the jsdebug file is not found unless the address of the endpoint is blank. The ScriptManager proxy seems to always generate a path of "MyService.svc/jsdebug" to look for the file even though my service has an address of "ajax". The proxy should generate the path as "MyService.svc/ajax/jsdebug".</p>
<p>Is there a setting to get the Proxy generated with the right path? My service is at the root of my website.</p>
<p>works:</p>
<pre><code><endpoint address=""
behaviorConfiguration="ajaxBehavior"
binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="MyTest.Web.ICustomerService" />
</code></pre>
<p>want this (doesn't work):</p>
<pre><code><endpoint address="ajax"
behaviorConfiguration="ajaxBehavior"
binding="webHttpBinding"
bindingConfiguration="webBinding"
contract="MyTest.Web.ICustomerService" />
</code></pre>
|
<p><code><enableWebScript /></code> also known as AJAX-enabled endpoints essentially hard-codes everything to do with address so you can generate the client-side code.</p>
<p>The way it's hard-coded is that everything is directly relative to the .svc file.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/library/bb628467.aspx" rel="nofollow noreferrer">How to: Use Configuration to Add an ASP.NET AJAX Endpoint</a></p>
<blockquote>
<p>The endpoint is configured at an empty
address relative to the .svc file, so
the service is now available and can
be invoked by sending requests to
<code>service.svc/<operation></code> - for example,
<code>service.svc/Add</code> for the <code>Add</code> operation.</p>
</blockquote>
<p>For this reason, you can't mix <code><enableWebScript /></code> with <code>UriTemplate</code>, which takes away half the fun out of WCF in my opinion. See <a href="http://blogs.msdn.com/justinjsmith/archive/2008/02/15/enablewebscript-uritemplate-and-http-methods.aspx" rel="nofollow noreferrer">enableWebScript, UriTemplate, and HTTP methods</a>.</p>
<p>Personally, I like to configure my URI and serve both POX and JSON, as well as SOAP. See <a href="http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html" rel="nofollow noreferrer">WCF RESTful POX, JSON and SOAP Coexist</a>.</p>
|
<p>In the ScriptManager, put MyService.svc/ajax instead of MyService.svc</p>
| 34,319
|
<p>The problem with my Anet E12 should be on USB connection itself.</p>
<ol>
<li>If powered down, the board still gets power from USB</li>
<li>If board is resett, USB will still connect</li>
<li>Still works on SD; seem like most part not damage.
What cause the problem? Where to check first? How to fix it?</li>
</ol>
<p>Note: This printer worked with no problem before.</p>
|
<p>Your formula doesn't seem to take into account two important factors: layer height and average speed.</p>
<p>Do the math differently:</p>
<p>voumetric flow rate [mm^3/s] = layer height [mm] * line width [mm] * speed [mm/s]</p>
<p>For example, 0.2 * 0.45 * 70 = 6.3 mm^3/s</p>
<p>which is realistic, the extruder on the Ender 3 cannot go much faster than that reliably.</p>
<p>PLA weighs 1.24 g/cm^3 = 0.00124 g/mm^3</p>
<p>To extrude 1 kg you need 1000/(0.00124 * 6.3) = 35 hours (70 for 2 kg).</p>
<p>However the printer does not reach 70 mm except on straight long moves, the average speed may be lower or much lower depending on what you print.</p>
<p>If you print technical parts with straight edges, maybe you can multiply by 1.5 (50 hours/kg), but if you print models and small statues or similar you may need to double it (70 hours/kg).</p>
<p>I use Klipper as firmware and I have a macro which keeps track of printing time and filament length used.</p>
|
<p>Your math looks correct, and is also a good approximation for what I've seen in the first few weeks with my own Ender 3.</p>
<p>Another way to calculate (to check yourself) is to calculate the volume extruded (nozzle area times extrusion percentage times print speed -- be sure you convert everything to the same units!) in a given second, multiply by the density of your filament (common PLA runs about 1.2 g/cm^3), and get a rough figure for how long it takes to print a kilogram of filament. Your actual print time will always be higher than this approximation, because there are moves during which the extruder isn't running, infill is often set to lower extrusion level, and of course there's setup and cleanup time to account for.</p>
| 1,952
|
<p>I have been searching for something that does this for a while now, but with no luck yet... We have an internal application that stores/uses text in HTML format. Now I am looking for a new control for editing it. </p>
<p>I <strong>do not</strong> need a full-featured HTML editor, just something that can deal with simple formatting. It also needs spell checking functionality. In the beginning, we used Word embedded with Microsoft's DSO framer control. That caused COM headaches and performance problems on the workstations. More recently we have been using IE in edit mode. That fixed the performance problems, but not the COM problems. </p>
<p>I would like to find something with no external dependencies, or at least that is all managed code. I wouldn't mind building a control of my own around the richtextbox, but I am concerned about the HTML->RTF->HTML conversions. Since we have to deal with incoming e-mails, we can't be too confident using only a subset of HTML. We would also consider buying a component if it fit our needs. I would prefer something light-weight. We don't need to embed Word all over again! </p>
<p>Has anyone else run into the same problem? How did you solve it?</p>
|
<p>Here are a couple of options for for an open source .NET-based text editor that handles syntax highlighting</p>
<ul>
<li>The ICSharpCode.TextEditor component of the <a href="http://www.icsharpcode.net/OpenSource/SD/Download/" rel="nofollow noreferrer">SharpDevelop</a> C# IDE</li>
<li><a href="http://www.codeplex.com/dotnetfireball" rel="nofollow noreferrer">DotNet Fireball</a></li>
</ul>
<p>It should be relatively easy to set these up for HTML, or find existing syntax definitions for HTML.</p>
<p>I'm not too sure about embedding spellcheck into it, but this article may be of interest:</p>
<p><a href="http://www.codeproject.com/KB/recipes/spellcheckparser.aspx" rel="nofollow noreferrer">SpellCheck.net spell checking parsing using C#</a></p>
|
<p>I solved it using this <a href="http://www.codeplex.com/WinformHtmlTextbox" rel="nofollow noreferrer">HTML textbox</a>? It encapsulates IE and uses it for HTML editing, just like you did. No Spell checker.</p>
| 32,435
|
<p>What are some good package naming conventions for domain specific object models. For example, say you have a <strong>Person.java</strong> POJO, would you put it in a <strong>mydomain.model</strong> or <strong>mydomain.entity</strong> or <strong>mydomain.om</strong> (object model) package. The idea is to separate the MVC model objects from the domain object model. Our MVC based application has a <strong>model</strong> package that contains behavior but using that package to contain our domain object model seems inappropriate and potentially confusing. </p>
|
<p>I use "com.mycompany.domain" personally, but that might not be the best answer.</p>
|
<p>Not only that, be careful in the naming convention of your namespaces. I've seen cases where namespace names where duplicated in different assemblies. Talk about confusion. </p>
| 12,237
|
<p>I just upgraded the nozzle (to 1 mm) on an Ender 3v2 and want to make a test print. I added a new printer for the new nozzle size.... and can't find a setting for it. Some screenshots on the internet show a nozzle diameter setting in the machine settings, but I do not have that. (<strong>Manage printers</strong> > <strong>Printers</strong> > <strong>Machine Settings</strong> > <strong>Extruder 1</strong>). Obviously, this was the first place I looked, and I also looked in the sidebar several times.</p>
<p>I have Cura 4.11.0 and am using the Ender 3 profile.</p>
<p>I've seen arguments about it's no longer a valid setting because line width is more important, I've seen discussions that you need to install some mods to get to that variable, and I've seen people say to make a custom printer and then you can change the nozzle diameter. I've also seen lots of people asking for help, and sometimes even posting "Oh I found it" later, but no details on where the setting is, why it's missing, etc.</p>
<p><a href="https://old.reddit.com/r/ender3/comments/bw5d43/nozzle_diameter_settings_in_cura_40_missing/" rel="nofollow noreferrer">https://old.reddit.com/r/ender3/comments/bw5d43/nozzle_diameter_settings_in_cura_40_missing/</a></p>
<p><a href="https://community.ultimaker.com/topic/21438-suggestion-easy-change-nozzle-size/" rel="nofollow noreferrer">https://community.ultimaker.com/topic/21438-suggestion-easy-change-nozzle-size/</a></p>
|
<h1>Mechanical interaction</h1>
<h2>Operator induced regular actions</h2>
<p>When an operator reaches into the machine and operates something on the bed, this can induce errors that slowly accumulate. The most typical operation would be to remove something from the printbed, cleaning the printbed or swapping the printbed wholesale all can result in a slow but steady unleveling.</p>
<p>Regular leveling can counteract this. With good training, you might vet away with once in a dozen or less.</p>
<h2>Maintenance of/work on the printhead</h2>
<p>During maintenance such as swapping nozzles, checking connections and cleaning the printhead, there is a very high chance that the printbed is touched due to the usually very cramped area one has to work in. For example, it is near impossible not to touch the printed when swapping nozzles on my Ender3, if I want to use my torque screwdriver. This is true even with the Z-Axis at the highest position, due to the dimensions of my torque screwdriver.</p>
<p>By virtue of the work on the printhead, the 0-level is usually thrown off anyway, and as such a relevel is <strong>always</strong> in order after any printhead maintenance more invasive than cleaning the fan ducts.</p>
<p>Avoiding nozzle swaps unless necessary can reduce the workload - it might be cheaper in the long term to have two machines with different setups than one machine where you swap the nozzle for each print - unless you charge for the accompanying work on the setup change.</p>
<h2>Operator induced irregular actions</h2>
<p>There are cases where the operator did not plan to operate in the area of the printbed but actually might impact it by reckless or accidental action. In other words: accidents happen, tools drop onto the printbed and hands end there if an operator stumbles.</p>
<p>While releveling might not be <em>necessary</em> after all such accidental contacts, occasionally checking it and fixing it is good practice.</p>
<h2>Mechanical failure</h2>
<p>The way you test and maintain your Z-level is paramount in how often you need to validate the Z-level. If your springs are too strong and push the leveling knobs off on their own or your Z-sensor is mounted only weakly, then these create problems on their own.</p>
<p>Note that even in normal operation, the oscillation of the printer will make any bolt under stress that is not glued in place or jammed in tight loosen a little over time. This does include the bed leveling knobs.</p>
|
<p>The only ones I have found are.</p>
<p>Manually putting pressure on the bed when removing prints.</p>
<p>Removing the bed covering, eg a glass plate</p>
<p>Damaging the bed in some way. For example my bed has high spots on it (always has). This means that if I remove the glass plate I use and put it back, it sits slightly different. If I orient the glass a different way from prior it always needs levelling.</p>
<p>Changing filament types.</p>
<p>Changing cover types eg magnetic and glass are different thicknesses.</p>
<p>Changing first layer needs. Sometimes I need the first layer squished a bit depending what I'm doing.</p>
<p>Lastly on my Ender 3 Pro if the z-axis switch isn't screwed in tight enough it can slip down a fraction.</p>
| 2,149
|
<p>I'm using an istream which could be stringstream, ifstream or a user-defined stream type and I need to know if, in the case of an ifstream, it was not opened in binary mode (so I can throw an exception). I have tried the following method:</p>
<pre><code>if ((_is.flags() & ios::binary) == 0)
throw exception(...)
</code></pre>
<p>but no exception is ever thrown. The test fails in this case because _is.flags() returns 0x201 and ios::binary is 0x20. Is there a way to find out if a stream was opened in text mode?</p>
|
<p>flags() returns <a href="http://www.cplusplus.com/reference/iostream/ios_base/fmtflags.html" rel="noreferrer">ios_base::fmtflags</a> which is formatting flags, whereas binary is an <a href="http://www.cplusplus.com/reference/iostream/ios_base/openmode.html" rel="noreferrer">ios_base::openmode</a> flag. I'm not sure if there is a way to find these out once the stream is already open. I was thinking that maybe there was a virtual member of the streambuf class that could help, but there doesn't really seem to be.</p>
|
<p>Nope, there is no way to test this.</p>
| 27,699
|
<p>I normally build my solution with MSBuild in order to keep Visual Studio responsive and save a bit of time. Right now, what I run at the command line is very simple:</p>
<pre><code>MSBuild.exe /m "C:\MyProject\MyProject.sln"
</code></pre>
<p>Up until now, this has worked just fine. However, today I added a class to a class library project whose DLL is loaded via reflection in my app, and I couldn't create an object of the new class. I looked in the debugger at the types contained in the DLL that I had loaded, and my new type wasn't present. I got the same results with Reflector.</p>
<p>When I finally went back to the IDE, right clicked on the project, and chose "Rebuild", my new type showed up in Reflector.</p>
<p>Is there some setting or command line flag I can set in MSBuild to make sure that new changes are caught every time?</p>
|
<p>This probably sounds like a stupid question, but are you sure the new class file was saved? Rebuild usually automatically saves all files, whereas MSBuild does not.</p>
|
<p>Try specifying "ReBuild" in your msbuild command line call.</p>
<p>msbuild /t:Rebuild /p:Configuration=Debug</p>
<p>Season to taste.</p>
| 48,289
|
<p>I have the function below ENCRYPT.</p>
<pre><code>Public Function Encrypt(ByVal plainText As String) As Byte()
Dim key() As Byte = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}
Dim iv() As Byte = {65, 110, 68, 26, 69, 178, 200, 219}
' Declare a UTF8Encoding object so we may use the GetByte
' method to transform the plainText into a Byte array.
Dim utf8encoder As UTF8Encoding = New UTF8Encoding()
Dim inputInBytes() As Byte = utf8encoder.GetBytes(plainText)
' Create a new TripleDES service provider
Dim tdesProvider As TripleDESCryptoServiceProvider = New TripleDESCryptoServiceProvider()
' The ICryptTransform interface uses the TripleDES
' crypt provider along with encryption key and init vector
' information
Dim cryptoTransform As ICryptoTransform = tdesProvider.CreateEncryptor(Me.key, Me.iv)
' All cryptographic functions need a stream to output the
' encrypted information. Here we declare a memory stream
' for this purpose.
Dim encryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, cryptoTransform, CryptoStreamMode.Write)
' Write the encrypted information to the stream. Flush the information
' when done to ensure everything is out of the buffer.
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
' Read the stream back into a Byte array and return it to the calling
' method.
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
</code></pre>
<p>How do i see the byte value of the text?</p>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx" rel="nofollow noreferrer">Encoding</a> class.</p>
<p>To convert array of bytes to a string you can use <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.getstring.aspx" rel="nofollow noreferrer">Encoding.GetString</a> method </p>
<p>There is a special version for UTF8: <a href="http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getstring.aspx" rel="nofollow noreferrer">UTF8Encoding.GetString</a></p>
|
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx" rel="nofollow noreferrer">Encoding</a> class.</p>
<p>To convert array of bytes to a string you can use <a href="http://msdn.microsoft.com/en-us/library/system.text.encoding.getstring.aspx" rel="nofollow noreferrer">Encoding.GetString</a> method </p>
<p>There is a special version for UTF8: <a href="http://msdn.microsoft.com/en-us/library/system.text.utf8encoding.getstring.aspx" rel="nofollow noreferrer">UTF8Encoding.GetString</a></p>
| 17,757
|
<p>I need to compile a wmi vbscript to executable (to automate configuration in several computers). Any free vbscript compiler or any other suggestions?</p>
|
<p>One thing I would be especially concerned about in doing this is you must really trust the product that is compiling the script. After all, what better way to embed a virus or worm than to offer a free compiler that compiles your VBScript into an unreadable executable. </p>
|
<p>ok that's interesting i guess, and I fully understand your point!</p>
<p>you can use the WSH Encoder <a href="http://www.microsoft.com/downloads/details.aspx?familyid=E7877F67-C447-4873-B1B0-21F0626A6329&displaylang=en" rel="nofollow noreferrer">here</a> (Windows Script Host), it's for free you can encrypt your scripts and this way no one can read them (just the not curious ones!)</p>
<p>and if you are looking for some strong and hard work also encryption you can try this book <a href="http://sites.google.com/site/martanifayssal/pro-decrypting-vbscript-viruses" rel="nofollow noreferrer">here</a></p>
| 46,842
|
<p><a href="https://stackoverflow.com/questions/109488/is-it-bad-design-to-use-table-tags-when-displaying-forms-in-html">Is it bad design to use table tags when displaying forms in html?</a></p>
<p>The accepted answer to this question in short: YES...</p>
<p>...but what about something like this:</p>
<p><img src="https://content.screencast.com/users/MarkusHausammann/folders/Jing/media/a3db75c8-49ce-452c-a3ba-9eb6ce8150e9/2012-05-21_1829.png" /></p>
<p>I can't really think of different & better solution. The example is from SurveyMonkey and uses tables too.</p>
<p><strong>Is it still bad design to use table tags for such likert type questions?</strong></p>
|
<p>This type of question leads more to opinions than to hard and fast facts, but I would say that in this case it's definitely OK to use tables -- you're wanting a tabular display of information.</p>
<p>Just use the table tag and don't let people make you feel guilty for it :-)</p>
|
<p>What everyone says is "you should only use tables for tabular data". So ... what does that mean?</p>
<p>Here's my criterion for when something actually is tabular data: when you can only know what something is/does by reference to its <em>coordinates</em>, its position in relation to column and row headers. </p>
<p>So, in the case above, what is the function of the ninth radio button?</p>
<p>There's no way of knowing what it is unless you look left to the kind of skill it refers to and look up to the kind of level you're claiming. Therefore, this is tabular data.</p>
| 42,921
|
<p>I know it is possible, and a lot faster than using GDI+. However I haven't found any good example of using DirectX to resize an image and save it to disk. I have implemented this over and over in GDI+, thats not difficult. However GDI+ does not use any hardware acceleration, and I was hoping to get better performance by tapping into the graphics card.</p>
|
<p>You can load the image as a texture, texture-map it onto a quad and draw that quad in any size on the screen. That will do the scaling. Afterwards you can grab the pixel-data from the screen, store it in a file or process it further. </p>
<p>It's easy. The basic texturing DirectX examples that come with the SDK can be adjusted to do just this.</p>
<p>However, it <em>is</em> slow. Not the rendering itself, but the transfer of pixel data from the screen to a memory buffer. </p>
<p>Imho it would be much simpler and faster to just write a little code that resizes an image using bilinear scaling from one buffer to another.</p>
|
<p>You can load the image as a texture, texture-map it onto a quad and draw that quad in any size on the screen. That will do the scaling. Afterwards you can grab the pixel-data from the screen, store it in a file or process it further. </p>
<p>It's easy. The basic texturing DirectX examples that come with the SDK can be adjusted to do just this.</p>
<p>However, it <em>is</em> slow. Not the rendering itself, but the transfer of pixel data from the screen to a memory buffer. </p>
<p>Imho it would be much simpler and faster to just write a little code that resizes an image using bilinear scaling from one buffer to another.</p>
| 20,873
|
<p>I'm trying to print a large piece with polycarbonate but it keeps warping, I'm using a Taz 5 printer and setting 290 C in the extruder and 145 C in the heating bed. </p>
<p>Other setting I have are:</p>
<ol>
<li>printing speed: 20 mm/s</li>
<li>layer height: 2.5mm</li>
<li>infil: 20%</li>
<li>brim: 15mm</li>
</ol>
<p>Can anyone tell me any tips or suggestions to avoid warping?</p>
|
<p>Adjusting the design may also be able to help limit the amount of warping you get.</p>
<p>One of the major causes of warping is upper layers contracting while cooling when laid down over now-cool(er) lower layers which no longer contract so much but are still thin enough to flex when subject to tension along their upper edge. Insertion of strategically placed gaps in upper layers can reduce the tension such layers are able to apply.</p>
<p>I was printing some long thin beams in ABS. I inserted horizontal-axis holes along the beams (making them look a bit like <a href="https://assets.madaboutbricks.uk/wp-content/uploads/2014/03/23161640/Lego-40490-Black-Technic-Beam-9_2.jpg" rel="nofollow noreferrer">LEGO Technic</a> beams rather than solid pieces). It did the job for me.</p>
|
<p>I would take a look <a href="http://reprap.org/wiki/Polycarbonate" rel="nofollow noreferrer">here</a> and <a href="https://www.matterhackers.com/articles/how-to-succeed-when-printing-with-polycarbonate-filament" rel="nofollow noreferrer">here</a>.
Literally the first two results of Google.</p>
<p>To summarize what they say,</p>
<p>You need good bed adhesion to keep the first layer from warping near the edges like you will get normally with ABS or PC(Polycarbonate). Some use hairspray or gluestick. I manage myself with buildtak surface. I would stay away from blue painters tape. Your looking for something very sticky. This of course makes it a nightmare to get the part off the bed but well worth the trouble if it keeps your print on the bed and flat.</p>
<p>Make sure the part receives adequate heat. Like someone wrote in the comments, a enclosure works best to keep the temperature of the entire print warm instead of just the few layers closest to the bed.</p>
<p>More perimeter layers works very well by providing more structural strength to try and combat the warping. I've stumbled upon this solution when I had trouble with ABS.</p>
<p>Lastly, first layer is always the most important part of any print. You want to make sure it is as level as possible and a good tip is to raise your bed just so slightly than usual so the first layer is jammed hard against the bed. This provides better surface area. Just be careful not to clog your printhead cause if you constrict the flow out of the nozzle too much, you'll might end up with plastic trying to flow upwards or maybe grind the filament with the extruder gear.</p>
| 739
|
<p>How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?</p>
<p>Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: </p>
<pre><code>Quellenstrasse 66/11
Quellenstr. 66a-11
</code></pre>
<p>I'm talking German addresses...
Thanks!</p>
|
<p>The earlier you can stop people, the easier it'll be in the long run! </p>
<p>Not being too familiar with your db schema or data entry form, I'd suggest a route something like the following:</p>
<ul>
<li><p>have distinct fields in your db for each address "part", e.g. street, city, postal code, Länder, etc.</p></li>
<li><p>have your data entry form broken down similarly, e.g. street, city, etc</p></li>
</ul>
<p>The reasoning behind the above is that each part will likely have it's own particular "rules" for checking slightly-changed addressed, ("Quellenstrasse"->"Quellenstr.", "66/11"->"66a-11" above) so your validation code can check if the values as presented for each field exist in their respective db field. If not, you can have a class that applies the transformation rules for each given field (e.g. "strasse" stemmed to "str") and checks again for duplicates.</p>
<p>Obviously the above method has it's drawbacks:</p>
<ul>
<li><p>it can be slow, depending on your data set, leaving the user waiting</p></li>
<li><p>users may try to get around it by putting address "Parts" in the wrong fields (appending post code to city, etc).
but from experience we've found that introducing even simple checking like the above will prevent a large percentage of users from entering pre-existing addresses.</p></li>
</ul>
<p>Once you've the basic checking in place, you can look at optimising the db accesses required, refining the rules, etc to meet your particular schema. You might also take a look at <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html#function_match" rel="noreferrer">MySQL's match() function</a> for working out similar text.</p>
|
<p>In my opinion, assuming that you already had a lot of dirty data in your DB, </p>
<p>You have to do build your "handmade" dirty filter which may detect a maximum of german abreviation ... </p>
<p>But If you treat a lot of data, you will take the risk to find some false-positive and true-negative sample...</p>
<p>Finally a semi automated job (machine with human assist when probability of a case of false-positive or true-negative is too high) will be the best solution.</p>
<p>More you treat "exception" (because human raise exception when filling data), more your "handmade" filter will fit your requierement.</p>
<p>In the other hand, you may also use a germany address verification service on user side, and store only the verified one...</p>
| 5,831
|
<p>Sometimes while debugging, I need to restart a service on a remote machine. Currently, I'm doing this via Remote Desktop. How can it be done from the command line on my local machine?</p>
|
<p>You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.</p>
<p>If you wish to use the command line only, you can use</p>
<pre><code>sc \\machine stop <service>
</code></pre>
|
<p>Well, if you have Visual Studio (I know it's in 2005, not sure about earlier versions though), you can add the remote machine to your "Server Explorer" tag. At that point, you'll have access to the SERVICES that are running, or can be ran, from that machine (as well as event logs, and queues, and a couple other interesting things).</p>
| 22,761
|
<p>I want to discard all remaining characters in a string as soon as one of several unwanted characters is encountered.</p>
<p>As soon as a blacklisted character is encountered, the string before that point should be returned.</p>
<p>For instance, if I have an array:</p>
<pre><code>$chars = array("a", "b", "c");
</code></pre>
<p>How would I go through the following string...</p>
<pre><code>log dog hat bat
</code></pre>
<p>...and end up with:</p>
<pre><code>log dog h
</code></pre>
|
<p>The <a href="http://php.net/manual/en/function.strcspn.php" rel="noreferrer">strcspn</a> function is what you are looking for.</p>
<pre><code><?php
$mask = "abc";
$string = "log dog hat bat";
$result = substr($string,0,strcspn($string,$mask));
var_dump($result);
?>
</code></pre>
|
<p>There is certainly nothing wrong with Vinko's answer and I might be more inclined to recommend that technique in a professional script because regex is likely to perform slower, but purely for a point of difference for researchers, regex could be used.</p>
<p>For the record, to convert the array of <code>['a', 'b', 'c']</code> to <code>abc</code>, just call <code>implode($array)</code> -- an empty glue string is not necessary.</p>
<p>Code: (<a href="https://3v4l.org/REAZ3" rel="nofollow noreferrer">Demo</a>) -- split in half on first occurrence of a|b|c, then access first element</p>
<pre><code>echo preg_split('~[abc]~', $string, 2)[0];
</code></pre>
<p>Code: (<a href="https://3v4l.org/f10IR" rel="nofollow noreferrer">Demo</a>) -- match leading substring of non-a|b|c characters, then access first element</p>
<pre><code>echo preg_match('~^[^abc]+~', $string, $match) ? $match[0] : '';
</code></pre>
<p>I should state that if any of your blacklisted characters have special meaning to the regex engine while inside of a character class, then they will need to be escaped.</p>
| 37,308
|
<p>Suppose I have the X, Y, and Z coordinates (either in a list or a function z = f(x,y)) that defines a shape as the one provided and I want to 3D print it with a solid bottom, is there an easy way to do this? If not, how can a functionally well-defined shape be put into a 3D modeling software like FreeCAD?</p>
<p><a href="https://i.stack.imgur.com/5bcSU.jpg" rel="nofollow noreferrer" title="3D graph"><img src="https://i.stack.imgur.com/5bcSU.jpg" alt="3D graph" title="3D graph" /></a></p>
|
<p>For stuff like this, OpenSCAD is your friend. There are several different approaches you could take:</p>
<ol>
<li><p>Generate an image file with grayscale color representing the height of the function on an XY grid, and use the <a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Other_Language_Features#Surface" rel="nofollow noreferrer"><code>surface</code></a> feature to import it as a heightmap.</p>
</li>
<li><p>Write the function as a mathematical expression in OpenSCAD language, and write a module to generate a <a href="https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Primitive_Solids#polyhedron" rel="nofollow noreferrer"><code>polyhedron</code></a> by iterating over a sufficiently fine coordiante grid, sampling the function, and producing points and triangles.</p>
</li>
<li><p>Use a library someone else has already written for this purpose. I'm not aware of specific ones but pretty sure there are quite a few.</p>
</li>
</ol>
|
<p>Not sure what you're asking exactly, but you can use this workflow:</p>
<ol>
<li>SideFX Houdini: math function + STL file generation
<a href="https://i.stack.imgur.com/28jr1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/28jr1.jpg" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/E0Itn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E0Itn.jpg" alt="enter image description here" /></a></li>
<li>(optional) FreeCAD: Import STL as mesh, do whatever you need to do in FreeCAD, export to STL
<a href="https://i.stack.imgur.com/txRno.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/txRno.png" alt="enter image description here" /></a></li>
<li>a slicer: import the STL and slice it.
<a href="https://i.stack.imgur.com/Ofydl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ofydl.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/zCxgG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zCxgG.jpg" alt="enter image description here" /></a></li>
</ol>
| 2,032
|
<p>I have an image (mx) and i want to get the uint of the pixel that was clicked.</p>
<p>Any ideas?</p>
|
<p>Here's an even simpler implementation. All you do is take a snapshot of the stage using the <strong>draw()</strong> method of bitmapData, then use <strong>getPixel()</strong> on the pixel under the mouse. The advantage of this is that you can sample anything that's been drawn to the stage, not just a given bitmap.</p>
<pre><code>import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;
stage.addEventListener(MouseEvent.CLICK, getColorSample);
function getColorSample(e:MouseEvent):void {
var bd:BitmapData = new BitmapData(stage.width, stage.height);
bd.draw(stage);
var b:Bitmap = new Bitmap(bd);
trace(b.bitmapData.getPixel(stage.mouseX,stage.mouseX));
}
</code></pre>
<p>Hope this is helpful!</p>
<hr>
<p><strong>Edit</strong>:</p>
<p>This edited version uses a single <code>BitmapData</code>, and removes the unnecessary step of creating a <code>Bitmap</code>. If you're sampling the color on <code>MOUSE_MOVE</code> then this is essential to avoid memory issues. </p>
<p>Note: if you're using a custom cursor sprite you'll have to use an object other than 'state' or else you'll be sampling the color of the custom sprite instead of what's under it.</p>
<pre><code>import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;
private var _stageBitmap:BitmapData;
stage.addEventListener(MouseEvent.CLICK, getColorSample);
function getColorSample(e:MouseEvent):void
{
if (_stageBitmap == null) {
_stageBitmap = new BitmapData(stage.width, stage.height);
}
_stageBitmap.draw(stage);
var rgb:uint = _stageBitmap.getPixel(stage.mouseX,stage.mouseY);
var red:int = (rgb >> 16 & 0xff);
var green:int = (rgb >> 8 & 0xff);
var blue:int = (rgb & 0xff);
trace(red + "," + green + "," + blue);
}
</code></pre>
|
<p>A few minutes on the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html" rel="nofollow noreferrer">BitmapData LiveDoc Page</a> will take you where you need to go. Once you have your image loaded into a Bitmap variable, you can access its BitmapData property. Add a <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/MouseEvent.html#CLICK" rel="nofollow noreferrer">Mouse Click Event</a> Listener to the image and then use <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html" rel="nofollow noreferrer">BitmapData::getPixel</a>. The example for getPixel shows how to convert the uint response to an rgb hex code.</p>
<p>Here's a modification of the Example given on the BitmapData page that worked for me (using mxmlc - YMMV):</p>
<pre><code>package {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;
public class BitmapDataExample extends Sprite {
private var url:String = "santa-drunk1.jpg";
private var size:uint = 200;
private var image:Bitmap;
public function BitmapDataExample() {
configureAssets();
}
private function configureAssets():void {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
var request:URLRequest = new URLRequest(url);
loader.load(request);
addChild(loader);
}
private function completeHandler(event:Event):void {
var loader:Loader = Loader(event.target.loader);
this.image = Bitmap(loader.content);
this.addEventListener(MouseEvent.CLICK, this.clickListener);
}
private function clickListener(event:MouseEvent):void {
var pixelValue:uint = this.image.bitmapData.getPixel(event.localX, event.localY)
trace(pixelValue.toString(16));
}
}
}
</code></pre>
| 10,427
|
<p>I'm interested in implementing autocomplete in Python. For example, as the user types in a string, I'd like to show the subset of files on disk whose names start with that string. </p>
<p>What's an efficient algorithm for finding strings that match some condition in a large corpus (say a few hundred thousand strings)? Something like:</p>
<pre><code>matches = [s for s in allfiles if s.startswith(input)]
</code></pre>
<p>I'd like to have the condition be flexible; eg. instead of a strict startswith, it'd be a match so long as all letters in input appears in s in the same order. What's better than the brute-force method I'm showing here?</p>
|
<p>For exact matching, generally the way to implement something like this is to store your corpus in a <a href="http://en.wikipedia.org/wiki/Trie" rel="noreferrer">trie</a>. The idea is that you store each letter as a node in the tree, linking to the next letter in a word. Finding the matches is simply walking the tree, and showing all children of your current location. eg. "cat", "cow" and "car" would be stored as:</p>
<pre><code> a--t
/ \
c r
\
o--w
</code></pre>
<p>When you get a c, you start at the c node, an a will then take you to the c/a node (children
"t" and "r", making cat and car as your completions).</p>
<p>Note that you'll also need to mark nodes that are complete words to handle names that are substrings of others (eg "car" and "cart")</p>
<p>To get the desired fuzzy matching, you may need to make some changes however.</p>
|
<p>The flexibility you want for matching your string is called <em>Fuzzy Matching</em> or <em>Fuzzy Searching</em> . I am not aware of any python implementation (but I haven't looked deeply in the subject) but there are C/C++ implementations that you can reuse, like the <a href="http://laurikari.net/tre/" rel="nofollow noreferrer">TRE packaged</a> that supports regexp with fuzzy parameters.</p>
<p>Apart from that, there is always the question of whether the total list of your words fits in memory or not. If not, keeping them in a list is not feasible and will have to cache something to disk or to a database.</p>
| 47,275
|
<p>I am very curious as to how people write their own obfuscator.</p>
<p>How hard would it be to simply do the following:</p>
<ol>
<li>rename all public methods with GUID type names.</li>
</ol>
<p>Where would I start? How would I go about reading the .net dll assemby, pulling the public methods out and renaming them? </p>
|
<p>You can check those two projects that are using <a href="http://www.mono-project.com/Cecil" rel="nofollow noreferrer" title="Cecil">Cecil</a> to write an open-source obfuscator:</p>
<ul>
<li><a href="http://code.google.com/p/obfuscar/" rel="nofollow noreferrer">http://code.google.com/p/obfuscar/</a></li>
<li><a href="http://www.codeplex.com/SharpObfuscator" rel="nofollow noreferrer">http://www.codeplex.com/SharpObfuscator</a></li>
</ul>
|
<p>If you're starting with source, it's pretty simple to do text replacements and then run the code through a compiler. If you are starting with a compiled assembly, then you need to use the stuff in the System.Reflection namespace to load the assembly and System.CodeDom to generate compilable code units.</p>
| 43,752
|
<p>I have built a 3D printer from salvaged/purchased parts. I am using an Arduino Uno and three easy driver stepper drivers with 3 CD-ROMs drives and a PC power unit. I ordered a 3D pen and have it mounted with a transistor to switch it on/off. Everything works but when I try to run code that I got from makercam.com it seems like it wants to fill in the shape rather than build up. </p>
<p>I followed this tutorial <a href="https://youtu.be/anIy6eb1fW0" rel="nofollow noreferrer">YouTube - How To Make A Cheap 3D Printer</a> and after modifying the G-code I am unable to get any successful prints.</p>
<p><a href="https://i.stack.imgur.com/LgHI1.jpg" rel="nofollow noreferrer" title="Bad prints"><img src="https://i.stack.imgur.com/LgHI1.jpg" alt="Bad prints" title="Bad prints"></a></p>
|
<p>Download an stl file from Thingiverse.com </p>
<p>Put your .stl file in a slicer program like cura</p>
<p>It will output gcode for 3d objects rather than 2d.</p>
|
<p>I would typically shy away from downloading gcode and printing it directly. Always slice it yourself since, inevitably, every printer is different. What happens if the gcode is setup for ABS (higher temps) and you are printing with PLA? If it's setup for a build platform larger than yours and you just hit endstops?</p>
<p>Definitely go with Aaron's idea, download a model (Thingiverse is great, but there are SO many sites where you can get files), configure a slicer for your print settings (I prefer slic3r to Cura, but both are great), slice it and print away.</p>
| 712
|
<p>I'm working on something that requires traversing through the file system and for any given path, I need to know how 'deep' I am in the folder structure. Here's what I'm currently using:</p>
<pre><code>int folderDepth = 0;
string tmpPath = startPath;
while (Directory.GetParent(tmpPath) != null)
{
folderDepth++;
tmpPath = Directory.GetParent(tmpPath).FullName;
}
return folderDepth;
</code></pre>
<p>This works but I suspect there's a better/faster way? Much obliged for any feedback.</p>
|
<p>Off the top of my head:</p>
<pre><code>Directory.GetFullPath().Split("\\").Length;
</code></pre>
|
<p>Maybe someone need also some performance testing...</p>
<pre><code> double linqCountTime = 0;
double stringSplitTime = 0;
double stringSplitRemEmptyTime = 0;
int linqCountFind = 0;
int stringSplitFind = 0;
int stringSplitRemEmptyFind = 0;
string pth = @"D:\dir 1\complicated dir 2\more complicated dir 3\much more complicated dir 4\only dir\another complicated dir\dummy\dummy.dummy.45682\";
//Heat Up
DateTime dt = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
linqCountFind = pth.Count(c => c == '\\');
}
_= DateTime.Now.Subtract(dt).TotalMilliseconds;
dt = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
stringSplitFind = pth.Split('\\').Length;
}
_ = DateTime.Now.Subtract(dt).TotalMilliseconds;
dt = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
stringSplitRemEmptyFind = pth.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
_ = DateTime.Now.Subtract(dt).TotalMilliseconds;
dt = DateTime.Now;
//Testing
dt = DateTime.Now;
for (int i = 0; i < 1000000; i++)
{
linqCountFind = pth.Count(c => c == '\\');
}
linqCountTime = DateTime.Now.Subtract(dt).TotalMilliseconds; //linq.Count: 1390 ms
dt = DateTime.Now;
for (int i = 0; i < 1000000; i++)
{
stringSplitFind = pth.Split('\\').Length-1;
}
stringSplitTime = DateTime.Now.Subtract(dt).TotalMilliseconds; //string.Split: 715 ms
dt = DateTime.Now;
for (int i = 0; i < 1000000; i++)
{
stringSplitRemEmptyFind = pth.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
stringSplitRemEmptyTime = DateTime.Now.Subtract(dt).TotalMilliseconds; // string.Split with RemoveEmptyEntries option: 720 ms
string linqCount = "linqCount - Find: "+ linqCountFind + "; Time: "+ linqCountTime.ToString("F0") +" ms"+ Environment.NewLine;
string stringSplit = "stringSplit - Find: " + stringSplitFind + "; Time: " + stringSplitTime.ToString("F0") + " ms" + Environment.NewLine;
string stringSplitRemEmpty = "stringSplitRemEmpty - Find: " + stringSplitRemEmptyFind + "; Time: " + stringSplitRemEmptyTime.ToString("F0") + " ms" + Environment.NewLine;
MessageBox.Show(linqCount + stringSplit + stringSplitRemEmpty);
// Results:
// linqCount - Find: 9; Time: 1390 ms
// stringSplit - Find: 9; Time: 715 ms
// stringSplitRemEmpty - Find: 9; Time: 720 ms
</code></pre>
<ul>
<li>So, for most cases, the best is string.split() (see results in code comments).</li>
<li>string.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries) is safer for path.</li>
<li>And for more complicated cases see:
<a href="https://cc.davelozinski.com/c-sharp/fastest-way-count-number-times-character-occurs-string" rel="nofollow noreferrer">https://cc.davelozinski.com/c-sharp/fastest-way-count-number-times-character-occurs-string</a>
and
<a href="https://cc.davelozinski.com/c-sharp/c-net-fastest-way-count-substring-occurrences-string" rel="nofollow noreferrer">https://cc.davelozinski.com/c-sharp/c-net-fastest-way-count-substring-occurrences-string</a></li>
</ul>
| 40,804
|
<p>With multiple developers working on the same Tomcat application, I'd like to tell the application to install to a different path, based on the current user and revision control client/view.</p>
<p>So, if Bob is building, the app should be installed in Bob's test environment, maybe /bob1 or something like that. Bob might have several revision control clients/views/workspaces he works with so he could have /bob1, /bob2, /bob3, etc.</p>
<p>The install location is specified in the build.properties file. Is there a way to avoid checking that file out and changing it for each specific user and revision control view?</p>
<p>Can "ant install" take arguments or be configured to consider environment variables for the install target?</p>
|
<p>I typically use a variation on the default properties answer already given:</p>
<pre><code><property file="local.properties" />
<property file="default.properties" />
</code></pre>
<p>I read the local properties file first and the default one second. Users don't edit the default one (then accidentally check it in), they just define the properties they want to override in the local.properties.</p>
|
<p>Defining properties with the -D option at the command line is fine, though it can get tedious if there are many of them frequently. In order to resist the urge to wrap the ant invocation in a bash script, there is the common practise to import property files.</p>
<p>In the main build file you put: </p>
<pre><code><property file="default.properties" />
</code></pre>
<p>Then you have a file named default.properties.sample with a sample configuration. This is being checked into version control. The developers check out default.properties.sample, copy it to default.properties and edit it according to their needs.</p>
<p>You should set an ignore default flag for default.samples in order to prevent it from being checked in accidentally (svn:ignore with subversion).</p>
| 34,479
|
<p>I have some source files that have comments written in Japanese. When I open these files in Visual Studio they appear like this:</p>
<pre><code>à–¾FNCAP‰¹—p‚̃XƒŒƒbƒh
</code></pre>
<p>I am using the English version of WinXP, but is there a way to get Visual Studio to display the actual Japanese characters rather than the random jibberish it currently is?</p>
|
<p>Presumably VS is interpreting the file with the wrong encoding.</p>
<p>Reopen it using "File -> Open -> File... -> Open -> Open With... -> Source Code (Text) Editor With Encoding" and try various encodings.</p>
|
<p>I faced the same issue and have found a solution that works for me.</p>
<p>The problem is that the files aren't unicode and VS is trying to open them with an encoding that matches your location. Luckily, you can set Windows default behavior for non-unicode files. Check out this link, <a href="http://msdn.microsoft.com/en-us/library/ms246590.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms246590.aspx</a>. Look under "To correctly display characters that are not included in the current code page."</p>
<p>These directions are incorrect for Windows 8 (I can't speak for 7 or older.) For Windows 8:</p>
<ol>
<li>Navigate to Control Panel</li>
<li>Select Clock, Language, and Region (yeah they still have the comma before and)</li>
<li>Region</li>
<li>Administrative</li>
<li>Change System Locale...</li>
<li>Select the desired language from the "Current System Locale" drop down</li>
</ol>
<p>Most of your programs should continue to function in English as this setting is only applied when programs and files don't support unicode.</p>
| 25,845
|
<p>I had problems with print bed adhesion when using white PLA (Arctic White) but no problems when using other colors. So I tried to print three bottom layers with transparent PLA and all other layers with white PLA. I did not change any setting and printed both tries one after another using the same .stl file.</p>
<p>There was some warping of the printed ring too. No problems when using transparent plus white PLA.</p>
<p><a href="https://i.stack.imgur.com/FngJU.jpg" rel="nofollow noreferrer" title="Photo of two printed rings"><img src="https://i.stack.imgur.com/FngJU.jpg" alt="Photo of two printed rings" title="Photo of two printed rings" /></a></p>
<p>Right: white PLA only, left: transparent PLA bottom layers plus white PLA above. View of the bottom sides.</p>
<p>Has anyone experienced similar problems?</p>
|
<p>Same G-code slice? The main cause of warping is temperature. If this is kept as a control variable and you have these results, it may be because of a different temperature the filament requires. Check the filament specs and adjust the bed/nozzle temperature to make the temperature difference smaller.</p>
<p>Edit: Another reason it might be needing different temperatures is because of absorbing moisture.</p>
|
<p>Problem was displaced by a factory reset of the 3D printer FlashForge Adventurer 3.</p>
<p><a href="https://i.stack.imgur.com/jxS9X.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jxS9X.jpg" alt="Photo of two versions" /></a></p>
<p>Right: white PLA only, left: transparent PLA bottom layers plus white PLA above. View of the bottom sides. No difference of print bed adhesion now.</p>
<p>The reason of the problem was not found, but print bed adhesion is good after the factory reset for both white and transparent PLA.</p>
| 2,047
|
<p>I'm currently having a problem with a ShoppingCart for my customer.</p>
<p>He wants to be able to add Text between the CartItems so I was wondering if there is some way to still only have one List.</p>
<p>My solution would be to have two lists, one of type IList that gets iterated over when calculating Weight and overall Price of the Cart while having another IList that only exposes the necessary fields for displaying it in the ListView and that is a SuperType of CartItem. (But how do I then access additional fields for the listView, defaulting weight and price to 0 in the Description-Text-Class would break LSP).</p>
<p>But having two lists somehow feels a bit odd (and still gives me problems), so I was wondering if I could do some sort of a TypedList where I specify the Type of each item.</p>
<p>Any suggestions are welcome, I'm not really happy with both options.</p>
|
<p>Use an interface:</p>
<pre><code> ICartListItem
</code></pre>
<p>And make your list be:</p>
<pre><code> List<ICartListItem>
</code></pre>
<p>Now, create several types, have all of them implement this interface, and you can store them all safely in your list.</p>
<p>Alternatively, if you want there to be some default logic in a CartItem, use a base class instead of an interface.</p>
|
<p>The Interface sounds like overkill. I'd just add a property to your current CartItem named something like "TextAfterItem".</p>
<p>Also: make sure your customer understands the cost of this feature in terms of security overhead. It sounds like they think this should be a simple update, but you're allowing users to enter text that will be displayed directly back to the page, and that's a dangerous proposition.</p>
| 40,977
|
<p>I have a given certificate installed on my server. That certificate has valid dates, and seems perfectly valid in the Windows certificates MMC snap-in.</p>
<p>However, when I try to read the certificate, in order to use it in an HttpRequest, I can't find it. Here is the code used:</p>
<pre><code> X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly); X509Certificate2Collection col =
store.Certificates.Find(X509FindType.FindBySerialNumber, "xxx", true);
</code></pre>
<p><code>xxx</code> is the serial number; the argument <code>true</code> means "only valid certificates". The returned collection is empty.</p>
<p>The strange thing is that if I pass <code>false</code>, indicating invalid certificates are acceptable, the collection contains one element—the certificate with the specified serial number.</p>
<p>In conclusion: the certificate appears valid, but the <code>Find</code> method treats it as invalid! Why?</p>
|
<p>Try verifying the certificate chain using the <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509chain.aspx" rel="noreferrer">X509Chain</a> class. This can tell you exactly why the certificate isn't considered valid.</p>
<p>As erickson suggested, your X509Store may not have the trusted certificate from the CA in the chain. If you used OpenSSL or another tool to generate your own self-signed CA, you need to add the public certificate for that CA to the X509Store.</p>
|
<p>I believe x509 certs are tied to a particular user. Could it be invalid because in the code you are accessing it as a different user than the one for which it was created?</p>
| 12,355
|
<p>When I try to use <code>curl</code> or <code>file_get_contents</code> to read something like <a href="http://example.com/python/json/" rel="nofollow noreferrer">http://example.com/python/json/</a> from <a href="http://example.com/" rel="nofollow noreferrer">http://example.com/</a> I should be getting a JSON response, but instead I get a 404 error. Using curl or any other method outside my own domain works perfectly well.</p>
<pre><code>echo file_get_contents('http://example.com/python/json/'); => 404
echo file_get_contents('http://google.com'); => OK
</code></pre>
<p>The same script works on my laptop, but I can't figure out what the difference is.</p>
|
<p>It looks like example.com is not the default domain for the IP address and that file_get_contents uses HTTP/1.0 instead of HTTP/1.1 and/or does not send a Host: header. Try the curl support in PHP instead:</p>
<pre><code>$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
</code></pre>
<p>Alternatively the /etc/hosts file sets the wrong IP address for example.com.</p>
|
<p>Something to do with the domain, maybe? Of course, you don't want to reveal it here, so you might have a bit to do, but I guess the sanity check would be that you can access that URL via a web browser (or command line tool such as GET if you're command-line only).</p>
<p>You could also just ping and/or traceroute to the domain - the results may well be illuminating.</p>
| 31,290
|
<p>I own a DIY Hypercube Evolution equipped with Tevo Titan extruder, Clone Chimera hotend and Capricorn's High-temp PTFE tube. I use RAMPS with Mega and A4988's.</p>
<p>During prints, my extruder motor randomly clicks. I touched the filament and during the clicks I'ven't felt any problems with extrusion. I looked at the motor shaft to control if it clicks at special angles or randomly, but it clicks randomly. My prints do look very good: clear and shiny.</p>
<p>Do you have any suggestions? (the sound really gives me headache)</p>
|
<p>Even though you may have acceptable extrusion, any clicking from that area of your printer is likely to be a missed step on the extruder motor. This may be insignificant with respect to print quality, but as you suggest, it is an irritation.</p>
<p>If you are confident that your nozzle is clean of debris (which is likely), you could consider to raise the nozzle temperature a few degrees. If the nozzle is not applying enough heat to the filament, it may resist being forced through and a click representing a delay, allows that much more heat to be applied.</p>
<p>You should not have to increase by much, certainly no more than five degrees. It's also possible that you can slow the feed rate a bit to accomplish a similar result.</p>
|
<p>Even though you may have acceptable extrusion, any clicking from that area of your printer is likely to be a missed step on the extruder motor. This may be insignificant with respect to print quality, but as you suggest, it is an irritation.</p>
<p>If you are confident that your nozzle is clean of debris (which is likely), you could consider to raise the nozzle temperature a few degrees. If the nozzle is not applying enough heat to the filament, it may resist being forced through and a click representing a delay, allows that much more heat to be applied.</p>
<p>You should not have to increase by much, certainly no more than five degrees. It's also possible that you can slow the feed rate a bit to accomplish a similar result.</p>
| 971
|
<p>I'm working in .Net 3.5sp1 in C# for an ASP.Net solution and I'm wondering if there's any way to turn on the Class Name and Method Name drop-downs in the text editor that VB.Net has at the top. It's one of the few things from VB that I actually miss.</p>
<p>Edit: Also, is there any way to get the drop downs to be populated with the possible events?</p>
<p>e.g. (Page Events) | (Declarations)</p>
|
<p>Go To:</p>
<pre><code>Tools -> Options -> Text Editor -> C# -> General -> Navigation Bar
</code></pre>
<p>Make sure it is clicked, and that should show something at the top of your code that has all the classes and methods listed in your file.</p>
|
<p>note that the lists don't fill in until the cursor is within the namespace/class</p>
| 19,259
|
<p>In toad, I can see unicode characters that are coming from oracle db. But when I click one of the fields in the data grid into the edit mode, the unicode characters are converted to meaningless symbols, but this is not the big issue.</p>
<p>While editing this field, the unicode characters are displayed correctly as I type. But as soon as I press enter and exit edit mode, they are converted to the nearest (most similar) non-unicode character. So I cannot type unicode characters on data grids. Copy & pasting one of the unicode characters also does not work.</p>
<p>How can I solve this?</p>
<p>Edit: I am using toad 9.0.0.160.</p>
|
<p>You just need to add a public method for invoking the event. Microsoft already does this for some events such as <em>PerformClick</em> for controls that expose a <em>Click</em> event.</p>
<pre><code>public class CustomGUIElement
{
public void PerformClick()
{
OnClick(EventArgs.Empty);
}
protected virtual void OnClick(EventArgs e)
{
if (Click != null)
Click(this, e);
}
}
</code></pre>
<p>You would then do the following inside your example event handler...</p>
<pre><code>public void CustomForm_Click(object sender, MouseEventArgs e)
{
_elements[0].PerformClick();
}
</code></pre>
|
<p>You really should wrap the code you want to be able to execute from the outside in a method. That method can then do whatever your event would do - and that event would also instead call that method.</p>
| 13,335
|
<p>We have a project consisting of multiple subprojects. With each subproject we potentially have some hibernate mapping files but in the end only <strong>one actual hibernate session</strong>. Those subprojects could be combined in several ways, some depend on each other. My problem is that actually I want to have a SessionFactoryBean which would be able to collect those mappings/mappinglocations from the applicationContext(s) and configure itself.</p>
<p>Has somebody written something like this, or do I have to do it myself (I envision something a bit like the urlresolver or viewresolver functionality from SpringMVC)?</p>
|
<p>Another (and simpler) approach would be to gather all your model classes in one project. Make all your other projects depend on it and have your SessionFactory created there. That is how I managed to solve the same problem and it works pretty well.</p>
|
<p><code>LocalSessionFactoryBean</code> has a configLocations property. You inject the list of config locations, and it will gather tham together for a single session factory configuration.</p>
| 19,034
|
<p>I'm trying to wrap my head around how to search for something that appears in the middle of a word / expression - something like searching for "LIKE %book% " - but in SQL Server (2005) full text catalog.</p>
<p>How can I do that? It almost appears as if both <code>CONTAINS</code> and <code>FREETEXT</code> really don't support wildcard at the <strong>beginning</strong> of a search expression - can that really be?</p>
<p>I would have imagined that <code>FREETEXT(*, "book")</code> would find anything with "book" inside, including "rebooked" or something like that. </p>
|
<p>unfortunately CONTAINS only supports prefix wildcards:</p>
<pre><code>CONTAINS(*, '"book*"')
</code></pre>
|
<p>why don't program an assembly in C# to compute all the non repeated sufixes. For example if you have the Text "eat the red meat" you can store in a field "eat at t the he e red ed d meat" (note that is not necesary to add eat at and t again) ind then in this field use full text search. A function for doing that can easily written in Csharp</p>
<p>x) I know it seems od... it's a workarround
x) I know I'm adding overhead in the insert / update .... only justified if this overhead is insignificant besides the improvement in the search function
x) I know there is also an overhead in the size of the stored data.</p>
<p>But I'm pretty conffident that will be quite fast</p>
| 37,727
|
<p>When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in <a href="http://djangoproject.com/" rel="nofollow noreferrer">Django</a>?</p>
|
<pre><code> from django import http
return http.HttpResponsePermanentRedirect('/yournewpage.html')
</code></pre>
<p>the browser will get the 301, and go to <code>/yournewpage.html</code> as expected. the other answer is technically correct, in that python is not handling the redirection per se, the browser is. this is what's happening under the hood:</p>
<pre><code>Browser Python HTTP
-------------------> GET /youroldpage.html HTTP/1.1
<------------------- HTTP/1.1 301 Moved Permanently
Location: /yournewpage.html
-------------------> GET /yournewpage.html HTTP/1.1
</code></pre>
|
<p>You can't.</p>
<p>301 is an HTTP return code that is directly acted upon by the browser. Many sites handle these two issues by first sending the user to a redirect-er page that tells the user about the change and then X seconds later sends them to the new page. But the redirect-er page <em>must</em> have a 200 code.</p>
<p>One small variant is to detect search engine spiders (by IP and/or user agent) and give <em>them</em> the 301. That way the search results point to your new page.</p>
| 34,838
|
<p>We recently installed SVN 1.5.2 (with VisualSVN/Apache) on some of our servers / virtual machines, and now when I send a commandline command with username/password they don't get cached anymore.
Before, we were running SVN 1.5.0 installed with CollabNet, on svn://, and the credentials were cached after the first command.</p>
<p>So far, I'm finding difficulties in troubleshooting this. My situation is:</p>
<ul>
<li>SERVER_SVN (SVN 1.5.2 via svn://)</li>
<li>SERVER_HTTP (SVN 1.5.2 via http://)</li>
</ul>
<p>Command from commandline to SERVER_SVN: credentials cached fine</p>
<p>Same command to SERVER_HTTP: credentials are not cached</p>
<p>So, it seems like an http/apache server problem... BUT, from Tortoise the credentials are cached to both servers, so it also seems a client call problem. I'm running out of ideas... </p>
<p>A sample command sequence I use:</p>
<pre><code>
svn ls c:\mylocalfolderSVN --username foo --password bar
svn ls c:\mylocalfolderSVN // this works
svn ls c:\mylocalfolderHTTP --username foo --password bar
svn ls c:\mylocalfolderHTTP // this fails
</code></pre>
<p>The last command stops and asks for authentication.</p>
<p>Is credentials caching different between svn:// and http://, or did we miss something in the server configuration?</p>
<p>Thanks in advance for any suggestion.</p>
|
<p>AFAIK the credential caching is a client responsibility. All the server does is ask for those credentials when necessary. I'd check the local client configuration files and maybe see what happens with different version clients.</p>
|
<p>Are you fully qualifying the domain name of the SVN server? If the caching for HTTP is cookie based and the server is writing a cookie with the FQDN, but your request doesn't use the FQDN (you are using svnserver and the FQDN is svnserver.company) then the cookie may not be valid and each request will need authentication.</p>
| 18,385
|
<p>What are the differences between a wiki and a CMS? Is there any?</p>
|
<p><strong>CMS:</strong></p>
<ol>
<li>A CMS focuses on <strong>content</strong> which is then published through standardized templates -- think of an online newspaper as driven by a huge CMS system. </li>
<li>It's about standardized <strong>publishing information</strong>. </li>
<li>CMS'es usually have a <strong>limited group</strong> of editors. </li>
<li>Useful for <strong>relatively static</strong> content, maintained by non-tech people.</li>
<li><strong>Much emphasis on style</strong>/presentation: very slick templates so it looks professional.</li>
</ol>
<p><strong>Wiki:</strong></p>
<ol>
<li>On the other hand, a wiki focuses on <strong>pages</strong> where each page represents a topic. </li>
<li>It's much more about <strong>collaboratively improving each topic</strong> (adding hyperlinks to other topics and websites counts as improving the topic). </li>
<li>Wikis are generally <strong>much more open to "the public"</strong> (or everybody in the company, vs. just the "internal communication" department).</li>
<li>Wikis are <em>meant</em> to be <strong>living, dynamic things,</strong> maintained by <em>everybody</em>.</li>
<li>Much <strong>emphasis on content:</strong> less slick templates but easier to find and update information.</li>
</ol>
|
<p>A CMS is a <strong>Content Management System</strong>. The idea behind the development of CMS evolved when the need for a Management System amplified. A CMS works as a cornerstone for web development by the help of which a developer can build powerful and feature-rich websites in minimum amount of time and effort. A good and powerful CMS not rectifies the frustrating need of writing repetitive and mundane codes, but also eliminates arduous and heavy tasks involved in building a website or web application.</p>
<p>Wikipedia on the other hand is an <strong>information directory</strong>. Sites such as Wikipedia can be built on a CMS, for instance <code>The New York Times</code> and <code>TechCrunch</code> is built on <code>WordPress</code>. In regard to information acquisition, Wikipedia is the best place that a user can go for - even better than Google. The number of articles Wikipedia contains is stupendous and highly reliable. The daily number of users depending on Wikipedia for information, itself serves as a testimonial for the service Wiki offers to us users.</p>
| 27,957
|
<p>In java, which regular expression can be used to replace these,
for example:</p>
<p>before:
aaabbb
after:
ab</p>
<p>before:
14442345
after:
142345</p>
<p>thanks!</p>
|
<p>In perl</p>
<pre><code>s/(.)\1+/$1/g;
</code></pre>
<p>Does the trick, I assume if java has perl compatible regexps it should work too.</p>
<p>Edit: Here is what it means</p>
<pre><code>s {
(.) # match any charater ( and capture it )
\1 # if it is followed by itself
+ # One or more times
}{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences)
</code></pre>
<p>Edit: As others have pointed out, the syntax in Java would become </p>
<pre><code>original.replaceAll("(.)\\1+", "$1");
</code></pre>
<p>remember to escape the \1</p>
|
<p>in TextEdit (assuming posix expressions)
find: [a]+[b]+
replace with: ab</p>
| 13,158
|
<p>Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why?</p>
<p>I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed.
I've always felt that the default settings had more to do with looking good on benchmarks, which tend to be small programs that will fit entirely within the L2 cache than what's best for overall performance, so I normally set it optimize for smallest size.</p>
|
<p>As a Gentoo user I have tried quite a few optimizations on the complete OS and there have been endless discussions on the <a href="http://forums.gentoo.org/" rel="noreferrer">Gentoo forums</a> about it. Some good flags for GCC can be found in the <a href="http://gentoo-wiki.com/Safe_Cflags" rel="noreferrer">wiki</a>.</p>
<p>In short, optimizing for size worked best on an old Pentium3 laptop with limited ram, but on my main desktop machine with a Core2Duo, -O2 gave better results over all.</p>
<p>There's also a <a href="http://www.pixelbeat.org/scripts/gcccpuopt" rel="noreferrer">small script</a> if you are interested in the x86 (32 bit) specific flags that are the most optimized.</p>
<p>If you use gcc and really want to optimize a specific application, try <a href="http://www.coyotegulch.com/products/acovea/" rel="noreferrer">ACOVEA</a>. It runs a set of benchmarks, then recompile them with all possible combinations of compile flags. There's an example using Huffman encoding on the site (lower is better):</p>
<pre><code>A relative graph of fitnesses:
Acovea Best-of-the-Best: ************************************** (2.55366)
Acovea Common Options: ******************************************* (2.86788)
-O1: ********************************************** (3.0752)
-O2: *********************************************** (3.12343)
-O3: *********************************************** (3.1277)
-O3 -ffast-math: ************************************************** (3.31539)
-Os: ************************************************* (3.30573)
</code></pre>
<p>(Note that it found -Os to be the slowest on this Opteron system.)</p>
|
<p>We always use maximize for optimal speed but then, all the code I write in C++ is somehow related to bioinformatics algorithms and speed is crucial while the code size is relatively small.</p>
| 7,739
|
<p>In Pseudo code</p>
<pre><code>If Domain inList(GB,US,ES,FR Then
Print This Html
Else
Print This HTML
EndIf
</code></pre>
|
<p>This is a<em>very</em> general form, but where you don't know the list at design-time, so long as you can get a reference to a nodeset which represents the list you can do a simple test like:</p>
<pre><code><xsl:when test="$listset/item[@property=$variable]">
</code></pre>
<p>where say $variable = /foo/bar/@property and $listset = /foo/list for XML</p>
<pre><code><?xml version="1.0"?>
<foo>
<bar property="gb" />
<list>
<item property="gb"/>
<item property="us"/>
</list>
</foo>
</code></pre>
|
<p>If you are using XSLT 2.0 given the file
</p>
<p>You can use something like this:<br>
<code>
<xsl:template match="list/item"><br>
Property [<xsl:value-of select="@property"/>] html<br>
</xsl:template><br>
<br>
<xsl:template match="list/item[some $x in ('us', 'gb') satisfies $x eq @property ]"><br>
Property [<xsl:value-of select="@property"/>] HTML<br>
</xsl:template><br>
</code></p>
| 48,587
|
<p>Is it better to do this:</p>
<pre><code>try
{
...
}
catch (Exception ex)
{
...
throw;
}
</code></pre>
<p>Or this:</p>
<pre><code>try
{
...
}
catch (Exception ex)
{
...
throw ex;
}
</code></pre>
<p>Do they do the same thing? Is one better than the other?</p>
|
<p>You should always use the following syntax to rethrow an exception. Else you'll stomp the stack trace:</p>
<pre><code>throw;
</code></pre>
<p>If you print the trace resulting from <code>throw ex</code>, you'll see that it ends on that statement and not at the real source of the exception.</p>
<p>Basically, it should be deemed a criminal offense to use <code>throw ex</code>.</p>
<hr />
<p>If there is a need to rethrow an exception that comes from somewhere else (AggregateException, TargetInvocationException) or perhaps another thread, you also shouldn't rethrow it directly. Rather there is the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo" rel="noreferrer">ExceptionDispatchInfo</a> that preserves all the necessary information.</p>
<pre><code>try
{
methodInfo.Invoke(...);
}
catch (System.Reflection.TargetInvocationException e)
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();
throw; // just to inform the compiler that the flow never leaves the block
}
</code></pre>
|
<p>It depends. In a debug build, I want to see the original stack trace with as little effort as possible. In that case, "throw;" fits the bill.</p>
<p>In a release build, however, (a) I want to log the error with the original stack trace included, and once that's done, (b) refashion the error handling to make more sense to the user. Here "Throw Exception" makes sense. It's true that rethrowing the error discards the original stack trace, but a non-developer gets nothing out of seeing stack trace information, so it's okay to rethrow the error.</p>
<pre><code> void TrySuspectMethod()
{
try
{
SuspectMethod();
}
#if DEBUG
catch
{
//Don't log error, let developer see
//original stack trace easily
throw;
#else
catch (Exception ex)
{
//Log error for developers and then
//throw a error with a user-oriented message
throw new Exception(String.Format
("Dear user, sorry but: {0}", ex.Message));
#endif
}
}
</code></pre>
<p>The way the question is worded, pitting "Throw:" vs. "Throw ex;" makes it a bit of a red herring. The real choice is between "Throw;" and "Throw Exception," where "Throw ex;" is an unlikely special case of "Throw Exception."</p>
| 21,506
|
<p>I was just wondering if anyone knew of a good way that I could parse the file at the bottom of the post.</p>
<p>I have a database setup with the correct tables for each section eg Refferal Table,Caller Table,Location Table. Each table has the same columns that are show in the file below</p>
<p>I would really like something that is fairly genetic so if the file layout changes it won't mess me around to much. At the moment I am just reading the file in a line at a time and just using a case statement to check which section i'm in. </p>
<p>Is anyone able to help me with this?</p>
<p>PS. I am using VB but C# or anything else will be fine, also the x's in the document are just personal info I have blanked</p>
<p>Thanks,
Nathan</p>
<p>File:---></p>
<pre><code>DIAL BEFORE YOU DIG
Call 1100, Fax 1300 652 077
PO Box 7710 MELBOURNE, VIC 8004
Utilities are requested to respond within 2 working days and reference the Sequence number.
[REFFERAL DETAILS]
FROM= Dial Before You Dig - Web
TO= Technical Services
UTILITY ID= xxxxxx
COMPANY= {Company Name}
ENQUIRY DATE= 02/10/2008 13:53
COMMENCEMENT DATE= 06/10/2008
SEQUENCE NO= xxxxxxxxx
PLANNING= No
[CALLER DETAILS]
CUSTOMER ID= 403552
CONTACT NAME= {Name of Contact}
CONTACT HOURS= 0
COMPANY= Underground Utility Locating
ADDRESS= {Address}
SUBURB= {Suburb}
STATE= {State}
POSTCODE= 4350
TELEPHONE= xxxxxxxxxx
MOBILE= xxxxxxxxxx
FAX TYPE= Private
FAX NUMBER= xxxxxxxxxx
PUBLIC ADDRESS= xxxxxxxxxx
PUBLIC TELEPHONE=
EMAIL ADDRESS= {Email Address}
[LOCATION DETAILS]
ADDRESS= {Location Address}
SUBURB= {Location Suburb}
STATE= xxx
POSTCODE= xxx
DEPOSITED PLAN NO= 0
SECTION & HUNDRED NO= 0
PROPERTY PHONE NO=
SIDE OF STREET= B
INTERSECTION= xxxxxx
DISTANCE= 0-200m B
ACTIVITY CODE= 15
ACTIVITY DESCRIPTION= xxxxxxxxxxxxxxxxxx
MAP TYPE= StateGrid
MAP REF= Q851_63
MAP PAGE=
MAP GRID 1=
MAP GRID 2=
MAP GRID 3=
MAP GRID 4=
MAP GRID 5=
GPS X COORD=
GPS Y COORD=
PRIVATE/ROAD/BOTH= B
TRAFFIC AFFECTED= No
NOTIFICATION NO= 3082321
MESSAGE= entire intersection of Allora-Clifton rd , Hillside
rd and merivale st
MOCSMESSAGE= Digsafe generated referral
Notice: Please DO NOT REPLY TO THIS EMAIL as it has been automatically generated and replies are not monitored. Should you wish to advise Dial Before You Dig of any issues with this enquiry, please Call 1100
(See attached file: 3082321_LLGDA94.GML)
</code></pre>
|
<p><a href="http://www.google.com/search?client=safari&rls=en-us&q=parse+.ini+vb+.net&ie=UTF-8&oe=UTF-8" rel="nofollow noreferrer">Google has the answers</a>, once you know that the file-format is called '.ini'</p>
<p><strong>Edit:</strong> That is, it's an .ini plus some extra leading/trailing gunk.</p>
|
<pre><code>Using f As StreamReader = File.OpenText("sample.txt")
Dim g As String = "undefined"
Do
Dim s As String = f.ReadLine
If s Is Nothing Then Exit Do
s = s.Replace(Chr(9), " ")
If s.StartsWith("[") And s.EndsWith("]") Then
g = s.Substring("[".Length, s.Length - "[]".Length)
Else
Dim ss() As String = s.Split(New Char() {"="c}, 2)
If ss.Length = 2 Then
Console.WriteLine("{0}.{1}={2}", g, Trim(ss(0)), Trim(ss(1)))
End If
End If
Loop
End Using
</code></pre>
| 19,468
|
<p>I'm setting up CI at present using Thoughtworks Studios' Cruise, Gallio to run xunit.net fact/tests, and ncover 2 to do code-coverage.</p>
<p>I noticed that running the code-coverage pegs one of the four CPUs that our build-agent server has, and wondered whether there was a multi-threaded test-runner that I might use instead, to take advantage of the other 3 cores that are sat idle? I had a quick search around, but most hits are in reference to testing multi-threaded code, not multi-threaded test running...</p>
|
<p>Gallio <a href="http://code.google.com/p/mb-unit/issues/detail?id=355" rel="nofollow noreferrer">implements</a> parallel test execution.</p>
|
<p>If nothing else, I know that in CruiseControl.NET, you could multiple two operations run simultaneously. I would think the same would be true for Cruise. You could have four instances of run on 1/4 of your tests each, and then stitch the results back together. Knowing when to merge them may be difficult though.</p>
| 36,080
|
<p>I'm having a problem with a POST I'm doing using the HttpWebRequest object from C#. In order to analyze the problem I would like to know exactly what is being sent over the wire. The problem is that I'm also using HTTPS so I can't sniff the wire. I need some way of printing out to the Console all the relevant information of the HttpWebRequest object or something like that. Thank you for your help.</p>
|
<p>You can use <a href="http://www.fiddler2.com/fiddler2/" rel="noreferrer">Fiddler</a> to debug HTTPS traffic.</p>
|
<p>Could you set a breakpoint in the code and look at the Request object in the debugger and look through the ServerVariables collections to see what it has? Alternatively, you could do a Response.Write looping over each element in the Request.ServerVariables and see the name/value pairs that are stored in a web page if you want that.</p>
| 40,631
|
<p>Tk GUI's seem to be universally considered ugly, but I'd like to know why specifically. Some in the Tcl/Tk world would argue that this is a moot point as there is much better support now for native look and feel, which is a big reason I decided on Tcl/Tk. Now, however, the problem is, because I'm leveraging a Tcl/Starkit vfs (virtual file system), the native file dialogs don't work, and I'm going to have to revert to pure Tk file dialogs.</p>
<p>Please I'm looking for specific, technical reasons, e.g. regarding font aliasing (or lack thereof) or font style, or color, etcetera. Because I personally don't buy the "it's just ugly to me". To me, its just different, and I switch between Mac and Windows and Linux with regularity, so I'm used to different looks/feels.</p>
<p>Specifically, motif-ish look of a traditional Tk GUI is regarded as ugly:<br></p>
<p><img src="https://web.archive.org/web/20140120195559/http://ascend4.org/images/e/e4/Browser01.png" alt="Tcl/Tk GUI Sample"></p>
|
<p>I think part of the reason is that Tk is surprisingly powerful and easy to use but it doesn't do much hand-holding. Since it is so easy, people with little experience in UI design can get something to work in very short order. But, without a lot of experience they rely on defaults and shortest-path-to-a-solution (read: don't take time to hide scrollbars when they aren't needed, don't use common idioms for toolbars, don't properly align widgets, etc). </p>
<p>Unfortunately, Tk's defaults aren't always the prettiest. As the screenshot in the question shows, the default uses relatively thick border widths and suboptimal fonts, and the checkboxes are indeed straight out of the 80's. In the hands of an expert, though, all these problems are minor issues that can be take care of in idle moments. </p>
<p>For example, with five minutes of tweaking, the original screenshot can look like this:</p>
<p><a href="https://i.stack.imgur.com/md7eD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/md7eD.png" alt="slightly improved ui"></a></p>
<p>Certainly that's still a bit clunky looking, but arguably it's better than the original by a considerable bit. With an hour dedicated to the task, several more improvements could be made.</p>
<p>With tk 8.5 (and actually for a couple years prior) there is support for themes and for native widgets, and even the X11 version gets a minor facelift. Tk is still behind the curve in eye candy though, forcing one to "roll their own" if the design calls for gradients, animations and so forth.</p>
<p>Tcl and Tk, however, remain a good pragmatic solution for most types of applications. If you're trying to compete with a flash application you'll lose. But if you have an industrial application that just needs to work and be usable and perhaps multi-platform, Tk is still one of the best choices out there.</p>
<hr>
<p>As of 2015, there's a nice write-up about modernizing Tkinter's IDLE IDE. The article describes some of the steps taken to make IDLE more modern looking:</p>
<ul>
<li><a href="http://www.tkdocs.com/tutorial/idle.html" rel="noreferrer">http://www.tkdocs.com/tutorial/idle.html</a></li>
</ul>
|
<p>Tk is beautiful or not, it depends on the person but I would say that its atleast not ugly (except for android). Have a look at the screenshots of a program I made using pure python and tkinter (Tk). You just need to know how to use it in more beautiful manner.<img src="https://i.stack.imgur.com/inPgJ.png" alt="enter image description here"><img src="https://i.stack.imgur.com/hWbTR.png" alt="enter image description here"></p>
| 45,465
|
<p>I have a page with a tab control and each control has almost 15 controls. In total there are 10 tabs and about 150 controls in a page (controls like drop down list, textbox, radiobutton, listbox only).</p>
<p>My requirement is that there is a button (submit) at the bottom of the page. I need to check using JavaScript that at least 3 options are selected out of 150 controls in that page irrespective of the tabs which they choose. </p>
<p>Please suggest the simplest and easiest way which this could be done in JavaScript on my aspx page.</p>
|
<p>Assuming there's only one form on the page (if more then loop through forms and nest the below loop within).</p>
<pre><code> var selectedCount = 0;
var element;
for (var i = 0; i < document.forms[0].elements.length; i++)
{
element = document.forms[0].elements[i];
switch (element.type)
{
case 'text':
if (element.value.length > 0)
{
selectedCount++;
}
break;
case 'select-one':
if (element.selectedIndex > 0)
{
selectedCount++;
}
break;
//etc - add cases for checkbox, radio, etc.
}
}
</code></pre>
|
<p>I would look at something based on the prototype <a href="http://www.prototypejs.org/api/form#method-serializeelements" rel="nofollow noreferrer">serialize</a> method - it can give you a hash of all form controls - it might give you a headstart on what you want. </p>
<p>Something like firebug will help you see what you get and assess if it meets your needs.</p>
| 22,648
|
<p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this', 'is', 'a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
|
<p>You want <code>split</code>, from the built-in <a href="https://docs.python.org/library/shlex.html" rel="noreferrer"><code>shlex</code></a> module.</p>
<pre><code>>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
</code></pre>
<p>This should do exactly what you want.</p>
<p>If you want to preserve the quotation marks, then you can pass the <code>posix=False</code> kwarg.</p>
<pre><code>>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
</code></pre>
|
<p>Try this:</p>
<pre><code> def adamsplit(s):
result = []
inquotes = False
for substring in s.split('"'):
if not inquotes:
result.extend(substring.split())
else:
result.append(substring)
inquotes = not inquotes
return result
</code></pre>
<p>Some test strings:</p>
<pre><code>'This is "a test"' -> ['This', 'is', 'a test']
'"This is \'a test\'"' -> ["This is 'a test'"]
</code></pre>
| 10,542
|
<p>How can I detect, using php, if the machine has oracle <code>(oci8 and/or pdo_oci)</code> installed?</p>
<p>I'm working on a <code>PHP</code> project where some developers, such as myself, have it installed, but there's little need for the themers to have it. How can I write a quick function to use in the code so that my themers are able to work on the look of the site without having it crash on them?</p>
|
<p>if the oci extension isn't installed, then you'll get a fatal error with farside.myopenid.com's answer, you can use function_exists('oci_connect') or extension_loaded('oci8') (or whatever the extension's actually called)</p>
|
<p>I dont know if I fully understand your question but a simple way would be to do this:</p>
<pre><code><?php
$connection = oci_connect('username', 'password', 'table');
if (!$connection) {
// no OCI connection.
}
?>
</code></pre>
| 13,666
|
<p>On my reading spree, I stumbled upon something called <a href="http://en.wikipedia.org/wiki/Intentional_programming" rel="noreferrer">Intentional Programming</a>.
I understood it somewhat, but I not fully. If anyone can explain it in better detail, please do. Is it being used in any real application?</p>
|
<p>You got me started on this one...<br>
Looks like C. Simonyi wanted to step to the next level of abstraction from High level languages. Reduce the dependency of customers on developers to make every change.. in code (cryptic for people not in development).
So he invents this new product called IP, which has <strong>a WYSIWYG type GUI editor</strong> to create a domain specific model. (i.e. IP has a GUI to create the building blocks for your app.. LISP allowed you to create the meta/building blocks but not in a way that domain experts could easily do it.)<br>
Like the models in UML, the promise is that you can <strong>auto-generate the corresponding source code</strong> at the "push of a button". So the domain experts can tweak the model in the future and press the Bake button to deliver the next version of the app.
It seems to utilise DSLs however with the added benefit that <strong>multiple user-created DSLs can talk with each other</strong> via a built-in IP mechanism... which means the finance model and sales model can interact and reuse blocks as needed. As with DSLs, you get the benefit of code that conveys developer intent rather than appeases implementation language constraints.</p>
<p>The idea being to give greater control to the BA and domain experts who actually know what's needed... </p>
<p><strong>Update</strong>:
Real world use looks like 'not yet'.. although Simonyi believes '<a href="http://d5.allthingsd.com/20070531/d5-charles-simonyi/" rel="nofollow noreferrer">absolutely in the long term</a>'.<br>
<em>Short Story</em>: MS squished IP in favor of .Net framework, Simonyi left MS and formed his own company '<a href="http://www.intentsoft.com/" rel="nofollow noreferrer">Intentional Software</a>'.. with the contract that he could use the IP ideas but he would have to rewrite his working proto from the ground up.. (that should slow him down). It's still Work-In-Progress I think.. and being written in C# (to boot) </p>
<p>Sources:</p>
<ul>
<li><a href="https://www.technologyreview.com/s/407091/anything-you-can-do-i-can-do-meta/" rel="nofollow noreferrer"><em>Anything you can do, I can do meta</em></a> by Scott Rosenberg, MIT Tech Review (2007)</li>
</ul>
<p>To think till yesterday.. I didn't know a thing about this. Investigative reporter signing off. Going back to day job :)</p>
|
<p>It's where you intend to program, you don't just accidently do it. ;)</p>
| 24,588
|
<p>I'm starting on a project that I expect will include a substantial amount of non-Java code (mostly shell and SQL scripts).</p>
<p>I would still like to manage this project with Maven. What are the best practices wrt non-Java source code and Maven? Where should the source go? What happens to them during the different lifecycle phases? Any pointers or links to more information would be greatly appreciated.</p>
|
<p>You must not put the non-Java code into resources, if you don't want to include these files into your JAR files like heckj has suggested. Everything that is located in resources is automatically copied into the JAR file and I guess you don't want shell scripts and SQL scripts be included in a JAR file, right?</p>
<p>So the Maven way would be to create additional folders under src/main. E.g. create a <strong>sql</strong> folder for your SQL scripts, an <strong>sh</strong> folder for your shell scripts and so on. This is the location where other Maven plugins also expect sources, e.g. for C++, Groovy and so on.</p>
|
<p>I keep in a separate folder src/main/sql. Check <a href="http://maven.apache.org/pom.html#Resources" rel="nofollow">this</a> link for more info.</p>
| 20,985
|
<p>Is there a master list of the Big-O notation for everything? Data structures, algorithms, operations performed on each, average-case, worst-case, etc.</p>
|
<p><a href="http://xlinux.nist.gov/dads/" rel="nofollow noreferrer">Dictionary of Algorithms and Data Structures</a> is a fairly comprehensive list, and includes complexity (Big-O) in the algorithms' descriptions. If you need more information, it'll be in one of the linked references, and there's always Wikipedia as a fallback.</p>
|
<p><a href="http://mitpress.mit.edu/algorithms/" rel="nofollow noreferrer">Introduction to Algorithms, Second Edition</a>, aka CLRS (Cormen, Leiserson, Rivest, Stein), is the closest thing I can think of.</p>
<p>If that fails, then try <a href="http://www-cs-faculty.stanford.edu/~knuth/taocp.html" rel="nofollow noreferrer">The Art of Computer Programming</a>, by Knuth. If it's not in those, you probably need to do some real research.</p>
| 21,778
|
<p>Is there a method (other than trial and error) I can use to find unused image files? How about CSS declarations for ID's and Classes that don't even exist in the site?</p>
<p>It seems like there might be a way to write a script that scans the site, profile it, and see which images and styles are never loaded.</p>
|
<p>You don't have to pay any web service or search for an addon, you already have this in Google Chrome under F12 <code>(Inspector)->Audits->Remove unused CSS rules</code></p>
<p>Screenshot:<img src="https://i.stack.imgur.com/Soozt.png" alt="Screenshot"></p>
<p><strong>Update: 30 Jun, 2017</strong></p>
<p>Now Chrome 59 provides <strong>CSS and JS code coverage</strong>. See <a href="https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage" rel="noreferrer">https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage</a></p>
<p><a href="https://i.stack.imgur.com/eBWA1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eBWA1.png" alt="enter image description here"></a></p>
|
<p>This little tool gives you a list of the css rules in use by some html.</p>
<p>Here it is on <a href="http://codepen.io/tmorrow-hyphensolutions/pen/GprdRQ" rel="nofollow">Code Pen</a></p>
<p>Click on <kbd>Run code snippet</kbd>, then click on <kbd>Full page</kbd> to get in to it. Then follow the instructions in the snippet. You can run it full page to see it work with your html / css.</p>
<p>But it's easier just to bookmark my code pen as a tool.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* CSS CLEANER INSTRUCTIONS
1. Paste your HTML into the HTML window
2. Paste your CSS into the CSS window
5. The web page result now ends with a list of just the CSS used by your HTML!
*/
function cssRecursive(e) {
var cssList = css(e);
for (var i = 0; i < e.children.length; ++i) {
var childElement = e.children[i];
cssList = union(cssList, cssRecursive(childElement));
}
return cssList;
}
function css(a) {
var sheets = document.styleSheets,
o = [];
a.matches = a.matches || a.webkitMatchesSelector || a.mozMatchesSelector || a.msMatchesSelector || a.oMatchesSelector;
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.matches(rules[r].selectorText)) {
o.push(rules[r].cssText);
}
}
}
return o;
}
function union(x, y) {
return unique(x.concat(y));
};
function unique(x) {
return x.filter(function(elem, index) {
return x.indexOf(elem) == index;
});
};
document.write("<br/><hr/><code style='background-color:white; color:black;'>");
var allCss = cssRecursive(document.body);
for (var i = 0; i < allCss.length; ++i) {
var cssRule = allCss[i];
document.write(cssRule + "<br/>");
}
document.write("</code>");</code></pre>
</div>
</div>
</p>
| 5,326
|
<p>In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:</p>
<pre><code>::foo();
</code></pre>
|
<p>It means global scope. You might need to use this operator when you have conflicting functions or variables in the same scope and you need to use a global one. You might have something like:</p>
<pre><code>void bar(); // this is a global function
class foo {
void some_func() { ::bar(); } // this function is calling the global bar() and not the class version
void bar(); // this is a class member
};
</code></pre>
<p>If you need to call the global bar() function from within a class member function, you should use ::bar() to get to the global version of the function.</p>
|
<p>referring to the global scope</p>
| 10,083
|
<p>I'm using Castle Windsor to do some dependency injection, specifically I've abstracted the DAL layer to interfaces that are now being loaded by DI.</p>
<p>Once the project is developed & deployed all the .bin files will be in the same location, but for while I'm developing in Visual Studio, the only ways I can see of getting the dependency injected project's .bin file into the startup project's bin folder is to either have a post-build event that copies it in, or to put in a manual reference to the DAL project to pull the file in.</p>
<p>I'm not totally thrilled with either solution, so I was wondering if there was a 'standard' way of solving this problem?</p>
|
<p>Could you set the build output path of the concrete DAL project to be the bin folder of the dependent project? </p>
|
<p>Mike: Didn't think of that, that could work, have to remember to turn off copy-local for any libraries / projects that are common between them</p>
| 5,156
|
<p>Can I use the ClickOnce deployment method to deploy and auto update applications targeted for the windows mobile platform (eg smartphone or pocket pc)?</p>
|
<p>True Click-Once is not supported. You might look at these articles to give you a better feel for what can be done:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/aa446503.aspx" rel="noreferrer">MSDN Article on Deployment Patterns</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/aa446487.aspx" rel="noreferrer">Alex Feinman's article on self-updating apps</a></li>
</ul>
<p>You can also package the app into a <a href="http://msdn.microsoft.com/en-us/library/aa446504.aspx" rel="noreferrer">CAB File</a> that you put on the web for OTA deployment. There are also a couple third-party providers like <a href="https://cloudsync.com" rel="noreferrer">CloudSync</a> and <a href="http://www.b2m-solutions.com" rel="noreferrer">mProdigy</a> (used neither so YMMV) for OTA as well.</p>
|
<p>No. Hopefully in the future.</p>
| 14,222
|
<p>I've got the following user control:</p>
<pre><code><TabItem
x:Name="Self"
x:Class="App.MyTabItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
>
<TabItem.Header>
<!-- This works -->
<TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/>
</TabItem.Header>
<TabItem.ContentTemplate>
<DataTemplate>
<!-- This binds to "Self" in the surrounding window's namespace -->
<TextBlock Text="{Binding ElementName=Self, Path=ShortLabel, UpdateSourceTrigger=PropertyChanged}"/>
</code></pre>
<p>This custom TabItem defines a <code>DependencyProperty</code> 'ShortLabel' to implement an interface. I would like to bind to this and other properties from within the <code>TabItem</code>'s <code>DataTemplate</code>. But due to strange interactions, the <code>TextBlock</code> within the <code>DataTemplate</code> gets bound to the <strong>parent container</strong> of the <code>TabItem</code>, which also is called "Self", but defined in another Xaml file.</p>
<h2>Question</h2>
<p>Why does the Binding work in the TabItem.Header, but not from within TabItem.ContentTemplate, and how should I proceed to get to the user control's properties from within the DataTemplate?</p>
<h2>What I already tried</h2>
<ul>
<li><code>TemplateBinding</code>: Tries to bind to the ContentPresenter within the guts of the <code>TabItem</code>.</li>
<li><code>FindAncestor, AncestorType={x:Type TabItem}</code>: Doesn't find the <code>TabItem</code> parent. This doesn't work either, when I specify the <code>MyTabItem</code> type.</li>
<li><code>ElementName=Self</code>: Tries to bind to a control with that name in the wrong scope (parent container, not <code>TabItem</code>). I think that gives a hint, why this isn't working: the DataTemplate is not created at the point where it is defined in XAML, but apparently by the parent container.</li>
</ul>
<p>I assume I could replace the whole <code>ControlTemplate</code> to achieve the effect I'm looking for, but since I want to preserve the default look and feel of the <code>TabItem</code> without having to maintain the whole <code>ControlTemplate</code>, I'm very reluctant to do so.</p>
<h2>Edit</h2>
<p>Meanwhile I have found out that the problem is: <code>TabControl</code>s can't have (any) <code>ItemsTemplate</code> (that includes the <code>DisplayMemberPath</code>) if the <code>ItemsSource</code> contains <code>Visual</code>s. There <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/956eaba3-53bd-4683-b3dd-28b20e4b7526/" rel="nofollow noreferrer">a thread on MSDN Forum explaining why</a>. </p>
<p>Since this seems to be a fundamental issue with WPF's TabControl, I'm closing the question. Thanks for all your help!</p>
|
<p>What appears to be the problem is that you are using a ContentTemplate without actualy using the content property. The default DataContext for the ContentTemplate's DataTemplate is the Content property of TabItem. However, none of what I said actually explains <strong>why</strong> the binding doesn't work. Unfortunately I can't give you a definitive answer, but my best guess is that it is due to the fact that the TabControl reuses a ContentPresenter to display the content property for all tab items.</p>
<p>So, in your case I would change the code to look something like this:</p>
<pre><code><TabItem
x:Class="App.MyTabItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}"
Content="{Binding ShortLabel, RelativeSource={RelativeSource Self}}" />
</code></pre>
<p>If ShortLabel is a more complex object and not just a string then you would want to indroduce a ContentTemplate:</p>
<pre><code><TabItem
x:Class="App.MyTabItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
Header="{Binding ShortLabel, RelativeSource={RelativeSource Self}}"
Content="{Binding ComplexShortLabel, RelativeSource={RelativeSource Self}}">
<TabItem.ContentTemplate>
<DataTemplate TargetType="{x:Type ComplexType}">
<TextBlock Text="{Binding Property}" />
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
</code></pre>
|
<p>Try this. I'm not sure if it will work or not, but </p>
<pre><code><TabItem
x:Name="Self"
x:Class="App.MyTabItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:App"
>
<TabItem.ContentTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=ShortLabel}"/>
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
</code></pre>
<p>If it doesn't work, try sticking this attribute in the <TabItem/>:</p>
<pre><code>DataContext="{Binding RelativeSource={RelativeSource self}}"
</code></pre>
| 17,914
|
<p>I am working on a .NET application that displays multiple charts. My users would like an easy way to say "take chart #3 and maximize it on my fourth monitor".</p>
<p>How can I determine the number of monitors so I can give them a selection of "monitor #1, monitor #2, etc"? (Not every user has the same number of monitors.)</p>
<p>And once the user has selected a particular monitor, how can I use that information to position the chart they're trying to maximize?</p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx" rel="nofollow noreferrer">Screen</a> class helps you a lot by finding the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.allscreens.aspx" rel="nofollow noreferrer">available screens</a>.</p>
<p>When you "maximize" a form, the form will automatically maximize to the size of the Screen the form is in.</p>
<p>You can position it yourself, or let Windows take care of it, by just placing the form on the right "Screen", and maximizing it. Or use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.workingarea.aspx" rel="nofollow noreferrer">WorkingArea</a> of the screen, and fill that yourself.</p>
|
<p>Try the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx" rel="nofollow noreferrer">Screen</a> class in System.Windows.Forms. The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.allscreens.aspx" rel="nofollow noreferrer">AllScreens</a> static member contains the list of all screens attached to the system. Once you choose a screen, you can use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.bounds.aspx" rel="nofollow noreferrer">Bounds</a> member to decide how to maximize a window to that screen.</p>
| 24,592
|
<p>I have an asp page that uses jQuery ajax to load member counts into a bunch of <code>div</code>s after a page is loaded.</p>
<p>It works perfectly well in FireFox, and with clients that have a small number of groups.</p>
<p>For the small number of clients that have many groups (500+), I am getting an error in IE. The ajax calls seem to be running synchronously, because the click events won't register until every ajax call has returned.</p>
<p>The series of ajax requests is just 1 request for most clients. It is only broken up into multiple requests for clients with a VERY large number of groups.</p>
<p>Now, I've seen the bug where <code>$("a").click</code> functions are not bound if links are added after the DOM is loaded. The links that aren't working are not being loaded by AJAX, they do not fall into this category.</p>
<p>Here is the pseudocode:</p>
<pre><code>ready()
{
// count the number of groups that this user has, adding the ids to a list
if( count < 50 )
{
runAjax();
}
else
{
// this calls the ajax request on groups of 50 ids
// it pauses briefly after each request by using setTimeout to call the next
runAjaxRecursively();
}
}
</code></pre>
<p>And here is the ajax request:</p>
<pre><code>// run the HTTPRequest
$.ajax({
async: true,
type: "POST",
url: "emailcatcount.asp?idList="+idList,
data: "idList="+idList,
dataType: "html",
success: function(html) { // blah blah blah }
});
</code></pre>
<p>Anyway, the code works fine, so please consider any errors as typos. The only problem is that, in IE, click events won't fire until every single ajax call has returned.</p>
<p>Does anyone know why this would occur? Notice that I am setting <code>async</code> to true.</p>
<p>Does it have anything to do with how jQuery's ready event is processed in IE?</p>
<p>I am bewildered, and have spent a few days on this, so any ideas are appreciated.</p>
|
<pre><code>int getNextDay(int days_mask, int today) {
if (!days_mask) return -1; // no days set
days_mask |= days_mask << 7; // duplicate days into next week
mask = 1 << (today % 7); // keep track of the day
while (!(mask & days_mask)) {
mask <<= 1;
++today;
}
return today % 7;
}
</code></pre>
<p>So that's just one if at the beginning and while loop. How's that?</p>
<p><strong>Edit:</strong> I just realized there was a degenerate case where if the use passes today>=14 (or greater than the highest bit set) the while loop becomes infinite. The (today % 7) on line 4 fixes this case.</p>
<p>And if I may grouse (light-heartedly) about the other version getting the checkmark, my version only have 2 modulus calls, while the checked solution will have a minimum of 1 and a maximum of 6 modulus calls.</p>
<p>Also, the comment about does the function return "today" if today is set is interesting. If the function should not return today unless today is the only day in the set would require that you pre-increment today on line 3 of my solution.</p>
|
<p>I understand your question this way:</p>
<pre><code>// returns t (today) if no weekday is set in the mask.
int getNextDay(int m, int t) {
int i, idx;
for(i = 0, idx=t%7; i<7 && !((1<<idx)&m); i++, idx=(idx+1)%7)
/* body empty */ ;
return (i == 7) ? t : (idx + 1);
}
// getNextDay(8|2, 2) == 4, getNextDay(64, 2) == 7
// getNextDay(128, 2) == 2
</code></pre>
| 45,742
|
<p>In my code behind I wire up my events like so:</p>
<pre><code>protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnUpdateUser.Click += btnUpateUserClick;
}
</code></pre>
<p>I've done it this way because that's what I've seen in examples. </p>
<ul>
<li>Does the base.OnInit() method need to be called? </li>
<li>Will it be implicitly be called? </li>
<li>Is it better to call it at the beginning of the method or at the end? </li>
<li>What would be an example where confusion over the base method can get you in trouble? </li>
</ul>
|
<p>I should clarify:</p>
<p>The guidelines recommend that firing an event should involve calling a virtual "On<em>EventName</em>" method, but they also say that if a derived class overrides that method and forgets to call the base method, the event should still fire.</p>
<p>See the "Important Note" about halfway down <a href="http://msdn.microsoft.com/en-us/library/ms229011.aspx" rel="nofollow noreferrer">this page</a>:</p>
<blockquote>
<p>Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.</p>
</blockquote>
|
<p>In this case, if you don't call the base OnInit, then the Init even will not fire.</p>
<p>In general, it is best practice to ALWAYS call the base method, unless you specifically know that you do not want the base behaviour to occur.</p>
<p>Whether its called at the start or the end depends on how you want things to work. In a case like this, where you are using an override instead of hooking up an event handler, calling it at the start of the method makes more sense. That way, your code will run after any handlers, which makes it more emulate a "normal" event handler.</p>
| 3,972
|
<p>I often find linq being problematic when working with custom collection object.
They are often defened as</p>
<p>The base collection</p>
<pre><code>abstract class BaseCollection<T> : List<T> { ... }
</code></pre>
<p>the collections is defined as</p>
<pre><code>class PruductCollection : BaseCollection<Product> { ... }
</code></pre>
<p>Is there a better way to add results from a linq expession to this collection than
addrange or concat?</p>
<pre><code>var products = from p in HugeProductCollection
where p.Vendor = currentVendor
select p;
PruductCollection objVendorProducts = new PruductCollection();
objVendorProducts.AddRange(products);
</code></pre>
<p>It would be nice if the object returned form the linq query was of my custom collection type. As you seem to need to enumerate the collection two times to do this.</p>
<p><strong>EDIT</strong> :
After reading the answers i think the best solution is to implementa a ToProduct() extention.
Wonder if the covariance/contravariance in c#4.0 will help solve these kinds of problems.</p>
|
<p>The problem is that LINQ, through extension methods on <code>IEnumerable<T></code>, knows how to build Arrays, Lists, and Dictionaries, it doesn't know how to build your custom collection. You could have your custom collection have a constructor that takes an <code>IEnumerable<T></code> or you could write you. The former would allow you to use the LINQ result in your constructor directly, the latter would allow you to decorate the LINQ statement with your extension and get back the collection you desire. Either way you'll need to do some sort of conversion from the generic collection to your specialized collection -- either in the constructor or in the extension. Or you could do both...</p>
<pre><code>public static class MyExtensions
{
public static ProductCollection
ToProducts( this IEnumerable<Product> collection )
{
return new ProductCollection( collection );
}
}
public class ProductCollection : BaseCollection<Product>
{
...
public ProductCollection( IEnumerable<Product> collection )
: base( collection )
{
}
...
}
var products = (from p in HugeProductCollection
where p.Vendor = currentVendor
select p).ToProducts();
</code></pre>
|
<p>Could this work with a BindingList ? as BindingList does not have a constructor which would take an IEnumerable but does implement it.</p>
<p>BindingList : Collection, IBindingList, IList, ICollection, IEnumerable, ICancelAddNew, IRaiseItemChangedEvents</p>
| 48,506
|
<p>I use several referenced tables with integer primary keys. Now I want to change ints to GUIDs leaving all references intact. What is the easiest way to do it?</p>
<p>Thank you!</p>
<p><strong>Addition</strong></p>
<p>I do understand the process in general, so I need more detailed advices, for example, how to fill new GUID column. Using default value newid() is correct, but what for already existing rows?</p>
|
<ul>
<li>Create a new column for the guid
value in the master table. Use the
uniqueidentifier data type, make it
not null with a newid() default so
all existing rows will be populated.</li>
<li>Create new uniqueidentifier columns
in the child tables.</li>
<li>Run update statements to build the guild relationships using the exisitng int relationships to reference the entities.</li>
<li>Drop the original int columns.</li>
</ul>
<p>In addition, leave some space in your data/index pages (specify fillfactor < 100) as guids are not sequential like int identity columns are. This means inserts can be anywhere in the data range and will cause page splits if your pages are 100% full.</p>
|
<p>I think, you must do it manualy. Or you can write some utility for it. The scenario should be:</p>
<ul>
<li>Duplicate the "int" PK/FK columns with new "guid" columns.</li>
<li>Generates new values for "guid" PK columns.</li>
<li>Update values in "guid" FK columns with specified values ( you find the records via "int" PK ).</li>
<li>Remove references ( relations ) with "int" PK/FK columns.</li>
<li>Create similar references ( relations ) with "guid" PK/FK columns.</li>
<li>Remove "int" PK/FK columns.</li>
</ul>
| 16,725
|
<p>Anyone have an idea of what this means for MS SQL Server? I'm also calling this from ColdFusion, although I'm guessing that doesn't make any difference.</p>
|
<p>Google implies that error 193 is a problem with the service. Does this happen for every query, or just one? Can you connect from SQL Management Studio?</p>
|
<p>Are you using custom JDBC driver? Try the one that comes with CF.</p>
| 27,063
|
<p>I'd like to inspect the content of a file before it is uploaded to the SharePoint doc library.<br>
I hooked up a handler to the <code>ItemAdding()</code> event but don't know how to get the content of the file.<br>
Note: I know that in the <code>ItemAdded()</code> I can use <code>properties.ListItem.File</code> but that's too late. </p>
<p>Thanks in advance.</p>
|
<p>Yes, the file has not been created at this point.</p>
<p>Try using the properties.AfterProperties or properties.BeforeProperties. </p>
<p>Edit: It is only <em>after</em> the file has been added that the lists properties are created.
SharePoint will add the defaults for the list metadata to the file (Office 2007 only) once the item has been created, but before the ItemAdded event. Bugger.</p>
|
<p>No you can't.<br>
During ItemAdding, you have access to document/item properties as Nat said, but you don't have access to file content. </p>
| 32,496
|
<p>I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests:</p>
<ol>
<li>See how much of my referenced code under test is getting executed</li>
<li>See how many methods of my code under test (if any) are not unit tested at all</li>
</ol>
<p>Setting up the VSTS code coverage tool (see the <a href="https://blogs.msdn.com/ms_joc/articles/406608.aspx" rel="nofollow noreferrer" title="MSDN Code Coverage Blog">link text</a>) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code. </p>
<pre><code>class CodeCoverageTarget
{
public:
std::string ThisMethodRuns() {
return "Running";
}
std::string ThisMethodDoesNotRun() {
return "Not Running";
}
};
#include <iostream>
#include "CodeCoverageTarget.h"
using namespace std;
int main()
{
CodeCoverageTarget cct;
cout<<cct.ThisMethodRuns()<<endl;
}
</code></pre>
<p>When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool? </p>
<p>Thanks in advance,
KGB</p>
|
<p>You could try adding a line of code to call the function only if some condition is true, and guarantee that that condition will never be true. Just make sure the compiler can't figure that out. For example,</p>
<pre><code>
int main(int argc, char **argv)
{
if(argv == NULL) // C runtime says this won't happen
someMethodWhichIsntReallyEverCalled();
}
</code></pre>
|
<p>Turn off inlining of functions. The easiest way to do this is to just compile in Debug mode.</p>
<p><strong>Edit:</strong> after seeing your clarification, I find my answer is in error. Perhaps if you moved the body of the function into another section of the .h file, using the "inline" keyword?</p>
| 13,052
|
<p>I'm trying to add a publisher policy file to the gac as per this <a href="https://stackoverflow.com/questions/283419/how-to-just-load-the-latest-version-of-dll-from-gac">thread</a> but I'm having problems when I try and add the file on my test server. </p>
<p>I get "A module specified in the manifest of assembly 'policy.3.0.assemblyname.dll' could not be found"</p>
<p>My policy file looks like this:</p>
<pre><code><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="*assemblyname*"
publicKeyToken="7a19eec6f55e2f84"
culture="neutral" />
<bindingRedirect oldVersion="3.0.0.0"
newVersion="3.0.0.1"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
</code></pre>
<p>Please help!</p>
<p>Thanks</p>
<p>Ben</p>
<hr>
<p>I've recreated the problem from scratch with a new assembly that has no dependancies (apart from the defaults) itself - all works fine on my local development machine (and redirects fine too) but gives the same error adding the policy file to the GAC on the server!</p>
<pre><code><configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="TestAsm"
publicKeyToken="5f55456fdcc9b528"
culture="neutral" />
<bindingRedirect oldVersion="3.0.0.0"
newVersion="3.0.0.1"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
</code></pre>
<p>linked in the following way</p>
<pre><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\al.exe /link:PublisherPolicy.xml /out:policy.3.0.TestAsm.dll /keyfile:..\..\key.snk /version:3.0.0.0
pause
</code></pre>
<p>Please help!</p>
|
<p>Wow - ok got it.</p>
<p>I should have paid more attention to exactly what this meant </p>
<p><a href="http://msdn.microsoft.com/en-us/library/dz32563a.aspx" rel="nofollow noreferrer">(MSDN) How to: Create a Publisher Policy</a></p>
<blockquote>
<p>Important Note: The publisher policy
assembly cannot be added to the global
assembly cache unless the original
publisher policy file is located in
the same directory as the assembly .</p>
</blockquote>
<p>That requirement is, frankly, so bizarre that it didn't register. The original policy file, that was compiled into the assembly i'm trying to add to the gac, has to be in the same folder as the policy assembly as you add the policy assembly.</p>
|
<p>To add policy assemblies to the GAC using Wise, you do the same thing as you do to add the assembly the policy is for. So you add the policy assembly to the "Global Assembly Cache" in Wise, and as long as you have the policy file (.config) in the same location on the machine, Wise will automatically add it to GAC as well.</p>
| 38,804
|
<p>Is there any way to create a ODBC DSN with C#?</p>
<p>Maybe a P/invoke?</p>
|
<p>You can use Registry classes to write the dsn info in the registry, under</p>
<pre><code>HKLM\Software\ODBC\ODBC.INI\ODBC Data Sources
</code></pre>
<p>You'll need to check what values are needed for you ODBC driver.</p>
|
<p>Following resources might be helpful:</p>
<p>MSDN:</p>
<p><a href="http://support.microsoft.com/kb/310988" rel="nofollow noreferrer">How To Use the ODBC .NET Managed Provider in Visual C# .NET and Connection Strings</a></p>
<p>CodeProject.com</p>
<p><a href="http://www.codeproject.com/KB/database/sdbODBCMngr.aspx" rel="nofollow noreferrer">An ODBC (DSN/Driver) Manager DLL written in C#</a></p>
<p>You can try to invoke functions: </p>
<p>SQLWriteDSNToIni and ConfigDSN (MSDN links are dead for some reason, try to google by functions names)</p>
| 11,794
|
<p>I have a Tab Control with multiple Tab Pages. I want to be able to fade the tabs back and forth. I don't see an opacity option on the Tab Controls. Is there a way to cause a fade effect when I switch from one Tab Page to another?</p>
|
<p>There is no magic Fade switch in the standard windows control.</p>
<p>You could dump the content of the tab to a bitmap (using <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.drawtobitmap.aspx" rel="nofollow noreferrer">DrawToBitmap</a> or <a href="http://msdn.microsoft.com/en-us/library/system.drawing.graphics.copyfromscreen.aspx" rel="nofollow noreferrer">CopyFromScreen</a>?), show that bitmap in front of the TabControl, switch tabs, and then fade the bitmap.</p>
|
<p>Depending on how your tabs/page work, you may be able to handle it at the page level by adding meta tags to the page:</p>
<pre><code><meta http-equiv="Page-Enter" content="blendTrans(Duration=0)">
<meta http-equiv="Page-Exit" content="blendTrans(Duration=0)">
</code></pre>
<p>Just change the duration to make the fade longer or shorter. This is commonly referred to as FAJAX.</p>
| 30,807
|
<p>According to Wikipedia, on the Comparison of programming languages page, it says that F# uses CLI. Does that mean that F# is designed for the purpose of making command-line applications and not graphical applications, or is there another meaning of CLI?</p>
|
<p>in .NET it's the Common Language Infrastructure.</p>
<p><a href="http://en.wikipedia.org/wiki/Common_Language_Infrastructure" rel="noreferrer">http://en.wikipedia.org/wiki/Common_Language_Infrastructure</a></p>
|
<p>Customer Loyalty Initiative - several companies use this to index themselves against their peers for improving/encouraging repeat business.</p>
<p>More items listedon Acronym Finder: <a href="http://www.acronymfinder.com/CLI.html" rel="nofollow noreferrer">http://www.acronymfinder.com/CLI.html</a></p>
| 21,657
|
<p>Imagine a .NET application designed using a Layered architecture.</p>
<p>Is it possible to use something like the <a href="http://msdn.microsoft.com/en-us/library/aa480587.aspx" rel="nofollow noreferrer">trusted subsystem</a> pattern when deploying all layers of an application to the same machine?</p>
<p>Is this design insecure by default?</p>
|
<p>It depends on how you're using the system and how your layers are deployed. </p>
<p>Let's say you have a machine where SQL Server is running in under one user account, your service layer is under another service account, and your users log in using a third account (without admin access, of course). Say the middle tier account is trusted to access the database, but no user account is. In this case, yes, this is basically your classical picture of a trusted subsystem model. </p>
<p>If you have a case, however, where the end-user account has access to the database AND the service layer, then you are indeed breaking the pattern and opening up a hole. If the end user is an admin and can somehow tamper with one of the layers, you are breaking the pattern. If the user has physical access to the machine and can tamper with IT, I'd even argue that you're breaking the pattern...</p>
|
<p>If all layers are deployed in the same process, then I'd say almost by definition you aren't using the trusted subsystem model.</p>
<p>You could (at least in theory) deploy different layers to the same physical machine while still using the trusted subsystem model, but of course it would be harder to guarantee the security of the middle tier. For example, your middle tier could be trusted web services running under IIS.</p>
| 45,253
|
<p>I have developed a simple page using JQuery. It works fine in almost all browsers (i.e. Firefox, IE, Chrome) but whenever the page is opened in IE, it prompts Javascript error like,</p>
<pre><code>'guid' is null or not an object on line 1834
</code></pre>
<p>Do you have any idea ?</p>
|
<p>Thanks guys for your messages.</p>
<p>The error was on my part. For hover event, I was not passing function for "out". Therefore the handler was passed as undefined in jQuery.event function and that causing error for statement ,</p>
<p>if ( !handler.guid )</p>
<p>written at 1834 line of jquery-1.2.6.js file.</p>
<p>While using I thought that out handler is not mandatory to specify, but I guess I am wrong.</p>
<p>Strangely, FF / Chrome does not prompt error but IE does :) which is bit different than what it used to be.</p>
<p>Regards,
Jatan</p>
|
<p>Maybe you're using the parentNode or parentElement property? There are some issues with that in IE vs other browsers.</p>
| 9,656
|
<p>I wish to ensure a user has access to an aspx page by 'Zone'. For example, "Financials" is a Security Zone which some users should not have access to.</p>
<p>The result should not involve patterns such as MVP, MVC, MVVM, etc. I'm looking for something that's light and quick to do.</p>
<p>To make things easier I have a base class which each aspx page derives from. What is the easiest/best way to have each page to be checked versus a security zone given the userID?</p>
<p>Thanks.</p>
|
<p>I've used this, whether it's the best way is seriously questionable. I have a class I derive from Page, called SecurePage. In that I usually have a cross table in a database that lists objects, such as the page, and groups/users that have access to that page. Running a stored procedure using the UserID and the Object name (Page name in this case, but can be a field, or whatever) it returns whether that user or a group that the user belongs in has access. You can check this during the page init, and if it doesn't match up, then response.redirect them or whatever you want to do. </p>
|
<p>Why not just use the security features such as forms authentication built into .NET? It's very easy.</p>
| 25,274
|
<p>Given the Marlin Firmware what is the difference between the following lines of code:</p>
<blockquote>
<p>G4 S20</p>
</blockquote>
<p>and</p>
<blockquote>
<p>G4 P2000</p>
</blockquote>
|
<p>The answer is that <strong><em>it depends on the type of firmware</em></strong> you are using.</p>
<p>Let us look at the documentation of <a href="https://reprap.org/wiki/G-code#G4:_Dwell" rel="nofollow noreferrer"><code>G4</code></a> to find that <code>G4</code> is valid for all the listed firmware types:
<a href="https://i.stack.imgur.com/Tt7wT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tt7wT.png" alt="enter image description here"></a></p>
<blockquote>
<p>Pause the machine for a period of time.</p>
</blockquote>
<p>Furthermore it states that:</p>
<blockquote>
<p><strong>Parameters</strong></p>
<ul>
<li>Pnnn Time to wait, in milliseconds (In Teacup, P0, wait until all previous moves are finished)</li>
<li>Snnn Time to wait, in seconds (Only on Repetier, Marlin, Smoothieware, and RepRapFirmware 1.16 and later)</li>
</ul>
</blockquote>
<p>It clearly shows that the <code>S</code> parameter (which defines the pause in seconds) is only supported by a few firmware types. Do note that this documentation may not be up-to-date, so it is best to look into the source code or the users manual of the particular firmware you are using.</p>
<hr>
<p>E.g. if you are using Marlin Firmware, <code>G4 S20</code> will pause the machine for 20 seconds while <code>G4 P2000</code> will pause the machine for 2000 milliseconds which is 2 seconds. This means that a different time is requested, to have 20 seconds waiting time you could use <code>G4 P20000</code></p>
<p>To answer your question what the <strong><em>actual difference</em></strong> between the 2 commands is:</p>
<ul>
<li>it is <strong>either</strong> 18 seconds of extra waiting time if your firmware supports the <code>S</code> parameter, <strong>or</strong> </li>
<li>a firmware that skips or chokes on the command because it is not supported (that also probably depends on your firmware).</li>
</ul>
|
<p>The code <code>G4</code> refers to <em>dwell</em>. (From what I'm seeing, it can be written as either <code>G4</code> or <code>G04</code>). <code>P</code>is the length of dwell time, usually in milliseconds. The parameter <code>S</code> seems to be invalid, because the only inputs are <code>X</code> (seconds), <code>P</code> (milliseconds), or <code>U</code> (undefined). If you have <code>S20</code> in your code, it is invalid, whereas <code>P2000</code> will cause all axes to remain unmoving for 2 seconds before moving on. </p>
<p>(Note: Not all machines will accept <code>X</code> or <code>U</code>.)</p>
<p><strong>EDIT:</strong> This answer is specific to <em>non-specific</em> g-code, taken from this <a href="https://all3dp.com/g-code-tutorial-3d-printer-gcode-commands/" rel="nofollow noreferrer"><em>Source</em></a>, since the OP did not state any specifics about their firmware type or equipment used.</p>
| 1,092
|
<p>In Ruby, I'm trying to do the following.</p>
<pre><code>def self.stats(since)
return Events.find(:all, :select => 'count(*) as this_count', :conditions => ['Date(event_date) >= ?', (Time.now - since)]).first.this_count
end
</code></pre>
<p>where "since" is a string representing an amount of time ('1 hour', '1 day', '3 days') and so on. Any suggestions?</p>
|
<p>I hacked this together with the ActiveSupport gem:</p>
<pre><code>require 'active_support'
def string_to_date(date_string)
parts = date_string.split
return parts[0].to_i.send(parts[1])
end
sinces = ['1 hour', '1 day', '3 days']
sinces.each do |since|
puts "#{since} ago: #{string_to_date(since).ago(Time.now)}"
end
</code></pre>
<p>[edit] To answer your question, you might try it like that:</p>
<pre><code>:conditions => ['Date)event_date) >= ?', (string_to_date(since).ago(Time.now))]
</code></pre>
|
<p>I agree with <a href="https://stackoverflow.com/a/40580/1933902">John Millikin</a>. <a href="http://chronic.rubyforge.org/" rel="nofollow noreferrer">Chronic</a>, or even your own helpers, would be a much lighter and effective dependency to carry than whole ActiveSupport, assuming you are not already trapped inside Rails.</p>
| 6,180
|
<p>Short version: I'm wondering if it's possible, and how best, to utilise CPU specific
instructions within a DLL?</p>
<p>Slightly longer version:
When downloading (32bit) DLLs from, say, Microsoft it seems that one size fits all processors.</p>
<p>Does this mean that they are strictly built for the lowest common denominator (ie. the
minimum platform supported by the OS)?
Or is there some technique that is used to export a single interface within the DLL but utilise
CPU specific code behind the scenes to get optimal performance? And if so, how is it done?</p>
|
<p>I don't know of any <em>standard</em> technique but if I had to make such a thing, I would write some code in the DllMain() function to detect the CPU type and populate a jump table with function pointers to CPU-optimized versions of each function.</p>
<p>There would also need to be a lowest common denominator function for when the CPU type is unknown.</p>
<p>You can find current CPU info in the registry here:</p>
<pre><code>HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor
</code></pre>
|
<p>An easy way to get the SSE/SSE2 optimizations is to just use the <code>/arch</code> argument for MSVC. I wouldn't worry about fallback--there is no reason to support anything below that unless you have a very niche application.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/7t5yh4fd.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/7t5yh4fd.aspx</a></p>
<p>I believe gcc/g++ have equivalent flags.</p>
| 15,927
|
<p>Using SQL Server - which is the fastest or best practice method to use for date retrieval? Is there a difference?</p>
|
<p><code>CURRENT_TIMESTAMP</code> is standard ANSI SQL, and so is theoretically one tiny little island of 'don't need to change' amongst your thousands of SQL Server-specific lines of SQL if you ever need to move databases....</p>
|
<p>Books Online tells us that <code>CURRENT_TIMESTAMP</code> "is equivalent to <code>GETDATE()</code>".</p>
| 22,579
|
<p>I'e been programming Java forever, but have been away from it for a while. Can anyone recommend a really good Java reference, where "really good" is defined by "Good coverage of the language, detailed coverage of recent extensions, and written for the technical reader (not a "for Dummies" sort of book)"?</p>
|
<p>As well as references saying what has changed in the languages (which other answers already cover better than I could) I can't recommend highly enough the <a href="https://rads.stackoverflow.com/amzn/click/com/0321356683" rel="noreferrer" rel="nofollow noreferrer">Second edition of Effective Java by Joshua Bloch</a> - which explains the most effective ways of using the language.</p>
|
<p>i've always liked cay horstmann's books: <a href="http://www.horstmann.com/corejava.html" rel="nofollow noreferrer">http://www.horstmann.com/corejava.html</a>. these are 8'th editions. and there is gosling's <a href="http://java.sun.com/docs/books/javaprog/" rel="nofollow noreferrer">http://java.sun.com/docs/books/javaprog/</a>. haven't seen anything for 1.6 yet.</p>
| 39,129
|
<p>How can I construct the following string in an Excel formula:</p>
<blockquote>
<p>Maurice "The Rocket" Richard</p>
</blockquote>
<p>If I'm using single quotes, it's trivial: <code>="Maurice 'The Rocket' Richard"</code> but what about double quotes?</p>
|
<p>Have you tried escaping with an additional double-quote? By escaping a character, you are telling Excel to treat the " character as literal text.</p>
<pre class="lang-sql prettyprint-override"><code>= "Maurice ""The Rocket"" Richard"
</code></pre>
|
<p>There is another way, though more for " How can I construct the following string in an Excel formula: "Maurice "The Rocket" Richard" " than " How to create strings containing double quotes in Excel formulas? ", which is simply to use two single quotes:</p>
<p><a href="https://i.stack.imgur.com/WCRke.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WCRke.jpg" alt="SO216616 example"></a></p>
<p>On the left is Calibri snipped from an Excel worksheet and on the right a snip from a VBA window.
In my view escaping as mentioned by @YonahW wins 'hands down' but two single quotes is no more typing than two doubles and the difference is reasonably apparent in VBA without additional keystrokes while, potentially, not noticeable in a spreadsheet.</p>
| 26,629
|
<p>We need to send email which contains Pound (currency) symbols in ColdFusion. Before sending email, we are dumping the data into a html file for preview. </p>
<ol>
<li>How to send a email with utf-8 encoding in ColdFusion</li>
<li>How to save a file with utf-8 encoding in ColdFusion</li>
</ol>
|
<p>E-Mails are sent in the encoding that is specified in the ColdFusion Administrator. For ColdFusion MX (6.0) and up this is UTF-8 by default.</p>
<p>You can explicitly mention the encoding like this, but it should not be necessary.</p>
<pre><code><cfmail type="text/html; Charset=UTF-8" ...><!--- body ---></cfmail>
</code></pre>
<p>For the HTML file you dump to disk, the following applies:</p>
<pre><code><cffile action="write" charset="UTF-8" ...>
</code></pre>
<p>And you should have the encoding as a META tag, so the browser you use for preview does not have to guess:</p>
<pre><code><meta http-equiv="Content-Type" content="text/html; Charset=UTF-8">
</code></pre>
|
<p>Try adding <code><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></code> in the <code><head></code> tag of your html file.</p>
| 44,141
|
<p>I've got many, many mp3 files that I would like to merge into a single file. I've used the command line method</p>
<pre><code>copy /b 1.mp3+2.mp3 3.mp3
</code></pre>
<p>but it's a pain when there's a lot of them and their namings are inconsistent. The time never seems to come out right either.</p>
|
<p>As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.</p>
<p>You're going to need to use a tool which can combine the audio data for you.</p>
<p><a href="http://mp3wrap.sourceforge.net/" rel="noreferrer">mp3wrap</a> would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.</p>
<p>The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.</p>
|
<p>Personally I would use something like mplayer with the audio pass though option eg -oac copy</p>
| 8,810
|
<p>I'm working with NHibernate and need to retrieve and process up to 2 million rows. Ideally, I could process each row - one at a time - without NHibernate loading all 2 million in memory at once (because, you know, that hurts). </p>
<p>I'd prefer to get an IEnumerable which would call the data reader iteratively for each read so I could process the data read - then discard it. By doing it this way I save a boatload of memory, and begin processing results far faster. I could also improve performance through multithreading and/or the use of PLinq.</p>
<p>Is this possible with NHibernate's ICriteria? Everything it returns seems to be IList, and fully loaded before handing the collection reference off. Why IList instead of IEnumerable?!</p>
<p>I don't mean "lazy" in the traditional sense that NHibernate uses with regards to loading child or parent objects. I want a <strong>lazy IEnumerable meaning someway of getting a IEnumerable from an ICriteria object</strong>. ICriteria only has a List() method which loads the results in an ArrayList.</p>
|
<p>ICriteria doesn't have any methods that return an IEnumerable, but <a href="http://fisheye3.atlassian.com/browse/nhibernate/trunk/nhibernate/src/NHibernate/IQuery.cs?r=3868#l96" rel="nofollow noreferrer">IQuery does</a>.</p>
|
<p>What you want to do is wrap your data access in a method like so:</p>
<pre><code>public IEnumerable<YourObject> GetALotOfRows() {
..execute DataReader
while(..read..) {
yield return yourObject;
}
}
</code></pre>
<p>Don't have VS or nHibernate handy now, so sorry for semi-pseudo code. But the key here is to use "yield return".</p>
| 47,368
|
<p>In the standard PrintDialog there are four values associated with a selected printer: Status, Type, Where, and Comment.</p>
<p>If I know a printer's name, how can I get these values in C# 2.0?</p>
|
<p>As <a href="https://stackoverflow.com/questions/296182/how-to-get-printer-info-in-cnet#296232">dowski suggested</a>, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.</p>
<pre><code>using System.Management;
</code></pre>
<p>...</p>
<pre><code>string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
try
{
foreach (ManagementObject printer in coll)
{
foreach (PropertyData property in printer.Properties)
{
Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
}
}
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
</code></pre>
|
<p>As an alternative to WMI you can get fast accurate results by tapping in to WinSpool.drv (i.e. Windows API) - you can get all the details on the interfaces, structs & constants from pinvoke.net, or I've put the code together at <a href="http://delradiesdev.blogspot.com/2012/02/accessing-printer-status-using-winspool.html" rel="nofollow">http://delradiesdev.blogspot.com/2012/02/accessing-printer-status-using-winspool.html</a></p>
| 37,875
|
<p>I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:</p>
<p>System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.</p>
<p>How do I customize the sorting or comparison logic to handle the null case?</p>
|
<p>The Nullable type exposes a comparison method for comparing nullable types, so the solution is to override the gridview sorting logic and manually specify a comparison:</p>
<pre><code>gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
// Only add custom handling for the sort expression on the
// Nullable<int> column
if (e.SortExpression == "MySortExpression")
{
// Convert datasource to a List<T>
list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)
{
return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);
}));
// Bind the sorted list back to the gridview
}
else
{
// delegate to the gridview to handle its own sorting
}
}
</code></pre>
|
<p>You could also override the null when you bind the data, placing a 0 instead. Your answer is far better. :)</p>
<p>You could also make a custom type that overrides the Compare operator. But that would just duplicate (and complicate) what you have above.</p>
| 20,232
|
<p>I need to do a dump of a table on a remote server, but I can't access the server directly. The only access I have is through PHP scripts.</p>
<p>Is there some way in which MySQL will return an </p>
<pre><code>INSERT INTO `table_name` (`field1`, `field2`) VALUES ('a', 'b'), ('c', 'd')
</code></pre>
<p>statement, like what <code>mysqldump</code> will return?</p>
<p>I don't have access to phpMyAdmin, and I preferably don't want to use <code>exec</code>, <code>system</code> or <code>passthru</code>.</p>
<p>See <a href="https://stackoverflow.com/questions/81934/easy-way-to-export-a-sql-table-without-access-to-the-server-or-phpmyadmin">this question</a> for another export method</p>
|
<p>1) can you run mysqldump from exec or passthru<br />
2) take a look at this: <a href="http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php" rel="noreferrer">http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php</a></p>
|
<p>If you can use php-scripts on the server i would recommend <a href="http://www.phpmyadmin.net/home_page/index.php" rel="nofollow noreferrer">phpmyadmin</a>. Then you can do this from the web-interface.</p>
| 8,887
|
<p>Has anyone got much experience deploying applications to Amazons EC2? I am considering doing this in future and wonder about peoples experiences compared to shared hosting and dedicated server hosting are.</p>
|
<p>So far, so good. Being able to turn on 5/10/50/100+ machines at a time is awesome. It's even better being able to turn them off and forget about them. You need to change your mindset about how you store your persistent data, but once you have the sky is the limit.</p>
<p>Performance wise, small instances are slow. They're fine for load balancers and serving static content, etc, but if you are doing anything processor intensive, you need at least a m1.medium instance.</p>
<p>It's all pretty new, so there aren't many tools to help out yet. I'm using <a href="http://reductivelabs.com/trac/puppet/" rel="nofollow noreferrer">Puppet</a> to configure my hosts and I have a set of PHP scripts for starting up clusters. I use LDAP as a host inventory database. </p>
<p>If you don't have the need/urge to build your own, see <a href="http://rightscale.com/" rel="nofollow noreferrer">Rightscale</a> for some really awesome tools for deploying/growing apps.</p>
|
<p>I have an image that has my full stack and a script on each that automates the deployment of wars (java) from an S3 bucket to the local file system. </p>
<p>When an image starts the rc2.local runs this script to get the latest wars before starting tomcat. This works well for me</p>
| 27,089
|
<p>Related to this question:
<a href="https://stackoverflow.com/questions/353207/url-characters-replacement-in-jsp-with-urlrewrite">URL characters replacement in JSP with UrlRewrite</a></p>
<p>I want to have masked URLs in this JSP Java EE web project.
For example if I had this:</p>
<pre><code>http://mysite.com/products.jsp?id=42&name=Programming_Book
</code></pre>
<p>I would like to turn that URL into something more User/Google friendly like:</p>
<pre><code>http://mysite.com/product-Programming-Book
</code></pre>
<p>I've been fighting with UrlRewrite, forwarding and RequestDispatcher to accomplish what I want, but I'm kind of lost. I should probably have a filter for all http requests, re format them, and forward the page. </p>
<p>Can anyone give some directions? Tips? </p>
<p>Thanks a lot. </p>
<p><strong>UPDATE:</strong> Servlets did it. Thanks Yuval for your orientation.
I had been using UrlRewrite, as you can see at the first sentence of the question I also asked a question about that. But I couldn't manage to get UrlRewrite work the way I wanted. Servlets did the job.</p>
|
<p>You could use a <code>URLRewrite filter</code>. It's like how mod_rewrite is for Apache's HTTP web server.</p>
<p><a href="http://tuckey.org/urlrewrite/" rel="nofollow noreferrer">http://tuckey.org/urlrewrite/</a></p>
<p>"Redirect one url</p>
<pre><code><rule>
<from>^/some/old/page\.html$</from>
<to type="redirect">/very/new/page.html</to>
</rule>
</code></pre>
<p>Tiny/Freindly url</p>
<pre><code><rule>
<from>^/zebra$</from>
<to type="redirect">/big/ugly/url/1,23,56,23132.html</to>
</rule>
</code></pre>
<p>"</p>
|
<p>Generally you're fronting your application with Apache. If so, look into using Apache's mod_rewrite. <a href="http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html" rel="nofollow noreferrer">http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html</a></p>
| 46,841
|
<p>I wonder if there is a way to either programatically or using a third party tool (profiler?) get an overview of how many instances of a class are currently active in the AppDomain (including or excluding derived classes), and even better, where they are allocated (not sure if that is even possible).</p>
<p>I know that I could change my own classes to include some running counter somehow, but I also want this for (managed) classes that I do not control.</p>
<p>Is that even possible? Some hints or keywords would be helpful :)</p>
|
<p>I think what you would want to use is SOS and the Windows Debugging Toolkit.</p>
<p>There is a great blog from Tess Ferandez which has tons of information on using it.</p>
<p><a href="http://blogs.msdn.com/tess/" rel="nofollow noreferrer">http://blogs.msdn.com/tess/</a></p>
|
<p>I'm almost hesitant to answer because there's got to be a bunch of easier ways, but using <a href="http://msdn.microsoft.com/en-us/library/cc265629.aspx" rel="nofollow noreferrer">adplus</a> to take a hang dump, and then use <a href="http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx" rel="nofollow noreferrer">WinDbg</a> with Son of Strike to navigate the dump file.</p>
<p>You can also get a <a href="http://msdn.microsoft.com/en-us/library/ms979205.aspx" rel="nofollow noreferrer">profiler</a> that will assist you with some rudimentary analysis on the hang dump.</p>
| 24,830
|
<p>Does Ruby have a stepwise debugger, similar to Perl's "perl -d"?</p>
|
<p>The <a href="https://rubygems.org/gems/ruby-debug" rel="nofollow noreferrer">ruby-debug</a> (for ruby 1.8), <a href="https://rubygems.org/gems/debugger" rel="nofollow noreferrer">debugger</a> (for ruby 1.9), <a href="https://rubygems.org/gems/byebug" rel="nofollow noreferrer">byebug</a> (for ruby 2.0) and also the <a href="https://rubygems.org/gems/trepanning" rel="nofollow noreferrer">trepanning</a> series all have an <code>-x</code> or <code>--trace</code> option. Inside the debuggers, the command <code>set linetrace</code> will turn on or off line tracing. Here is <a href="http://bashdb.sourceforge.net/ruby-debug.html" rel="nofollow noreferrer">the manual for ruby-debug</a></p>
<p><em>The original answer has been revised because the link to the datanoise article, alas, no longer works. Also added are the successors to ruby-debug</em></p>
|
<p>From the command line (if you have the <code>debug</code> module available):</p>
<pre><code>ruby -r debug /path/to/ruby_script.rb
</code></pre>
| 32,409
|
<p>I have a number of icons used throughout an application - let's take ok/cancel icons as an example. At the moment they might be a tick and a cross (tick.png, cross.png) but I may want to replace them in future. Also, I would like to keep the resource path in one place.</p>
<p>Is this ok:</p>
<pre><code>public class Icons {
public static Icon OK = new ImageIcon(Icons.class.getResource("/icons/tick.png");
public static Icon CANCEL = new ImageIcon(Icons.class.getResource("/icons/cross.png");
}
</code></pre>
<p>Or should I be doing this a different way? I don't mind relying on the existence of the image files at runtime since they're in the .jar</p>
<p><strong>Solution</strong></p>
<p>I've used Bent's idea for initialisation, and I've made the constants final:</p>
<pre><code>public final class Icons {
private static final Logger logger = Logger.getLogger(Icons.class);
public static final Icon OK = icon("/icons/add.png");
public static final Icon CANCEL = icon("/icons/cancel.png");
private static Icon icon(String path) {
URL resource = Icons.class.getResource(path);
if(resource==null) {
logger.error("Resource "+path+" does not exist");
return new ImageIcon();
}
return new ImageIcon(resource);
}
}
</code></pre>
|
<p>You may want to mark the constants as final.</p>
|
<p>That seems to be a fairly easy way to do that. Although I would name the images with the same name as what they are for ("ok.png", "cancel.png"). And make sure that it is clear that removing or renaming the images may cause issues.</p>
| 48,237
|
<p>I've got a situation where I need to use LINQ's ExecuteCommand method to run an insert.</p>
<p>Something like (simplified for purposes of this question):</p>
<pre><code>object[] oParams = { Guid.NewGuid(), rec.WebMethodID };
TransLogDataContext.ExecuteCommand (
"INSERT INTO dbo.Transaction_Log (ID, WebMethodID) VALUES ({0}, {1})",
oParams);
</code></pre>
<p>The question is if this is SQL injection proof in the same way parameterized queries are?</p>
|
<p>Did some research, and I found this:</p>
<blockquote>
<p>In my simple testing, it looks like
the parameters passed in the
ExecuteQuery and ExecuteCommand
methods are automatically SQL encoded
based on the value being supplied. So
if you pass in a string with a '
character, it will automatically SQL
escape it to ''. I believe a similar
policy is used for other data types
like DateTimes, Decimals, etc.</p>
</blockquote>
<p><a href="http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/scottgu/archive/2007/08/27/linq-to-sql-part-8-executing-custom-sql-expressions.aspx</a><br>
(You have scroll way down to find it)</p>
<p>This seems a little odd to me - most other .Net tools know better than to "SQL escape" anything; they use real query parameters instead. </p>
|
<p>LINQ to SQL uses <em>exec_sql</em> with parameters, which is much safer than concatenating into the ad-hoc query string. It should be as safe againt SQL injection as using SqlCommand and its Paramaters collection (in fact, it's probably what LINQ to SQL uses internally). Then again, how safe is <em>that</em>?</p>
| 19,097
|
<p>I have some code which ignores a specific exception. </p>
<pre><code>try
{
foreach (FileInfo fi in di.GetFiles())
{
collection.Add(fi.Name);
}
foreach (DirectoryInfo d in di.GetDirectories())
{
populateItems(collection, d);
}
}
catch (UnauthorizedAccessException ex)
{
//ignore and move onto next directory
}
</code></pre>
<p>of course this results in a compile time warning as ex is unused. Is there some standard accept noop which should be used to remove this warning? </p>
|
<p>Just rewrite it as</p>
<pre><code>catch (UnauthorizedAccessException) {}
</code></pre>
|
<p>Even though I'm a Java developer (not C#), @Scott Dorman is absolutely right. Why are you "swallowing the exception"? Better yet, what <em>could</em> throw the UnauthorizedAccessException? Here are common-sense possibilities:</p>
<ol>
<li>The file doesn't exist</li>
<li>The directory doesn't exist</li>
<li>The current thread of control does not have the correct security privileges. In the *nix world, the current thread may be in the wrong group or the wrong user.</li>
<li>The disk crashed</li>
<li>The file's ACL is set to write only but not read. Likewise, for the directory.</li>
</ol>
<p>The above of course is an incomplete list.</p>
| 28,755
|
<p>I've recently been trying to create units tests for some legacy code.</p>
<p>I've been taking the approach of using the linker to show me which functions cause link errors, greping the source to find the definition and creating a stub from that. </p>
<p>Is there an easier way?
Is there some kind of C++ parser that can give me class definitions, in some easy to use form, from which I can generate stubs?</p>
|
<p>You may want to investigate <a href="http://os.inf.tu-dresden.de/vfiasco/related.html#parsing" rel="noreferrer">http://os.inf.tu-dresden.de/vfiasco/related.html#parsing</a>. But C++ parsing is hard.</p>
<p>On the other hand, maybe ctags or something similar can extract class definitions...</p>
<p>You may also try to write your own simple (?) parser to generate class stubs from header files...</p>
<p>I tried to give you some pointers. As you see, the problem is not easy. But hopefully you can automate at least some part of it.</p>
|
<p>If you're on the Windows platform, you might want to have a look at the <a href="http://research.microsoft.com/Phoenix/" rel="nofollow noreferrer">Microsoft Phoenix project</a>. It's a new compiler framework that lets you hook into any stage of the compilation process.</p>
| 29,213
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.