instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>What strategies have you used with Model Based Testing?</p>
<ul>
<li>Do you use it exclusively for
integration testing, or branch it
out to other areas
(unit/functional/system/spec verification)? </li>
<li>Do you build focused "sealed" models or do you evolve complex onibus models over time?</li>
<li>When in the product cycle do you invest in creating MBTs?</li>
<li>What sort of base test libraries do you exclusively create for MBTs?</li>
<li><p>What difference do you make in your functional base test libraries to better support MBTs?
</p></li>
</ul>
|
<p>[There are several essays worth reading on this. Stack Overflow won't let me post more than one, so I've aggregated them in a blog post, linked at the end of this answer.]</p>
<p>First, a quick note on terms. I tend to use James Bach’s definition of Testing as “Questioning a product in order to evaluate it”. All test rely on /mental/ models of the application under test. The term Model-Based Testing though is typically used to describe programming a model which can be explored via automation. For example, one might specify a number of states that an application can be in, various paths between those states, and certain assertions about what should occur in on the transition between those states. Then one can have scripts execute semi-random permutations of transitions within the state model, logging potentially interesting results.</p>
<p>There are real costs here: building a useful model, creating algorithms for exploring it, logging systems that allow one to weed through for interesting failures, etc. Whether or not the costs are reasonable has a lot to do with <em>what are the questions you want to answer?</em> In general, start with “What do I want to know? And how can I best learn about it?” rather than looking for a use for an interesting technique.</p>
<p>All that said, some excellent testers have gotten a lot of mileage out of automated model-based tests. Sometimes we have important questions about the application under test that are best explored by automated, high-volume semi-randomized tests. Harry Robinson (one of the leading theorists and proponents of model-based testing) describes one very colorful example where he discovered many interesting bugs in Google driving directions using a model-based test (written with ruby’s Watir library). <a href="http://testingjeff.wordpress.com/2009/06/03/question-about-model-based-testing/" rel="noreferrer">1</a></p>
<p>Robinson has used MBT successfully at companies including Bell Labs, Microsoft, and Google, and has a number of helpful essays.[2]</p>
<p>Ben Simo (another great testing thinker and writer) has also written quite a bit worth reading on model-based testing.[3] </p>
<p>Finally, a few cautions: To make good use of a strategy, one needs to explore both its strengths and its weaknesses. Toward that end, James Bach has an excellent talk on the limits and challenges of Model-Based Testing. This blog post of Bach’s links to his hour long talk (and associated slides).[4]</p>
<p>I’ll end with a note about what Boris Beizer calls the Pesticide Paradox: “Every method you use to prevent or find bugs leaves a residue of subtler bugs against which those methods are ineffective.” Scripted tests (whether executed by a computer or a person) are particularly vulnerable to the pesticide paradox, tending to find less and less useful information each time the same script is executed. Folks sometimes turn to model-based testing thinking that it gets around the pesticide problem. In some contexts model-based testing may well find a much larger set of bugs than a given set of scripted tests…but one should remember that it is still fundamentally limited by the Pesticide Paradox. Remembering its limits — and starting with questions MBT addresses well — it has the potential to be a very powerful testing strategy.</p>
<p>Links to all essays mentioned above can be found here: <a href="http://testingjeff.wordpress.com/2009/06/03/question-about-model-based-testing/" rel="noreferrer">http://testingjeff.wordpress.com/2009/06/03/question-about-model-based-testing/</a></p>
|
<p>The best way is to try by yourself a Model based testing tool. It's the best way for know if the model based testing is adapted in your context. And what sort of strategies is the good one.</p>
<p>I advise you the "MaTeLo" tool of All4Tec (www.all4tec.net)</p>
<p>"MaTeLo is a test cases generator for black box functional and system testing. Conformed to the Model Based Testing approach, MaTeLo uses Markov chains for modeling the test. This statistic addin allows products validation in a Systematic way. The efficiency is achieved by a reduction of the human resources needed, an increase of the model reuse and by the enhancement of the test strategy relevance (due to the reliability target). MaTeLo is independent and user-friendly, offers to the validation activities to pass from test scripting to real test engineering and to focus on the real added value of testing: the test plans"</p>
<p>You can ask an evaluation licence and try by yourself.</p>
<p>You can find some exemples here : <a href="http://www.all4tec.net/wiki/index.php?title=Tutorials" rel="nofollow noreferrer">http://www.all4tec.net/wiki/index.php?title=Tutorials</a></p>
| 4,565
|
<p>I am calling an unmanaged C++ dll that expects a char* as one of its parameters and I want to push a byte[] into it. The project is written in VB.NET. </p>
<p>What type of marshalling will work for this?</p>
|
<p>If you need to pin a managed structure in order to pass it as a parameter you can use the following code.</p>
<pre><code> // (c) 2007 Marc Clifton
/// <summary>
/// A helper class for pinning a managed structure so that it is suitable for
/// unmanaged calls. A pinned object will not be collected and will not be moved
/// by the GC until explicitly freed.
/// </summary>
internal class PinnedObject<T> : IDisposable where T : struct
{
protected T managedObject;
protected GCHandle handle;
protected IntPtr ptr;
protected bool disposed;
public T ManangedObject
{
get
{
return (T)handle.Target;
}
set
{
Marshal.StructureToPtr(value, ptr, false);
}
}
public IntPtr Pointer
{
get { return ptr; }
}
public int Size
{
get { return Marshal.SizeOf(managedObject); }
}
public PinnedObject()
{
managedObject = new T();
handle = GCHandle.Alloc(managedObject, GCHandleType.Pinned);
ptr = handle.AddrOfPinnedObject();
}
~PinnedObject()
{
Dispose();
}
public void Dispose()
{
if (!disposed)
{
if (handle.IsAllocated)
handle.Free();
ptr = IntPtr.Zero;
disposed = true;
}
}
}
}
</code></pre>
<p>You can then call the unmanaged code using PinnedObject.Pointer. In your extern declaration, use IntPtr as the Type for that parameter.</p>
<pre><code>PinnedObject<BatteryQueryInformation> pinBatteryQueryInfo = new PinnedObject<BatteryQueryInformation>();
pinBatteryQueryInfo.ManangedObject = _structBatteryQueryInfo;
Unmanaged.Method(pinBatteryQueryInfo.Pointer);
</code></pre>
|
<p>I'm not a .net expert, but I've needed to do something similar recently.</p>
<p>It is not just a matter of serialization, you also have to stop the garbage collector from cleaning up your byte array while it is being used in C++ land...</p>
<p>The below snippet of C# should help.</p>
<pre>// pin the byte[] (byteArray)
GCHandle handle = GCHandle.Alloc(byteArray, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();
// Do your C++ stuff, using the address pointer.
// Cleanup
handle.Free();</pre>
| 33,105
|
<p>Nowadays, we have tons of Javascript libraries per page in addition to the Javascript files we write ourselves. How do you manage them all? How do you minify them in an organized way? </p>
|
<p><strong>Organization</strong></p>
<p>All of my scripts are maintained in a directory structure that I follow whenever I work on a site. The directory structure normally goes something like this:</p>
<pre><code>+--root
|--javascript
|--lib
|--prototype.js
|--scriptaculous
|--scriptaculous.js
|--effects.js
|--..
|--myOwnScript.js
|--myOwnScript2.js
</code></pre>
<p>If, on the off chance, that I'm working on a team uses an inordinate amount of scripts, then I'll normally create a <em>custom</em> directory in which we'll organize scripts by relationship. This doesn't happen terribly often, though.</p>
<p><strong>Compression</strong></p>
<p>Though there are a lot of different compressors and obfuscators out there, I always come back to <a href="http://developer.yahoo.com/yui/compressor/" rel="noreferrer">YUI Compressor.</a></p>
<p><strong>Inclusion</strong></p>
<p>Unless a site is using some form of a master page, CMS, or something that dictates what can be included on a page beyond my control, I only included the scripts necessarily <em>for the given page</em> just for the small performance sake. If a page doesn't require any script, there will be no script inclusions on that page.</p>
|
<p>I'v been using this lately:
<a href="http://code.google.com/apis/ajaxlibs/" rel="nofollow noreferrer">http://code.google.com/apis/ajaxlibs/</a></p>
<p>And then have a "jscripts" folder where I keep my custom code. </p>
| 26,985
|
<p>We have been asked to look into a fully open source solution for a big project, they want the project be as near to 100% Open Source as possible, mainly because as it's a community project there may be very little money available in the future except for the running of a host. Using OS software saves on licence costs as the server will be managed in house by the existing IT systems team.</p>
<p>One of the suppliers is proposing .net as the makeup of system, which is fine I understand that .net applications can quite rightly be released under open source licences such as the GPL etc.</p>
<p>However as I'm not a .net developer, I'm a little confused when it comes to what powers the .net. Does it HAVE to be a windows server, which of course leads to higher server costs and a tie in to MS products, or is it possible to run .net applications on open source servers such as Linux etc.</p>
<p>Please don't turn this into a MS Vs Linux argument and the benefits or using one or the other. We are just wanting to make sure we are fully informed when it comes to using .net and just how open source it can be. I'm hoping to have my eyes opened.</p>
|
<p>"True" .NET only runs on Windows. However, the <a href="http://www.mono-project.com/Main_Page" rel="nofollow noreferrer">Mono project</a> allows applications written for .NET to run on Linux (and other platforms) so long as there aren't any compatibility issues. Mono has a <a href="http://www.mono-project.com/MoMA" rel="nofollow noreferrer">compatibility checker</a> which can help you to have a cursory look at how many problems you're likely to have, but I don't have any experience with it myself. There's also a <a href="http://www.mono-project.com/Guidelines:Application_Portability" rel="nofollow noreferrer">Portability Guidelines</a> page which you may find very useful.</p>
|
<p>Further to some previous answers; some other Mono details:</p>
<p><li>Currently the compiler targeting .NET 2.0 and 3.5 is <a href="http://mono-project.com/Languages" rel="nofollow noreferrer">NOT the default compiler</a>. To me this suggests an immature platform. If you're starting out a new project, being able to use all that the .NET framework has to offer reliably is a huge plus. IMHO, Mono doesn't bring that to the table if you need to push the .NET framework to it's limit/edge cases.</p>
<p><li>Mono is sponsored by Novell, which does speak of its potential longevity as a platform.</p>
| 49,051
|
<p>I've inherited a rather large application that really could use some cleanup. There is data access code littered throughout the application. In code behinds, some in business logic classes, some inline in in classic asp pages. </p>
<p>What I'd like to do is refactor this code, removing all the data access code into a few DAL classes. </p>
<p>All the data access is done through stored procedures (Microsoft SQL 2000). There are 300-400 of them.</p>
<p>It seems like there should be an automated way to analyse the store procedures, and automatically generate c# methods for each of them, mapping the Method parameters to the stored procedure parameters, with a method returning a datatable. </p>
<p>I don't have any experience with ORM products, and I'm not sure if what I'm looking for is a full blown ORM, or just a 3rd party utility that will help generate simple wrappers around the sp calls.</p>
|
<p>If you have access to .NET Framework 3.5 and Linq to SQL, you can do it very easily, check this video:</p>
<p><a href="http://weblogs.asp.net/scottgu/archive/2007/08/16/linq-to-sql-part-6-retrieving-data-using-stored-procedures.aspx" rel="nofollow noreferrer">LINQ to SQL: Using Stored Procedures</a></p>
<blockquote>
<p>Using existing stored procedures and
functions is easy with LINQ. We simply
drag the stored procedures onto the
O/R mapping surface and call them from
the generated Data Context object.</p>
</blockquote>
|
<p>dragging and dropping the stored procedures onto a dataset design surface (in .net 2.0 and higher) generates a wrapping function</p>
<p>but if you have a lot of them to do, you might be better off using or writing a simple code generator</p>
<p>two options for this: </p>
<ol>
<li>generate the wrapping code yourself as C# classes/methods</li>
<li>generate a dataset.xsd file then open it in visual studio and let the designer generate the classes/methods for you</li>
</ol>
<p>the latter can be maintained via the dataset design surface, but may be tricky to get generated right (the first time)</p>
| 36,825
|
<p>I often have trouble with prints being especially difficult to remove from the build plate on my Micro3D printer. My wife suggested using a hair dryer on the underside of the plate. I was initially appalled at the idea, but now I think she may be on to something. Is this safe? Good idea? Bad idea? Heresay?</p>
|
<p>Typically, people <em>cool down</em> their build plates to get parts to release, rather than heat them up. That said, I doubt a hair drier will get hot enough to do any damage to the build plate. You could try it with no harm done.</p>
|
<p>cold wind can help to acceleratory cool down and dry the build plates to make it easy to part them.</p>
| 352
|
<p>I am trying to optimize some stored procedures on a SQL Server 2000 database and when I try to use SQL Profiler I get an error message "In order to run a trace against SQL Server you have to be a member of sysadmin fixed server role.". It seems that only members of the sysadmin role can run traces on the server (something that was fixed in SQL Server 2005) and there is no way in hell that I will be granted that server role (company policies)</p>
<p>What I'm doing now is inserting the current time minus the time the procedure started at various stages of the code but I find this very tedious </p>
<p>I was also thinking of replicating the database to a local installation of SQL Server but the stored procedure is using data from many different databases that i will spend a lot of time copying data locally</p>
<p>So I was wondering if there is some other way of profiling SQL code? (Third party tools, different practices, something else )</p>
|
<p>That's what cronjobs are made for. <code>man crontab</code> assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.</p>
|
<p>Command line PHP + cron would be the way I would go. It's simple and should fit the bill. It is usually installed with PHP as a matter of course.</p>
| 14,625
|
<p>I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA_OPTS environment variable, but I'm testing that with jconsole to see if it works and it... doesn't.</p>
<p>As per the comment below, CATALINA_OPTS doesn't work either. So far, the only way I can get it to work is via the Tomcat configuration GUI, and that's not an acceptable solution for my problem.</p>
|
<p>Serhii's suggestion works and here is some more detail.</p>
<p>If you look in your installation's bin directory you will see catalina.sh
or .bat scripts. If you look in these you will see that they run a
setenv.sh or setenv.bat script respectively, if it exists, to set environment variables.
The relevant environment variables are described in the comments at the
top of catalina.sh/bat. To use them create, for example, a file
$CATALINA_HOME/bin/setenv.sh with contents</p>
<pre><code>export JAVA_OPTS="-server -Xmx512m"
</code></pre>
<p>For Windows you will need, in setenv.bat, something like</p>
<pre><code>set JAVA_OPTS=-server -Xmx768m
</code></pre>
<p>Hope this helps,
Glenn</p>
|
<p>Just edit your your catalina/bin/startup.sh script. Add the following commands in it: </p>
<pre><code>#Adjust it to the size you want. Ignore the from bit.
export CATALINA_OPTS="-Xmx1024m"
#This should point to your catalina base directory
export CATALINA_BASE=/usr/local/tomcat
#This is only used if you editing the instance of your tomcat
/usr/share/tomcat6/bin/startup.sh
</code></pre>
<p>Sailab: <a href="http://www.facejar.com/member/page-id-477.html" rel="nofollow">http://www.facejar.com/member/page-id-477.html</a></p>
| 36,331
|
<p>I want to delete all but the 4 newest directories in my parent directory. How would you do this in Bash?</p>
|
<pre><code>ls -atrd */ | head --lines=-4 | xargs rm -rf
</code></pre>
<p><strong>Edit:</strong> added 'a' argument to ls</p>
|
<p>Another, BSD-safe, way to do it, with arrays (why not?)</p>
<pre><code>#!/bin/bash
ARRAY=( `ls -td */` )
ELEMENTS=${#ARRAY[@]}
COUNTER=4
while [ $COUNTER -lt $ELEMENTS ]; do
echo ${ARRAY[${COUNTER}]}
let COUNTER=COUNTER+1
done
</code></pre>
| 9,743
|
<p>I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.</p>
<pre><code>def analyser(testFunc):
print testFunc.__name__, 'belongs to the class, ...
</code></pre>
<p>I thought </p>
<pre><code>testFunc.__class__
</code></pre>
<p>would solve my problems, but that just tells me that testFunc is a function.</p>
|
<pre><code>testFunc.im_class
</code></pre>
<p><a href="https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy" rel="nofollow noreferrer">https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy</a></p>
<blockquote>
<p><code>im_class</code> is the class of <code>im_self</code> for
bound methods or the class that asked
for the method for unbound methods</p>
</blockquote>
|
<p>Please use following function to get method names inside of a class </p>
<pre><code>def getLocalMethods(clss):
import types
# This is a helper function for the test function below.
# It returns a sorted list of the names of the methods
# defined in a class. It's okay if you don't fully understand it!
result = [ ]
for var in clss.__dict__:
val = clss.__dict__[var]
if (isinstance(val, types.FunctionType)):
result.append(var)
return sorted(result)
</code></pre>
| 39,359
|
<p>What criteria should I use to decide whether I write VBA code like this:</p>
<pre><code>Set xmlDocument = New MSXML2.DOMDocument
</code></pre>
<p>or like this:</p>
<pre><code>Set xmlDocument = CreateObject("MSXML2.DOMDocument")
</code></pre>
<p>?</p>
|
<p>As long as the variable is not typed as object</p>
<pre><code>Dim xmlDocument as MSXML2.DOMDocument
Set xmlDocument = CreateObject("MSXML2.DOMDocument")
</code></pre>
<p>is the same as</p>
<pre><code>Dim xmlDocument as MSXML2.DOMDocument
Set xmlDocument = New MSXML2.DOMDocument
</code></pre>
<p>both use early binding. Whereas</p>
<pre><code>Dim xmlDocument as Object
Set xmlDocument = CreateObject("MSXML2.DOMDocument")
</code></pre>
<p>uses late binding. See MSDN <a href="http://support.microsoft.com/kb/245115" rel="noreferrer">here</a>.</p>
<p>When you’re creating externally provided objects, there are no differences between the New operator, declaring a variable As New, and using the CreateObject function.</p>
<p>New requires that a type library is referenced. Whereas CreateObject uses the registry.</p>
<p>CreateObject can be used to create an object on a remote machine.</p>
|
<p>For the former you need to have a reference to the type library in your application. It will typically use early binding (assuming you declare your variable as MSXML2.DOMDocument rather than as Object, which you probably will), so will generally be faster and will give you intellisense support.</p>
<p>The latter can be used to create an instance of an object using its ProgId without needing the type library. Typically you will be using late binding.</p>
<p>Normally it's better to use "As New" if you have a type library, and benefit from early binding. </p>
| 20,528
|
<p>I'm trying to find a way of applying graphics to my ABS printed parts. </p>
<p>I need a robust method which can produce a decent amount of detail with true color and legible fine text .
I also was hoping to avoid the use of stickers and opt for something that's slightly more permanent. </p>
<p>I was wondering if there are ways in which a vinyl decal or other types of decal material could be pressed into the face of a plastic part and then thermally fuse the two layers together using heat transfer method?</p>
<p>Most of the surfaces I work with would be flat, but there are some parts that are slightly curved and it would be totally amazing if I could somehow apply graphics to those areas as well.</p>
<p>Thanks for any hints</p>
|
<p>Industry has for years used a 'pad printer' to put images on complex shapes, like plastic or ceramic travel mugs, etc.</p>
<p>I have observed these, but never used one. I see no reason why there couldn't be a DIY version made.</p>
<p>Best of luck, and I look forward to seeing what you come up with!</p>
|
<p>You really can't. That said the only group that has this kind of tech is .. Disney of all companies. That said their tech is good at simple shapes. Nothing more.</p>
<p>I have seen some hydro transfer techniques. However that will not let you position a graphic as it is all done with a stretch transfer material ontop of a water bed. No one has a hand steady enough. </p>
<p>Realistically you either need a high end full color powered base 3d printer, or simple designs that you can apply with you hand, or paint by hand.</p>
<p>Well. Rereading your question... If you just want readable text. Then use a 2+ nozzle printer and print in colors that are contract. IE white model and black text. A lot more work but an order of magnitude cheaper than other options.</p>
<p><a href="http://www.3ders.org/articles/20160503-full-color-3d-models-made-faster-and-cheaper-with-computational-thermoforming.html" rel="nofollow noreferrer">Disney article</a></p>
<p><a href="https://www.youtube.com/watch?v=B-2oaSfy8RE" rel="nofollow noreferrer">Hydro transfer video</a></p>
<p><a href="https://i.stack.imgur.com/XsAtW.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XsAtW.jpg" alt=""></a></p>
| 349
|
<p>Is there a catchall function somewhere that works well for sanitizing user input for SQL injection and XSS attacks, while still allowing certain types of HTML tags?</p>
|
<p>It's a common misconception that user input can be filtered. PHP even has a (now deprecated) "feature", called <a href="https://www.php.net/manual/en/security.magicquotes.php" rel="noreferrer">magic-quotes</a>, that builds on this idea. It's nonsense. Forget about filtering (or cleaning, or whatever people call it).</p>
<p>What you should do, to avoid problems, is quite simple: whenever you embed a a piece of data within a foreign code, you must treat it according to the formatting rules of that code. But you must understand that such rules could be too complicated to try to follow them all manually. For example, in SQL, rules for strings, numbers and identifiers are all different. For your convenience, in most cases there is a dedicated tool for such an embedding. For example, when you need to use a PHP variable in the SQL query, you have to use a prepared statement, that will take care of all the proper formatting/treatment.</p>
<p>Another example is HTML: If you embed strings within HTML markup, you must escape it with <a href="http://php.net/manual/function.htmlspecialchars.php" rel="noreferrer"><code>htmlspecialchars</code></a>. This means that every single <code>echo</code> or <code>print</code> statement should use <code>htmlspecialchars</code>.</p>
<p>A third example could be shell commands: If you are going to embed strings (such as arguments) to external commands, and call them with <a href="http://php.net/manual/function.exec.php" rel="noreferrer"><code>exec</code></a>, then you must use <a href="http://php.net/manual/function.escapeshellcmd.php" rel="noreferrer"><code>escapeshellcmd</code></a> and <a href="http://php.net/manual/function.escapeshellarg.php" rel="noreferrer"><code>escapeshellarg</code></a>.</p>
<p>Also, a very compelling example is JSON. The rules are so numerous and complicated that you would never be able to follow them all manually. That's why you should never ever create a JSON string manually, but always use a dedicated function, <a href="https://www.php.net/json_encode" rel="noreferrer"><code>json_encode()</code></a> that will correctly format every bit of data.</p>
<p>And so on and so forth ...</p>
<p>The <em>only</em> case where you need to actively filter data, is if you're accepting preformatted input. For example, if you let your users post HTML markup, that you plan to display on the site. However, you should be wise to avoid this at all cost, since no matter how well you filter it, it will always be a potential security hole.</p>
|
<p>There is the filter extension (<a href="http://devolio.com/blog/archives/413-Data-Filtering-Using-PHPs-Filter-Functions-Part-one.html" rel="nofollow noreferrer">howto-link</a>, <a href="http://php.net/filter" rel="nofollow noreferrer">manual</a>), which works pretty well with all GPC variables. It's not a magic-do-it-all thing though, you will still have to use it.</p>
| 15,760
|
<p>I have a few longtables that stretch several pages and I want to use pageref and hyperref to link to these rows.</p>
<p>But whatever I try, the links always refer to the start of the table.
When I look into the aux file, the labels all seem to be re-defined into table.[number of table].</p>
<p>I tried putting invisible dummy figures into the table, but that just gives me errors of too many floats.</p>
<p>I also tried putting the labels into minipages, to no avail.</p>
<p>Even putting the labels into footnotes doesn't work, somehow longtable always seems to get to them.</p>
|
<p>I solved this problem by introducing a custom counter and label command:</p>
<pre><code>\newcounter{mycounter}
\newcommand{\mylabel}[1]{\refstepcounter{mycounter} \label{#1}}
</code></pre>
|
<p>According to <a href="http://newsgroups.derkeiler.com/Archive/Comp/comp.text.tex/2008-05/msg01417.html" rel="nofollow noreferrer">This article</a> and <a href="http://www.ctan.org/tex-archive/macros/latex/contrib/hyperref/" rel="nofollow noreferrer">The readme for Hyperref</a> you need to include the Hyperref package after you include Longtable</p>
| 38,705
|
<p>I want to create dynamic content based on this. I know it's somewhere, as web analytics engines can get this data to determine how people got to your site (referrer, search terms used, etc.), but I don't know how to get at it myself.</p>
|
<p>You can use the "referer" part of the request that the user sent to figure out what he searched for. Example from Google:</p>
<blockquote>
<p><a href="http://www.google.no/search?q=stack%20overflow" rel="nofollow noreferrer">http://www.google.no/search?q=stack%20overflow</a></p>
</blockquote>
<p>So you must search the string (in ASP(.NET) this can be found be looking in <code>Request.Referer</code>) for "q=" and then URLDecode the contents.</p>
<p>Also, you should take a look at this article that talks more about referrers and also other methods to track your visitors:</p>
<p><a href="http://www.15seconds.com/issue/021119.htm" rel="nofollow noreferrer">http://www.15seconds.com/issue/021119.htm</a></p>
|
<p>This is some code to backup the idea of using a querystring method and if that's not available using the UrlReferrer property of the Request object. This can then be stashed in a session object (or somewhere else if that works better for you) so that you can track the source between pages. (Page_Load doesn't seem to be formatted correctly inside the code sample here)</p>
<pre><code>public void Page_Load(Object Sender, EventArgs E) {
if (null == Session["source"] || Session["source"].ToString().Equals(string.Empty)) {
if (Request.QueryString["src"] != null) {
Session["source"] = Server.UrlDecode(Request.QueryString["src"].ToString());
} else {
if (Request.UrlReferrer != null) {
Session["source"] = Request.UrlReferrer.ToString();
} else {
Session["source"] = string.Empty;
}
}
}}
</code></pre>
| 8,120
|
<p>Suppose A.css styles B.html. What tools/techniques are there to programmatically reduce the size of A.css while holding its styling effects on B.html constant? Here are some techniques I would imagine such a tool using:</p>
<ol>
<li><p><strong>Remove redundancies in A.css.</strong> For example, if the same class is defined twice you can remove the second definition without affecting semantics. This seems pretty easy.</p></li>
<li><p><strong>Remove style definitions that aren't used</strong>. Does A.css style any elements that don't appear in B.html? If so, remove them.</p></li>
<li><p><strong>Combine styles where appropriate</strong>. If A.css defines styles for div.x and div.y and every div that happens to have class x also has class y, one could combine the class definitions in A.css.</p></li>
</ol>
<p>A different strategy would be to have a tool that examines the computed styles of each element in a piece of styled HTML and spits out the minimal style sheet that would preserve the computed styles. Does something like <em>this</em> exist?</p>
<h2>UPDATE</h2>
<p>Let me explain how I got in this situation. The CSS file in question is for an <strong>email</strong>, and it was created by basically copying a similar CSS file that we used in an associated web page. Because the HTML in the email is a proper subset of the HTML in the web page from which the CSS came, some of the CSS in the email is superfluous.</p>
|
<p>Generally you just remove all unnecessary whitespace. Remember to keep the original as well, so you don't lose readability when editing the site later.</p>
|
<p>Unless you have an usually large CSS file, I would opt for readability and modifiability of the CSS file rather than having a smaller CSS file. Since CSS files are static (for the most part), most browsers will do a really good job of caching them. While all your suggestions are good ones, combining things that are the same now for different document elements can wreak havoc in the future when you only want to change one of those items.</p>
| 25,616
|
<p>During our build process we run <code>aspnet_compiler.exe</code> against our websites to make sure that all the late-bound stuff in ASP.NET/MVC actually builds (I know nothing about ASP.NET but am assured this is necessary to prevent finding the failures at runtime).</p>
<p>Our sites are fairly large in size, with a few hundred pages/views/controls/etc. however the time taken seems excessive in the 10-15 minute range (for reference, this is longer than it takes the entire solution with approx 40 projects to compile, and we're only pre-compiling two website projects).</p>
<p>I doubt that hardware is the issue as I'm running on the latest Quad core Intel chip, with 4GB RAM and a WD Velociraptor 10,000rpm hard disk. And part of what's odd is that the EXE doesn't seem to be using much CPU (1-5%) and doesn't seem to be doing an awful lot of I/O either.</p>
<p>So... is this a known issue? Why is it so slow? And is there any way to speed it up?</p>
<p><strong>Note:</strong> To clarify a couple of things people have answered about, I am not talking about the compilation of code within Visual Studio. We're using web application projects already, and the speed of compilation of those is not the issue. The problem is the pre-compilation of the site <em>after</em> these projects have already been compiled (<a href="http://msdn.microsoft.com/en-us/library/ms229863.aspx" rel="noreferrer">see this MSDN page for more details</a>) as part of the dev build script. We are performing in-place pre-compilation, not copying the files to a target directory.</p>
|
<ol>
<li>Compiler should generate second code-behind file for every .aspx page, <a href="http://webproject.scottgu.com/CSharp/UnderstandingCodeBehind/UnderstandingCodeBehind.aspx" rel="nofollow noreferrer" title="check">check</a></li>
<li>During compilation, aspnet_compiler.exe will copy ALL of the web site files to the output directory, including css, js and images.</li>
</ol>
<p>You'll get better compilation times using <a href="http://webproject.scottgu.com/" rel="nofollow noreferrer" title="Web application project">Web application project</a> instead of Web site model.</p>
|
<p>Just my 2 cents.</p>
<p>One of the things slowing down ASP.NET views precompilation significantly is the <code>-fixednames</code> command line option for <code>aspnet_compiler.exe</code>. <strong>Do not use it</strong> especially if you're on Razor/MVC.</p>
<p>When publishing the wep app from Visual Studio make sure you select "Do not merge", and <strong>do not</strong> select "create separate assembly" cause this is what causes the global lock and slows things down.</p>
<p><a href="https://i.stack.imgur.com/qw0ge.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qw0ge.png" alt="enter image description here"></a></p>
<p>More info here <a href="https://msdn.microsoft.com/en-us/library/hh475319(v=vs.110).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/hh475319(v=vs.110).aspx</a></p>
| 36,927
|
<p>Given a heapdump or a running VM, how do I discover what the contents of the permanent generation is ? I know about 'jmap -permstat' but that's not available on Windows.</p>
|
<p>The permanent generation contains the class object.
So you should check the heap dump or other form of object list for classes.
If you have problem with the size of permanent generation usually it is caused by two reason:</p>
<ul>
<li>your program or a library you use creates classes dynamically and the default size of permanent generation is too small - simple increate the size with -XX:MaxPermSize=256m</li>
<li>your program or a library you use creates new classes dynamically every time it is called, so the size of permanent generation increases non-stop - this is a programming error you should fix it (or search a fix/create a bug report)</li>
</ul>
<p>To see which is your case check the size of the permanent generation over a larger period.</p>
<p>And a good overview about permanent generation:</p>
<p><a href="http://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation" rel="nofollow noreferrer">http://blogs.oracle.com/jonthecollector/entry/presenting_the_permanent_generation</a></p>
|
<p>you can use JConsole or jvisualvm.exe(with jdk 1.6 7) to find what is where. If you want to know how all of your objects are related to each other and tree of objects, then you might want to try Eclipse Memory Analyzer -- <a href="http://www.eclipse.org/mat/" rel="nofollow noreferrer">http://www.eclipse.org/mat/</a>.</p>
<p>IN summary, you will get want you want from "<a href="http://www.eclipse.org/mat/" rel="nofollow noreferrer">http://www.eclipse.org/mat/</a>".</p>
<p>Good luck,</p>
| 23,619
|
<p>I am writing some software to identify tracking numbers (in the same way that Google identifies FedEx or UPS numbers when you search for them). Most couriers use a system, such as a "weighted average mod system" which can be used to identify if a number is a valid tracking number. Does anyone know if TNT consignment numbers use such a system, and if so, what it is? I have asked TNT support, and the rep told me they do not... but I'd like to doublecheck.</p>
|
<p>OK, so it's three months since you asked but I stumbled across this as I'm writing a similar piece of software. As far as we know TNT uses the <a href="http://en.wikipedia.org/wiki/S10_(UPU_standard)" rel="nofollow noreferrer">S10</a> tracking number system. Which means that their numbers will be of the type AA#########AA. With the last two letters corresponding to a ISO/IATA country code. Having said that TNT uses WW which we believe must stand for worldwide. This is not quite an answer, at least it's not about checksums or algorithms, but it might be useful? Hope that helps</p>
<p>Willow</p>
|
<p>As far as I can tell, there isn't one. Sorry.</p>
<p>I take it you're trying to validate the tracking number entered to make sure it was entered properly?</p>
<p>-- Kevin Fairchild</p>
| 8,124
|
<p>I have a set of mercurial repositories being served online with hgwebdir.cgi. I would like to be able to show a graphical representation of the branches and merges in the same way that <a href="http://hg.serpentine.com/mercurial/book/graph" rel="nofollow noreferrer">this site</a> does. I can't seem to find any reference to how to do that though. Does the functionality only exist in hgweb and not hgwebdir?</p>
|
<p>Until version 1.1 comes out (in a few days) you'd need to clone and install from the <a href="http://hg.intevation.org/mercurial/crew/" rel="nofollow noreferrer">Mercurial crew respository</a></p>
|
<p>This future will be enabled in next release, try use develop version from repo.</p>
<p>In console u can use <a href="http://www.selenic.com/mercurial/wiki/index.cgi/GraphlogExtension" rel="nofollow noreferrer">glog extension</a></p>
| 34,364
|
<p>I'm using the .NET TWAIN code from <a href="http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx" rel="nofollow noreferrer">http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx</a> in my application.
When I try to scan an image when the scanner is not plugged in, the application freezes.</p>
<p>How can I check if the device is plugged in, using the TWAIN driver?</p>
|
<p>Maybe I'm taking the question too literally, but using the TWAIN API, it is not possible to check if a device is plugged in i.e. connected and powered on. The TWAIN standard does define a capability for this purpose called CAP_DEVICEONLINE, but this feature is so poorly conceived and so few drivers implement it correctly that it is useless in practice.</p>
<p>The closest you can get is this: Open the device (MSG_OPENDS): Almost all drivers will check for device-ready when they are opened, and will display an error dialog to the user. <em>There is no TWAIN mechanism for suppressing or detecting this dialog</em> Some drivers will allow the user to correct the problem and continue, in which case you (your app) will never know there was a problem. Some drivers will allow the user to cancel, in which case the MSG_OPENDS operation will fail, probably returning TWRC_CANCEL but maybe TWRC_FAILURE</p>
<p>A few TWAIN drivers will open without error even though the device is off-line. Such a driver <em>may</em> return FALSE to a query of CAP_DEVICEONLINE. Such a driver will probably do the device-online check when you enable the device with MSG_ENABLEDS, and then if the device is not on-line, you get the error dialog to the user, and so on as above.</p>
<p>Aside and IMPO: WIA is 'more modern' but also much less comprehensive for scanning than TWAIN, and in my experience unusable for multipage scanning from a document feeder. WIA's designers and maintainers seem not to understand or care about scanners other than low-end consumer flatbeds. It's good for cameras.</p>
|
<p>i try do this but dont work good with TWAIN mybe try WIA </p>
<p>mybe try this:</p>
<p>on buton run scanner </p>
<pre><code>timer1.Interval = 30000;
switch (cmd)
{
case TwainCommand.TransferReady:
{
..........
}
default:
{
timer1.Start();
break;
}
</code></pre>
<p>on event timer tick </p>
<pre><code>{
EndingScan();
tw.CloseSrc();
}
</code></pre>
| 12,556
|
<p>If you know the local path and file name of the file you want the end user to upload (via browser). Then is it possible to pre-set these properties for the HTML file input element (or any upload control)? So when the user clicks 'browse' to select the file to upload, then the dialog has preselected the filename.</p>
<p>Btw, assume that this is for an intranet where the necessary directory/file do exist locally.</p>
|
<p>Unless it is a custom upload control, this cannot be done for security reasons. </p>
<p>If a html page could set the file to be uploaded using javascript, for instance, an arbitrary html page could upload any file from the client computer (form submission can be triggered via javascript)</p>
|
<p>This type of interaction with file-upload controls is disabled for security reasons.</p>
| 45,657
|
<p>What are differences between CallContext and ThreadStatic?</p>
<p>I've understood that in an ASP.NET environment data stored in CallContext could be persisted throughout the request until it ends while ThreadStatic may or may not work since the request may switch threads. I've also learned that the HttpContext is internally stored using the CallContext.</p>
<p>In a regular application they both seem to persist throughout the same thread call. When isn't this the case? </p>
<hr>
<p><strong>Edit:</strong> In the comments I learned that the call context is an abstraction over a thread static store. The ASP.NET framework explicitly moves the data from one thread to the next that is to handle one request. Other framework that wants to provide thread agility could do the same to for contextual storage.</p>
|
<p>Very often a request will use the same thread throughout, but it certainly won't always be the case - ASP.NET exhibits <em>thread agility</em>. There's an old <a href="http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html" rel="nofollow noreferrer">in-depth blog article about the matter</a> from 2005, but as of .NET 4.5 <a href="https://blog.stephencleary.com/2013/04/implicit-async-context-asynclocal.html" rel="nofollow noreferrer">things are rather better</a>.</p>
|
<p>Items stored as ThreadStatic are available to more than one request. IIS reuses the thread after a request is complete to process subsequent requests, it can even swap a request from one thread to another during processing. ASP.Net clears down the CallContext after each request.</p>
| 34,427
|
<p>I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? </p>
<p>For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!</p>
<p>I can do this using my own ValidationEngine framework: </p>
<pre><code>Customer customer = new Customer();
customer.FirstName = "John";
customer.LastName = String.Empty;
ValidationEngine.Validate(customer);
if (customer.BrokenRules.Count > 0)
{
// do something display the broken rules!
}
</code></pre>
|
<p>A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx" rel="noreferrer">IDataErrorInfo</a> interface on your business object, using Bindings with <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesondataerrors.aspx" rel="noreferrer"><code>ValidatesOnDataErrors</code></a><code>=true</code>. For customizing the look of individual controls in the case of errors, set a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errortemplate.aspx" rel="noreferrer"><code>Validation.ErrorTemplate</code></a>.</p>
<h3>XAML:</h3>
<pre><code><Window x:Class="Example.CustomerWindow" ...>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Save"
CanExecute="SaveCanExecute"
Executed="SaveExecuted" />
</Window.CommandBindings>
<StackPanel>
<TextBox Text="{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button>
<TextBlock Text="{Binding Error}"/>
</StackPanel>
</Window>
</code></pre>
<p>This creates a <code>Window</code> with two <code>TextBox</code>es where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The <code>TextBlock</code> beneath the button shows the current errors, so the user knows what's up.</p>
<p>The default <code>ErrorTemplate</code> is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at <a href="http://www.codeproject.com/KB/WPF/wpfvalidation.aspx" rel="noreferrer">Validation in Windows Presentation Foundation</a> article on CodeProject for an in-depth look into what can be done about that.</p>
<p>To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer.</p>
<h3>Code Behind</h3>
<pre><code>// The CustomerWindow class receives the Customer to display
// and manages the Save command
public class CustomerWindow : Window
{
private Customer CurrentCustomer;
public CustomerWindow(Customer c)
{
// store the customer for the bindings
DataContext = CurrentCustomer = c;
InitializeComponent();
}
private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ValidationEngine.Validate(CurrentCustomer);
}
private void SaveExecuted(object sender, ExecutedRoutedEventArgs e)
{
CurrentCustomer.Save();
}
}
public class Customer : IDataErrorInfo, INotifyPropertyChanged
{
// holds the actual value of FirstName
private string FirstNameBackingStore;
// the accessor for FirstName. Only accepts valid values.
public string FirstName {
get { return FirstNameBackingStore; }
set {
FirstNameBackingStore = value;
ValidationEngine.Validate(this);
OnPropertyChanged("FirstName");
}
}
// similar for LastName
string IDataErrorInfo.Error {
get { return String.Join("\n", BrokenRules.Values); }
}
string IDataErrorInfo.this[string columnName]
{
get { return BrokenRules[columnName]; }
}
}
</code></pre>
<p>An obvious improvement would be to move the <code>IDataErrorInfo</code> implementation up the class hierarchy, since it only depends on the <code>ValidationEngine</code>, but not the business object.</p>
<p>While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data.</p>
|
<p>The description of your problem is a little vague to me. I mean, I'm not exactly sure what your difficulty is.
Assuming that the DataContext is some sort of presenter or controller that has a propetry representing the customer instance, and ValidateCommand is a property of type ICommand:</p>
<pre><code> <StackPanel>
<TextBox Text="{Binding CurrentCustomer.FirstName}" />
<TextBox Text="{Binding CurrentCustomer.LastName}" />
<Button Content="Validate"
Command="{Binding ValidateCommand}"
CommandParameter="{Binding CurrentCustomer}" />
<ItemsControl ItemsSource="{Binding CurrentCustomer.BrokenRules}" />
</StackPanel>
</code></pre>
<p>This XAML is really simplified, of course, and there are other ways to do it.
As a Web developer who is now heavily involved with WPF, I find most tasks like this significantly easier in WPF.</p>
| 13,012
|
<p>Need to an expression that returns only things with an "I" followed by either a "J" or a "V" (No Quotes) and then a minimum of 1 number up to 3 numbers.</p>
<p>I J### <br />
I V### <br />
I J## <br />
I V## <br />
I J# <br />
I v# <br /></p>
|
<p>Depends on your flavor</p>
<pre><code>I(J|V)[0-9]{1,3}
</code></pre>
<p>Do you also need a space after an "I"?</p>
<pre><code>I (J|V)[0-9]{1,3}
</code></pre>
|
<p>I think the others missed the <code>v#</code> spec. </p>
<pre><code>I[JVv]\d{1,3}
</code></pre>
<p>Of course perhaps the lowercase <code>v</code> was a typo.</p>
| 39,933
|
<p>How can I make my <code>std::fstream</code> object start reading a text file from the second line?</p>
|
<p>Use getline() to read the first line, then begin reading the rest of the stream.</p>
<pre><code>ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
...
</code></pre>
<p>(Changed to std::getline (thanks dalle.myopenid.com))</p>
|
<pre><code>#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char buffer[256];
ifstream myfile ("test.txt");
// first line
myfile.getline (buffer,100);
// the rest
while (! myfile.eof() )
{
myfile.getline (buffer,100);
cout << buffer << endl;
}
return 0;
}
</code></pre>
| 19,866
|
<p>I have a pivot table on an olap cube. I can go into a page field and manually deselect multiple items. How can I do this in VBA based on a list of items I need excluded? (n.b. I do not have a corrresponding list of items I need included)</p>
<p>I know how to exclude these items in other ways, by altering the underlying query for example. I specifically want to replicate the user action of deselecting items in the pivot.</p>
|
<p>You do not have to run an MDX query to list the members of a dimension, you can look at the properties of the cube object in VBA.
Start with this and see where it gets you!</p>
<p>Set oCat = New ADOMD.Catalog</p>
<p>loop through this for example:
oCat.CubeDefs(sCube).Dimensions(3).Hierarchies(0).Levels(2).Members(i)</p>
|
<p>I apologize for this example being in C#, but I really don't know enough VBA to translate it (perhaps someone can edit this entry and add it below).</p>
<p>Are you refering to something like this?</p>
<pre><code>((MOE.PivotField)pivotTableObject.PivotFields("[NAME]")).Delete();
</code></pre>
<p>Where MOE is the Microsoft.Office.Interop.Excel namespace and [NAME] is the name of the field you want to remove</p>
| 12,664
|
<h2><strong>Edit: I have solved this by myself. See <a href="https://stackoverflow.com/questions/145241/change-the-value-of-a-text-box-to-its-current-order-in-a-sortable-tab/145388#145388">my answer below</a></strong></h2>
<p>I have set up a nice sortable table with jQuery and it is quite nice. But now i want to extend it.</p>
<p>Each table row has a text box, and i want i am after is to, every time a row is dropped, the text boxes update to reflect the order of the text boxes. <strong>E.g. The text box up the top always has the value of '1', the second is always '2' and so on.</strong></p>
<p>I am using jQuery and the <a href="http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/" rel="nofollow noreferrer">Table Drag and Drop JQuery plugin</a></p>
<h3>Code</h3>
<p><strong>Javascript:</strong></p>
<pre><code><script type = "text/javascript" >
$(document).ready(function () {
$("#table-2").tableDnD({
onDrop: function (table, row) {
var rows = table.tBodies[0].rows;
var debugStr = "Order: ";
for (var i = 0; i < rows.length; i++) {
debugStr += rows[i].id + ", ";
}
console.log(debugStr)
document.forms['productform'].sort1.value = debugStr;
document.forms['productform'].sort2.value = debugStr;
document.forms['productform'].sort3.value = debugStr;
document.forms['productform'].sort4.value = debugStr;
},
});
});
</script>
</code></pre>
<p><strong>HTML Table:</strong></p>
<pre class="lang-html prettyprint-override"><code><form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr>
<td>Product</td>
<td>Order</td>
</tr>
</thead>
<tbody>
<tr class="row1" id="Pol">
<td><a href="1/">Pol</a></td>
<td><input type="textbox" name="sort1"/></td>
</tr>
<tr class="row2" id="Evo">
<td><a href="2/">Evo</a></td>
<td><input type="textbox" name="sort2"/></td>
</tr>
<tr class="row3" id="Kal">
<td><a href="3/">Kal</a></td>
<td><input type="textbox" name="sort3"/></td>
</tr>
<tr class="row4" id="Lok">
<td><a href="4/">Lok</a></td>
<td><input type="textbox" name="sort4"/></td>
</tr>
</tbody>
</table>
</form>
</code></pre>
|
<p>Hardnrg in #jquery ended up solving it for me.</p>
<p>It involved adding an id="" to each input:</p>
<pre><code><form name="productform">
<table cellspacing="0" id="table-2" name="productform">
<thead>
<tr><td>Product</td> <td>Order</td></tr>
</thead>
<tbody>
<tr class="row1" id="Pol"> <td><a href="1/">Pol</a></td> <td><input id="Pol_field" type="textbox" name="sort1"/></td> </tr>
<tr class="row2" id="Evo"> <td><a href="2/">Evo</a></td> <td><input id="Evo_field" type="textbox" name="sort2"/></td> </tr>
<tr class="row3" id="Kal"> <td><a href="3/">Kal</a></td> <td><input id="Kal_field" type="textbox" name="sort3"/></td> </tr>
<tr class="row4" id="Lok"> <td><a href="4/">Lok</a></td> <td><input id="Lok_field" type="textbox" name="sort4"/></td> </tr>
</tbody>
</table>
</form>
</code></pre>
<p>And add this js to the OnDrop event:</p>
<pre><code>for (var i=0; i < rows.length; i++) {
$('#' + rows[i].id + "_field").val(i+1);
}
</code></pre>
<p>Easy peasy!</p>
|
<p>Hmmm..
I think you want to do something like this:</p>
<pre><code>$("input:text", "#table-2").each( function(i){ this.value=i+1; });
</code></pre>
<p>The $().each() function's info is here: <a href="http://docs.jquery.com/Core/each" rel="nofollow noreferrer">http://docs.jquery.com/Core/each</a></p>
| 17,510
|
<p>I know it's bad to use HTML Tables for everything... and that tables should be used only to present tabular data and not to achieve some style goal. </p>
<p>My question is, how do you make HTML forms with CSS so they look nice and aligned like when using tables?</p>
|
<p>Nick Rigby wrote an excellent article for A List Apart titled <a href="http://www.alistapart.com/articles/prettyaccessibleforms/" rel="noreferrer">Prettier Accessible Forms</a></p>
<p>Uses fieldset, legend, label. Highly semantic.</p>
|
<p>I would lookup using the div tag to layout data on a page.</p>
<p>Tables are still very much useful for tabular data, but its frowned upon for laying out a page.</p>
<p>View source here on stackoverflow.com, there's probably some good examples.</p>
| 21,701
|
<p>Date coming out of a database, need to format as "mm/dd/yy"</p>
<pre><code>For Each dr as DataRow in ds.Tables(0).Rows
Response.Write(dr("CreateDate"))
Next
</code></pre>
|
<pre><code>string.Format( "{0:MM/dd/yy}", dr("CreateDate") )
</code></pre>
<p>Edit: If dr("CreateDate") is DBNull, this returns "".</p>
|
<pre><code>Response.Write(DateTime.Parse(dr("CreateDate").ToString()).ToString("MM/dd/yyyy"))
</code></pre>
| 15,615
|
<p>The only thing I've found has been;</p>
<pre class="lang-css prettyprint-override"><code>.hang {
text-indent: -3em;
margin-left: 3em;
}
</code></pre>
<p>The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a <code><span class="hang"></span></code> type of thing.</p>
<p>I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work.</p>
|
<p><code><span></code> is an inline element. The term <em>hanging indent</em> is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on <code><p></code> or <code><div></code> or any other block element to get rid of extra vertical space between paragraphs.</p>
<p>You may want something like <code>display: run-in</code>, where the tag will become either block or inline depending on context... sadly, this is <a href="http://quirksmode.org/css/css2/display.html" rel="noreferrer">not yet universally supported by browsers</a>.</p>
|
<p>ysth's answer is best with one debatable exception; the unit of measure should correspond to the size of the font.</p>
<pre class="lang-css prettyprint-override"><code>p {
text-indent: -2en;
padding-left: 2en;
}
</code></pre>
<p>"3" would also work adequately well; "em" is not recommended as it is wider than the average character in an alphabetic set. "px" should only be used if you intended to align hangs of text blocks with differing font sizes.</p>
| 3,293
|
<p>How can I bind an array parameter in the HQL editor of the HibernateTools plugin?
The query parameter type list does not include arrays or collections.</p>
<p>For example:<br>
<code>Select * from Foo f where f.a in (:listOfValues)</code>.<br>
How can I bind an array to that listOfValues?</p>
|
<p>You probably cannot. Hibernate replaces the objects it gets out of the database with it's own objects (kind of proxies). I would strongly assume Hibernate cannot do that with an array. So if you want to bind the array-data put it into a List on access by Hibernate.</p>
<p>As an example one could do:</p>
<pre><code>select * from Foo f where f.a in f.list
</code></pre>
|
<p>I am sure you have already got the answer for this but for anyone else viewing this. it appears that the HQL editor for hibernate tools does not support querying collections. you whould have to not use the parameter and hard code it while testing in the Hibernate Tools HQL editor </p>
<pre><code>Select * from Foo f where f.a in (123,1234)
</code></pre>
<p>The change the query back to what boutta posted when you put it back in your code.</p>
| 12,025
|
<p>My company makes its money off of a great user experience using IE6, 7, Firefox and Safari. 90% of our traffic ends up IE and probably 60% of that traffic is still IE6. IE6 has a bunch of known gotcha's such as accessing DOM objects while they are still being inserted crashing the browser. Almost none of these issues surface during routine testing, they almost always include some odd timing race condition that only affects our most important client of the week. </p>
<p>What process or tools do you use to ensure that known patterns that crash IE are not present in your code? </p>
<p>Added: For those suggesting sticking to 3rd party libraries: I agree that it will help a lot, but you still have to glue those APIs together with Javascript. Is there anyone that is not just crossing their fingers and waiting for someone out in the wild to let them know that there code has just crashed their system?</p>
|
<p>We don't worry about it. Instead, we use a third party tool like jQuery (well, <strong>EXACTLY</strong> like jQuery in our company) to ensure cross-platform idiosyncrasies are handled.</p>
|
<blockquote>
<p>Beleive it or not some of jQuery (and
other libraries) functions don't work
on all browsers.</p>
</blockquote>
<p>Ofcourse, if you relate to IE5 or NN4, jQuery may not be the best pick. Otherwise, you won't have a problem with this.
I use jQuery for a HUGE site and i don't have problems with library. I have problems with plugins, but this is a different story.
And btw, i have less than 10 lines of pure js in my files. If you learn to use jquery efficiently, you won't need any js knowledge (sounds weird, but... this is my case :P )</p>
| 41,738
|
<p>I've created a dtsx package with Sql Server Business Intelligence Development studio, and I am executing it using the dtexec utility. Using dtexec I am setting certain properties at runtime using the /set switch. So my command looks something like:</p>
<pre><code>dtexec /f "mypackage.dtsx" /set
\Package.Connections[Destination].Properties[UserName];myUserName
</code></pre>
<p>This works perfectly when I run it on my local system (the one it was developed on). Unfortunately, when I copy this package to a different system and attempt to run this exact same command, I receive the following error:</p>
<pre><code>Warning: The package path referenced an object that could not be found:
\Package.Connections[Destination].Properties[UserName]. This occurs when an
attempt is made to resolve a package path to an object that cannot not be found.
</code></pre>
<p>The new system that the package was moved to has SSIS installed and is running the same version of Sql Server as my local system (SP2). Maybe I'm misunderstanding something about the intended use of dtsx packages, but I really don't see how/why this is happening.</p>
|
<p>This steps is for creating an XML configuration file (.dtsConfig) which can keep your sensitive data, like the password of your connection string, without having a Protection Level that can make you difficult to move the package from one machine to another.</p>
<p>In this example, assumed you have an OLE DB Connection to an SQL database called MyDb.</p>
<ol>
<li><p>Control Flow, Property: set "ProtectionLevel" to "DontSaveSensitive"</p></li>
<li><p>Control Flow, right-click empty space to get menu: click "Package Configuration"</p></li>
<li><p>Package Configuration Organizer: tick "Enable package configuration"; click "Add"</p></li>
<li><p>Package Configuration Wizard, Select Configuration Type: set "Configuration type" to "XML configuration file"; choose "Specify configuration directly" radio button; click "Browse..."</p></li>
<li><p>Select Configuration File Location, fill "Filename": [PackageName].dtsConfig (easy if same folder and same filename as the package itself, just different extension); click "Save"</p></li>
<li><p>Package Configuration Wizard, Select Configuration Type: click "Next >"</p></li>
<li><p>Package Configuration Wizard, Select Properties to Export: traverse the following tree nodes and tick its checkbox; click "Next >"</p>
<p>\[PackageName]\Connection Managers\MyDb\Properties\Connection String</p>
<p>\[PackageName]\Connection Managers\MyDb\Properties\Password</p></li>
<li><p>Package Configuration Wizard, Completing Wizard, click "Finish"</p></li>
<li><p>Package Configuration Organizer: click "Close"</p></li>
<li><p>Solution Explorer: right click the root tree for menu, click "Add", "Existing Item...", click [PackageName].dtsConfig, click "Add"</p></li>
<li><p>Solution Explorer: double click \Miscellaneous\[PackageName].dtsConfig to load into editor;</p></li>
<li><p>Main menu: click "Edit", click "Advanced", click "Format Document"</p></li>
<li><p>Traverse the XML tree node: \DTSConfiguration\Configuration[Path="\Package.Connections[MyDb].Properties[Password]"]\ConfiguredValue; key in the database password; save the file</p></li>
<li><p>Windows Explorer: navigate and double click [PackageName].dtsx</p></li>
<li><p>Execute Package Utility, Configuration, click "Add", double click [PackageName].dtsConfig, click "Execute"</p></li>
</ol>
<p>When required to move the .dtsx to another machine, simply accompany it with its .dtsConfig. Hope this helps.</p>
<p>Cheers, Ari.</p>
|
<p>Here are the guidelines from MSDN about package security. <a href="http://msdn.microsoft.com/en-us/library/ms141747.aspx" rel="nofollow">Setting the Protection Level of Packages</a></p>
| 32,932
|
<p>At work I work closely with MS-Office. I have managed to generate some scripts that perform various tasks. While I can port functions to VBA with some difficulty, I do not fully understand the foundations of the VBA language.</p>
<p>Items for which I seek basic syntax and examples include: 'hello world' program, loops, flow control, variable declaration, variable type conversions, Objects (if possible), file/user input/output, when 'with' block can be used, and so on.</p>
<p>Could someone provide me with a link to a VBA tutorial, perhaps with the details of the above items?</p>
|
<p>The versions of VBA post Office 2000 are almost identical to VB6. This <a href="http://msdn.microsoft.com/en-us/vbasic/ms789086.aspx" rel="nofollow noreferrer">MSDN site</a> is a great place to start. The <a href="http://msdn.microsoft.com/en-au/vbrun/default.aspx" rel="nofollow noreferrer">VB6 resource center</a> might also be of use.</p>
|
<p>I think you will find this video tutorial pretty helpful:</p>
<p><a href="http://developresource.weebly.com/10/post/2011/11/vba.html" rel="nofollow">http://developresource.weebly.com/10/post/2011/11/vba.html</a></p>
<p>And there are some other great stuffs you can find there so have a try :)</p>
| 37,301
|
<p>How would I drag and drop something into a static control? It looks like I need to create a sub class of COleDropTarget and include that as a member variable in a custom CStatic. That doesn't appear to be working though. When I try and drag something onto the Static control I get the drop denied cursor.</p>
|
<p>The static control's <code>m_hWnd</code> must be valid when you call <code>COleDropTarget::Register</code>, which is why it doesn't work from within your <code>CMyStatic</code> constructor. What you can do is override <code>CWnd::PreSubclassWindow</code> within your <code>CMyStatic</code> class:</p>
<pre><code>class CMyStatic : public CStatic {
...
virtual void PreSubclassWindow();
};
void CMyStatic::PreSubclassWindow()
{
CStatic::PreSubclassWindow();
m_MyDropTarget.Register(this);
}
</code></pre>
<p>There's a really good article <a href="http://www.codeproject.com/KB/dialog/presubclasswindow.aspx" rel="nofollow noreferrer">here</a> on CodeProject that you may find helpful.</p>
|
<p>In addition to the PreSubClassWindow() addition, you also have to set your CStatic control to have the Notify flag set in its resource parameters. Otherwise the control won't let the app know about mouse movements and hence not trigger the OnDragEnter() method.</p>
| 25,716
|
<p>I have got the following situation. On a machine there is a <strong>Fritz ISDN</strong> card. There is a process that is responsible for playing a certain wave file on this device's wave out (<strong>ISDN</strong> connection is made at startup and made persistent). The scenario is easy, whenever needed the process calls <code>waveOutWrite()</code> on the previously opened wave device (everything initialized without any problems of course) and a callback function waits for <code>MM_WOM_DONE</code> msg to know that the playback has been finished. </p>
<p>Since a few days however (nothing changed neither in the process nor the machine) the <code>MM_WOM_DONE</code> message has been coming immediately after calling <code>waveOutWrite()</code> even though the wave lasts a couple of seconds. Again no error is reported, it looks like the file was played but had zero length (which is not the case). I am also sure that <code>waveOutReset()</code> was not called by my process (it would also trigger sending the mentioned message). I have already used to have some strange problems in the past that where solved simply by reinstalling <strong>TAPI</strong> drivers. This time for some reason it is problematic for me to perform that once again and I am trying more analytical approach :). Any suggestions what might cause such a behavior? Maybe something on the other end of the <strong>ISDN</strong> line?</p>
|
<p>I don't have the time to Google too much for this, but I know that either Larry Osterman or Raymond Chen blogged about a similar situation.</p>
<p>I'll check back later when I have more time to see if this question is still open.</p>
|
<p>What is the return value when the sound does not play? If you get MMSYSERR_NOERROR that points to the driver incorrectly reporting to the OS that the buffer was processed.</p>
<p>Has the WAV file itself changed? This <a href="http://blogs.msdn.com/larryosterman/archive/2007/07/24/playsound-is-failing-on-vista-what-s-wrong.aspx" rel="nofollow noreferrer">blog entry</a> indicates that some pretty in-depth validation is done on the metadata.</p>
| 3,101
|
<p>I'm creating a low level keyboard hook in c# using SetWindowsHookEx, question is how can I make the on keyboard event function run on a thread other from the main thread? Also I currently don't have a thread other then the main thread, so how can I create one that will halt until a keyboard hook event will occur?</p>
|
<p>Here is the code for the <a href="http://forum.cheatengine.org/viewtopic.php?t=192699&sid=d25bb4a9d48a3518bba28ec63d6510a2" rel="nofollow noreferrer">C# Keyboard hook</a>.</p>
<p>You just need to call Hook.CreateHook(METHODNAMEHERE); in a new Thread (see the Thread class).</p>
|
<p>As there is an answer how to set a hook on new thread, this only answers the second part of the question:</p>
<p>If you are using a windows form application, there are some catches in using additional threads. They need to use Control.Invoke to communicate with the form controls.</p>
<p>Other than that, start your "worker" thread, and make it wait on some ManualResetEvent or AutoResetEvent. When your keyboard hook receives a notification for key press, use some "shared" field to place the key, then reset the event so, the "waiting" thread can process it.</p>
<p>Do not forget to implement proper locking around the "shared" field.</p>
| 21,509
|
<p>I've been playing with mod_python in apache2 which seems to work differently than python does in general - there's a bit different syntax and things you need to do. It's not very well documented and after a few days of playing with it, I'm really not seeing the point of mod_python at all, especially when things like php are so well documented and available.</p>
<p>I can see how Python works well for system programming, but can anyone give any information as to why I shouldn't just dump python for a web-based application?</p>
|
<ol>
<li>Don't use mod_python. A common mistake is take mod_python as "mod_php, but for python" and that is <strong>not true</strong>. Use <a href="http://code.google.com/p/modwsgi/" rel="noreferrer">mod_wsgi</a> instead.</li>
<li>Choose a web framework. <a href="http://cherrypy.org/" rel="noreferrer">CherryPy</a>. <a href="http://pylonshq.com" rel="noreferrer">Pylons</a>. <a href="http://www.djangoproject.com/" rel="noreferrer">Django</a>.</li>
<li>Look at <a href="http://wsgi.org" rel="noreferrer">wsgi.org</a></li>
</ol>
|
<p>mod_python wasn't really made for doing basic webprogramming. I suggest you go with a framework:</p>
<ul>
<li><a href="http://www.djangoproject.com/" rel="noreferrer">django</a></li>
<li><a href="http://cherrypy.org" rel="noreferrer">cherrypy</a></li>
<li><a href="http://webpy.org" rel="noreferrer">web.py</a></li>
</ul>
<p>My suggestion is to give python some time. It's easy to get simplicity and lack of power confused. :)</p>
| 26,530
|
<p>Here's a hypothetical situation I've been wondering about lately. Suppose I have an interactive page created in ASP.NET and Ajax that I want multiple users to be able to manipulate at the same time. What would be the best way to maintain this page's state? Especially if the page was relatively ephemeral, and did not particularly need to be stored in a database?</p>
<p>As a concrete example, suppose I'm implementing a basic game of checkers. The server needs to maintain the state of the board at all times. The clients need to check the board's status periodically, and need to be able to transmit their changes to the board. When all the players leave, or when the game ends, the board is no longer needed and the server can dispose of it.</p>
<p>I could store everything in a database, retrieving it when the clients ask for a board update, and saving it when the server receives an update. But that seems like a lot of extra overhead.</p>
<p>What about static variables? Are they reliable enough/efficient enough for this job? Is there another storage mechanism I could use? Or is this so far outside the limits of what ASP.NET can do efficiently that I should be looking at an entirely different technology if I ever want to implement this?</p>
<p><strong>Update:</strong><br>
One quick update, to see if I can get another round of answers. After a bit of research, here's what I have so far:<br>
<a href="https://stackoverflow.com/questions/176473/creating-a-shared-workspace-with-aspnet-and-ajax#176568">Manu</a> has suggested using MemCached independently to store the data. I like that this solution works even in multi-server environments, but I have noted a few drawbacks:<br>
1) MemCached's site states that it's for read-heavy applications (which this isn't, relative to a traditional web app), and that it's "unreliable." I haven't gotten far enough to determine how important these characteristics are (i.e. are writes slow? Is there a propagation delay?).<br>
2) In an implementation somewhat close to my application (storing session data), the MemCached site uses a database behind the cache, even though the data does not need to be persisted.<br>
3) I have some concerns about how usable MemCached would be in a hosted environment.</p>
<p>Looking at static variables, they do seem to be fast. They aren't thread safe, but that can be accounted for. However, they ARE local to the worker process, so I'm not sure how they work with load balancing or a web garden.</p>
<p>Finally, there is at least one implementation of an <a href="http://www.dynamicajax.com/fr/AJAX_Web_Chat_ASP_NET-.html" rel="nofollow noreferrer">ASP.NET-based chat client</a> (VERY similar to this example) which uses a database as a back-end. With proper caching, this may just be "good enough."</p>
|
<p>I beleive there are a few ways you can do this:
1) Stream the pdf binary data to the browser and change the mime type so the browser handles it as pdf, or
2) Stream the pdf bindara data to the broswer using the "attachment;file=" header which will cause the browser to give you the option of opening or saving the file.</p>
<p>The second option may solve your problem with the intermittent choking of the browser, although it is not as seamless as the first option and may not be the exact behaviour you want.</p>
|
<p>What headers are you serving up with the PDF? IE has issues with downloadable files if the cache headers are set to no-cache, and (although) I doubt this is the issue, IE can't handle very large downloads (e.g. 2.x Gig)</p>
| 21,259
|
<p>Using .NET 1.1, I have a DataGrid that contains three columns for each row. </p>
<p>Row one has a label with some text.</p>
<p>Row three will always have two radio buttons and two checkboxes and those are in the HTML side of the page.</p>
<p>Row two will have dynamically generated controls (just textboxes for now) and there can be 1 or more per row. These will be used for user input.</p>
<p>There is a button on the page and when the user clicks the button I need to update the DataGrid’s source (my DataTable) with the new values from the user’s input. </p>
<p>The issue is the DataGrid seems to be losing the dynamically generated controls on PostBack. I can loop through each Item in the DataGrid and I can access the radio buttons and the checkboxes, but the textboxes aren’t there. </p>
<p>Any ideas?</p>
|
<p>Remember: every time a postback occurs you are working with a <em>new instance</em> of your page class. Dynamic controls added to the page during a previous postback went to the garbage collector as soon as the page for that postback rendered to the browser, along with the rest of that page instance. You need to re-create your dynamic controls on every postback.</p>
|
<p>you have to regenerate the controls. You should be able to get their values from the http request object</p>
| 24,570
|
<p>I have an application that has several objects (about 50 so far, but growing). There is only one instance of each of these objects in the app and these instances get shared among components.</p>
<p>What I've done is derive all of the objects from a base BrokeredObject class:</p>
<pre><code>class BrokeredObject
{
virtual int GetInterfaceId() = 0;
};
</code></pre>
<p>And each object type returns a unique ID. These IDs are maintained in a header file.</p>
<p>I then have an ObjectBroker "factory". When someone needs an object, then call GetObjectByID(). The boker looks in an STL list to see if the object already exists, if it does, it returns it. If not, it creates it, puts it in the list and returns it. All well and good.</p>
<pre><code>BrokeredObject *GetObjectByID(int id)
{
BrokeredObject *pObject;
ObjectMap::iterator = m_objectList.find(id);
// etc.
if(found) return pObject;
// not found, so create
switch(id)
{
case 0: pObject = new TypeA; break;
case 1: pObject = new TypeB; break;
// etc.
// I loathe this list
}
// add it to the list
return pObject;
}
</code></pre>
<p>What I find painful is maintaining this list of IDs and having to have each class implement it. I have at least made my consumer's lives slightly easier by having each type hold info about it's own ID like this:</p>
<pre><code>class TypeA : public BrokeredObject
{
static int get_InterfaceID() { return IID_TYPEA; }
int GetInterfaceID() { return get_InterfaceID(); }
};
</code></pre>
<p>So I can get an object like this:</p>
<pre><code>GetObjectByID(TypeA::get_InterfaceID());
</code></pre>
<p>Intead of having to actually know what the ID mapping is but I still am not thrilled with the maintenance and the potential for errors. It seems that if I know the type, why should I also have to know the ID?</p>
<p>What I long for is something like this in C#:</p>
<pre><code>BrokeredObject GetOrCreateObject<T>() where T : BrokeredObject
{
return new T();
}
</code></pre>
<p>Where the ObjectBroker would create the object based on the <em>type</em> passed in.</p>
<p>Has C# spoiled me and it's just a fact of life that C++ can't do this or is there a way to achieve this that I'm not seeing?</p>
|
<p>Yes, there is a way. A pretty simple even in C++ to what that C# code does (without checking for inheritance though):</p>
<pre><code>template<typename T>
BrokeredObject * GetOrCreateObject() {
return new T();
}
</code></pre>
<p>This will work and do the same as the C# code. It is also type-safe: If the type you pass is not inherited from BrokeredObject (or isn't that type itself), then the compiler moans at the return statement. It will however always return a new object.</p>
<h3>Singleton</h3>
<p>As another guy suggested (credits to him), this all looks very much like a fine case for the singleton pattern. Just do <code>TypeA::getInstance()</code> to get the one and single instance stored in a static variable of that class. I suppose that would be far easier than the above way, without the need for IDs to solve it (i previously showed a way using templates to store IDs in this answer, but i found it effectively is just what a singleton is). </p>
<p>I've read that you will leave the chance open to have multiple instances of the classes. One way to do that is to have a <em>Mingleton</em> (i made up that word :))</p>
<pre><code>enum MingletonKind {
SINGLETON,
MULTITON
};
// Singleton
template<typename D, MingletonKind>
struct Mingleton {
static boost::shared_ptr<D> getOrCreate() {
static D d;
return boost::shared_ptr<D>(&d, NoopDel());
}
struct NoopDel {
void operator()(D const*) const { /* do nothing */ }
};
};
// Multiton
template<typename D>
struct Mingleton<D, MULTITON> {
static boost::shared_ptr<D> getOrCreate() {
return boost::shared_ptr<D>(new D);
}
};
class ImASingle : public Mingleton<ImASingle, SINGLETON> {
public:
void testCall() { }
// Indeed, we have to have a private constructor to prevent
// others to create instances of us.
private:
ImASingle() { /* ... */ }
friend class Mingleton<ImASingle, SINGLETON>;
};
class ImAMulti : public Mingleton<ImAMulti, MULTITON> {
public:
void testCall() { }
// ...
};
int main() {
// both do what we expect.
ImAMulti::getOrCreate()->testCall();
ImASingle::getOrCreate()->testCall();
}
</code></pre>
<p>Now, you just use <code>SomeClass::getOrCreate()</code> and it cares about the details. The custom deleter in the singleton case for shared_ptr makes deletion a no-op, because the object owned by the shared_ptr is allocated statically. However, be aware of problems of destruction order of static variables: <a href="https://stackoverflow.com/questions/335369/finding-c-static-initialization-order-problems">Static initialization order fiasco</a></p>
|
<p>You should almost certainly be using dependency injection.</p>
| 47,454
|
<p>I have a small command line program that uses the Team System API. When the correct Team System isn't installed on the machine, the program prints a traceback with System.IO.FileNotFoundException, but it also <strong>crashes</strong> and shows the standard error messasge:</p>
<blockquote>
<p>XXX has encountered a problem and
needs to close. We are sorry for the
inconvenience.</p>
</blockquote>
<p>I just want my program to print a "The program requires Team System 2008" message to the console and quit without crashing.</p>
<p>From what I understand this whole loading process is happening before the first line of my C# code is run. Is there any way to control this?</p>
|
<p>.NET code is JITted on a method-by-method basis. Does your "Main" method make reference to the external libraries? If so, consider:</p>
<pre><code>[MethodImpl(MethodImplOptions.NoInlining)]
static int Main() { // add "args" etc if needed
try {
return Main2();
} catch (Exception ex) {
Console.Error.WriteLine(ex.Message);
return 1;
}
}
static int Main2() { // add "args" etc if needed
// your real code
}
</code></pre>
<p>I can't guarantee it will work, but it is worth a try...</p>
|
<p>Yes. The assembly will be loaded the first time you use a type that itself references a type from the assembly to be loaded. </p>
<p>So the solution is to create a helper class that wraps all interaction with the API. Then wrap calls to this wrapper class in a try/catch.</p>
<p>Something like:</p>
<pre><code>public class Program
{
static void Main()
{
try
{
WrapperClass.CallApi(...);
}
catch(FileNotFoundException)
{
... you can e.g. show a MessageBox and exit here ...
}
}
}
internal class WrapperClass
{
public void CallApi(...)
{
... you can reference types from the Team System assembly in WrapperClass
}
}
</code></pre>
| 26,419
|
<p>If you use a GUID as a password for a publicly facing application as a means to gain access to a service, is this security through obscurity?</p>
<p>I think the obvious answer is yes, but the level of security seems very high to me since the chances of guessing a GUID is very very low correct?</p>
<p><b>Update</b></p>
<p>The GUID will be stored in a device, when plugged in, will send over the GUID via SSL connection.</p>
<p>Maybe I could generate a GUID, then do a AES 128 bit encrption on the GUID and store that value on the device?</p>
|
<p>Actually, using a GUID as a password is not a good idea (compared to coming up with a truly random password of equivalent length). Although it appears long, it's actually only 16 bytes which typically includes the user's MAC address, the date/time and a smallish random element. If a hacker can determine the users MAC address, it's relatively straightforward to guess possible GUID's that he would generate.</p>
|
<p>I recommend against using a GUID as a password (except maybe as an initial one to be changed later). Any password that has to be written down to be remembered is <strike>inherently</strike> unsafe. It will get written down.</p>
<p><strong>Edit:</strong> "inherently" is inaccurate. see conversation in comments</p>
| 37,017
|
<p>In Vc++ 6.0 mscomm control,please any body explain this function How it works ,what it does</p>
<pre><code>if (m_comm.GetCommEvent()==2 )
{
VARIANT in_dat;
in_dat = m_comm.GetInput();
CString strInput(in_dat.bstrVal);
m_input = m_input + strInput;
UpdateData(FALSE);
}
</code></pre>
|
<p>The code checks whether a comm event occured. If it did, then the input data is obtained from the control and appended to m_input. Afterwards, the data is updated.</p>
<p>The code does not offer much more insight.</p>
|
<p>Just in case you don't know, "the data is updated" in HS' post means 'the dialog box fields are updated to show the new data'</p>
| 41,811
|
<p>Is there a difference between just saying <code>throw;</code> and <code>throw ex;</code> assuming <code>ex</code> is the exception you're catching?</p>
|
<p><code>throw ex;</code> will erase your stacktrace. Don't do this unless you mean to clear the stacktrace. Just use <code>throw;</code></p>
|
<p>You have two options throw; or throw the orginal exceptional as an innerexception of a new exception. Depending on what you need.</p>
| 11,415
|
<p>Suppose a database table has a column "Name" which is defined as key for the table.
Usual name values will be "Bill", "Elizabeth", "Bob", "Alice". Lookups on the table will be done by the name key as well.</p>
<p>Does hashing the values optimize the operations in any way? i.e. entering each name as some hashed value of the name (suppose MD5 - 32 bits).</p>
<p>If so - shouldn't this be a feature of the database and not something the client handles?</p>
|
<p>Assuming your database generates an index for the primary key (and I can't imagine it wouldn't) it's doing it for you. So yes, it should absolutely be something that the database handles.</p>
|
<p>No, don't hash them. Your database will build an index based on the data, and hashing won't help. The only time it <em>might</em> help is if your key values were much longer than the hash.</p>
| 27,938
|
<p>A number of forms in my project inherit from a base form. It is easy to get at the Controls collection of the derived forms, but I have not found a simple way to access the Components collection, since VS marks this as private. </p>
<p>I assume this could be done with reflection, but I'm not really sure how best to go about it, not having worked with reflection before.</p>
<p>Right now, I'm using a sort of clunky workaround, in which I override a function GetComponents and return an array of the components I'm interested in. This is obviously prone to errors, since it's easy to forget to implement the overridden function or update it when components are added.</p>
<p>If anyone has any tips or can suggest a better way, I'd be glad to hear.</p>
|
<p>If you set the Modifiers property of your components to strict protected makes them accessible without the use of a components collection. </p>
<p>Edit:
Discoverability could be done using reflection to walk over each field. Although that might be suboptimal in your case.</p>
|
<p>If you're worried about forgetting to override the function, then make it abstract.</p>
| 5,104
|
<p>I have this legacy code base <strong>(Compaq PERL)</strong>, about 1500 lines of code, that I need to port to Windows. I wanted to use <strong>gnu PASCAL</strong> (which I have installed and have working). I have already got our assembler <strong>(HP 64000 8051)</strong> off the VAX and on to <strong>Windows (KEIL 8051)</strong>. </p>
<p>The director of Software engineering would like to get all products off the VAX. Here is the rub, I have tried to compile the <strong>PASCAL</strong> from the VAX on CYGWIN using <strong>gpc</strong>. There seems to be alot of things that would need to be done to get (IO and algorithmic ) equivalence from one PASCAL to the other. </p>
<p>I know PERL,FORTRAN,C and C++ fairly well( and JAVA but I would rather not). My question boils down to with 1500 lines of code would it be more productive to port the PASCAL code to the other PASCAL, or would it be more productive to port it to another language? VAX PASCAL was my first language in college but I haven't actively programed in it in 8 years. I work with PERL,C,C++, and FORTRAN all frequently and professionally . </p>
<p>I would say as far as my choice, PERL would be it if I was going to convert to another language.</p>
<p>What the code does is perform fills and a check sums for INTEL hex and TEX HEX image files. I am aware of the Srec 1.4 program that will work, but it is not an option,because I have to get my code qualified for DO-178B (And my company is leery of using open source code)(They have no problem with open source tools; just code).</p>
|
<p>I would try to port it to <a href="http://www.freepascal.org/" rel="nofollow noreferrer">Free Pascal</a>, but with a time limit. If it's too hard, then fall back to a more recently used (by you) language.</p>
<p>Is there any way to test if the new (ported or translated) version behaves the same as the old one?</p>
|
<p>I think porting 1500 lines of code to any language/platform should not be too hard given the fact that all you need to do is "perform fills" and compute checksums. Personally I would have preferred C# - it has a soothing effect on my mind :) but given your proficiency in C/C++ I would advise that you go with C++ for the simple reason that C++ is the world's best assembly language and will fulfill your requirements perfectly. I think pascal is some what antiquated and new projects should avoid it. Please feel free to correct me if I am wrong.</p>
<p>Programming in C is a chore and to leave some room for further enhancements to your program C++ seems to be the best option. Also do not forget unlike C, C++ has some very capable libraries backing it up (STL, Boost etc).</p>
| 45,148
|
<p>I'd like to have some rails apps over different servers sharing the same session. I can do it within the same server but don't know if it is possible to share over different servers. Anyone already did or knows how to do it?</p>
<p>Thanks</p>
|
<p>Depending on how your app is set up, you <em>can</em> easily share cookies from sites in the same domain (foo.domain, bar.domain, domain) by setting your apps up to use the same secret:
<a href="http://www.russellquinn.com/2008/01/30/multiple-rails-applications/" rel="nofollow noreferrer">http://www.russellquinn.com/2008/01/30/multiple-rails-applications/</a></p>
<p>Now, if you have disparate sites, such as sdfsf.com, dsfsadfsdafdsaf.com, etc. you'll have to do a lot more tricks because the very nature of cookies restricts them to the specific domain. Essentially what you're trying to do is use cross-site scripting to, instead of hijack your session, read it from the other ones.</p>
<p>In that case, a combination of using the same cookie secret etc and then some cross-site scripting you can manually extract the session info and re-create it on each site (or if you use ActiveRecord session {or NFS session dir}, link up with the existing one). It's not easy, but it can be done.</p>
<p>Or, the low-tech way (which I've done before) is simply have the login page visit a specially crafted login page on each site that sets an app cookie on it and bounces you to the next one. It isn't pretty.</p>
|
<p>Try using database-backed sessions.</p>
| 13,041
|
<p>When developing whether its Web or Desktop at which point should a developer switch from SQLite, MySQL, MS SQL, etc</p>
|
<p>It depends on what you are doing. You might switch if:</p>
<ul>
<li>You need more scalability or better performance - say from SQLite to SQL Server or Oracle.</li>
<li>You need access to more specific datatypes.</li>
<li>You need to support a customer that only runs a particular database.</li>
<li>You need better DBA tools.</li>
<li>Your application is using a different platform where your database no longer runs, or it's libraries do not run.</li>
<li>You have the ability/time/budget to actually make the change. Depending on the situation, the migration could be a bigger project than everything in the project up to that point. Migrations like these are great places to introduce inconsistencies, or to lose data, so a lot of care is required.</li>
</ul>
<p>There are many more reasons for switching and it all depends on your requirements and the attributes of the databases.</p>
|
<p>BrianLy hit the nail on the head, but I'd also add that you may end up using different databases at different levels of development. It's not uncommon for developers to use SQLite on their workstation when they're coding against their personal development server, and then have the staging and/or production sites using a different database tool.</p>
<p>Of course, if you're using extensions or capabilities specific to a certain database tool (say, PostGIS in PostGreSQL), then obviously that wouldn't work.</p>
| 2,688
|
<p>Regarding the following excerpt of <a href="https://stackoverflow.com/questions/247389/please-help-me-understand-the-specifics-of-the-gpl#247428">this comment</a>:</p>
<blockquote>
<p>AFAIK, it's fine to interact with GPL
code over a network adapter. It's not
normally OK (again, AFAIK) to have
code that's more tightly coupled than
that, particularly if your code can't
function without the GPL code, but
that's a gray area.</p>
</blockquote>
<p>So if I want to use a graphics library that's GPL (and not LGPL), could I decide to make it part of a graphics service available on a linux computer as long as I release my code that implements this service with this library?</p>
<p>Say the library implements SVG, and I decide I want to do all of my screen drawing in vector graphics with SVG. Rather then rolling SVG into my several apps (and thus opening their source code), I create a service (or kernel driver even) that listens on a socket (or implements a graphics device) which takes SVG data and renders it to the screen using the library. I release the service/kernel driver code as per the library's GPL. I do not release code for any of my programs that use that service or kernel driver. I publish the API for the service/kernel driver so others can implement it, replace it, and still run my binaries with a different service/driver, or develop reflectors, etc.</p>
<ul>
<li>Am I violating the legal clauses of GPL</li>
<li>Am I violating the spirit of the GPL</li>
</ul>
<p>I'm certain others have thought about this - has it occurred, and what was the community reaction?</p>
<p>-Adam</p>
|
<p>I agree with earlier comments that this looks bad as far as the spirit of the GPL goes. Doing it anyway would probably meet some resistance in the community which might take forms like:</p>
<ul>
<li>Not checking your work back into project trunks</li>
<li>Not distributing your work if published separately</li>
<li>Checking it in, then modifying the API as they see fit without regard to how it affects your closed program, and distributing the changed version through the normal channels (in effect guaranteeing dll hell for your users)</li>
</ul>
<p>and of course</p>
<ul>
<li>Writing, distributing and pushing a competing front end.</li>
</ul>
<p>So you might ask yourself if it is worth it. (Remember that reputation based communities can have long memories for some kinds of slights.)</p>
<hr>
<p>Past community reactions to dodgy approaches to the GPL have included:</p>
<ul>
<li>The GPLv3 which is structured to make some of these tricks more difficult</li>
<li>A broad coalition in the linux kernel community against the inclusion of modules that exist to load closed-firmware.</li>
<li>Naming and shaming of violators, and (just as important) public recognition for those who have cleaned up their acts.</li>
</ul>
|
<p>Obligatory I Am Not A Lawyer.</p>
<p>Are you violating the legal clauses of the GPL?
Probably not. ATI and nVidia do this sort of thing with their graphics drivers for Linux. However, it's important to note that Linux is GPLv2; this may have changed with GPLv3.</p>
<p>Are you violating the spirit of the GPL?
Yes, and judging from the way your question was written, you already knew this.</p>
| 30,814
|
<p>We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.</p>
<p>Is there a reason why "null" has even been included in the language?</p>
<p>After all, if there were no "null", I would have no bug, right?</p>
<p>In other words, what feature in the language couldn't work without null?</p>
|
<p>Anders Hejlsberg, "C# father", just spoke about that point in <a href="https://www2.computerworld.com.au/article/261958/a-z_programming_languages_c_/?pp=3" rel="nofollow noreferrer">his Computerworld interview</a>:</p>
<blockquote>
<p>For example, in the type system we do not have separation between value and reference types and nullability of types. This may sound a little wonky or a little technical, but in C# reference types can be null, such as strings, but value types cannot be null. It sure would be nice to have had non-nullable reference types, so you could declare that ‘this string can never be null, and I want you compiler to check that I can never hit a null pointer here’.</p>
<p>50% of the bugs that people run into today, coding with C# in our platform, and the same is true of Java for that matter, are probably null reference exceptions. If we had had a stronger type system that would allow you to say that ‘this parameter may never be null, and you compiler please check that at every call, by doing static analysis of the code’. Then we could have stamped out classes of bugs.</p>
</blockquote>
<p>Cyrus Najmabadi, a former software design engineer on the C# team (now working at Google) discuss on that subject on his blog: (<a href="http://blogs.msdn.com/cyrusn/archive/2005/04/25/411617.aspx" rel="nofollow noreferrer">1st</a>, <a href="http://blogs.msdn.com/cyrusn/archive/2005/04/25/411630.aspx" rel="nofollow noreferrer">2nd</a>, <a href="http://blogs.msdn.com/cyrusn/archive/2005/04/26/412040.aspx" rel="nofollow noreferrer">3rd</a>, <a href="http://blogs.msdn.com/cyrusn/archive/2005/04/27/412444.aspx" rel="nofollow noreferrer">4th</a>).
It seems that the biggest hindrance to the adoption of non-nullable types is that notation would disturb programmers’ habits and code base. Something like 70% of references of C# programs are likely to end-up as non-nullable ones.</p>
<p>If you really want to have non-nullable reference type in C# you should try to use <a href="http://research.microsoft.com/specsharp/" rel="nofollow noreferrer">Spec#</a>
which is a C# extension that allow the use of "!" as a non-nullable sign.</p>
<pre><code>static string AcceptNotNullObject(object! s)
{
return s.ToString();
}
</code></pre>
|
<p>Null is an essential requirement of any OO language. Any object variable that hasn't been assigned an object reference has to be null. </p>
| 21,456
|
<p>I'm trying to generate some code at runtime where I put in some boiler-plate stuff and the user is allowed to enter the actual working code. My boiler-plate code looks something like this:</p>
<pre><code>using System;
public class ClassName
{
public double TheFunction(double input)
{
// user entered code here
}
}
</code></pre>
<p>Ideally, I think I want to use string.Format to insert the user code and create a unique class name, but I get an exception on the format string unless it looks like this:</p>
<pre><code>string formatString = @"
using System;
public class ClassName
{0}
public double TheFunction(double input)
{0}
{2}
{1}
{1}";
</code></pre>
<p>Then I call string.Format like this:</p>
<pre><code>string entireClass = string.Format(formatString, "{", "}", userInput);
</code></pre>
<p>This is fine and I can deal with the ugliness of using {0} and {1} in the format string in place of my curly braces except that now my user input cannot use curly braces either. Is there a way to either escape the curly braces in my format string, or a good way to turn the curly braces in the user code into {0}'s and {1}'s?</p>
<p>BTW, I know that this kind of thing is a security problem waiting to happen, but this is a Windows Forms app that's for internal use on systems that are not connected to the net so the risk is acceptable in this situation.</p>
|
<p>Escape them by doubling them up:</p>
<pre><code>string s = String.Format("{{ hello to all }}");
Console.WriteLine(s); //prints '{ hello to all }'
</code></pre>
<p>From <a href="http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1" rel="noreferrer">http://msdn.microsoft.com/en-us/netframework/aa569608.aspx#Question1</a></p>
|
<p>Be extra extra cautious in who has access to the application. A better solution might be to create a simple parser that only expects a few, limited, commands.</p>
| 19,429
|
<p>Which of the two databases is most popular in business/industry? I ask this because in terms of straight revenue or market share, I suspect they're about 50-50, because US government is big on DB2. So, discounting government, military, and academia, which database vendor has the greatest share of the business segment?</p>
|
<p>"Lies, damned lies, and statistics". Being a DB2 guy I am baised. But if you believe statistics from Gartner and other consultants Oracle has a lead over DB2 in terms of revenue. I don't think anyone really estimates number of server installs and I am not going to attempt to do this either but I can tell you that we had tremendous success with our <a href="http://www.ibm.com/db2/express/download.html?S_TACT=LKFREE002&S_CMP=ECDDWW01" rel="noreferrer">DB2 Express-C</a> offering. This is a real DB2 but it is offered free of license charges i.e. you don't have to pay IBM to use it for development, production or even redistribution. You can get optional support and extra features for a very low ($2,995/server) yearly charge. This is the same as MySQL Enterprise. Actually, it is $4 cheaper :-) </p>
<p>Since you are comparing DB2 and Oracle I figured I'd direct you to a comparison of DB2 Express-C and <a href="http://freedb2.com/2008/06/19/comparing-free-databases-oracle-xe-vs-db2-express-c/" rel="noreferrer">Oracle XE</a> on my <a href="http://FreeDB2.com" rel="noreferrer">http://FreeDB2.com</a> blog.</p>
|
<p>For a more recent press release originating from <a href="http://www.gartner.com/" rel="nofollow noreferrer">Gartner</a>, see <a href="http://www.sqlmanager.net/en/news/sql/1189" rel="nofollow noreferrer">here</a></p>
| 23,846
|
<p>My Access 2000 DB causes me problems - sometimes (haven't pinpointed the cause) the "book" form won't close. Clicking its close button does nothing, File -> Close does nothing, even closing Access results in no action. I don't have an OnClose handler for this form. The only workaround I can find involves opening the Vba editor, making a change to the code for that form (even adding a space and then immediately deleting the space), and then going back to close the "book" form, closing it, and saying "no, I don't want to save the changes". Only then will it close. Any help?</p>
|
<p>Here's a forum post describing, I think, the same problem you face. Excerpt belows states a workaround.</p>
<blockquote>
<p>What I do is to put code on the close button that reassigns the sourceobject
of any subforms to a blank form, such as:</p>
<p>me!subParts.sourceobject = "subBlank" 'subBlank is my form that is
totally blank, free of code and controls, etc.
docmd.close acForm, "fParts", acSaveNo</p>
<p>The above 2 lines is the only way I've found to prevent the Access prompt
from popping up.</p>
<p><a href="http://bytes.com/forum/thread681889.html" rel="nofollow noreferrer">http://bytes.com/forum/thread681889.html</a></p>
</blockquote>
|
<p>That sure is weird. Do you have any timer controls on the form? If you do, try disabling it in the OnClose.</p>
| 10,993
|
<p>I have a folder that is my working copy. How do I remove all SVN functionality from this folder? There is a reason for me doing this, somehow my master folder that contains all my working copies of sites, has somehow been turned into a working copy itself, so I have a working copy within itself as such.</p>
<p>So, is there an easy way of removing version control from a folder? </p>
|
<p>Just remove all ".svn" folders in it. That's it.</p>
|
<p>can't you just delete the .svn subfolder?</p>
<p>As far as I know SVN stores everything about its connection to the repository in this subfolder (at least in windows)</p>
| 22,136
|
<p>How do I create a resource that I can reference and use in various parts of my program easily?</p>
<p>My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time. </p>
|
<p>Well, after searching around and cobbling together various points from around StackOverflow (gee, I love this place already), most of the problems were already past this stage. I did manage to work out an answer to my problem though.</p>
<p><strong>How to create a resource:</strong></p>
<p>In my case, I want to create an icon. It's a similar process, no matter what type of data you want to add as a resource though.</p>
<ul>
<li>Right click the project you want to add a resource to. Do this in the Solution Explorer. Select the "Properties" option from the list.</li>
<li>Click the "Resources" tab.</li>
<li>The first button along the top of the bar will let you select the type of resource you want to add. It should start on string. We want to add an icon, so click on it and select "Icons" from the list of options.</li>
<li>Next, move to the second button, "Add Resource". You can either add a new resource, or if you already have an icon already made, you can add that too. Follow the prompts for whichever option you choose.</li>
<li>At this point, you can double click the newly added resource to edit it. Note, resources also show up in the Solution Explorer, and double clicking there is just as effective.</li>
</ul>
<p><strong>How to use a resource:</strong></p>
<p>Great, so we have our new resource and we're itching to have those lovely changing icons... How do we do that? Well, lucky us, C# makes this exceedingly easy.</p>
<p>There is a static class called <code>Properties.Resources</code> that gives you access to all your resources, so my code ended up being as simple as:</p>
<pre><code>paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
</code></pre>
<p>Done! Finished! Everything is simple when you know how, isn't it?</p>
|
<p>Code posted by Matthew Scharley has a memory leak:</p>
<pre><code>paused = !paused;
if (paused)
notifyIcon.Icon = Properties.Resources.RedIcon;
else
notifyIcon.Icon = Properties.Resources.GreenIcon;
</code></pre>
<p>You should <code>Dispose()</code> notifyIcon.Icon before replacing it, because <code>Properties.Resources.SOME_ICON</code> creates a new <code>Icon</code> each time it is used.
This can be observed in the log, with this code:</p>
<pre><code>Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
Console.WriteLine(Properties.Resources.RedIcon.GetHashCode());
</code></pre>
<p>You will see 3 different Hash Codes in the log. This means these are different Objects.</p>
<p>So, the simple fix will be:</p>
<pre><code>paused = !paused;
notifyIcon.Icon?.Dispose();
notifyIcon.Icon = paused
? Properties.Resources.RedIcon;
: Properties.Resources.GreenIcon;
</code></pre>
| 11,603
|
<p>Some of my colleagues use special comments on their bug fixes, for example:</p>
<pre><code>// 2008-09-23 John Doe - bug 12345
// <short description>
</code></pre>
<p>Does this make sense?<br>
Do you comment bug fixes in a special way?</p>
<p>Please let me know.</p>
|
<p>I don't put in comments like that, the source control system already maintains that history and I am already able to log the history of a file.</p>
<p>I do put in comments that describe why something non-obvious is being done though. So if the bug fix makes the code less predictable and clear, then I explain why.</p>
|
<p>To locate ones specific comment we use <strong>DKBUGBUG</strong> - which means David Kelley's fix and reviewer can easily identity, Ofcourse we will add Date and other VSTS bug tracking number etc along with this. </p>
| 15,074
|
<p>I inherited a project that uses SQL Server 200x, wherein a column that stores a value that is always considered as a percentage in the problem domain is stored as its greater than 1 decimal equivalent. For example, <em>70%</em> (0.7, literally) is stored as <em>70</em>, <em>100%</em> as <em>100</em>, etc. Aside from the need to remember to * 0.01 on retrieved values and * 100 before persisting values, it doesn't seem to be a problem in and of itself. <strike>It does make my head explode though</strike>... so is there a good reason for it that I'm missing? Are there compelling reasons to fix it, given that there is a fair amount of code written to work with the pseudo-percentages?</p>
<p>There are a few cases where greater than 100% occurs, but I don't see why the value wouldn't just be stored as 1.05, for example, in those cases.</p>
<p>EDIT: Head feeling better, and slightly smarter. Thanks for all the insights.</p>
|
<p>There are actually four good reasons I can think of that you might want to store—and calculate with—whole-number percentage values rather than floating-point equivalents:</p>
<ol>
<li>Depending on the data types chosen, the integer value may take up less space.</li>
<li>Depending on the data type, the floating-point value may lose precision (remember that not all languages have a data type equivalent to SQL Server's <code>decimal</code> type).</li>
<li>If the value will be input from or output to the user very frequently, it may be more convenient to keep it in a more user-friendly format (decision between convert when you display and convert when you calculate ... but see the next point).</li>
<li><p>If the principle values are also integers, then</p>
<pre><code>principle * integerPercentage / 100
</code></pre>
<p>which uses all integer arithmetic is usually faster than its floating-point equivalent (likely <em>significantly</em> faster in the case of a floating-point type equivalent to T-SQL's <code>decimal</code> type).</p></li>
</ol>
|
<p>And to add to the data storage issue, if you can use integer arithmetic for whatever processing you are doing, the performance is much better than when doing floating point arithmetic... So storing ther percetages as integer values may allow the processing logic to itilize integer arithmetic </p>
| 36,738
|
<p>Should you set all the objects to <code>null</code> (<code>Nothing</code> in VB.NET) once you have finished with them? </p>
<p>I understand that in .NET it is essential to dispose of any instances of objects that implement the <code>IDisposable</code> interface to release some resources although the object can still be something after it is disposed (hence the <code>isDisposed</code> property in forms), so I assume it can still reside in memory or at least in part?</p>
<p>I also know that when an object goes out of scope it is then marked for collection ready for the next pass of the garbage collector (although this may take time).</p>
<p>So with this in mind will setting it to <code>null</code> speed up the system releasing the memory as it does not have to work out that it is no longer in scope and are they any bad side effects?</p>
<p>MSDN articles never do this in examples and currently I do this as I cannot
see the harm. However I have come across a mixture of opinions so any comments are useful.</p>
|
<p>Karl is absolutely correct, there is no need to set objects to null after use. If an object implements <code>IDisposable</code>, just make sure you call <code>IDisposable.Dispose()</code> when you're done with that object (wrapped in a <code>try</code>..<code>finally</code>, or, a <code>using()</code> block). But even if you don't remember to call <code>Dispose()</code>, the finaliser method on the object should be calling <code>Dispose()</code> for you.</p>
<p>I thought this was a good treatment:</p>
<blockquote>
<p><a href="http://web.archive.org/web/20090311003201/http://msdn.microsoft.com/en-us/magazine/cc163392.aspx" rel="noreferrer">Digging into IDisposable</a></p>
</blockquote>
<p>and this </p>
<blockquote>
<p><a href="http://web.archive.org/web/20090426210049/www.marcclifton.com/tabid/79/Default.aspx" rel="noreferrer">Understanding IDisposable</a></p>
</blockquote>
<p>There isn't any point in trying to second guess the GC and its management strategies because it's self tuning and opaque. There was a good discussion about the inner workings with Jeffrey Richter on Dot Net Rocks here: <a href="http://www.dotnetrocks.com/default.aspx?showNum=361" rel="noreferrer">Jeffrey Richter on the Windows Memory Model</a> and
Richters book <a href="http://amzn.eu/d/aitTG0A" rel="noreferrer">CLR via C#</a> chapter 20 has a great treatment: </p>
|
<p>Some object suppose the <code>.dispose()</code> method which forces the resource to be removed from memory.</p>
| 2,491
|
<p>I'm preparing a class on Visual Basic 2005 targeting Visual Basic 6 programmers migrating to the .NET platform.<br /><br/>
I would like a word of advice about whether to recommend them to always enable <strong>Option Strict</strong> or not.<br /><br/>
I've worked exclusively with C-style programming languages, mostly Java and C#, so for me <strong>explicit casting</strong> is something I always expect I have to do, since it's never been an option.<br/>However I recognize the value of working with a language that has built-in support for <strong>late-binding</strong>, because not having to be excessively explicit about types in the code indeed saves time. This is further proved by the popular diffusion of <strong>dynamic typed languages</strong>, even on the .NET platform with the Dynamic Language Runtime.
<br><br/>
With this in mind, should someone who is approaching .NET for the first time using VB.NET and with a VB6 background be encouraged to get into the mindset of <strong>having to work with compile-time type checking</strong> because that's the "best practice" in the CLR? Or is it "OK" to continue enjoying the benefits of late-binding?</p>
|
<p>Yes! Option Strict is definitely a best practice with .Net. Emphasize that .Net is at it's core a strongly typed platform, and will be until the DLR is more completely supported. With few exceptions, every <code>Dim</code> and <code>Function</code> should have an explicit type declared to go with it. Things like LINQ or Boo and JScript are the exceptions that prove the rule.</p>
<p>Here are some other things to point out. I'm sure you're well aware of all this, but I've had to work with and maintain a lot of VB.Net code written by former VB6ers, and so this is something of a sore spot for me:</p>
<ul>
<li>Don't use the old string functions: <code>LEN()</code>, <code>REPLACE()</code>, <code>TRIM()</code>, etc</li>
<li>Hungarian warts are no longer recommended. <code>oMyObject</code> and <code>sMyString</code> are not kosher. Show them the reference in <a href="http://msdn.microsoft.com/en-us/library/ms229042.aspx" rel="nofollow noreferrer">Microsoft's Design Guidelines</a> if they don't believe you.</li>
<li>Make sure they learn about the new <code>AndAlso</code>/<code>OrElse</code> logical operators</li>
<li>PARAMETERIZED QUERIES and modern ADO.Net. Can't emphasize that enough. They should never need to call <code>CreateObject()</code> again.</li>
<li>Scope works differently (and is more important) in .Net than it was in VB6. VB.Net still has modules, but they're now more analogous to a static class. It's important to understand how developing in a real object oriented environment be different, as opposed to the partial OOP support provided by VB6. There's no good reason anymore to allow methods to run to ungodly lengths.</li>
<li>Make sure they get an introduction to Generics and Interfaces (including <code>IEnumeralbe(Of T)</code>), and learn why they should never use an <code>ArrayList</code> again.</li>
</ul>
<p>I could keep going, but I'll just point you to the <a href="https://stackoverflow.com/questions/102084/hidden-features-of-vbnet">Hidden Features of VB.Net</a> Question to close out this rant.</p>
|
<p>If you're used to having your types checked, then you probably want option strict on. turning it off can have advantages, but if your brain isn't tuned to spotting errors where your compiler would usually complain, then I would say to leave it on. I've worked in VB.Net a lot, and I have to say, that even though I work with options strict turned off most of the time, I've seen plenty of situations where having it turned on would have prevented quite a few bugs.</p>
| 27,430
|
<p>If one Googles for "difference between <code>notify()</code> and <code>notifyAll()</code>" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in <code>notify()</code> and all in <code>notifyAll()</code>.</p>
<p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.</p>
<p>What's the <strong>useful</strong> difference between <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29" rel="noreferrer">notify()</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29" rel="noreferrer">notifyAll()</a> then? Am I missing something?</p>
|
<blockquote>
<p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition.</p>
</blockquote>
<p>That is not correct. <code>o.notifyAll()</code> wakes <em>all</em> of the threads that are blocked in <code>o.wait()</code> calls. The threads are only allowed to return from <code>o.wait()</code> one-by-one, but they each <em>will</em> get their turn.</p>
<hr>
<p>Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time?</p>
<p>In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use <b>notifyAll()</b> to wake up all waiting threads at the same time.</p>
<p>Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use <b>notify()</b>. Properly implemented, you <i>could</i> use <b>notifyAll()</b> in this situation as well, but you would unnecessarily wake threads that can't do anything anyway.</p>
<hr>
<p>In many cases, the code to await a condition will be written as a loop:</p>
<pre><code>synchronized(o) {
while (! IsConditionTrue()) {
o.wait();
}
DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain();
}
</code></pre>
<p>That way, if an <code>o.notifyAll()</code> call wakes more than one waiting thread, and the first one to return from the <code>o.wait()</code> makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.</p>
|
<p>Waking up all does not make much significance here.
wait notify and notifyall, all these are put after owning the object's monitor. If a thread is in the waiting stage and notify is called, this thread will take up the lock and no other thread at that point can take up that lock. So concurrent access can not take place at all. As far as i know any call to wait notify and notifyall can be made only after taking the lock on the object. Correct me if i am wrong.</p>
| 5,764
|
<p>I truly love VIM - it's one of only a handful of applications I've every come across that make you feel warm and fuzzy inside. However, for PHP development, I still use PDT Eclipse although I would love to switch. </p>
<p>The reason I can't quite at the moment is the CTRL+SPACE code-assist functionality that I rely on so much - it's so useful, especially when type hinting, or using PHPDoc variable comment blocks. </p>
<p>I know there are cool plugins for VIM out there that can probably replicate this functionality and then some - but what are they? </p>
|
<p>Vim has <a href="http://vimdoc.sourceforge.net/htmldoc/version7.html#new-omni-completion" rel="nofollow noreferrer">OmniCompletion</a> built in, you should add this to your .vimrc:</p>
<pre><code>filetype plugin on
au FileType php set omnifunc=phpcomplete#CompletePHP
</code></pre>
<p>In addition I recommend you this plugins:</p>
<ul>
<li><a href="http://www.vim.org/scripts/script.php?script_id=184" rel="nofollow noreferrer">VTreeExplorer</a></li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=1318" rel="nofollow noreferrer">snippetsEmu</a></li>
</ul>
<p>and also take a look to this <a href="http://tech.blog.box.net/2007/06/20/how-to-debug-php-with-vim-and-xdebug-on-linux/" rel="nofollow noreferrer">article</a> about php debugging in Vim, and this <a href="http://www.scribd.com/doc/263139/VIM-for-PHP-Programmers" rel="nofollow noreferrer">paper</a>, it has many useful tips for using Vim in PHP Development. </p>
|
<p>Code assist it's a new feature of VIM 7
[Ctrl+x] [Ctrl+o] will auto complete your code or open a popup of options</p>
<p>More features of VIM 7 can be found in this <a href="http://linuxhelp.blogspot.com/2006/09/visual-walk-through-of-couple-of-new.html" rel="nofollow noreferrer">blogpost</a></p>
<p>Btw, I too like vim, but the PDT (and other IDEs) has much more features than code assist that make me preffer them over it.</p>
| 24,789
|
<p>I have an <code>.xsd</code>, <code>.vb</code>, <code>.xsc</code>, and <code>.xss</code> file for a dataset in Visual Studio 2008 that I copied over from another Visual Studio project, however I need to make changes to the dataset. Thus I got into the XSD file, created new columns, deleted ones that aren't needed, etc., etc. However I realized when I attempted to use the new dataset I did not have the Visual Basic code behind the scenes. This code is typically found in <code>dataset.designer.vb</code>. When I copied the old one over of course it was no longer valid since columns changed.</p>
<p>How I can force Visual Studio 2008 to use a <code>.xsd</code> file and to have it create/update its designer code?</p>
|
<p>You just have to exclude your <code>.xsd</code> file and include it again. It will regenerate your <code>designer.vb</code> file.</p>
|
<p>Unfortunately, this is in the gray area of things things that I can do when I need to, but I haven't needed to do enough to impart the knowledge to others. </p>
<p>All I know is that <code>*.designer.vb</code> means that this code was generated by Visual Studio, and if it generated it once it can do it again. Additionally, the very few times (maybe twice, both in Visual Studio 2005) that I have done this, it seemed like it was as simple as adding the *.xsd file to Solution Explorer. If that alone doesn't do it, try showing all files or right/double clicking on the *.xsd.</p>
| 36,122
|
<p>I am looking for a way to maintain PHP sessions across multiple domains on the same server. I am going to be integrating my sites with a Simple Machines Forum so I will need to use MySQL based sessions. Thanks!</p>
|
<p>Depending upon your preferred method of modifying PHP variables (Apache's config, .htaccess), change the session.cookie_domain value to be a consistent value.</p>
<p>I have multiple sub-domains, and each VirtualHost section in the Apache config file contains the following line:</p>
<p>php_value session.cookie_domain mydomain.com</p>
<p>The syntax should be similar if you make the changes in a .htaccess file.</p>
<p>Updated for bobert5064's comment:</p>
<p>For multiple domains (ie domain1.com, domain2.org), I think it is only necessary to choose a common domain name (ie domain1.com). I have never tried this, so I cannot verify that it works, but the logic seems accurate.</p>
<p>There is also a method to set the variables direction in PHP described at <a href="http://us.php.net/manual/en/function.session-set-cookie-params.php" rel="noreferrer">http://us.php.net/manual/en/function.session-set-cookie-params.php</a>. The documentation makes no reference to the ability or inability to set cookies on a different domain.</p>
|
<p>If one site is going to forward or link to a second it can include the session id in the <em>href</em> of the link or as an <em>input</em> in a form. Similar to George's <em>img tag</em> method, but the session would only move over if and when it was needed. </p>
<p>Which is best depends on the usage pattern of your sites really.</p>
| 30,245
|
<p>How does one go about converting an image to black and white in PHP?</p>
<p>Not just turning it into greyscale but every pixel made black or white?</p>
|
<p>Simply round the grayscale color to either black or white.</p>
<pre><code>float gray = (r + g + b) / 3
if(gray > 0x7F) return 0xFF;
return 0x00;
</code></pre>
|
<p>For each pixel you must convert from color to greyscale - something like
$grey = $red * 0.299 + $green * 0.587 + $blue * 0.114;
(these are NTSC weighting factors; other similar weightings exist. This mimics the eye's varying responsiveness to different colors).</p>
<p>Then you need to decide on a cut-off value - generally half the maximum pixel value, but depending on the image you may prefer a higher value (make the image darker) or lower (make the image brighter).</p>
<p>Just comparing each pixel to the cut-off loses a lot of detail - ie large dark areas go completely black - so to retain more information, you can dither. Basically, start at the top left of the image: for each pixel add the error (the difference between the original value and final assigned value) for the pixels to the left and above before comparing to the cut-off value.</p>
<p>Be aware that doing this in PHP will be very slow - you would be much further ahead to find a library which provides this.</p>
| 31,734
|
<p>Can I really and truly trust .NET to initialize fields (like ints, structs and the like)? And what if I still want to initialize those fields - what could be the repercussions?</p>
|
<p>The <a href="http://www.ecma-international.org/publications/standards/Ecma-334.htm" rel="nofollow noreferrer">C# specification</a> states on p.305 (17.4.4)</p>
<blockquote>
<p>The initial value of a field, whether it be a static field or an instance field, is the default value (§12.2) of the
field’s type. It is not possible to observe the value of a field before this default initialization has occurred,
and a field is thus never “uninitialized”.</p>
</blockquote>
|
<p>Yes, you can really trust .NET to initialize fields to their default values.
There are basically no repercussions for doing it explicitly. (One small caveat here: if you initialize static fields explicitly, then anyone running the type initializer a second time via reflection will end up re-initializing those fields. This is a real corner case though!)</p>
<p>Do whatever promotes the most readability in your particular codebase.</p>
| 33,679
|
<p>I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells. The cells may contain text, numbers or be blank. I am not very familiar / comfortable working with the concept of 'Range'. Therefore, any sample codes would be greatly appreciated. (I did try to google it, but the code snippets I found didn't quite do what I needed)</p>
<p>Thank you.</p>
|
<p>If you only need to look at the cells that are in use you can use:</p>
<pre><code>sub IterateCells()
For Each Cell in ActiveSheet.UsedRange.Cells
'do some stuff
Next
End Sub
</code></pre>
<p>that will hit everything in the range from A1 to the last cell with data (the bottom right-most cell)</p>
|
<p>In Excel VBA, this function will give you the content of any cell in any worksheet.</p>
<pre><code>Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function
</code></pre>
<p>So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.</p>
| 9,949
|
<p>I've been working with LINQ To SQL for a little while now and when it comes to removing an entity from the DB, I've always called the table's .DeleteOnSubmit and passed in the entity. Sometimes I've found myself writing something like:</p>
<pre><code>db.Users.DeleteOnSubmit(db.Users.Where(c => c.ID == xyz).Select(c => c).Single());
</code></pre>
<p>This of course causes two queries. One to get the entity matching the criteria and then another to delete it. Often I have the ID of the record I need removing and I am wondering if there is a more direct way to remove a row from a table via the ID only?</p>
|
<p>Here is a solution...</p>
<pre><code>public static void DeleteByPK<TSource, TPK>(TPK pk, DataContext dc)
where TSource : class
{
Table<TSource> table = dc.GetTable<TSource>();
TableDef tableDef = GetTableDef<TSource>();
dc.ExecuteCommand("DELETE FROM [" + tableDef.TableName
+ "] WHERE [" = tableDef.PKFieldName + "] = {0}", pk);
}
</code></pre>
<p>It's not my code! See for explaination - <a href="http://msmvps.com/blogs/omar/archive/2008/10/30/linq-to-sql-delete-an-entity-using-primary-key-only.aspx" rel="noreferrer">http://msmvps.com/blogs/omar/archive/2008/10/30/linq-to-sql-delete-an-entity-using-primary-key-only.aspx</a></p>
<p>Hope this helps.</p>
|
<p>I don't believe Linq to Sql can do this natively, although writing a stored procedure would give you what you want, with syntax like:</p>
<pre><code>db.spDeleteUserById(id);
</code></pre>
<p>This would requre writing a stored procedure for each table, but it's a pretty trivial amount of SQL.</p>
<hr>
<p>Check out <a href="http://www.aneyfamily.com/terryandann/post/2008/04/Batch-Updates-and-Deletes-with-LINQ-to-SQL.aspx" rel="nofollow noreferrer">this blog post</a>, in which the author has created an extension method that generates its own delete statement. You might be able to take this concept and run with it to create a delete routine that doesn't require a select. The downside is, you might end up with an extension method that is specific to your own schema.</p>
<p>I understand that you want to keep your logic out of the database layer, but in this case I think it would be far simpler to go the stored proc route. It wouldn't be subject to the problems with tightly coupled data access logic, since deleting a row by id isn't likely to ever need refactoring.</p>
| 44,021
|
<p>I have a .NET string which is Base64 encoded representation of an array of encrypted bytes. It is produced like this:</p>
<pre><code>String Encrypt( String message )
{
CryptoStream cryptostream = ...
StreamWriter stream = new StreamWriter( cryptostream );
...
return Convert.ToBase64String( ... );
}
</code></pre>
<p>Now I want a decryption function like</p>
<pre><code>String Decrypt( String cypher )
{
TextReader reader = new StringReader( cypher );
byte[] buffer = new byte[ cypher.Length ];
for( int i = 0; i < cypher.Length; ++i )
{
buffer[ i ] = (byte) reader.Read();
}
FromBase64Transform transformer = new FromBase64Transform();
MemoryStream raw = new MemoryStream
(
transformer.TransformFinalBlock( buffer, 0, buffer.Length )
);
...
}
</code></pre>
<p>Is there a way to use FromBase64Transform <em>directly</em> with CryptoStream (as the .NET documentation suggests), instead of manually converting the string to bytes, then manually decoding the bytes, and finally decrypting the decoded bytes?</p>
|
<p>I always the the <a href="http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx" rel="nofollow noreferrer">Convert</a> class to convert the string into an array of Byte.</p>
<p>An example:</p>
<pre><code> public static string DeCryptString(string s) {
byte[] b = System.Convert.FromBase64String(s);
using (MemoryStream ms = new MemoryStream(b))
using (CryptoStream cs = /* Create decrypting stream here */)
using (StreamReader sr = new StreamReader(cs)) {
string buf = sr.ReadToEnd();
return buf;
}
} // DeCryptString
</code></pre>
|
<p>There is no public built-in way to stream from a string, as of .NET 3.5.</p>
<p>You can implement a simple StringStream class that inherits from Stream, which will free you from having to convert the string to an array of bytes.</p>
| 22,675
|
<p>Lifehacker had a post a couple days ago asking people about <a href="http://lifehacker.com/5054519/" rel="nofollow noreferrer">the best mouse you've ever had</a> and it appears some people have traded their mouse for a tablet.</p>
<p>I'm curious if anyone here has traded their mouse in for a tablet? Does it work well for development? Looking for pros and cons from people who have tried it or are using it.</p>
<p>Thanks.</p>
|
<p>I don't know Java best practices, but it occurs to me that if you are claiming that serialization will never happen, you could add a writeObject method which throws. Then suppress the warning, safe in the knowledge that it cannot possibly apply to you.</p>
<p>Otherwise someone might in future serialize your object through the parent class, and end up with a default serialized form where:</p>
<ul>
<li>the form isn't compatible between different versions of your code.</li>
<li>you've suppressed the warning that this is the case.</li>
</ul>
<p>Adding an ID sounds like a bodge, since what you really want to do is not serialize. Expecting callers not to serialize your object means that you expect them to "know" when their HttpServlet is of your class. That breach of polymorphism is on your head for having a Serializable object which must not be serialized, and the least you can do is make sure unwary callers know about it.</p>
|
<p>Please follow this link to get detailed explanation: <a href="http://technologiquepanorama.wordpress.com/2009/02/13/what-is-use-of-serialversiouid/" rel="nofollow noreferrer">http://technologiquepanorama.wordpress.com/2009/02/13/what-is-use-of-serialversiouid/</a></p>
| 17,661
|
<p>I have example of code below. </p>
<pre><code><script type="text/javascript" src="assets/scripts/somescript.php">.
</script>
</code></pre>
<p>So, will my browser still cache this just by not setting this scripts headers meta tag cache to must-revalidate?</p>
|
<p>Some browsers are more agressive with default caching than others. However, there are cache control headers you can send to indicate when to reload the code. </p>
<pre><code>header("Expires: " . date("r", time() + ( 60 * 60 * 24 * 7 * 1 ) ) ); // Expires in 1 week
header("Content-Type: application/x-javascript");
</code></pre>
<p>Is a code-snippet I've been known to use. </p>
<p>You can use more fancy stuff like If-Not-Modified headers and ETags, but Expire times are the only ones that eliminate extra server calls. </p>
|
<p>If you send a <code>Content-type: text/javascript; charset="your_charset"</code> the browser will recognize your PHP script as a valid Javascript resource and will handle it like any other Javascript. You can control browser caching behavior by issuing the correct headers in your PHP script using <a href="http://de.php.net/manual/en/function.header.php" rel="nofollow noreferrer"><code>header()</code></a>.</p>
| 38,642
|
<p>More information from <a href="http://en.wikipedia.org/wiki/Perl_6#Junctions" rel="noreferrer">the Perl 6 Wikipedia entry</a></p>
<p><strong>Junctions</strong></p>
<p>Perl 6 introduces the concept of junctions: values that are composites of other values.[24] In the earliest days of Perl 6's design, these were called "superpositions", by analogy to the concept in quantum physics of quantum superpositions — waveforms that can simultaneously occupy several states until observation "collapses" them. A Perl 5 module released in 2000 by Damian Conway called Quantum::Superpositions[25] provided an initial proof of concept. While at first, such superpositional values seemed like merely a programmatic curiosity, over time their utility and intuitiveness became widely recognized, and junctions now occupy a central place in Perl 6's design.</p>
<p>In their simplest form, junctions are created by combining a set of values with junctive operators:</p>
<pre><code>my $any_even_digit = 0|2|4|6|8; # any(0, 2, 4, 6, 8)
my $all_odd_digits = 1&3&5&7&9; # all(1, 3, 5, 7, 9)
</code></pre>
<p>| indicates a value which is equal to either its left or right-hand arguments. & indicates a value which is equal to both its left and right-hand arguments. These values can be used in any code that would use a normal value. Operations performed on a junction act on all members of the junction equally, and combine according to the junctive operator. So, ("apple"|"banana") ~ "s" would yield "apples"|"bananas". In comparisons, junctions return a single true or false result for the comparison. "any" junctions return true if the comparison is true for any one of the elements of the junction. "all" junctions return true if the comparison is true for all of the elements of the junction.</p>
<p>Junctions can also be used to more richly augment the type system by introducing a style of generic programming that is constrained to junctions of types:</p>
<pre><code>sub get_tint ( RGB_Color|CMYK_Color $color, num $opacity) { ... }
sub store_record (Record&Storable $rec) { ... }
</code></pre>
|
<p>How many days are in a given month?</p>
<pre><code>given( $month ){
when any(qw'1 3 5 7 8 10 12') {
$day = 31
}
when any(qw'4 6 9 11') {
$day = 30
}
when 2 {
$day = 29
}
}
</code></pre>
|
<p>The most attractive feature of junctions is that you don't need to write a lot of code test for complex situations. You describe the situation with the junctions, then apply the test. You don't think about how you get the answer (for instance, using short circuit operators or if blocks) but what question you are asking.</p>
| 12,782
|
<p>I'm receiving feedback from a developer that "The only way visual basic (6) can deal with a UNC path is to map it to a drive." Is this accurate? And, if so, what's the underlying issue and are there any alternatives other than a mapped drive?</p>
|
<p>We have a legacy VB6 app that uses UNC to build a connection string, so I know VB6 can do it. Often, you'll find permissions problems to be the culprit.</p>
|
<p>What sort of file I/O are you doing? If it's text, look into using a FileSystemObject.</p>
| 11,194
|
<p>I have had a 3d printer for a while now, and I have a lot of the quality settings dialed in pretty well, but one thing that constantly bugs me is removing the raft from my finished prints. I am using Repetier and I have set the air gap to 0.2 mm. That led to much better results than the default 0, which were impossible to remove at all, but it is still not great. Are there any settings I should look at changing to get easier to remove rafts? Does the filament affect this? I am printing in Hatchbox PLA at high temps. I have a heated bed, and reducing the temp on that did seem to help. Maybe it keeps the layers on the raft from fusing with the layers on the part? Any help is greatly appreciated. Thanks.</p>
|
<p>I have been able to get rafts that peel off by editing the g-code after the raft has finished and adding an M104 set temperature command telling my printer to cool the nozzle down to about 40 degrees and then another M104 command to tell the nozzle to heat back up again. This gives the raft enough time to cool and then the raft doesn't weld to the rest of the print. If you are using a heated bed I would suggest trying the M190 command and turning that off after the raft and then back on after the first layer as well. </p>
|
<p>I use raft almost always for ABS and PLA. My favorite setting for gap is somewhere between 0.11-0.13 mm both for 0.1 and 0.2 mm layer height.</p>
<p>By using 3-4 layers of raft I always get predictably good quality of a lower layer and not have any issues with removing prints from the surface which I had without using raft (especially with large or weak prints)</p>
| 692
|
<p>I'm looking for a .NET library that will allow creation of a Word document. I need to export HTML based content to a Word doc (97-2003 format, not docx).</p>
<p>I know that there are the Microsoft Office Automation libraries and Office interop, but as far as I can tell, they require that you have office actually installed and they do the conversion by opening word itself. But I don't want to have the requirement of having office installed for the conversion to work.</p>
<p>Edit: Converting to RTF may even work, if possible.</p>
|
<p><em>Would it work if I somehow converted the CSS to be embedded in the HTML??</em></p>
<p>Yes. I use an internal style sheet, as I mentioned.</p>
<p>Document Example:</p>
<pre><code><html>
<head>
<STYLE type="text/css">
h1 {text-align:center; font-size:12.0pt; font-family:Arial; font-weight:bold;}
p {margin:0in; margin-bottom:0pt; font-size: 10.0pt;font-family: Arial;}
p.Address {text-align:center;font-family:Times; margin-bottom: 10px;}
</style></head>
<body>
<p class="Address">The Street</p>
<h1>Head</h1>
</code></pre>
|
<p>Since the doc format specification is not open, and the interop assemblies are the Microsoft solution, I fear that they are your primary (or even only) option.</p>
<p>They do indeed require office to be installed, and they open Word (although showing a window is optional).</p>
<p>I think Word can open HTML documents; is that an option for you?</p>
| 35,782
|
<p><em>[This question is related to but not the same as <a href="https://stackoverflow.com/questions/206564/what-is-the-performance-implication-of-converting-to-bool-in-c">this one</a>.]</em></p>
<p>If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (<code>?:</code>) to convert to a bool. Using two not operators (<code>!!</code>) seems to do the same thing.</p>
<p>Here's what I mean:</p>
<pre><code>typedef long T; // similar warning with void * or double
T t = 0;
bool b = t; // performance warning: forcing 'long' value to 'bool'
b = t ? true : false; // ok
b = !!t; // any different?
</code></pre>
<p>So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with <code>void *</code> or <code>double</code> for <code>T</code>)?</p>
<p>I'm not asking if <code>!!t</code> is good style. I am asking if it is semantically different than <code>t ? true : false</code>.</p>
|
<p>The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for </p>
<pre><code>b = (t != 0);
</code></pre>
<p>No implicit conversions.</p>
|
<p>The double not feels funny to me and in debug code will be very different than in optimized code.</p>
<p>If you're in love with !! you could always Macro it.</p>
<pre><code>#define LONGTOBOOL(x) (!!(x))
</code></pre>
<p>(as an aside, the ternary operator is what I favor in these cases)</p>
| 25,249
|
<p>There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."</p>
<p>Is JavaScript an object-oriented language?</p>
|
<p>IMO (and it is only an opinion) <strong>the</strong> key characteristic of an object orientated language would be that it would support <a href="http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming" rel="nofollow noreferrer"><em>polymorphism</em></a>. Pretty much all dynamic languages do that.</p>
<p>The next characteristic would be <a href="http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29" rel="nofollow noreferrer"><em>encapsulation</em></a> and that is pretty easy to do in Javascript also.</p>
<p>However in the minds of many it is <a href="http://en.wikipedia.org/wiki/Inheritance_%28object-oriented_programming%29" rel="nofollow noreferrer"><em>inheritance</em></a> (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented.</p>
<p>Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation.</p>
<p>So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn't pass.</p>
<p><strong>Edit</strong>: The supplementary question is raised "how does prototypal inheritance sacrifice encapsulation?" Consider this example of a non-prototypal approach:-</p>
<pre><code>function MyClass() {
var _value = 1;
this.getValue = function() { return _value; }
}
</code></pre>
<p>The _value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:-</p>
<pre><code>function MyClass() {
var _value = 1;
}
MyClass.prototype.getValue = function() { return _value; }
</code></pre>
<p>Well this is broken. Since the function assigned to getValue is no longer in scope with _value it can't access it. We would need to promote _value to an attribute of <code>this</code> but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken.</p>
<p>Despite this my vote still remains that Javascript is object oriented. Why? Because given an <a href="http://en.wikipedia.org/wiki/Object-oriented_design" rel="nofollow noreferrer">OOD</a> I can implement it in Javascript.</p>
|
<p>I would say it has capabilities to seem OO. Especially if you take advantage of it's ability to create methods on an existing object (anonymous methods in some languages). Client script libraries like jquery (jquery.com) or prototype (prototypejs.org) are good examples of libraries taking advantage of this, making javascript behave pretty OO-like.</p>
| 13,293
|
<p>I have a desktop application having heavyweight components (JxBrowser) in a JFrame. How can I make a snapshot from the GUI and save it to for example a png file? </p>
<p>Note: The method using Graphics2d and Component.paint()/paintAll()/print/printAll works only for lightweight components. </p>
<p>Any answers appreciated!</p>
<p><strong>EDIT</strong></p>
<p>I have already tried this:</p>
<pre><code>robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
</code></pre>
<p>But I want the inner component to be captured...</p>
<p><strong>EDIT</strong></p>
<p>The situation seems to converge to this solution: if I have a bigger heavyweight component in my JFrame, so it is rendered on a JScrollPane then there exist no other method to get a snapshot of it programatically then to scroll it/screenshot it with screencapture?</p>
|
<p>My name is Roman and I'm developer at TeamDev.</p>
<p>JxBrowser component it's a heavyweight component that embedds a native mozilla window to display web pages. To get screenshot of a full web page from JxBrowser component you can really use the Java Robot functionality with web page scrolling. For small web pages this solution is ok. But receiving screenshot of a large web page will take a lot of time. Also please note that Java Robot allows capturing only screen. So if some window will appears over the JxBroser component, then it will be captured too.</p>
<p>We have already started working on this functionality in terms of JxBrowser project. The solution that will allow capturing a full web page including its invisible part is based on Mozilla internal stuff. You will be able to capture a full web page and save it as image very easy.</p>
<p>We are going to add this functionality in one of the next release of JxBrowser library, but the release date is not defined yet. If you wish you can subscribe to TeamDev's RSS feed: <a href="http://support.teamdev.com/blogs/feeds/tags/company_news" rel="nofollow noreferrer">http://support.teamdev.com/blogs/feeds/tags/company_news</a></p>
<p>Or just let me know and I will inform you when this functionality will be available. Please let me know if you have any further questions. I will be happy to help.</p>
<p>Regards,
Roman</p>
|
<p>You can try also to create a screenshot by implementing this:</p>
<pre><code> int width = frameContainer.getWidth();
int height = frameContainer.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
frameContainer.paint(g2);
return image;
</code></pre>
| 43,120
|
<p>I know how to find what I need from XML using XPath. The syntax takes a little getting used to, but it is quite powerful. I'm interested in learning XQuery also, but the SQL like syntax seems awkward. Even so, if it can provide not just a select equivalent, but also update, insert, and delete as SQL does, I will forgive all awkwardness.</p>
<p>So, does XQuery have equivalents to Update, Insert, and Delete as well as Select?</p>
<p>Does XPath have these equivalents that I have overlooked?</p>
|
<p>No. None of <a href="http://www.w3.org/TR/xpath20/" rel="noreferrer"><strong>XPath</strong></a> or <a href="http://www.w3.org/TR/xquery/" rel="noreferrer"><strong>XQuery</strong></a> has SQL-like update/insert/delete functionality.</p>
<p>You need to look for an implementation of the "<a href="http://www.w3.org/TR/xquery-update-10/" rel="noreferrer"><strong>XQuery 1.0 Update Facility</strong></a>".</p>
<p>At this moment (Nov. 2008), three such are known:</p>
<ol>
<li><a href="http://www.saxonica.com/" rel="noreferrer"><strong>SaxonSA XSLT and XQuery Processor</strong></a> — by <a href="http://en.wikipedia.org/wiki/Michael_Kay_(software_engineer)" rel="noreferrer"><strong>Michael Kay</strong></a>; Supported since version 9.1, but only in the commercial version.</li>
<li><a href="http://monetdb.cwi.nl/XQuery/" rel="noreferrer"><strong>MonetDB/XQuery</strong></a> - An open source XQuery processor on top of the <a href="http://monetdb.cwi.nl/Home/index.html" rel="noreferrer"><strong>MonetDB</strong></a> relational database system.</li>
<li><a href="http://xqilla.sourceforge.net/" rel="noreferrer"><strong>XQilla</strong></a> - An open source (<a href="http://www.apache.org/licenses/LICENSE-2.0.html" rel="noreferrer">ASL2.0</a>) XQuery processing library with support for the latest XQuery Update features. XQilla is written in C++ and includes a command line executable shell to execute queries against XML content stored on a local filesystem. This library is actively developed and part of a supported Oracle product, <a href="http://www.oracle.com/database/berkeley-db/xml/" rel="noreferrer">Berkeley DB XML</a>. </li>
</ol>
|
<p>XPath is a language for addressing parts of an XML document. So it cannot have any DML statement. It is select statement by definition.</p>
| 39,842
|
<p>I'm SSHing into a remote server on the command line, and trying to copy a directory onto my local machine with the <code>scp</code> command. However, the remote server returns this "usage" message:</p>
<pre><code>[Stewart:console/ebooks/discostat] jmm% scp -p ./styles/
usage: scp [-1246BCEpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
[-l limit] [-o ssh_option] [-P port] [-S program]
[[user@]host1:]file1 [...] [[user@]host2:]file2
[Stewart:console/ebooks/discostat] jmm%
</code></pre>
<p>I'd like to be able to transfer files in both directions. From what I read, I thought the above command would work for downloading, and <code>scp -p [localpath] [remotepath]</code> for uploading? </p>
|
<p>You need to <code>scp</code> something somewhere. You have <code>scp ./styles/</code>, so you're saying secure copy <code>./styles/</code>, but not where to copy it to.</p>
<p>Generally, if you want to download, it will go:</p>
<pre><code># download: remote -> local
scp user@remote_host:remote_file local_file
</code></pre>
<p>where <code>local_file</code> might actually be a directory to put the file you're copying in. To upload, it's the opposite:</p>
<pre><code># upload: local -> remote
scp local_file user@remote_host:remote_file
</code></pre>
<p>If you want to copy a whole directory, you will need <code>-r</code>. Think of <code>scp</code> as like <code>cp</code>, except you can specify a file with <code>user@remote_host:file</code> as well as just local files.</p>
<p>Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.</p>
|
<p>No, you still need to <code>scp [from] [to]</code> whichever way you're copying</p>
<p>The difference is, you need to <code>scp -p server:serverpath localpath</code></p>
| 44,703
|
<p>I have need to write an application which uses a speech recognition engine -- either the built in vista one, or a third party one -- that can display a word or phrase, and recognise when the user reads it (or an approximation of it). I also need to be able to switch quickly between languages, without changing the language of the operating system.</p>
<p>The users will be using the system for very short periods. The application needs to work without the requirement of first training the recognition engine to the users' voices.</p>
<p>It would also be fantastic if this could work on Windows XP or lesser versions of Windows Vista.</p>
<p>Optionally, the system needs to be able to read information on the screen back to the user, in the user's selected language. I can work around this specification using pre-recorded voice-overs, but the preferred method would be to use a text-to-speech engine.</p>
<p>Can anyone recommend something for me?</p>
|
<p>A similar question was asked on Joel on Software a while back. You can use the <a href="http://msdn.microsoft.com/en-us/library/system.speech.recognition.aspx" rel="noreferrer">System.Speech.Recognition</a> namespace to do this...with some limitations. Add System.Speech (should be in the GAC) to your project. Here's some sample code for a WinForms app:</p>
<pre><code>public partial class Form1 : Form
{
SpeechRecognizer rec = new SpeechRecognizer();
public Form1()
{
InitializeComponent();
rec.SpeechRecognized += rec_SpeechRecognized;
}
void rec_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
lblLetter.Text = e.Result.Text;
}
void Form1_Load(object sender, EventArgs e)
{
var c = new Choices();
for (var i = 0; i <= 100; i++)
c.Add(i.ToString());
var gb = new GrammarBuilder(c);
var g = new Grammar(gb);
rec.LoadGrammar(g);
rec.Enabled = true;
}
</code></pre>
<p>This recognizes the numbers from 1 to 100, and displays the resulting number on the form. You'll need a form with a label called lblLetter on it.</p>
<p>System.Speech only works with a pre-defined list of words or phrases; it's not exactly NaturallySpeaking, either in versatility or in recognition quality. But you don't have to train it to the user's voice, and if you only have a few different things the user can say, it works reasonably well. And it's free! (if you have Visual Studio)</p>
<p>It won't work well if you use very short phrases; I made a program for my kid to say letters of the alphabet and see them on-screen, but it doesn't do that well since many of the letters sound alike (especially from the mouth of a four-year-old).</p>
<p>As for more flexible options...well, there's the aforementioned NaturallySpeaking, which has an SDK. But you have to contact sales to get any sort of access to it, and no pricing is listed, so it comes across as one of those "How much does it cost? Well, how much have you got?" kind of things. There doesn't seem to be a "download and play around with it" option. :(</p>
<p>As for text-to-speech, <a href="http://msdn.microsoft.com/en-us/library/system.speech.synthesis.aspx" rel="noreferrer">System.Speech.Synthesis</a> does this. It's even easier than the speech recognition. I wrote a small program to let me type, hit Enter, and read the text aloud. My four-year-old gets mesmerized by it. :) ("Daddy, I wanna tawk to da wobot.")</p>
|
<p><a href="http://www.nuance.com/for-developers/dragon/index.htm" rel="nofollow noreferrer">Dragon Naturally Speaking SDK</a> might be worth looking at.
<a href="http://www.codeproject.com/KB/cs/TextToSpeechWindowsSAPI.aspx" rel="nofollow noreferrer">This project</a> looked interesting.</p>
<p>Haven't got to play with either of them though.</p>
| 28,105
|
<p>I'm using this script to display all the images in a folder, but I can't figure out how to get each image's file name to display underneath it. Any suggestions?</p>
<pre><code><?php
$dirname = "images";
$images = scandir($dirname);
$ignore = Array(".", "..", "otherfiletoignore");
foreach($images as $curimg){
if (!in_array($curimg, $ignore)) {
echo "<img src='images/$curimg' /><br />\n";
}
}
?>
</code></pre>
|
<pre><code>echo "<img src='images/$curimg' /><br />$curimg<br />\n";
</code></pre>
|
<p>I think nickf's suggestion is the simplest thing you can do achieve what you want without any css or complex structure..</p>
| 32,185
|
<p>I've spent hours trying to get my code to work, its a rats nest of if/elses. Basically I want to check a country name against these two arrays:</p>
<pre><code>//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("eire","hispaniola");
</code></pre>
<p>and thats it. </p>
<p>Its sending me batty, and to be honest I'm embarassed to show you my code. Lets just say it has 2 if statements, 2 else statements and 2 foreach loops. Its a blooming mess, and I was hoping someone can dumbfound me by showing me a good way of doing this? I expect there is a way using only 1 line of code, or something sickening like that.
Thank you.</p>
|
<p>This builds on @sgehrig's answer, but note the change in your exceptions:</p>
<pre><code>//if its in this array add a 'THE'
$keywords = array("bahamas","island","kingdom","republic","maldives","netherlands",
"isle of man","ivory","philippines","seychelles","usa");
//if its in this array, take THE off!
$exceptions = array("the eire","the hispaniola");
$countryKey = strtolower($country);
if (in_array($countryKey, $keywords)) {
$country = 'The ' . $country;
} else if (in_array($countryKey, $exceptions)) {
$country = substr($country, 4);
}
</code></pre>
|
<p>The easiest would be to split it into two steps, ad the "the" for the countries that match the first list, and then just remove it if if matches the words in the second list.</p>
| 35,980
|
<p>What do you consider the most rapid RAD environment for a working prototype? Not for debate. </p>
<ul>
<li>language</li>
<li>platform</li>
<li>IDE</li>
<li>DB </li>
<li>(personal note)</li>
</ul>
<p>Thank you.</p>
<p>P.S.1 I was pretty happy with PERL for back-end prototyping... I get stuck when dealing with the UI... it doesn't seem to come as easy...</p>
|
<p>For prototypes on Windows, Visual Basic is hard to beat. If you need to suppoort another platform (or multiple platforms), then Tcl/Tk is fairly productive, as well.</p>
|
<p>I'd say Python with <a href="http://wxpython.org/" rel="nofollow noreferrer">wxPython</a></p>
| 14,930
|
<p>Got a quick question. Does anyone know how to let JAXB (marshall) render boolean fields as 1 and 0 instead of printing out "true" and "false"?</p>
|
<p>The adapter class:</p>
<pre><code>import javax.xml.bind.annotation.adapters.XmlAdapter;
public class BooleanAdapter extends XmlAdapter<Integer, Boolean>
{
@Override
public Boolean unmarshal( Integer s )
{
return s == null ? null : s == 1;
}
@Override
public Integer marshal( Boolean c )
{
return c == null ? null : c ? 1 : 0;
}
}
</code></pre>
<p>Usage:</p>
<pre><code>@XmlElement( name = "enabled" )
@XmlJavaTypeAdapter( BooleanAdapter.class )
public Boolean getEnabled()
{
return enabled;
}
</code></pre>
|
<p>You can write a pair of parser/writers and define the property mapping in binding JAXB XML.</p>
| 44,697
|
<p>My last couple of projects have involved websites that sell a product/service and require a 'checkout' process in which users put in their credit card information and such. Obviously we got SSL certificates for the security of it plus giving peace of mind to the customers. I am, however, a little clueless as to the subtleties of it, and most importantly as to which parts of the website should 'use' the certificate.</p>
<p>For example, I've been to websites where the moment you hit the homepage you are put in https - mostly banking sites - and then there are websites where you are only put in https when you are finally checking out. Is it overkill to make the entire website run through https if it doesn't deal with something on the level of banking? Should I only make the checkout page https? What is the performance hit on going all out?</p>
|
<p>I personally go with "SSL from go to woe". </p>
<p>If your user never enters a credit card number, sure, no SSL. </p>
<p>But there's an inherent possible security leak from the cookie replay. </p>
<ol>
<li>User visits site and gets assigned a cookie. </li>
<li>User browses site and adds data to cart ( using cookie )</li>
<li>User proceeds to payment page using cookie. </li>
</ol>
<p>Right here there is a problem, especially if you have to handle payment negotiation yourself. </p>
<p>You have to transmit information from the non-secure domain to the secure domain, and back again, with no guarantees of protection. </p>
<p>If you do something dumb like share the same cookie with unsecure as you do with secure, you may find some browsers ( rightly ) will just <em>drop</em> the cookie completely ( Safari ) for the sake of security, because if somebody sniffs that cookie in the open, they can forge it and use it in the secure mode to, degrading your wonderful SSL security to 0, and if the Card details ever get even temporarily stored in the session, you have a dangerous leak waiting to happen. </p>
<p>If you can't be certain that your software is not prone to these weaknesses, I would suggest SSL from the start, so their initial cookie is transmitted in the secure. </p>
|
<p>I only ever redirect my sites to SSL when it requires the user to enter sensitive information. With a shopping cart as soon as they have to fill out a page with their personal information or credit card details I redirect them to a SSL page.
For the rest of the site its probably not needed - if they are just viewing information/products on your commerce site.</p>
| 13,300
|
<p>I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to:</p>
<pre><code>sun.util.calendar.ZoneInfo[id="GMT-08:00",
offset=-28800000,
dstSavings=0,
useDaylight=false,
transitions=0,
lastRule=null]
</code></pre>
<p>Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's <a href="http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getDisplayName()" rel="noreferrer">display name</a>, and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon.</p>
<p>Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration.</p>
<hr>
<p>Ok, here's an update. A coworker suggested I update JAVA_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden).</p>
<p>However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround.</p>
<hr>
<p>I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution.</p>
|
<p>It's a "quirk" in the way the JVM looks up the zoneinfo file. See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6456628" rel="noreferrer">Bug ID 6456628</a>.</p>
<p>The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work:</p>
<pre><code># sudo cp /etc/localtime /etc/localtime.dist
# sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime
</code></pre>
<p>I haven't had any problems with the symlink approach.</p>
<p>Edit: Added "sudo" to the commands.</p>
|
<p>It may help to double-check the timezone rules your OS is using.</p>
<pre><code>/usr/bin/zdump -v /etc/localtime | less
</code></pre>
<p>This file should contain your daylight savings rules, like this one for the year 2080:</p>
<pre><code>/etc/localtime Sun Mar 31 01:00:00 2080 UTC = Sun Mar 31 02:00:00 2080 BST isdst=1 gmtoff=3600
</code></pre>
<p>You can compare this with the timezone rules you think you should be using. They can be found in <strong>/usr/share/zoneinfo/</strong>.</p>
| 2,814
|
<p>I have to develop a system to <strong>monitor</strong> the <strong>generation/transmission</strong> of reports.</p>
<ul>
<li>System data will be stored in database tables (Sybase)</li>
<li>Reports will be generated with different schedules ("mon-fri 10pm", "sat 5am", "1st day of the month", etc.)</li>
<li>System will just monitor that the reports were created. It will not create the reports itself.</li>
<li>System will notify appropriate personnel when a report did not finish.</li>
<li>System will maintain a log of all generated reports</li>
</ul>
<p>Anyone know of a good(tried and proven) table(s) design for storing the task shedules?. I already have an idea, but I don't want reinvent the wheel.</p>
|
<p>Something in the lines of</p>
<pre><code>myString.split("\\s+");
</code></pre>
<p>This groups all white spaces as a delimiter.</p>
<p>So if I have the string:</p>
<pre><code>"Hello[space character][tab character]World"
</code></pre>
<p>This should yield the strings <code>"Hello"</code> and <code>"World"</code> and omit the empty space between the <code>[space]</code> and the <code>[tab]</code>.</p>
<p>As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send <em>that</em> to be parsed. What you want, is the literal <code>"\s"</code>, which means, you need to pass <code>"\\s"</code>. It can get a bit confusing.</p>
<p>The <code>\\s</code> is equivalent to <code>[ \\t\\n\\x0B\\f\\r]</code>.</p>
|
<p>Study this code.. good luck</p>
<pre><code> import java.util.*;
class Demo{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Input String : ");
String s1 = input.nextLine();
String[] tokens = s1.split("[\\s\\xA0]+");
System.out.println(tokens.length);
for(String s : tokens){
System.out.println(s);
}
}
}
</code></pre>
| 27,852
|
<p>The scenario is trying to adjust font size to get a nice graphic arrangement, or trying to decide where to break a caption/subtitle.
a) In XL VBA is there a way to find out whether a text on a textbox, or caption on a label, still fits the control?
b) Is there a way to know where was the text/caption broken on multiline control?</p>
|
<p>I gave this a rest, gave it enough back-of-head time (which produces far better results than "burp a non-answer ASAP, for credits"), and...</p>
<pre><code>Function TextWidth(aText As String, Optional aFont As NewFont) As Single
Dim theFont As New NewFont
Dim notSeenTBox As Control
On Error Resume Next 'trap for aFont=Nothing
theFont = aFont 'try assign
If Err.Number Then 'can't use aFont because it's not instantiated/set
theFont.Name = "Tahoma"
theFont.Size = 8
theFont.Bold = False
theFont.Italic = False
End If
On Error GoTo ErrHandler
'make a TextBox, fiddle with autosize et al, retrive control width
Set notSeenTBox = UserForms(0).Controls.Add("Forms.TextBox.1", "notSeen1", False)
notSeenTBox.MultiLine = False
notSeenTBox.AutoSize = True 'the trick
notSeenTBox.Font.Name = theFont.Name
notSeenTBox.SpecialEffect = 0
notSeenTBox.Width = 0 ' otherwise we get an offset (a ""feature"" from MS)
notSeenTBox.Text = aText
TextWidth = notSeenTBox.Width
'done with it, to scrap I say
UserForms(0).Controls.Remove ("notSeen1")
Exit Function
ErrHandler:
TextWidth = -1
MsgBox "TextWidth failed: " + Err.Description
End Function
</code></pre>
<p>I feel I'm getting/got close to answer b), but I'll give it a second mind rest... because it works better than stating "impossible" in a flash.</p>
|
<p>I'm sure there is no way to do this with the ordinary Excel controls on the Forms toolbar, not least because (as I understand it) they are simply drawings and not full Windows controls.</p>
<p>The simplest approach may be to make a slightly conservative estimate of the maximum text length for each control, through a few tests, and use these to manage your line breaks.</p>
| 32,045
|
<p>There are a ton of drivers & famous applications that are not available in 64-bit. Adobe for instance does not provider a 64-bit Flash player plugin for Internet Explorer. And because of that, even though I am running 64-bit Vista, I have to run 32-bit IE. Microsoft Office, Visual Studio also don't ship in 64-bit AFAIK.</p>
<p>Now personally, I haven't had much problems building my applications in 64-bit. I just have to remember a few rules of thumb, e.g. always use SIZE_T instead of UINT32 for string lengths etc.</p>
<p>So my question is, what is preventing people from building for 64-bit?</p>
|
<p>If you are starting from scratch, 64-bit programming is not that hard. However, all the programs you mention are not new. </p>
<p>It's a whole lot easier to build a 64-bit application from scratch, rather than port it from an existing code base. There are many gotchas when porting, especially when you get into applications where some level of optimization has been done. Programmers use lots of little assumptions to gain speed, and these are not always easy to quickly port to 64-bit. A few examples I've had to deal with:</p>
<ul>
<li>Proper alignment of elements within a struct. As data sizes change, assumptions that certain fields in a struct will be aligned on an optimal memory boundary may fail</li>
<li>Length of <code>long</code> integers change, so if you pass values over a socket to another program that may not be 64-bit, you need to refactor your code</li>
<li>Pointer lengths change, as so hard to decipher code written be a guru that has left the company become a little trickier to debug</li>
<li>Underlying libraries will also need to have 64-bit support to properly link. This is a large part of the problem of porting code if you rely on any libraries that are not open source</li>
</ul>
|
<p>Their <a href="http://blogs.adobe.com/penguin.swf/2006/10/whats_so_difficult_64bit_editi.html" rel="nofollow noreferrer">Linux/Flash blog</a> goes some way to explain why there isn't a 64bit Flash Player as yet. Some is Linux-specific, some is not.</p>
| 19,360
|
<p>Ok, so at some point in time, somebody checked in some files with names that require a case sensitive file system into the trunk of a repository that I constantly check out. This of course leads to my local working copy locking up when I try to check it out (on my Windows computer). Is there any way that I can set my local subversion copy so that it will ignore any files whose names differ only in case?</p>
|
<p>You can use the repository browser to remove/rename the offending file then update your working copy as per normal, fix up any references to the file you renamed that may need fixing up, and commit the fixes.</p>
<p>Then drag up a shotgun and shoot whoever did this in the first place. Case sensitivity abuse is one of the few bad smells that I have trouble forgiving.</p>
<p>(edit: This assumes TortoiseSVN, but the solutions work for any SVN implementation. You just don't get to use a pretty browser.)</p>
<p><strong>Edit:</strong></p>
<p>The other option is to rename the local version of the file, then use the repository browser to check out the second version of the clashing files, move things around, sort out references as above, then commit the changes.</p>
<p>This has the advantage of only requiring one commit, and not messing around with other people unnecessarily who may or may not be working with the two files.</p>
|
<p>Recompile svn using Interix's compiler. Now it handles case correctly on NTFS.</p>
| 24,921
|
<p>I've heard people referring to this table and was not sure what it was about.</p>
|
<p>It's a sort of dummy table with a single record used for selecting when you're not actually interested in the data, but instead want the results of some system function in a select statement:</p>
<p>e.g. <code>select sysdate from dual;</code></p>
<p>See <a href="http://www.adp-gmbh.ch/ora/misc/dual.html" rel="nofollow noreferrer">http://www.adp-gmbh.ch/ora/misc/dual.html</a></p>
<p>As of 23c, Oracle supports <code>select sysdate /* or other value */</code>, without <code>from dual</code>, as has been supported in MySQL for some time already.</p>
|
<p>It's a object to put in the from that return 1 empty row. For example:
select 1 from dual;
returns 1</p>
<p>select 21+44 from dual;
returns 65</p>
<p>select [sequence].nextval from dual;
returns the next value from the sequence.</p>
| 9,947
|
<p>It would seem the Immediate window needs some jazzing up ala IntelliSense?</p>
<p>Anyone agree/disagree? Is this coming in VS2008/2010?</p>
|
<p>Ctrl + Space in immediate if you don't have the intellisense coming up automatically. Like Joel, intellisense seems to come in go in the immed window.</p>
|
<p>When debugging in Visual Studio 2008, you can get intellisense to pop up by pressing ctrl+space. Also, it will pop up in a quick watch window with the same keystroke. Very handy.</p>
| 36,697
|
<p>Using .Net 3.0 and VS2005. </p>
<p>The objects in question are consumed from a WCF service then serialized back into XML for a legacy API. So rather than serializing the TestObject, it was serializing .TestObject which was missing the [XmlRoot] attribute; however, all the [Xml*] attributes for the child elements were in the generated proxy code so they worked just fine. So all the child elements worked just fine, but the enclosing element did not because the [XmlRoot] attribute wasn't included in the generated proxy code. The original object that included the [XmlRoot] attribute serializes fine manually.</p>
<p><strong>Can I have the proxy code include the [XmlRoot] attribute so the generated proxy class serializes correctly as well?</strong> If I can't do that I suspect I'll have to use [XmlType] but that causes minor havoc requiring me to change other components so I would prefer the former. I also want to avoid having to manually edit the autogenerated proxy class.</p>
<p>Here is some sample code (I have included the client and the service in the same app because this is quick and for test purposes. Comment out the service referencing code and add the service reference while running the app, then uncomment the service code and run.)</p>
<pre><code>namespace SerializationTest {
class Program {
static void Main( string[] args ) {
Type serviceType = typeof( TestService );
using (ServiceHost host = new ServiceHost(
serviceType,
new Uri[] {
new Uri( "http://localhost:8080/" )
}
))
{
ServiceMetadataBehavior behaviour = new ServiceMetadataBehavior();
behaviour.HttpGetEnabled = true;
host.Description.Behaviors.Add( behaviour );
host.AddServiceEndpoint( serviceType, new BasicHttpBinding(), "TestService" );
host.AddServiceEndpoint( typeof( IMetadataExchange ), new BasicHttpBinding(), "MEX" );
host.Open();
TestServiceClient client = new TestServiceClient();
localhost.TestObject to = client.GetObject();
String XmlizedString = null;
using (MemoryStream memoryStream = new MemoryStream()) {
XmlSerializer xs = new XmlSerializer( typeof( localhost.TestObject ) );
using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream)) {
xs.Serialize( xmlWriter, to );
memoryStream = (MemoryStream)xmlWriter.BaseStream;
XmlizedString = Encoding.UTF8.GetString( memoryStream.ToArray() );
Console.WriteLine( XmlizedString );
}
}
}
Console.ReadKey();
}
}
[Serializable]
[XmlRoot( "SomethingElse" )]
public class TestObject {
private bool _worked;
public TestObject() { Worked = true; }
[XmlAttribute( AttributeName = "AttributeWorked" )]
public bool Worked {
get { return _worked; }
set { _worked = value; }
}
}
[ServiceContract]
public class TestService {
[OperationContract]
[XmlSerializerFormat]
public TestObject GetObject() {
return new TestObject();
}
}
}
</code></pre>
<p>Here is the Xml this generates.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" AttributeWorked="true" />
</code></pre>
|
<p><strong>== IF ==</strong></p>
<p>This is only for the <code>XmlRoot</code> attribute. The <code>XmlSerializer</code> has one constructor where you can specify the <code>XmlRoot</code> attribute.</p>
<p>Kudos to csgero for pointing it. His comment should be the solution.</p>
<pre><code>XmlSerializer Constructor (Type, XmlRootAttribute)
</code></pre>
<blockquote>
<p>Initializes a new instance of the
<code>XmlSerializer</code> class that can serialize
objects of the specified type into XML
documents, and deserialize an XML
document into object of the specified
type. It also specifies the class to
use as the XML root element.</p>
</blockquote>
|
<p>I found someone who provides a means to solve this situation:</p>
<p><a href="http://www.request-response.com/blog/PermaLink,guid,efa4e231-ddf1-48f4-9a26-54363e799d42.aspx" rel="nofollow noreferrer">Matevz Gacnik's Weblog</a></p>
<p>Using that approach of <code>XmlAttributeOverrides</code>, I wrote the following:</p>
<pre><code> private static XmlSerializer GetOverridedSerializer()
{
// set overrides for TestObject element
XmlAttributes attrsTestObject = new XmlAttributes();
XmlRootAttribute rootTestObject = new XmlRootAttribute("SomethingElse");
attrsTestObject.XmlRoot = rootTestObject;
// create overrider
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
xOver.Add(typeof(localhost.TestObject), attrsTestObject);
XmlSerializer xSer = new XmlSerializer(typeof(localhost.TestObject), xOver);
return xSer;
}
</code></pre>
<p>Just put that method in the <code>Program</code> class of your example, and replace the following line in <code>Main()</code>:</p>
<pre><code> //XmlSerializer xs = new XmlSerializer(typeof(localhost.TestObject));
XmlSerializer xs = GetOverridedSerializer();
</code></pre>
<p>And then run to see the results.</p>
<p>Here is what I got:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?><SomethingElse xmlns:xsi="http://www.w3.o
rg/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Attribu
teWorked="true" />
</code></pre>
| 19,279
|
<p>I am sending newsletters from a Java server and one of the hyperlinks is arriving missing a period, rendering it useless:</p>
<pre><code>Please print your <a href=3D"http://xxxxxxx.xxx.xx.edu=
au//newsletter2/3/InnovExpoInviteVIP.pdf"> VIP invitation</a> for future re=
ference and check the Innovation Expo website <a href=3D"http://xxxxxxx.xx=
xx.xx.edu.au/2008/"> xxxxxxx.xxxx.xx.edu.au</a> for updates.
</code></pre>
<p>In the example above the period was lost between edu and au on the first hyperlink.</p>
<p>We have determined that the mail body is being line wrapped and the wrapping splits the line at the period, and that it is illegal to start a line with a period in an SMTP email:</p>
<p><a href="https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc2821#section-4.5.2</a></p>
<p>My question is this - what settings should I be using to ensure that the wrapping is period friendly and/or not performed in the first place?</p>
<p>UPDATE: After a <em>lot</em> of testing and debugging it turned out that our code was fine - the client's Linux server had shipped with a <em>very</em> old Java version and the old Mail classes were still in one of the lib folders and getting picked up in preference to ours.
JDK prior to 1.2 have this bug.</p>
|
<p>From an SMTP perspective, you can start a line with a period but you have to send two periods instead. If the SMTP client you're using doesn't do this, you may encounter the problem you describe.</p>
<p>It might be worth trying an IP sniffer to see where the problem really is. There are likely at least two separate SMTP transactions involved in sending that email.</p>
|
<p>I am not sure, but it looks a bit as if your email is getting encoded. 0x3D is the hexadecimal character 61, which is the equals character ('=').</p>
<p>What classes/libary are you using to send the emails? Check the settings regarding encoding.</p>
| 14,564
|
<p>I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe:</p>
<pre><code>windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ...
</code></pre>
<p>I tried loading the icon using:</p>
<pre><code>hinst = win32api.GetModuleHandle(None)
hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE)
</code></pre>
<p>But this produces an (very unspecific) error:<br>
<strong>pywintypes.error: (0, 'LoadImage', 'No error message is available')</strong><br>
<br>
If I try specifying 0 as a string</p>
<pre><code>hicon = win32gui.LoadImage(hinst, '0', win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE)
</code></pre>
<p>then I get the error:<br>
<strong>pywintypes.error: (1813, 'LoadImage', 'The specified resource type cannot be found in the image file.')</strong><br>
<br>So, what's the correct method/syntax to load the icon?<br>
<em>Also please notice that I don't use any GUI toolkit - just the Windows API via PyWin32.</em></p>
|
<p>@efotinis: You're right. </p>
<p>Here is a workaround until py2exe gets fixed and you don't want to include the same icon twice:</p>
<pre><code>hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 1), True)
</code></pre>
<p>Be aware that <strong>1</strong> is not the ID you gave the icon in setup.py (which is the icon group ID), but the resource ID <em>automatically</em> assigned by py2exe to each icon in each icon group. At least that's how I understand it.</p>
<p>If you want to create an icon with a specified size (as CreateIconFromResource uses the system default icon size), you need to use CreateIconFromResourceEx, which isn't available via PyWin32:</p>
<pre><code>icon_res = win32api.LoadResource(None, win32con.RT_ICON, 1)
hicon = ctypes.windll.user32.CreateIconFromResourceEx(icon_res, len(icon_res), True,
0x00030000, 16, 16, win32con.LR_DEFAULTCOLOR)
</code></pre>
|
<p>You should set the icon ID to something other than 0:</p>
<pre><code>'icon_resources': [(42, 'my_icon.ico')]
</code></pre>
<p>Windows resource IDs must be between 1 and 32767.</p>
| 11,610
|
<p>I was wondering if I could pop up <code>JOptionPane</code>s or other Swing components from within a browser using JSP.</p>
|
<p>If you embed an applet. But I don't think that's what you want. Swing is for desktop apps. JSP web pages. If you want components, try looking into JSF or some of the many AJAX Javascript frameworks like prototype.</p>
|
<p>Assuming you're familiar with Swing, you may want to introduce yourself to <a href="http://wicket.apache.org/" rel="nofollow noreferrer">Apache Wicket</a> which is very similar to the way you build web pages as Swing is to building GUI:s. That is, in Wicket you add new instancef of Label, Button, DataTable etc. etc. to page and link those to bean property data which is then ultimately transformed to fully functioning web page.</p>
<p>As for the actual question, you really can't do it as-is. If choosing a new/different/another web framework to help you isn't possible, the only proper way I can think of is doing what sblundy suggested.</p>
| 29,876
|
<p>I have written a very simple bash script to help me migrate from dev to staging. What it does is it deletes all files in staging, copies the files over from dev to stage.</p>
<p>However, the config.inc.php file needs to have the first instance of "dev" to be changed to "stage", and no other instance changed.</p>
<p>Second, everytime I run it (I run the script from the dev directory), i'd like it to write a log back in the dev directory which will append the date/time stamp that I ran the staging bash script into this log.</p>
<p>Thanks.</p>
|
<p>This will change only the first appearance of "dev" to "stage"</p>
<pre><code>sed -i '0,/dev/ s/dev/stage/' config.inc.php
</code></pre>
<p>Be aware that it changes "devel" into "stageel". This version behaves just like you want, only a "dev" is searched, not a "devel" (in fact, <code>s/\<dev\>/stage/</code> as the substitution expression should work, but it does not seem to work as expected? I'll be glad if anyone with more sed-fu can explain. )</p>
<pre><code>sed -i "/\<dev\>/,/\<dev\>/ s/dev/stage/" config.inc.php
</code></pre>
<p>For logging:</p>
<pre><code>date >> /path/to/dev/run.log
</code></pre>
<hr>
<p><em>Added by Jonathan Leffler</em></p>
<ul>
<li>Assuming other issues are resolved (see below), the second <code>sed</code> command can still change <code>devel</code> to <code>stagel</code> if the line contains, for example, "<em>move devel code from /some/dev/location to /some/stage/location</em>".</li>
<li>Also, the second <code>sed</code> command will map each <code>dev</code> found between the first line containing <code>dev</code> and the second such line. This matters if there's more than one matching line, whereas the original '<code>0,/dev/</code>' (or amended '<code>0,/\<dev\>/</code>') only matches the first line as requested.</li>
<li>The reason <code>"s/\<dev\>/stage/"</code> doesn't work is not a <code>sed</code> issue but a shell issue. Use single quotes and you'd be almost OK. With double quotes, the back-slash less-than sequence appears to <code>sed</code> as just less-than.</li>
<li><strong>Rule of Thumb</strong>: use single quotes around any argument in a shell script containing regular expression material. Unlesss it is saturated with single quotes, replace each single quote in the regular expression with the sequence quote, backslash, quote, quote "<code>'\''</code>". (The first quote terminates the single quote string; the backslash quote is a single quote; the last quote restarts the single quote string.)</li>
<li>Note that the '<code>-i</code>' option is a GNU extension to <code>sed</code>; it is a legimate part of the answer since the question is tagged Linux, where GNU <code>sed</code> is used; be aware if you need to move to a platform such as Solaris, AIX, HP-UX.</li>
<li>Finally, <code>sed</code> does not support extended regular expressions as standard; you have to explicitly enable them in GNU sed with the '<code>-r</code>' option.</li>
</ul>
<p>In my estimation, assuming overwrite is desirable, the command should be:</p>
<pre><code>sed -i -r '0,/\<dev\>/s/\<dev\>/stage/' config.inc.php
</code></pre>
|
<p>The first part (editing your file) can be done well with the stream editor utility <code>sed</code>:</p>
<pre><code>sed -i -e s/dev/stage/ config.inc.php
</code></pre>
<p>This edits the file in-place (<code>-i</code>) with no backup, using expression <code>/dev/stage/</code> (<code>-e</code>) to replace one expression with another.</p>
| 45,105
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.