input
stringlengths 51
42.3k
| output
stringlengths 18
55k
|
|---|---|
How to find two adjacent repeating digits and replace them with a single digit in Java? <p>I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples:</p>
<p>123345 should be 12345
77433211 should be 74321</p>
|
<p>Probably a <code>replaceAll("(\\d)\\1+", "$1")</code></p>
<ul>
<li><code>$</code> plays a special role in a replacing string, designating the first capturing group.</li>
<li><code>+</code> allows for replacing as many identical number as possible <code>(\\d)\\1</code> would only replace them by pair: <code>777xx</code> => <code>77xx</code> (thank you <a href="http://stackoverflow.com/users/12267/ben-doom">Ben Doom</a> for the remark)</li>
</ul>
<p>So:</p>
<pre><code>System.out.println("77433211".replaceAll("(\\d)\\1+", "$1"));
</code></pre>
<p>will return</p>
<pre><code>74321
</code></pre>
<hr>
<pre><code>String java.lang.String.replaceAll(String regex, String replacement)
</code></pre>
<p>Replaces each substring of this string that matches the given regular expression with the given replacement. </p>
<p>An invocation of this method of the form <code>str.replaceAll(regex, repl)</code> yields exactly the same result as the expression </p>
<pre><code>java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)
</code></pre>
<hr>
<p><strong>Warning</strong>: <code>String.replaceAll()</code> function does not modify the String on which it is applied. It returns a modified String (or <em>a new String with the same content</em> if the pattern does not match anything)</p>
<p>So you need to affect the result of a <code>replaceAll()</code> call to itself to actually update your String with the regexp changes.</p>
<pre><code>String aString = "77433211"
aString = aString.replaceAll("(\\d)\\1+", "$1"));
</code></pre>
|
using jython and open office 2.4 to convert docs to pdf <p>I completed a python script using pyuno which successfully converted a document/ xls / rtf etc to a pdf.
Then I needed to update a mssql database, due to open office currently supporting python 2.3, it's ancientness, lacks support for decent database libs. So I have resorted to using Jython, this way im not burdened down by running inside OO python environment using an old pyuno.</p>
<p>This also means that my conversion code is broken, and I need to now make use of the java libraries instead of the pyuno libs.</p>
<blockquote>
<p>import com.sun.star.beans.PropertyValue as PropertyValue<br />
import com.sun.star.bridge.XUnoUrlResolver as XUnoUrlResolver<br />
import com.sun.star.comp.helper.Bootstrap as Bootstrap<br />
->> import com.sun.star.frame.XComponentLoader as XComponentLoader<br />
->> import com.sun.star.frame.XStorable as XStorable<br />
import com.sun.star.lang.XMultiComponentFactory as XMultiComponentFactory<br />
import com.sun.star.uno.UnoRuntime as UnoRuntime<br />
import com.sun.star.uno.XComponentContext as XComponentContext </p>
</blockquote>
<p>The includes with the '->>' do not import the compiler does not recognise the com.sun.star.frame cant see the 'frame' bit. These are the libs I have included.</p>
<p><img src="http://www.freeimagehosting.net/uploads/eda5cda76d.jpg" alt="alt text" /></p>
<p>Some advice on this matter would be well received</p>
<blockquote>
<p>context = XComponentContext<br />
xMultiCompFactory = XMultiComponentFactory<br />
xcomponentloader = XComponentLoader </p>
<p>//used in python<br />
ctx = None<br />
smgr = None<br />
doc = None<br />
url = None </p>
<p>context = Bootstrap.bootstrap()<br />
xMultiCompFactory = self.context.getServiceManager()<br />
xcomponentloader = UnoRuntime.queryInterface(XComponentLoader.class, ....xMultiCompFactory.createInstanceWithContext("com.sun.star.frame.Desktop", context)) </p>
<p>file = "file:\\" + file<br />
// also what is the equivalent of url = uno.systemPathToFileUrl(file) in Java so that I can make use of it to nicely format my path<br />
properties = []<br />
p = PropertyValue()<br />
p.Name = "Hidden"<br />
p.Value = True<br />
properties.append(p)<br />
properties = tuple(properties)<br />
doc = xcomponentloader.loadComponentFromURL(file, "_blank",0, properties) </p>
</blockquote>
|
<p>And so it goes, according to this guy, you need some oil.... and it works like a charm</p>
<p><a href="http://www.oooforum.org/forum/viewtopic.phtml?p=304263#304263" rel="nofollow">http://www.oooforum.org/forum/viewtopic.phtml?p=304263#304263</a></p>
<p>include this lib C:\OpenOffice_24\program\classes\unoil.jar</p>
|
Sensitive data in Viewstate? <p>I need to store sensitive data across few pages (run over https) per session.</p>
<p>I can't use session object, for the primary reason being that the session store is designed as just as backup store (primarily make service calls and load the session). If the session has been restarted or in other words that the key in the session does not exist, make the service and re-populate the session.</p>
<p>So, in the case of user keyed in sensitive data, i need to carry this data forward across pages, we do not have a persistent store for now, therefore option left is storing these sensitive data in Viewstate. </p>
<p>1) Should I encrypt the data and store then in Viewstate (not recommended though - sec & perf. implications)
OR
2) Should i store the data in a serializable class and store that in Viewstate? (not recommended again due to perf. implications)</p>
<p>Any opinion please?</p>
|
<blockquote>
<p>I need to store sensitive data across
few pages (run over https) per
session.</p>
</blockquote>
<p>ViewState is set and maintained on the page level. It cannot be carried across different page requests, only postbacks of the current page. Assuming you really mean you have to carry the data "across a few pages" rather than postbacks.</p>
<p>You could potentially store your sensitive data in a cookie, but that comes with some security risks.</p>
<p>You could also store your sensitive data in a server side data store (xml file, database, etc.) and store a key to the data in the client side cookie. Slightly more secure.</p>
|
How can I create an editable dropdownlist in HTML? <p>I'd like to create a text field with a dropdown list that lets the user choose some predefined values. The user should also be able to type a new value or select a predefined one from a dropdown list. I know that I can use two widgets for that but in my app it would be more ergonomnic if it was unified in a one widget.</p>
<p>Is there a standard widget or do I have to use a third party javascript?</p>
<p>How about browser portability?</p>
|
<p>You can accomplish this by using the <code><datalist></code> tag in HTML5.</p>
<pre><code><input type="text" name="product" list="productName"/>
<datalist id="productName">
<option value="Pen">Pen</option>
<option value="Pencil">Pencil</option>
<option value="Paper">Paper</option>
</datalist>
</code></pre>
<p>If you double click on the input text in the browser a list with the defined option will appear.</p>
|
Best way to automagically migrate tests from JUnit 3 to JUnit 4? <p>I have a bunch of JUnit 3 classes which extend TestCase and would like to automatically migrate them to be JUnit4 tests with annotations such as <code>@Before</code>, <code>@After</code>, <code>@Test</code>, etc.<br>
Any tool out there to do this in a big batch run?</p>
|
<p>In my opinion, it cannot be that hard. So let's try it:</p>
<h2>0. Imports</h2>
<p>You need to import three annotations:</p>
<pre><code>import org.junit.After;
import org.junit.Before;
import org.junit.Test;`
</code></pre>
<p>After you've made the next few changes, you won't need <code>import junit.framework.TestCase;</code>.</p>
<h2>1. Annotate <code>test*</code> Methods</h2>
<p>All methods beginning with <code>public void test</code> must be preceded by the <code>@Test</code> annotation.
This task is easy with a regex.</p>
<h2>2. Annotate SetUp and TearDown methods</h2>
<p>Eclipse generates following <code>setUp()</code> method:</p>
<pre><code>@Override
protected void setUp() throws Exception { }
</code></pre>
<p>Must be replaced by:</p>
<pre><code>@Before
public void setUp() throws Exception { }
</code></pre>
<p>Same for <code>tearDown()</code>:</p>
<pre><code>@Override
protected void tearDown() throws Exception { }
</code></pre>
<p>replaced by</p>
<pre><code>@After
public void tearDown() throws Exception { }
</code></pre>
<h2>3. Get rid of <code>extends TestCase</code></h2>
<p>Remove exactly one occurence per file of the string</p>
<pre><code>" extends TestCase"
</code></pre>
<h2>4. Remove main methods?</h2>
<p>Probably it's necessary to remove/refactor existing main methods that will execute the test.</p>
<h2>5. Convert <code>suite()</code> method to <code>@RunWithClass</code></h2>
<p>According to saua's comment, there must be a conversion of the <code>suite()</code> method. Thanks, saua!</p>
<pre><code>@RunWith(Suite.class)
@Suite.SuiteClasses({
TestDog.class
TestCat.class
TestAardvark.class
})
</code></pre>
<h2>Conclusion</h2>
<p>I think, it's done very easy via a set of regular expressions, even if it will kill my brain ;)</p>
|
gdi+ Graphics::DrawImage really slow~~ <p>I am using a GDI+ Graphic to draw a 4000*3000 image to screen, but it is really slow. It takes about 300ms. I wish it just occupy less than 10ms.</p>
<pre><code>Bitmap *bitmap = Bitmap::FromFile("XXXX",...);
</code></pre>
<p>//--------------------------------------------
// this part takes about 300ms, terrible!</p>
<pre><code>int width = bitmap->GetWidth();
int height = bitmap->GetHeight();
DrawImage(bitmap,0,0,width,height);
</code></pre>
<p>//------------------------------------------</p>
<p>I cannot use CachedBitmap, because I want to edit the bitmap later.</p>
<p>How can I improve it? Or is any thing wrong? </p>
<p>This native GDI function also draws the image into the screen, and it just take 1 ms:</p>
<pre><code>SetStretchBltMode(hDC, COLORONCOLOR);
StretchDIBits(hDC, rcDest.left, rcDest.top,
rcDest.right-rcDest.left, rcDest.bottom-rcDest.top,
0, 0, width, height,
BYTE* dib, dibinfo, DIB_RGB_COLORS, SRCCOPY);
</code></pre>
<p>//--------------------------------------------------------------</p>
<p>If I want to use StretchDIBits, I need to pass BITMAPINFO, But how can I get BITMAPINFO from a Gdi+ Bitmap Object? I did the experiment by FreeImage lib, I call StretchDIBits using FreeImageplus object, it draw really fast. But now I need to draw Bitmap, and write some algorithm on Bitmap's bits array, how can I get BITMAPINFO if I have an Bitmap object? It's really annoying -<strong>_______</strong>-|</p>
|
<p>If you're using GDI+, the TextureBrush class is what you need for rendering images fast. I've written a couple of 2d games with it, getting around 30 FPS or so.</p>
<p>I've never written .NET code in C++, so here's a C#-ish example:</p>
<pre><code>Bitmap bmp = new Bitmap(...)
TextureBrush myBrush = new TextureBrush(bmp)
private void Paint(object sender, PaintEventArgs e):
{
//Don't draw the bitmap directly.
//Only draw TextureBrush inside the Paint event.
e.Graphics.FillRectangle(myBrush, ...)
}
</code></pre>
|
Is it worth switching from Visual Studio 2005 to Visual Studio 2008? <p>As a team we are using Visual Studio 2005 with framework 3.0. I am thinking if it will be nice for us to switch to Visual Studio 2008 with framework 3.5 ? Is it worth it ?</p>
<p>Thanks.</p>
|
<p>Yes, it is 100% worth it. Visual Studio 2008 supports 2005 code (.net 2.0) completely. There are also a lot of improvements that you'll enjoy as you use 2008.</p>
|
Count Duplicate URLs, fastest method possible <p>I'm still working with this huge list of URLs, all the help I have received has been great.</p>
<p>At the moment I have the list looking like this (17000 URLs though):</p>
<p><a href="http://www.domain.com/page?CONTENT_ITEM_ID=1" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=1</a><br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=3" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=3</a><br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=2" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=2</a><br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=1" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=1</a><br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=2" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=2</a><br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=3" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=3</a><br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=3" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=3</a><br /></p>
<p>I can filter out the duplicates no problem with a couple of methods, awk etc. What I am really looking to do it take out the duplicate URLs but at the same time taking a count of how many times the URL exists in the list and printing the count next to the URL with a pipe separator. After processing the list it should look like this:</p>
<p><strong>url | count</strong><br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=1" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=1</a> | 2<br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=2" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=2</a> | 2<br />
<a href="http://www.domain.com/page?CONTENT_ITEM_ID=3" rel="nofollow">http://www.domain.com/page?CONTENT_ITEM_ID=3</a> | 3<br /></p>
<p>What method would be the fastest way to achieve this?</p>
<p>Cheers</p>
|
<p>This is probably as fast as you can get without writing code.</p>
<pre>
$ cat foo.txt
http://www.domain.com/page?CONTENT_ITEM_ID=1
http://www.domain.com/page?CONTENT_ITEM_ID=3
http://www.domain.com/page?CONTENT_ITEM_ID=2
http://www.domain.com/page?CONTENT_ITEM_ID=1
http://www.domain.com/page?CONTENT_ITEM_ID=2
http://www.domain.com/page?CONTENT_ITEM_ID=3
http://www.domain.com/page?CONTENT_ITEM_ID=3
$ sort foo.txt | uniq -c
2 http://www.domain.com/page?CONTENT_ITEM_ID=1
2 http://www.domain.com/page?CONTENT_ITEM_ID=2
3 http://www.domain.com/page?CONTENT_ITEM_ID=3
</pre>
<p>Did a bit of testing, and it's not particularly fast, although for 17k it'll take little more than 1 second (on a loaded P4 2.8Ghz machine)</p>
<pre>
$ wc -l foo.txt
174955 foo.txt
vinko@mithril:~/i3media/2008/product/Pending$ time sort foo.txt | uniq -c
54482 http://www.domain.com/page?CONTENT_ITEM_ID=1
48212 http://www.domain.com/page?CONTENT_ITEM_ID=2
72261 http://www.domain.com/page?CONTENT_ITEM_ID=3
real 0m23.534s
user 0m16.817s
sys 0m0.084s
$ wc -l foo.txt
14955 foo.txt
$ time sort foo.txt | uniq -c
4233 http://www.domain.com/page?CONTENT_ITEM_ID=1
4290 http://www.domain.com/page?CONTENT_ITEM_ID=2
6432 http://www.domain.com/page?CONTENT_ITEM_ID=3
real 0m1.349s
user 0m1.216s
sys 0m0.012s
</pre>
<p>Although O() wins the game hands down, as usual. Tested S.Lott's solution and</p>
<pre>
$ cat pythoncount.py
from collections import defaultdict
myFile = open( "foo.txt", "ru" )
fq= defaultdict( int )
for n in myFile:
fq[n] += 1
for n in fq.items():
print "%s|%s" % (n[0].strip(),n[1])
$ wc -l foo.txt
14955 foo.txt
$ time python pythoncount.py
http://www.domain.com/page?CONTENT_ITEM_ID=2|4290
http://www.domain.com/page?CONTENT_ITEM_ID=1|4233
http://www.domain.com/page?CONTENT_ITEM_ID=3|6432
real 0m0.072s
user 0m0.028s
sys 0m0.012s
$ wc -l foo.txt
1778955 foo.txt
$ time python pythoncount.py
http://www.domain.com/page?CONTENT_ITEM_ID=2|504762
http://www.domain.com/page?CONTENT_ITEM_ID=1|517557
http://www.domain.com/page?CONTENT_ITEM_ID=3|756636
real 0m2.718s
user 0m2.440s
sys 0m0.072s
</pre>
|
Using Samba for random access without mounting the file system? <p>I am using a machine on which I do not have root access and would like to access files on a Samba server in random access mode. I know I can transfer the files in their entirety using smbclient but the files are very large (>1GB) and I would rather just treat them as remote files on which I can do random access.</p>
<p>The problem as noted is that I don't have root access to this machine (a Linux box) so I can't mount the remote Samba file system. </p>
<p>Is there a user-level solution that will let me randomly access the contents of a file on a Samba server? Seems it should be possible to do everything that the kernel file system client is doing but from a user-level application.</p>
<p>I only need read-only access btw and the remote file is guaranteed not to change.</p>
|
<p>To answer my own question after digging around in the Samba source: there is a client library libsmbclient which includes all the usual file handling stuff: smbc_open, smbc_fstat, smbc_lseek, smbc_read etc. For instance, here is a snippet I just wrote which reads a file backwards (just to check it was doing a true seek):</p>
<pre><code>fd = smbc_open(path, O_RDONLY, 0);
smbc_fstat(fd, &st);
for (offset = st.st_size - BUFLEN; offset > 0; offset -= BUFLEN) {
smbc_lseek(fd, offset, SEEK_SET);
smbc_read(fd, buffer, BUFLEN);
}
</code></pre>
<p>(error checking removed for clarity)</p>
|
Have you tried Spring Workflow already? <p><a href="http://www.springsource.org/extensions/se-workflow">Spring Workflow</a> has now been published.</p>
<ul>
<li>Have you tried it yet? For what kind of scenario?</li>
<li>What is your impression? How do you find it stacks up against other workflow libs?</li>
<li>Found any good docs or tutorials?</li>
</ul>
|
<p>OK, ignoring my beliefs shown in my previous post I did try spring workflow, only to find out that I was right. Getting the sources and building is not that hard, they use svn, ant and ivy as repository manager.</p>
<p>Making it work is another story. I took the sample sources, an placed them in a new project. At this poit I had to rename all imports since they were built for test eviron ment i guess. This is easy with help from the IDE in classes, but you also have to rename them in spring's XML context files. Further on, it starts to look bad once you try to run the project. First you get a NullPointerException, because of the following lines :</p>
<pre><code>public final void afterPropertiesSet() throws Exception {
if (this.flowInstanceDescriptorPersisters == null) {
this.flowInstanceDescriptorPersisters.put(DEFAULT_PERSISTER, new DefaultFlowInstanceDescriptorPersister());
}
}
</code></pre>
<p>I simply created a new HashMap, rebuit the project and gave it another try. Now it will fail at an Assert if you did not include spring security. There is a hidded dependency (because reflection is used). Added the lib. and ran it again. I got another Assert fail, and when I looked that up I realised the samples are not even supposed to work. A method intentionally returns null and it shouldn't. I went to the interface, of cource, no javadoc, but i suspected what it should return from it's name, so i placed a hardcode value. At this point it biulds and it runs but it does not work, it's supposed to (at least i think it is, there are no docs.) do a transition, but the flow remains unchanged after the performTransition call.</p>
<p>So there you have it. Dont try it just yet.</p>
|
Java Video Player <p>I need a java api, that cannot use JMF, to play video interpreted by the SO codecs but i want to retrieve the each frames in java code. Somebody know some?</p>
|
<p>Have a look at <a href="http://fmj-sf.net/index.php" rel="nofollow">FMJ</a>. It does <em>not</em> require the <a href="http://java.sun.com/javase/technologies/desktop/media/jmf/" rel="nofollow">Java Media Framework</a> (JMF).</p>
<p>They have an <a href="http://fmj-sf.net/ffmpeg-java/getting_started.php" rel="nofollow">example</a> at the bottom of the page that writes out the first 5 frames of the video to files, so you should be able to get to the individual frames.</p>
|
Remote posting from one application to another application. Security issue? <p>Is there any security issue if let say in one application we do a hidden post to another application to make use of that application functionality?</p>
|
<p>Depends. Are you using some sort of authentication and encryption? </p>
<p>There are ways this could cause many security issues. Though you could say that of many implementations. Most anything configured badly can be a security issue. </p>
|
UTF-16 to UTF-8 conversion (for scripting in Windows) <p>what is the best way to convert a UTF-16 files to UTF-8? I need to use this in a cmd script.</p>
|
<p>There is a GNU tool <a href="http://www.gnu.org/software/recode/recode.html">recode</a> which you can also use on Windows.
E.g.</p>
<pre><code>recode utf16..utf8 text.txt
</code></pre>
|
Doing a generic <sql:query> in Grails <p>This is a generic way to select data from a table and show the results in an HTML table using JSP taglibs. What is the generic way to do this in Grails? That is, take a few lines of SQL and generate an HTML table from scratch in Grails, including the column names as headers.</p>
<pre>
<sql:query var="results" dataSource="${dsource}">
select * from foo
</sql:query>
(# of rows: ${results.rowCount})
<table border="1">
<!-- column headers -->
<tr bgcolor=cyan>
<c:forEach var="columnName" items="${results.columnNames}">
<th><c:out value="${columnName}"/></th>
</c:forEach>
</tr>
<!-- column data -->
<c:forEach var="row" items="${results.rowsByIndex}">
<tr>
<c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
</c:forEach>
</tr>
</c:forEach>
</table>
</pre>
|
<p>This question could be rephrased as, how do I write code like a naive ASP.NET developer?
(Not all ASP.NET developers are naive, some can be quite good)</p>
<ol>
<li>Any static method is available to you in a gsp page. You can use any MyDomain.findBy, list(), count you want from page scope.</li>
<li><p>You could also use a criteria query MyDomain.createCriteria()
You can then pass the result to a taglib.</p>
<p>But all of this seems to violate MVC principles. Your view should just be a view....</p></li>
</ol>
<p>What you asked really isn't idomatic to a grails application. I realize it is commonplace in the Microsoft world, execute a query, pass it to a datagrid....But there is no direct analouge in Grails and probably for good reason</p>
|
MSV08-C#: How do I stop two groupboxes from auto-parenting themselves when dragged on top of one another? <p>IDE: Microsoft Visual Studio Professional 2008</p>
<p>Language: C#</p>
<p>Background:
I have one form and two groupboxes that are going to be used as preference catagory groupboxes. My problem is that everytime I drag one groupbox on top of the other (hide/show groupboxes upon listview catagory select), the base groupbox auto-parents the second groupbox I just dragged on top.</p>
<p>Question:
How do I stop the two groupboxes from auto-parenting themselves when dragged on top of one another?</p>
<p>// Edit;</p>
<p>Q) I assume you are trying to acheive a layout where you swap out the visible box? --Mitchel Sellers</p>
<p>A) Yes I am. I know I could do it at runtime but I'd like to make that my last option in case there is a more appropriate solution.</p>
|
<p>You may consider resizing your second GroupBox into position over the first. Drag one side or one corner of the second group box until it covers the first GroupBox and continue to resize the second GroupBox until it is positioned as you desire. </p>
<p>Also available, in the Layout Toolbar, are the alignment and sizing buttons. Select both of your GroupBoxes to enable these options. The GroupBox displaying white grab handles is the one that will remain stationary when you use the alignment and sizing buttons, which include options to "Make Same Size" and "Align Middle".</p>
<p>Furthermore, don't forget the keyboard right in front of you. The arrow keys will move the selected controls. Try holding various combinations of [ctrl] [alt] and [shift] while using the arrow keys. </p>
|
Best tool for creating a societal model <p>Lets say I wanted to create some software that models a society. People exist, meet, have children, learn, share experiences etc. Which programming language should I use?</p>
<p>I would assume that a dynamic language that enables me to swap out methods and/or implement types at run-time would reduce the amount of plumbing that i'd otherwise have to create in a statically typed language. Am I correct?</p>
|
<p>In my earlier <a href="http://stackoverflow.com/questions/166661/agent-based-modeling-resources">question</a> I mentioned <a href="http://repast.sourceforge.net/" rel="nofollow">Repast</a>, <a href="http://www.swarm.org/" rel="nofollow">Swarm</a>, and <a href="http://www.aitia.hu/services_and_products/simulation_systems/mass" rel="nofollow">MASS</a> as agent-based modeling frameworks. They are useful tools to model societies of agents.</p>
|
Paths and CreateProcess <p>I have a question regarding a symptom of my misuse of CreateProcess. I'm using the lpcommandline parameter to feed the path to my executable and parameters. My misuse is that I have not surrounded the path to the exe with quotes. </p>
<p>My question is, why does the CreateProcess work just fine on most computers and not others? I know that the path will have a space in most of the time, yet on 90% of XP machines it works. I of course found out my issue on those 10% where it did not. But I'm wondering what is different on the machines where it does not work? Is there a setting or a policy that any of you folks know about. And yes, I am going to fix the quote issue. Just curious about why something like this would not have just failed off the bat. </p>
<p>So the code would look something like below and the szCommandLine Parameter would be something like below. Notice no quotes around the path to the exe.</p>
<p>"C:\Program Files\My Company\doit.exe parameter1 parameter2"</p>
<pre><code>CreateProcess(
NULL,
szCommandLine,
NULL,
NULL,
FALSE,
NULL,
NULL,
NULL,
&si,
&pi )
</code></pre>
|
<p>As the document Martin York linked to hinted, CreateProcess() has some behaviour for back-compat with pre-long-name programs.</p>
<p>"c:\program files\sub dir\program name arg1 arg2" will look for:</p>
<blockquote>
<pre><code>"c:\program.exe" files\sub dir\program name arg1 arg2
"c:\program files\sub.exe" dir\program name arg1 arg2
"c:\program files\sub dir\program.exe" name arg1 arg2
"c:\program files\sub dir\program name.exe" arg1 arg2
</code></pre>
</blockquote>
<p>So if any of these files exist, Windows will to call them, not your program. Also, I would assume if you did not have read access to any of the folders these possible matches are in, CreateProcess() may fail out immediatly, instead of checking if you have read to the later possible matches. (Windows by default checks read access only the final folder.)</p>
|
Messaging over HTTPS <p>I'm about to start a project that requires XML messages to be sent between a couple of servers over HTTPS. A brief summary is this: I have an application in use by clients that will send information to a central server. That server will communicate these XML messages to another company's server. I will also receive messages back from that server and need to fan them out from the central server to the correct clients. My assumption is that I can write some pages that will receive the messages from my application, post them to the foreign server, and also receive messages from the foreign server, parse them and redirect them accordingly. Either side can initiate communications. </p>
<p>I have not decided on which language to use yet, the most likely seems to be ASP.NET.</p>
<p>I am looking for some further reading material, but since I am poorly versed in the lingo, I am having trouble locating it. Does anyone have some good places to start getting acquainted with what I am trying to accomplish? </p>
|
<p>Are the messages from the foreign server immediate replies to your messages? If not (either side can initiate a message whenever it likes), consider having both ends implement RESTful web services - the XML can be the payload, and https requests are trivially supportable.</p>
<p>Since invoking the web service is just an http request (POST, probably, from your description) there's good language/library support for this.</p>
<p>See <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="nofollow">http://en.wikipedia.org/wiki/Representational_State_Transfer</a></p>
|
AspectJ: parameter in a pointcut <p>I'm using AspectJ to advice all the public methods which do have an argument of a chosen class. I tried the following:</p>
<pre><code>pointcut permissionCheckMethods(Session sess) :
(execution(public * *(.., Session)) && args(*, sess));
</code></pre>
<p>This is working wonderfully for methods with at least 2 arguments:</p>
<pre><code>public void delete(Object item, Session currentSession);
</code></pre>
<p>but it does not work with methods like:</p>
<pre><code>public List listAll(Session currentSession);
</code></pre>
<p>How may I change my pointcut to advice both methods executions? In other words: I expected the ".." wildcard to represent "zero or more arguments", but it looks like it means instead "one or more"...</p>
|
<p>Oh well... I worked that around with this nasty trick. Still waiting for someone to show up with an "official" pointcut definition.</p>
<pre><code>pointcut permissionCheckMethods(EhealthSession eheSess) :
(execution(public * *(.., EhealthSession)) && args(*, eheSess))
&& !within(it.___.security.PermissionsCheck);
pointcut permissionCheckMethods2(EhealthSession eheSess) :
(execution(public * *(EhealthSession)) && args(eheSess))
&& !within(it.___.security.PermissionsCheck)
&& !within(it.___.app.impl.EhealthApplicationImpl);
before(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods(eheSess)
{
Signature sig = thisJoinPointStaticPart.getSignature();
check(eheSess, sig);
}
before(EhealthSession eheSess) throws AuthorizationException : permissionCheckMethods2(eheSess)
{
Signature sig = thisJoinPointStaticPart.getSignature();
check(eheSess, sig);
}
</code></pre>
|
What's the best type 4 Oracle JDBC driver? <p>What's the best type 4 Oracle JDBC driver?</p>
<p>What I want:</p>
<ul>
<li>Stable, few bugs and quick fixes</li>
<li>Should warn about the usual JDBC pitfalls (connection leaks, etc)</li>
<li>Must support CLOB</li>
</ul>
<p>[EDIT] My main issues with the "free" Oracle Type 4 driver are:</p>
<ul>
<li>I spent two weeks hunting down a cursor leak in the CLOB support code (closing the stream would not close the underlying cursor)</li>
<li>When you fetch values from a ResultSet, you must process them in order (so you can't get column #3 anymore after fetching column #4)</li>
<li>getMetaData() on a result set doesn't work until after fetching the first row.</li>
<li>There were many other bugs and deficiencies but I don't remember them anymore.</li>
</ul>
<p>So all in all, a driver which costs me $1,000 per seat is more "cheap" than the "free" one from Oracle. The only good thing about the driver was that I didn't have to put databases into TNSNAMES and that I could use a single driver to access Oracle 8, 9 and 10. That's why I ask.</p>
|
<p>Oracle's type 4 JDBC driver is pretty good. Obviously, as with any software, there are bugs, but they're generally not bad. And the price (free) can't be beat.</p>
<p>If you are looking for third-party commercial drivers, I have always had good experiences with DataDirect products in this realm. I wouldn't normally bother licensing a type 4 JDBC driver, but if you have particularly high end requirements, it may be worthwhile.</p>
|
HTTP Request Timeout <p>In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class:
<a href="http://docs.python.org/library/httplib.html#httplib.HTTPConnection" rel="nofollow">http://docs.python.org/library/httplib.html#httplib.HTTPConnection</a></p>
<p>However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the <b>request</b>, not the connection. This doesn't seem to be supported by httplib.</p>
<p>Is there any way to emulate this behavior?</p>
|
<p>You can set a global socket timeout <sup>(*)</sup>:</p>
<pre><code>import socket
timeout = 10
socket.setdefaulttimeout(timeout)
</code></pre>
<hr>
<p><sup>(*)</sup> <strong>EDIT</strong>: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.</p>
|
XSL parent child problem <p>I have a xml build of</p>
<pre><code><elig>
<subscriber code="1234"/>
<date to="12/30/2004"
from="12/31/2004"/>
<person name="bob"
ID="654321"/>
<dog type="labrador"
color="white"/>
<location name="hawaii"
islandCode="01"/>
</subscriber>
</elig>
</code></pre>
<p>In XSL I have:</p>
<pre><code><xsl:template match="subscriber">
<xsl:for-each select="date">
<xsl:apply-templates match="person" />
<xsl:apply-templates match="location" />
<xsl:apply-templates match="dog" />
</xsl:for-each>
</xsl:template>
</code></pre>
<p>The problem I have is that I need the location block in between the person and the dog block. I have tried ../ and it does not work. I simplified this majorly but the point comes across. I can't seem to remember what I need to place in front of location to get it to work. Thanks.</p>
|
<p>I modified one typo in your example XML:</p>
<pre><code><elig>
<subscriber code="1234">
<date to="12/30/2004" from="12/31/2004"/>
<person name="bob" ID="654321"/>
<dog type="labrador" color="white"/>
<location name="hawaii" islandCode="01"/>
</subscriber>
</elig>
</code></pre>
<p>And using this stylesheet everything works just fine:</p>
<pre><code><xsl:template match="subscriber">
<xsl:for-each select="date">
<xsl:apply-templates select="../person" />
<xsl:apply-templates select="../location" />
<xsl:apply-templates select="../dog" />
</xsl:for-each>
</xsl:template>
<xsl:template match="person">person</xsl:template>
<xsl:template match="location">location</xsl:template>
<xsl:template match="dog">dog</xsl:template>
</code></pre>
<p>Output is:</p>
<pre><code>personlocationdog
</code></pre>
|
Generating PDFs with PHP <p>I have a PHP application and a need to generate a PDF with the result of query. The easiest way a found to do this was to use the DOMPDF to generate the PDF for me. So a made a function that generates the HTML for me then a pass this to DOMPDF. In the development and testing enviroment everything was fine but on production enviroment I had some problems with memory usage.</p>
<p>So I would like to know if my strategy was the best one or if there's a better and easy way to do this.</p>
<p>How would you do that?</p>
|
<p>I once did a PHP project generating PDF. I used <a href="http://www.fpdf.org/">FPdf</a>.</p>
<p>I never had any memory problems. It's free, it's pure PHP code. You don't have to load any extensions.</p>
<p>I don't know if there's some helpers to auto-generate document from a query, but in the website, you have some scripts that shows how to use it with MySql.</p>
<p>HTH</p>
|
How to query range of data in DB2 with highest performance? <p>Usually, I need to retrieve data from a table in some range; for example, a separate page for each search result. In MySQL I use LIMIT keyword but in DB2 I don't know. Now I use this query for retrieve range of data.</p>
<pre><code>SELECT *
FROM(
SELECT
SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO
, DATA_KEY_VALUE
, SHOW_PRIORITY
FROM
EMPLOYEE
WHERE
NAME LIKE 'DEL%'
ORDER BY
NAME DESC
FETCH FIRST 20 ROWS ONLY
) AS TMP
ORDER BY
TMP.RUNNING_NO ASC
FETCH FIRST 10 ROWS ONLY
</code></pre>
<p>but I know it's bad style. So, how to query for highest performance?</p>
|
<p>My requirement have been added into DB2 9.7.2 already.</p>
<p>DB2 9.7.2 adds new syntax for limit query result as illustrate below:</p>
<pre><code>SELECT * FROM TABLE LIMIT 5 OFFSET 20
</code></pre>
<p>the database will retrieve result from row no. 21 - 25 </p>
|
Show new WinForms window unfocused <p>I'm generating and showing a new WinForms window on top of a Main Window. How can I achieve that the original (Main Window) keeps the focus? Setting the focus back after showing the new window does not solve my problem because I need to prevent the Main Window's title bar from flickering. The new window has to stay on top of the Main Window so I have to set topMost=true. However, this makes no difference for the problem I think.</p>
<p>Thank you!</p>
|
<p>Setting the focus after you show the new form works fine. My taskbar does not flicker.</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.TopMost = true;
f2.Show();
this.Focus();
}
</code></pre>
<p>Can I ask why you want to set the focus back on the main form because the new form will, by default, draw on top of the main window and you'll have to close or move the new form to view the main window.</p>
|
Best way to strip punctuation from a string in Python <p>It seems like there should be a simpler way than:</p>
<pre><code>import string
s = "string. With. Punctuation?" # Sample string
out = s.translate(string.maketrans("",""), string.punctuation)
</code></pre>
<p>Is there?</p>
|
<p>From an efficiency perspective, you're not going to beat translate() - it's performing raw string operations in C with a lookup table - there's not much that will beat that but writing your own C code.
If speed isn't a worry, another option though is:</p>
<pre><code>exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
</code></pre>
<p>This is faster than s.replace with each char, but won't perform as well as non-pure python approaches such as regexes or string.translate, as you can see from the below timings. For this type of problem, doing it at as low a level as possible pays off.</p>
<p>Timing code:</p>
<pre><code>import re, string, timeit
s = "string. With. Punctuation"
exclude = set(string.punctuation)
table = string.maketrans("","")
regex = re.compile('[%s]' % re.escape(string.punctuation))
def test_set(s):
return ''.join(ch for ch in s if ch not in exclude)
def test_re(s): # From Vinko's solution, with fix.
return regex.sub('', s)
def test_trans(s):
return s.translate(table, string.punctuation)
def test_repl(s): # From S.Lott's solution
for c in string.punctuation:
s=s.replace(c,"")
return s
print "sets :",timeit.Timer('f(s)', 'from __main__ import s,test_set as f').timeit(1000000)
print "regex :",timeit.Timer('f(s)', 'from __main__ import s,test_re as f').timeit(1000000)
print "translate :",timeit.Timer('f(s)', 'from __main__ import s,test_trans as f').timeit(1000000)
print "replace :",timeit.Timer('f(s)', 'from __main__ import s,test_repl as f').timeit(1000000)
</code></pre>
<p>This gives the following results:</p>
<pre><code>sets : 19.8566138744
regex : 6.86155414581
translate : 2.12455511093
replace : 28.4436721802
</code></pre>
|
CSS for container divs and falling to the next line <p>I'm more of a programmer than a designer, and I'm trying to embrace <code><div></code>s rather than using tables but am getting stuck.</p>
<p>Here's what I'm trying to do. I am setting up a survey page. I want each question's text to sit at the top of the blue div, and wrap if it's too long. I want all of the red divs to line up at the top right corner of the container div.</p>
<p><img src="http://img528.imageshack.us/img528/4330/divsforsurveyop2.jpg" alt="Layout"></p>
<p>Here's what I've started with, it works fine so long as the frame is more than 420 pixels wide. Then the red div skips to the next line. I think I may have approached it wrong, perhaps I should be floating things to the right?</p>
<pre><code>.greencontainer{
width:100%;
spacing : 10 10 10 10 ;
float: left;
}
.redcontainer{
float: left;
width: 20px;
padding: 2 0 2 0;
font-size: 11px;
font-family: sans-serif;
text-align: center;
}
.bluecontainer{
clear: both;
float: left;
width: 400px;
padding: 2 2 2 10;
font-size: 11px;
font-family: sans-serif;
text-align: left;
}
</code></pre>
|
<p>Don't float anything but the red container, and float it to the right. Make sure the HTML for the red containers is placed before the HTML for the blue containers. Keep the static width on the blue container, and keep your clear:both on the green container.</p>
|
How to set a timeout during remote ejb lookup? <p>I'm trying to access a remote ejb which is not available yet. But the lookup takes 5 min before I get the NameNotFoundException. Is there a way I can set the lookup timeout to a lesser value so that the client application doesn't hang for 5 mins?
Thanks in advance...</p>
|
<p>Do the lookup in another thread, so that the client GUI does not hang. You can use plain Runnable to do this, or try a better option like <a href="https://swingworker.dev.java.net/" rel="nofollow">swingworker</a>.</p>
<p>To customize the JNDI lookup timeout, I am afraid, you will have to hack the internals of an open source app server, if that is an option.</p>
|
Can we see the source code for PowerShell cmdlets? <p>I'm learning some PowerShell. Is it possible to see the source code for a built-in cmdlet like <a href="http://technet.microsoft.com/en-us/library/hh849800.aspx">Get-ChildItem</a>?</p>
|
<p>Actually, your best bet is to go check out <a href="http://www.codeplex.com/PowerShellCX">PowerShell Community Extensions</a>. This open source software community project is "aimed at providing a widely useful set of additional cmdlets...". The developers on the project are PowerShell MVPs and know their stuff.</p>
<p>As far as using reflection on the existing PowerShell cmdlets, PowerShell MVP Oisin Grehan made a handy function titled "<a href="http://www.nivot.org/2008/10/30/ATrickToJumpDirectlyToACmdletsImplementationInReflector.aspx">Reflect-Cmdlet</a>". I won't steal his code and place it here, but basically what you do is:</p>
<pre><code>Get-Command Get-ChildItem | Reflect-Cmdlet
</code></pre>
<p>And then <a href="http://en.wikipedia.org/wiki/.NET_Reflector">.NET Reflector</a> pops up with the right assembly opened up and expanded and everything. It's really pretty cool. Here's a screenshot:</p>
<p><img src="http://halr9000.com/images/screenshots/reflector.png" alt="Alt text"></p>
|
2008 MFC and threads? <p>I was reading this thread/post: <a href="http://stackoverflow.com/questions/262298/windows-c-ui-technology">http://stackoverflow.com/questions/262298/windows-c-ui-technology</a></p>
<p>and am also wondering about a non .NET UI framework. Specifically - prior to .NET having support for serial ports (I can't believe they left that out of the first release of .NET) I was forced to use MFC for an application. I had not been a GUI developer and quickly found myself pulling my hair out due to the horrendous lack of ability for MFC to play nice with other threads in my app - e.g. calling a UI control method to update data or do other things from another thread. Most of those challenges were dealt with, but the application code is so overly complex with messaging and the like just to handle the shortcomings of MFC.</p>
<p>So - my question: does the "New and improved" mfc have support for threads - i.e. if I call some mfc control for a gui object from another thread will it crash/puke like the old mfc, or can it play in the real world?</p>
<p>EDIT</p>
<p>To clarify - I understand the concern about munging with the GUI in separate threads, but what I was hoping for was that instead of the programmer creating custom messages and sending them from the worker threads - that the GUI framework would do all that work for me and I could just call the object methods from other threads. Perhaps that is too much to hope for - especially if threads are not part of the language spec yet.</p>
|
<p>This is not a limitation of MFC - it's the design of Windows. You can't start sending messages to arbitrary controls from random other threads. (Well, you can, sometimes, but you need to know what you're doing.) This is equally true in the .NET world - once a control is visible you need to use a delegate to update it, so that the updating action occurs on the correct thread.</p>
<p>More generally, I'd say that from experience, you're almost always better off only having one thread handling the GUI in an application, and making the remaining threads purely workers. Having multiple threads interact with the GUI leads to madness trying to keep track of what's going on.</p>
<p>EDIT</p>
<p>The short answer to the original question is, I'm afraid, "no": there's been no fundamental re-work of how threads, MFC and Windows interact. At this point, with MFC hardly being a priority at Microsoft, I don't expect this to change.</p>
|
How do I unit test jdbc code in java? <p>I'd like to write some unit tests for some code that connects to a database, runs one or more queries, and then processes the results.
(Without actually using a database)</p>
<p>Another developer here wrote our own DataSource, Connection, Statement, PreparedStatement, and ResultSet implementation that will return the corresponding objects based on an xml configuration file. (we could use the bogus datasource and just run tests against the result sets it returns).</p>
<p>Are we reinventing the wheel here? Does something like this exist already for unit testing?
Are there other / better ways to test jdbc code?</p>
|
<p>You have several options:</p>
<ul>
<li>Mock the database with a Mock library, e.g. <a href="http://www.jmock.org/" rel="nofollow">JMock</a>. The huge drawback of this that your queries and the data will most likely be not tested at all.</li>
<li>Use a light weight database for the tests, such as <a href="http://hsqldb.org/" rel="nofollow">HSQLDB</a>. If your queries are simple, this is probably the easiest way to go. </li>
<li>Dedicate a database for the tests. <a href="http://dbunit.sourceforge.net/" rel="nofollow">DBUnit</a> is a good option, or if you are using Maven, you can also use the <a href="http://mojo.codehaus.org/sql-maven-plugin/" rel="nofollow">sql-maven-plugin</a> to set up and tear down the database properly (be careful of dependencies between tests). I recommend this option as it will give you the biggest confidence that the queries work properly with your db vendor. </li>
</ul>
<p>Sometimes it is necessary and useful to make these tests configurable so that these tests are only executed if the database is available. This can be done with e.g. build properties.</p>
|
modern for loop for primitive array <p>Is there any performance difference between the for loops on a primitive array? </p>
<p>Assume:</p>
<pre><code>double[] doubleArray = new double[300000];
for (double var: doubleArray)
someComplexCalculation(var);
</code></pre>
<p>or :</p>
<pre><code>for ( int i = 0, y = doubleArray.length; i < y; i++)
someComplexCalculation(doubleArray[i]);
</code></pre>
<p><strong>Test result</strong></p>
<p>I actually profiled it:</p>
<pre><code>Total timeused for modern loop= 13269ms
Total timeused for old loop = 15370ms
</code></pre>
<p>So the modern loop actually runs faster, at least on my Mac OSX JVM 1.5. </p>
|
<p>My opinion is that you don't know and shouldn't guess. Trying to outsmart compilers these days is fruitless. </p>
<p>There have been times people learned "Patterns" that seemed to optimize some operation, but in the next version of Java those patterns were actually slower.</p>
<p>Always write it as clear as you possibly can and don't worry about optimization until you actually have some user spec in your hand and are failing to meet some requirement, and even then be very careful to run before and after tests to ensure that your "fix" actually improved it enough to make that requirement pass.</p>
<p>The compiler can do some amazing things that would really blow your socks off, and even if you make some test that iterates over some large range, it may perform completely differently if you have a smaller range or change what happens inside the loop.</p>
<p>Just in time compiling means it can occasionally outperform C, and there is no reason it can't outperform static assembly language in some cases (assembly can't determine beforehand that a call isn't required, Java can at times do just that.</p>
<p>To sum it up: the most value you can put into your code is to write it to be readable.</p>
|
System.Collections.Generic List and F# <p>I have a C# class the returns a List, using System.Collections.Generic Lists not F# List</p>
<p>I want to iterate though the list to find a object or not find it. Here is how I would do it in C#. How would I accomplish the similar thing in F#</p>
<pre><code>foreach (AperioCaseObj caseObj in CaseList)
{
if (caseObj.CaseId == "")
{
}
else
{
}
}
</code></pre>
|
<pre><code>match Seq.tryfind ((=) "") caseList with
None -> print_string "didn't find it"
| Some s -> printfn "found it: %s" s
</code></pre>
|
Possible Causes for a Large Number of Sleeping Connections to a MySQL Server? <p>What are possible causes for a large number of sleeping connections to a MySQL Server? I'm using CodeIgniter with persistent connections disabled.</p>
|
<p>Even though the app doesn't keep the connection open, the OS lets it hang around. See <a href="http://www.mysqlperformanceblog.com/2006/11/12/are-php-persistent-connections-evil/" rel="nofollow">http://www.mysqlperformanceblog.com/2006/11/12/are-php-persistent-connections-evil/</a></p>
|
Why is a char and a bool the same size in c++? <p>I'm reading <em>The C++ Programming Language.</em> In it Stroustrup states that <code>sizeof(char) == 1</code> and <code>1 <= sizeof(bool)</code>. The specifics depend on the implementation. Why would such a simple value as a boolean take the same space as a char?</p>
|
<p>In modern computer architectures, a byte is the smallest addressable unit of memory. To pack multiple bits into a byte requires applying extra bit-shift operations. At the compiler level, it's a trade off of memory vs. speed requirements (and in high-performance software, those extra bit-shift operations can add up and slow down the application needlessly).</p>
|
Why doesn't MSBuild copy as I would expect <p>I'm needing to script my build. I'm using MSBUILD because of it's integration with VS.net. I am trying to copy some files from the build environment to the deployment folder. I'm using the copy task of MSBuild. But instead of copying the directory tree as I would expect. it copies all the contents into a single folder. I repeat all the files from the directory tree end up in one folder. I need it to copy the tree of folders and directories into the destination folder. Is there something I'm missing?</p>
<p>Here is the relavant parts of my build script:</p>
<pre><code><PropertyGroup>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<Source>outputfolder</Source>
<DestEnv>x</DestEnv>
<DeployPath>\\networkpath\$(DestEnv)</DeployPath>
</PropertyGroup>
<ItemGroup>
<TargetDir Include="$(DeployPath)\**\*" Exclude="**\web.config"></TargetDir>
<SourceDir Include="$(Source)\**\*" />
</ItemGroup>
<Target Name="Clean" >
<!-- clean detail ... -->
</Target>
<Target Name="migrate" DependsOnTargets="Clean">
<Copy DestinationFolder="$(DeployPath)" SourceFiles="@(SourceDir)" />
</Target>
</code></pre>
|
<p>Just a gem we found as we were debugging MSBuild issues around copying:</p>
<p><a href="http://blog.scrappydog.com/2008/06/subtle-msbuild-bug-feature.html">http://blog.scrappydog.com/2008/06/subtle-msbuild-bug-feature.html</a></p>
<p>ItemGroups are parsed before Targets, so any Targets that create new files (e.g. compiles!) won't be picked up when an ItemGroup is referenced further along the script.</p>
<p>Eric Bowen also describes a work-around for this "feature", the <strong>CreateItem</strong> task:</p>
<pre><code><Target Name="Copy" >
<CreateItem Include="..\Source\**\bin\**\*.exe"
Exclude="..\Source\**\bin\**\*.vshost.exe">
<Output TaskParameter="Include" ItemName="CompileOutput" />
</CreateItem>
<Copy SourceFiles="@(CompileOutput)"
DestinationFolder="$(OutputDirectory)"></Copy>
</Target>
</code></pre>
<p>Many kudos to him!</p>
|
Most efficient way to close a load() page using the X sign in jquery <p>I'm new to Jquery and I'm trying to use a div container to load a URL, however, I want to give a user an option to close it with an X sign on the top right corner like in Amazon.com. What's the best way to accomplish this?</p>
<p>Here's what I have and seems clumsy to figure out where the top right corner is and place the image X:</p>
<pre><code>$("#url_link_details").click(function() {
$("#details").load("tooltip_address.htm", function() {
$(this).addClass("openwindow").show();
$(".img_close").addClass("img_close_show").show();
})
});
</code></pre>
<p>Any help is appreciated.</p>
|
<p>some html:</p>
<pre><code><div id="popup">
<img src="x.gif" alt="Close" class="img_close" />
<div class="details"></div>
</div>
</code></pre>
<p>some css:</p>
<pre><code>#popup .img_close {
float: right;
}
#details {
clear: right; /* if you want there to be a "titlebar" area */
}
</code></pre>
<p>some jQuery</p>
<pre><code>$('#url_link_details").click(function() {
$('#details').load('tooltip_address.htm', function() {
$('#popup')
.show()
.find('.img_close')
.click(function() {
$('#popup').hide();
})
;
})
})
</code></pre>
|
Why does Javadoc generate non-compliant XHTML? <p>I just pasted some generated javadoc into an eclipse project, to discover none of the HTML is compliant.</p>
<p>There is even cases of closing tags that were never opened.</p>
<p>Is there some way to fix this? Maybe a "be compliant" option...</p>
|
<p>After some googling, I discovered <a href="http://linux.softpedia.com/get/Documentation/XHTML-Doclet-28836.shtml">
XHTML Doclet 0.4</a>.</p>
<blockquote>
<p>XHTML Doclet is a standards-compliant
alternative to the Javadoc standard
HTML doclet. The project revises the
document structure to exclude outdated
tags and inline styles, creates valid
XHTML markup, and provides better
hooks for more flexible CSS
manipulation.</p>
</blockquote>
<p>Looks like someone made a plugin.</p>
<p>Any better options?</p>
<p><b>Edit:</b> Here's the plugin's <a href="http://xhtmldoclet.sourceforge.net/">Official page</a> as linked to by <a href="http://java.sun.com/j2se/javadoc/faq/index.html#xhtmldoclet">Sun's Javadoc FAQ</a>.</p>
|
What is the "Operation Aborted" error in Internet Explorer? <p>I recently added JQuery's date-picker control to a project. In Internet Exploder, I get the following error message:</p>
<blockquote>
<p>Internet Explorer cannot open the
Internet site</p>
<p><a href="http://localhost/">http://localhost/</a></p>
<p>Operation aborted</p>
</blockquote>
<p>What is causing this problem?</p>
|
<p><strong>There was a related question earlier today</strong>:</p>
<p><a href="http://stackoverflow.com/questions/266585/operation-aborted-error-in-ie7"><strong>Operation Aborted Error in IE</strong></a></p>
<p>This is a common problem.</p>
<p>It occurs in IE when a script tries to modify the DOM before the page is finished loading. </p>
<p>Take a look at what sort of scripts are executing. You'll find that something is getting started before the page is finished loading. You can use the window.onload event to correct the problem (or one of the onDomReady library functions).</p>
|
Visual Studio Solutions Folder as real Folders <p>I have a Visual Studio Solution. Currently, it is an empty solution (=no projects) and I have added a few solution folders.</p>
<p>Solution Folders only seem to be "virtual folders", because they are not really created in the Filesystem and files inside solution folders are just sitting in the same folder as the .sln file.</p>
<p>Is there a setting that i've overlooked that tells Visual Studio to treat Solution Folders as "real" folders, that is to create them in the file system and move files into it when I move them inside the solution into one of those folders?</p>
<p><strong>Edit:</strong> Thanks. Going to make a suggestion for VS2010 then :)</p>
|
<p>No special setting. I don't think it's supported.</p>
<p>You can create real folders in a "project" within the solution, but not in the solution itself.</p>
|
Equivalent to Windows getch() for Mac/Linux crashes <p>I am using <code>getch()</code> and my app crashes instantly. Including when doing:</p>
<pre><code>int main()
{
getch();
}
</code></pre>
<p>I can't find the link but supposedly the problem is that it needs to turn off buffering or something strange along those lines, and I still want <code>cout</code> to work along with cross platform code.</p>
<p>I was told to use <code>std::cin.get()</code>, but I'd like the app to quit when a key is pressed, not when the user typed in a letter or number then press enter to quit.</p>
<p>Is there any function for this? The code must work under Mac (my os) and Windows.</p>
<hr>
<p>Linking/compiling is not an <a href="http://stackoverflow.com/questions/267250/equivalent-to-getch-mac-linux-crash#comment14636199_267281">issue</a>; I include <code><curses.h></code> and link with <code>-lcurses</code> in XCode, while Windows uses <code><conio.h></code>.</p>
|
<p>Have you looked in <code><curses.h></code> to see what the <code>getch()</code> function does?</p>
<p>Hint: OSX and Linux are not the same as Windows.</p>
<p>Specifically, as a macro in <code><curses.h></code>, we find:</p>
<pre><code>#define getch() wgetch(stdscr)
</code></pre>
<p>Now, there appears, on your system, to be an actual function <code>getch()</code> in the curses library, but it expects <code>stdscr</code> to be set up, and that is done by the curses initialization functions (<code>initscr()</code> and relatives), and that is signally not done by your code. So, your code is invoking undefined behaviour by calling curses routines before the correct initialization is done, leading to the crash.</p>
<p>(Good hint from dmckee - it helped get the link line out of acidzombie24, which was important.)</p>
<p>To get to a point where a single key-stroke can be read and the program terminated cleanly, you have to do a good deal of work on Unix (OSX, Linux). You would have to trap the initial state of the terminal, arrange for an <code>atexit()</code> function - or some similar mechanism - to restore the state of the terminal, change the terminal from cooked mode into raw mode, then invoke a function to read a character (possibly just <code>read(0, &c, 1)</code>), and do your exit. There might be other ways to do it - but it certainly will involve some setup and teardown operations.</p>
<p>One book that might help is <a href="http://rads.stackoverflow.com/amzn/click/0131411543" rel="nofollow">Advanced Unix Programming, 2nd Edn</a> by Mark Rochkind; it covers terminal handling at the level needed. Alternatively, you can use <code><curses.h></code> properly - that will be simpler than a roll-your-own solution, and probably more reliable.</p>
|
UIWebView within a ScrollView does not redraw <p>I have UIWebView within a UIScrollView. Then as I scroll, the web view displays first two pages correctly but does draws only half of the third the page. If I tap on the web view it draws the content or if I call <code>-[UIWebView reload]</code> in <code>-scrollViewDidEndDecelerating</code>, it shows the content. </p>
<p>Is there any way I can make the web view draw correctly?</p>
|
<p>UIWebViews cannot be loaded concurrently. You must load one, wait til it finishes, then load the next, and so on.</p>
<p>You can do this on a timer, or wait until when the scrolled UIWebView has the focus before loading the data.</p>
|
What are the best practices on MS-SQL when Windows Authentications is not an option? <p>What is the best option for a windows application that uses SQL server authentication? Should I create a single SQL account and manage the users inside the application (using a users table). Or should I create a SQL server account for each user. What is your experience? Thank you!</p>
|
<p>Depends on whether the username/password for the SQL server would be exposed to the user, and whether that would be a problem. Generally for internal apps (in smaller organisations), one would trust the users not too log in directly to the sql server. If you have a middleware layer (ie webservices) the password can be hidden from user.</p>
<p>I prefer to use a general login for the DB and manage users in the application. Even if you do create a login to sql for each application user, they could still connect directly, so why not just use a generic sql login that is easier to manage. This is of course assuming all users have the same accesses.</p>
<p>One good practice, if the users potentially can get direct access to the db, would be to grant access only through Stored Procedures and not directly to tables, so that only certain actions can be performed. Steer away from writing business logic or security checks (except basic ones) within the stored procs.</p>
<p>One way I would solve your problem is to write some webservices that check security and does your CRUD (via datasets, etc), but again it depends on the app and environment.</p>
<p>In summary if you have a middle layer or all users have the same access manage the user within the application and use a single user login. Otherwise use a login per user or role.</p>
|
How do you bind data to multiple columns in a list view? <p>I have a datasource that I want to bind to a listview that has multiple columns. How do I bind my datasource to that listview</p>
<p>Here is some pseudo code that doesn't work to help illustrate what I am trying to do:</p>
<pre><code>MyDataTable dt = GetDataSource();
ListView1.DataBindings.Add("Column1.Text", dt, "MyDBCol1");
ListView1.DataBindings.Add("Column2.Text", dt, "MyDBCol2");
</code></pre>
<p>-- edit --</p>
<p>Sorry, I forgot to mention it was winforms. </p>
|
<p>It seems there is a lacuna in functionality of WinForms ListView control (thought it's possible to <a href="http://msdn.microsoft.com/en-us/library/ms750972.aspx#BindingDatatoaListView" rel="nofollow">databind</a> new WPF ListBox). </p>
<p>This article by Nick Karnik describes how to add databinding capability to custom control inherited from WinForms ListView - <a href="http://www.codeproject.com/KB/list/ListView_DataBinding.aspx" rel="nofollow">Data binding a ListView</a>.</p>
|
TCL: Two way communication between threads in Windows <p>I need to have two way communication between threads in Tcl and all I can get is one way with parameters passing in as my only master->helper communication channel. Here is what I have:</p>
<pre><code>proc ExecProgram { command } {
if { [catch {open "| $command" RDWR} fd ] } {
#
# Failed, return error indication
#
error "$fd"
}
}
</code></pre>
<p>To call the tclsh83, for example ExecProgram "tclsh83 testCases.tcl TestCase_01"</p>
<p>Within the testCases.tcl file I can use that passed in information. For example:</p>
<pre><code>set myTestCase [lindex $argv 0]
</code></pre>
<p>Within testCases.tcl I can puts out to the pipe:</p>
<pre><code>puts "$myTestCase"
flush stdout
</code></pre>
<p>And receive that puts within the master thread by using the process ID:</p>
<pre><code>gets $app line
</code></pre>
<p>...within a loop.</p>
<p>Which is not very good. And not two-way.</p>
<p>Anyone know of an easy 2-way communication method for tcl in Windows between 2 threads?</p>
|
<p>Here is a small example that shows how two processes can communicate. First off the child process (save this as child.tcl):</p>
<pre><code>gets stdin line
puts [string toupper $line]
</code></pre>
<p>and then the parent process that starts the child and comunicates with it:</p>
<pre><code>set fd [open "| tclsh child.tcl" r+]
puts $fd "This is a test"
flush $fd
gets $fd line
puts $line
</code></pre>
<p>The parent uses the value returned by open to send and receive data to/from the child process; the r+ parameter to open opens the pipeline for both read and write.</p>
<p>The flush is required because of the buffering on the pipeline; it is possible to change this to line buffering using the fconfigure command.</p>
<p>Just one other point; looking at your code you aren't using threads here you are starting a child process. Tcl has a threading extension which does allow proper interthread communications. </p>
|
query: cross product instead of join <p>I have two tables that I would like to join but I am getting an error from MySQL</p>
<pre><code>Table: books
bookTagNum ShelfTagNum
book1 1
book2 2
book3 2
Table: shelf
shelfNum shelfTagNum
1 shelf1
2 shelf2
</code></pre>
<p>I want my results to be:</p>
<pre><code>bookTagNum ShelfTagNum shelfNum
book1 shelf1 1
book2 shelf2 2
book3 shelf2 2
</code></pre>
<p>but instead I am also getting an extra result:</p>
<pre><code>book1 shelf2 2
</code></pre>
<p>I think my query is doing a cross product instead of a join:</p>
<pre><code>SELECT `books`.`bookTagNum` , `books`.`shelfNum` , `shelf`.`shelfTagNum` , `books`.`title`
FROM books, shelf
where `books`.`shelfNum`=`books`.`shelfNum`
ORDER BY `shelf`.`shelfTagNum` ASC
LIMIT 0 , 30
</code></pre>
<p>What am I doing wrong?</p>
|
<p>I think you want</p>
<pre><code>where `books`.`shelfTagNum`=`shelf`.`shelfNum`
</code></pre>
<p>In order to match rows from the <code>books</code> and <code>shelf</code> tables, you need to have terms from each in your <code>where</code> clause - otherwise, you're just performing a no-operation check on the rows of <code>books</code>, since every row's <code>shelfNum</code> will be equal to its <code>shelfNum</code>.</p>
<p>As @<a href="#267544" rel="nofollow">fixme.myopenid.com</a> suggests, you could also go the explicit <code>JOIN</code> route, but it's not necessary.</p>
|
.Access violation reading location <p>I've met a really strange problem.</p>
<p>The code is as follow:</p>
<pre><code>::boost::shared_ptr<CQImageFileInfo> pInfo=CQUserViewDataManager::GetInstance()->GetImageFileInfo(nIndex);
Image* pImage=pInfo->m_pThumbnail;
if(pImage==NULL)
pImage=m_pStretchedDefaultThumbImage;
else
{
//
int sourceWidth = pInfo->GetWidth();
int sourceHeight = pInfo->GetHeight();
int destX = 0,
destY = 0;
float nPercent = 0;
float nPercentW = ((float)GetThumbImageWidth()/(float)sourceWidth);;
float nPercentH = ((float)GetThumbImageHeight()/(float)sourceHeight);
if(nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = (int)((GetThumbImageWidth() - (sourceWidth * nPercent))/2);
}
else
{
nPercent = nPercentW;
destY = (int)((GetThumbImageHeight() - (sourceHeight * nPercent))/2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
rcShowImage=CRect(rc.left+destX, rc.top+destY,rc.left+destX+destWidth,rc.top+destY+destHeight);
}
ASSERT(pImage != NULL); // passed assertion...
graphics.DrawImage(pImage,rcShowImage.left,rcShowImage.top,
rcShowImage.Width(),rcShowImage.Height()); // problem happened here.
</code></pre>
<p>I received the following exception:</p>
<pre><code>First-chance exception at 0x004095b0 in ec.exe: 0xC0000005: Access violation reading location 0xfeeefef2.
Unhandled exception at 0x004095b0 in ec.exe: 0xC0000005: Access violation reading location 0xfeeefef2.
</code></pre>
<p>I have checked the <code>pImage</code>, I am sure when <code>graphics.DrawImage</code> is called, it is not <code>NULL</code>.</p>
<ul>
<li>why such a problem happened?</li>
<li>What is <code>0xfeeefef2</code>?</li>
</ul>
|
<p><code>0xfeeefeee</code> is a fill pattern that the debug version of the Windows heap (not the C runtime heap) uses for uninitialized memory. <code>0xfeeefef2</code> is <code>0xfeeefeee+4</code>. It sounds like you're dereferencing an uninitialized pointer located in (or copied from) a block of memory allocated from the heap.</p>
<p>The debug heap automatically gets enabled when you start your program in the debugger, as opposed to attaching to an already-running program with the debugger.</p>
<p>The book <em><a href="http://www.advancedwindowsdebugging.com/">Advanced Windows Debugging</a></em> by Mario Hewardt and Daniel Pravat has some decent information about the Windows heap, and it turns out that the chapter on heaps is <a href="http://www.advancedwindowsdebugging.com/ch06.pdf">up on the web site as a sample chapter</a>.</p>
|
How to create a picture with animated aspects programmatically <p>Background</p>
<p>I have been asked by a client to create a picture of the world which has animated arrows/rays that come from one part of the world to another. </p>
<p>The rays will be randomized, will represent a transaction, will fade out after they happen and will increase in frequency as time goes on. The rays will start in one country's boundary and end in another's. As each animated transaction happens a continuously updating sum of the amounts of all the transactions will be shown at the bottom of the image. The amounts of the individual transactions will be randomized. There will also be a year showing on the image that will increment every n seconds.</p>
<p>The randomization, summation and incrementing are not a problem for me, but I am at a loss as to how to approach the animation of the arrows/rays.</p>
<p><strong>My question is what is the best way to do this? What frameworks/libraries are best suited for this job?</strong></p>
<p>I am most fluent in python so python suggestions are most easy for me, but I am open to any elegant way to do this.
The client will present this as a slide in a presentation in a windows machine.</p>
|
<blockquote>
<p>The client will present this as a slide in a presentation in a windows machine</p>
</blockquote>
<p>I think this is the key to your answer. Before going to a 3d implementation and writing all the code in the world to create this feature, you need to look at the presentation software. Chances are, your options will boil down to two things:</p>
<ol>
<li>Animated Gif</li>
<li>Custom Presentation Scripts</li>
</ol>
<p>Obviously, an animated gif is not ideal due to the fact that it repeats when it is done rendering, and to make it last a long time would make a large gif.</p>
<p>Custom Presentation Scripts would probably be the other way to allow him to bring it up in a presentation without running any side-programs, or doing anything strange. I'm not sure which presentation application is the target, but this could be valuable information.</p>
<p>He sounds like he's more non-technical and requesting something he doesn't realize will be difficult. I think you should come up with some options, explain the difficulty in implementing them, and suggest another solution that falls into the 'bang for your buck' range.</p>
|
Java Instance Variable Accessibility <p>What is the difference in the accessibility of the following variables in Java?</p>
<pre><code>public class Joe {
public int a;
protected int b;
private int b;
int c;
}
</code></pre>
<p>I'm most interested in what the last one is doing.</p>
|
<ul>
<li>public: read/writable for anyone</li>
<li>protected: read/writable for
instances of subclasses <strong>and from within the enclosing package</strong></li>
<li>private: read/writable for <strong>any</strong> instance of the class
and inner or outer (enclosing) instance</li>
<li>int c :
package-private, read/writable for
all classes inside same package</li>
</ul>
<p>See the <a href="http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285" rel="nofollow">JLS</a> for more details</p>
<p>EDIT: Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for private. I remember now... ;-)</p>
|
How do I prevent this System.IO.IOException when copying a file? <p>When I run the following code to test copying a directory, I get a System.IO.IOException when fileInfo.CopyTo method is being called. The error message is: "The process cannot access the file 'C:\CopyDirectoryTest1\temp.txt' because it is being used by another process." </p>
<p>It seems like there's a lock on file1 ("C:\CopyDirectoryTest1\temp.txt") which is created a few lines above where the error is occurring, but I don't know how to release this if so. Any ideas?</p>
<pre><code>using System;
using System.IO;
namespace TempConsoleApp
{
class Program
{
static void Main(string[] args)
{
string folder1 = @"C:\CopyDirectoryTest1";
string folder2 = @"C:\CopyDirectoryTest2";
string file1 = Path.Combine(folder1, "temp.txt");
if (Directory.Exists(folder1))
Directory.Delete(folder1, true);
if (Directory.Exists(folder2))
Directory.Delete(folder2, true);
Directory.CreateDirectory(folder1);
Directory.CreateDirectory(folder2);
File.Create(file1);
DirectoryInfo folder1Info = new DirectoryInfo(folder1);
DirectoryInfo folder2Info = new DirectoryInfo(folder2);
foreach (FileInfo fileInfo in folder1Info.GetFiles())
{
string fileName = fileInfo.Name;
string targetFilePath = Path.Combine(folder2Info.FullName, fileName);
fileInfo.CopyTo(targetFilePath, true);
}
}
}
}
</code></pre>
|
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.file.create.aspx"><code>File.Create</code></a> returns an open <a href="http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx"><code>FileStream</code></a> - you need to close that stream.</p>
<p>Just</p>
<pre><code>using (File.Create(file1)) {}
</code></pre>
<p>should do the trick.</p>
|
OffTopic: Would you consider HTML + CSS + Webserver to be MVC? <p>these are just my wonderings and I thought I'd share them...</p>
<p>Simply put, MVC is the pattern for separating contents (model) from presentation (view), and having a mechanism in place (controller) defining how to gather both.</p>
<p>If you already see where I am going at, I am very interested to hear your opinion on the matter. Of course, MVC applies to serverside mechanics and all, but think out of the box here with me for a second.</p>
<p>"Visitors" of the web, both human and robot/Google will be likely to see HTML and what comes with it. Writing structured and meaningful HTML, together with separating it from presentation using CSS has become more important over the years, and future technology such as HTML5 only contributes to this separation by offering a more content-focused set of elements, and mechanisms for working with the pure visual representation.</p>
<p>Considering all this, I was wondering if it would be correct in some way to say that the MVC paradigm applies to the front-end as well, where:</p>
<ul>
<li>The model would be HTML, as in the pure httpwise contents that it has become</li>
<li>The view being CSS; it makes your content be presented a certain way</li>
<li>The controller being the webserver and all that lies underneath, it is what gathers and separates the model and view, and does all the decision making</li>
</ul>
<p>Makes sense? Not?</p>
<p>Thanks,</p>
<p>Martin</p>
<p>Update: VonC pointed me to an article that definitely changed my thoughts on the controller part. The browser takes up a major part of the controller too, as it handles a great deal of user interaction and how the model and view work together.</p>
|
<p>You can generally find MVC in anything if you look hard enough.</p>
|
java webstart decompiler <p>Is there anyway to decompile java webstart application? </p>
|
<p>Start the application, then fetch the JAR(s) from the webstart cache. Proceed to decompile like with any other Java application.</p>
|
To check whether the string value has numeric value or not in C# <p>I am having an string like this</p>
<p>string str = "dfdsfdsf8fdfdfd9dfdfd4"</p>
<p>I need to check whether the string contains number by looping through the array.</p>
|
<p>What about a regular expression:</p>
<pre><code>bool val = System.Text.RegularExpressions.Regex.IsMatch(str, @"\d");
</code></pre>
|
ASP.NET user control - can't get client-side (JavaScript) altered value back into control <p>Ok guys and gals, here is my problem:</p>
<p>I've built a custom control that uses a textbox to present data to the user. </p>
<p>When the user interacts with the control the <strong>value of that textbox is altered with client side javascript</strong>.</p>
<p>I also have a button on my page. When the user clicks the button I want to take the value from the custom control (aka. the textbox) and use it elsewhere.</p>
<p>So, in the onClick event for the button I do something like this:</p>
<pre><code>this.myLabel.Text = this.customControl.Value;
</code></pre>
<p>The problem is that the custom control does not have the new textbox value available. In the custom control the textbox is empty. However, I can see the correct value in the Request.Form collection.</p>
<p>Am I doing something wrong here? Or should I be reading from Request.Form?!</p>
|
<p>Interesting, I didn't realize readonly TextBox doesn't get updated from viewstate.</p>
<p>When I pull stunts like that in my web sites, I usually setup asp:HiddenFields that I dump data into with javascript (gotta love jQuery), and that I read values from on postbacks.</p>
<p>Keeps things cleaner I find.</p>
|
How do I write a console application in Windows that would minimize to the system tray? <p>I have a written a Visual C++ console application (i.e. subsystem:console) that prints useful diagnositic messages to the console.</p>
<p>However, I would like to keep the application minimized most of the time, and instead of minimizing to the taskbar, appear as a nice icon on the system tray. I would also like to restore the console when the system tray icon is clicked.</p>
<p>How should I change my program to do this?</p>
|
<p>This is going to be an ugly hack.</p>
<p>First, you have to retrieve the <code>hWnd</code> / <code>hInstance</code> of you console application. Right now, I can only come up with one way:</p>
<ul>
<li>Create a Guid with <code>CoCreateGuid()</code></li>
<li>Convert it to a string</li>
<li>Set the title of the console window to this guid with <code>SetConsoleTitle()</code></li>
<li>Find the <code>hWnd</code> of the your window with the Guid as the tile with <code>FindWindow()</code></li>
<li>And you can do it from the usual way from this point. <a href="http://www.gidforums.com/t-9218.html">See <a href="http://www.gidforums.com/t-9218.html">http://www.gidforums.com/t-9218.html</a> for more info.</a></li>
<li>Don't forget the rename your console window to the original title once you're done.</li>
</ul>
<p>As you can see, even though this is possible to do, it's a horrible and painful solution. Please don't do it. Please do not minimize console applications to the system tray. <strong>It is not something you are supposed to be able to do in the Windows API.</strong></p>
|
Really Basic Graphics in C# 2.0 Tutorials <p>I work for a ticketing agency and we print out tickets on our own ticket printer. I have been straight coding the ticket designs and storing the templates in a database. If we need a new field adding to a ticket I manually add it and use the arcane co-ordinate system to estimate where the fields should go and how much the other fields need to move by to accomodate new info.</p>
<p>We always planned to make this system automate with a simple (I stress the word simple) graphical editor. Basically we don't forsee tickets changing radically in shape any time soon, we have one size of ticket and the ticket printer firmware is super simple because it's more of an industrial machine, it has about 10 fonts and some really basic sizing interactions.</p>
<p>I need to make this editor display a rectangle of the dimensions by pixel of the tickets (can even be actual size) and have a resizable grid which can toggle between superimposition and invisibility on top of the ticket rectangle and represented by dots rather than lines.</p>
<p>Then I want to be able to represent fields by drawing rectangles filled with the letter "x" that show the maximum size of the field (to prevent overlaps). These fields should be selectable, draggable and droppable in a snap to grid fashion.</p>
<p>I've worked out the maths of it but I have no idea how to draw rectangles and then draw grids in layers and then put further rectangles full of 'x'es on top of those. I also don't really know much about changing drawn positions in accordance with mouse events. It's simply not something I've ever had to do.</p>
<p>All the tutorials I've seen so far presume that you already know a lot about using the draw objects and are seeking to extend a basic knowledge of these things. I just need pointing in the direction of a good tutorial in manipulating floating objects in a picturebox in the first place.</p>
<p>Any ideas?</p>
|
<p>For those of you in need of a guide to this unusual (at least those of us with a BIS background) field I would heartily endorse:</p>
<p><a href="http://www.bobpowell.net/faqmain.htm" rel="nofollow">http://www.bobpowell.net/faqmain.htm</a></p>
<p>I am now happily drawing graphical interfaces and getting them to respond to control inputs with not too much hassle.</p>
|
Execute a JavaScript function in a C# application <p>Without using a WebBrowser control, how could I execute a JavaScript function, that is decoupled from any browser DOM dependencies, in a C# application? I am investigating implementing validation rules only once, for both server and client validation. See <a href="http://stackoverflow.com/questions/265343/automatically-duplicating-business-logic-on-web-client">this question</a> for reference if you like. Are there any JS interpretor libraries I could use?</p>
<p><em>Addendum:</em>
My goal here is to automatically deploy and invoke exactly the same validation logic on client and server, without communication between the two during the actual validation. So, ideally I would code my validation logic in JavaScript, and render that to the page. Alternatively, I could code my logic in C#, convert that to JavaScript using <a href="http://projects.nikhilk.net/ScriptSharp/" rel="nofollow">Script#</a>, and render that to the page. </p>
<p>I don't want separate validation functions being maintained client and server side, and I don't want AJAX calls to server validation functions, and I don't want client only or server only validation.</p>
|
<p>You could use <a href="http://en.wikipedia.org/wiki/JScript_.NET" rel="nofollow">JScript.Net</a></p>
<p>Either that, or investigate <a href="http://projects.nikhilk.net/ScriptSharp/" rel="nofollow">Script#</a></p>
|
What are the differences / similarities between JBI and SCA <p>Could point me to some good links, or share experiences of the differences / similarities between the JBI and SCA specifications?</p>
<p>Many thanks :-)</p>
|
<p>This article can provide the beginning of an answer (even though it does not detail the specifications)</p>
<p><a href="http://www.osoa.org/display/Main/Relationship+of+SCA+and+JBI" rel="nofollow">OSOA article</a></p>
<blockquote>
<p>SCA allows multiple technologies to be used to implement services (e.g. Java, BPEL, C++) and multiple bindings for communicating with services (e.g. Web services or JMS). However, SCA does not describe how you would introduce a new implementation type or new binding into a runtime. This is exactly where JBI is targeted. </p>
<p>JBI is a Java Platform integration 'micro kernel' standard that provides an open architecture in support of multi-vendor Java Composite Application Platform tools and infrastructure. It defines a set of service provider interfaces for middleware providers to implement if they want to install new service engines (which correspond to SCA's implementation types) or binding components (which correspond to SCA's bindings) into a JBI-compliant runtime.</p>
</blockquote>
<p>You can find a quick feedback and some reactions in this article: <a href="http://www.infoq.com/news/2008/05/sca-jbi-together" rel="nofollow">
SCA and JBI, Best of Both Worlds?</a>.</p>
|
Automatic BizTalk Versioning in My Build Process <p>In all of my other .net apps my build process (a mixture of nant and custom tasks) automatically updates the [AssemblyVersionAttribute] AssemblyInfo.cs with the current build number before the call to msbuild, stamping in the build number in the version number.</p>
<p>I'm now working on my first BizTalk project and I'd like to do the same thing with the version numbers of the BizTalk assemblies, but I've run into trouble!</p>
<p>First of all the aseembly version numbers are stored in the btproj files, so I did some googling and found www.codeplex.com/biztalk which looked like the answer to my problem, but there is a deeper problem!</p>
<p>I have a project for my schemas and another for my pipelines, the pipelines project references my schemas project as I have a flat file dis/assemblers. The problem comes when I update the version numbers, as updating them even from within visual studio does not update the pipeline components references to the schemas.</p>
<p>So if I update all the version numbers manually in the VS IDE from 1.0.0.0 to 1.1.0.0, the build fails as the pipeline components flat file dis/assemblers still reference the old 1.0.0.0 version of the schemas! They don't automatically update!</p>
<p>Is this really a manual process of updating the version numbers of the BizTalk projects in the property pages, then building the projects and manually updating the references to them in the properties of all the pipeline components that reference them?</p>
<p>This means that I can't have my build process control the build number part of my version numbers!</p>
<p>Or is there a better method of managing the version numbers of the BizTalk assemblies?</p>
|
<p>I'm sorry to disappoint you but I've been down the exact some road I had to give up. I guess it could be possible to achieve it but it would require a lot of changes to both the binding files and other XML files (as you mentioned and even more if you have published services etc).</p>
<p>Maybe it could be possible to wrap all these necessary changes in a build step (a MSBuild step or similar in other build frameworks) - that would be <strong><em>useful!</em></strong></p>
|
jQuery document.createElement equivalent? <p>I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.</p>
<pre><code>var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
</code></pre>
<p>I would like to know if there is a better way to do this using jQuery. I've been experimenting with:</p>
<pre><code>var odv = $.create("div");
$.append(odv);
// And many more
</code></pre>
<p>But I'm not sure if this is any better.</p>
|
<p>here's your example in "one" line.</p>
<pre><code>this.$OuterDiv = $('<div></div>')
.hide()
.append($('<table></table>')
.attr({ cellSpacing : 0 })
.addClass("text")
)
;
</code></pre>
<hr>
<p><em>Update</em>: I thought I'd update this post since it still gets quite a bit of traffic. In the comments below there's some discussion about <code>$("<div>")</code> vs <code>$("<div></div>")</code> vs <code>$(document.createElement('div'))</code> as a way of creating new elements, and which is "best".</p>
<p>I put together <a href="http://jsbin.com/elula3">a small benchmark</a>, and here's roughly the results of repeating the above options 100,000 times:</p>
<p><strong>jQuery 1.4, 1.5, 1.6</strong></p>
<pre><code> Chrome 11 Firefox 4 IE9
<div> 440ms 640ms 460ms
<div></div> 420ms 650ms 480ms
createElement 100ms 180ms 300ms
</code></pre>
<p><strong>jQuery 1.3</strong></p>
<pre><code> Chrome 11
<div> 770ms
<div></div> 3800ms
createElement 100ms
</code></pre>
<p><strong>jQuery 1.2</strong></p>
<pre><code> Chrome 11
<div> 3500ms
<div></div> 3500ms
createElement 100ms
</code></pre>
<p>I think it's no big surprise, but <code>document.createElement</code> is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we're talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds <em>per thousand elements</em>. </p>
<p><strong>Update 2</strong></p>
<p>Updated for jQuery 1.7.2 and put the benchmark on JSPerf which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!</p>
<p><a href="http://jsperf.com/jquery-vs-createelement">http://jsperf.com/jquery-vs-createelement</a></p>
|
Is it OK to return a KeyValuePair from a .NET function? <p>I was just working on a function that I needed to return two values, one being a column name and one being the value of that column for that current row. I am returning KeyValuePair(of String,Object). I was wondering if this is a good idea or does it make it hard to read/use? </p>
|
<p>If it genuinely is a key-value pair, then that seems a pretty reasonable thing to do. .NET 4.0 will include a proper <code>Tuple</code> class for cases where there isn't a key-value relationship.</p>
<p>The alternative is to use out/ref parameters, letting the caller decide whether or not to keep the values together - but I prefer the <code>KeyValuePair</code> approach when there's an obvious relationship and the caller is likely to want to keep them combined.</p>
|
How can I monitor the active thread count of a process (jvm) on linux? <p>I would like to monitor the number of threads used by a specific jvm process on linux.
Is there an easy way to get this information without impacting the performance of the jvm process.</p>
<p>More specifically I am interested in the number of threads per state.</p>
|
<p>try</p>
<pre><code>ps huH p <PID_OF_U_PROCESS> | wc -l
</code></pre>
<p>or <a href="http://htop.sourceforge.net/">htop</a></p>
|
Swing: Canvas overlaps menu <p>I have a JFrame with a menu bar and a canvas covering all the remaining surface. When I click on the menu bar, the menu opens <strong>behind</strong> the Canvas and I can't see it. Has anyone experienced this? Other than resizing the Canvas (which I am reluctant to do) is there any solution?</p>
<p>Thanks,<br/>
Vlad</p>
|
<p>You're experiencing heavyweight vs. lightweight issues.</p>
<p>The quick fix: </p>
<pre><code>// Call this sometime before you use your menus
JPopupMenu.setDefaultLightWeightPopupEnabled(false)
</code></pre>
<p><a href="http://java.sun.com/products/jfc/tsc/articles/mixing/index.html">Heavyweight vs. Lightweight</a></p>
|
Easy way to add a context action to Eclipse <p>I'm trying to add a very simple action to the context menu of Eclipse: clicking with right button over a folder object, this action should call an external tool (configured in the "External Tools") using the path of the folder as the only parameter.</p>
<p>I've found a <a href="http://www.eclipse.org/articles/article.php?file=Article-action-contribution/index.html" rel="nofollow">tutorial on how to add a context menu</a>, but it's more complex than what I need -- I don't really want to create a plugin, I don't even want to create classes to do what I want. My only purpose is to call an external tool.</p>
<p>How can I do it?</p>
|
<p>If you want to extend Eclipse with functionality such as editing context menu's, the only way to go is by writing a plug-in. However, this can be very light-weight and targeted to your needs, so the tutorial you found might be a good way to do it. </p>
|
Accessing a ColdFusion datasource from Java code <p>I have a servlet that I would like to run within ColdFusion MX 7. I would like to make use of an existing ColdFusion DSN as a javax.sql.DataSource, if possible.</p>
<p>I thought something like </p>
<pre><code>coldfusion.server.ServiceFactory.getDataSourceService().getDatasource(dsname);
</code></pre>
<p>would work, but unfortunately the servlet returns</p>
<pre><code>java.lang.NoClassDefFoundError: coldfusion/server/ServiceFactory
</code></pre>
|
<p>That code will work fine, you just don't have ServiceFactory in your classpath. Ie, Java can't load that class. Try including a dependency on cfusion.jar from C:\CFusionMX7\lib.</p>
|
Besides version control systems, are there any tools that support release management? <p>Most of the time, I've seen release management handled as a defined process with the supporting tool as the version control system (usually via branching and tagging). However, are there any tools dedicated to release management? I'm looking for both open source and closed source tools, if any exist.</p>
|
<p>You can use <a href="http://ant.apache.org/" rel="nofollow">ant</a> or <a href="http://maven.apache.org/" rel="nofollow">maven</a> for automating tasks like generating packages and deploys to remote servers.</p>
|
What is the best way to store and search through object transactions? <p>We have a decent sized object-oriented application. Whenever an object in the app is changed, the object changes are saved back to the DB. However, this has become less than ideal.</p>
<p>Currently, transactions are stored as a transaction and a set of transactionLI's.</p>
<p>The transaction table has fields for who, what, when, why, foreignKey, and foreignTable. The first four are self-explanatory. ForeignKey and foreignTable are used to determine which object changed.</p>
<p>TransactionLI has timestamp, key, val, oldVal, and a transactionID. This is basically a key/value/oldValue storage system.</p>
<p>The problem is that these two tables are used for every object in the application, so they're pretty big tables now. Using them for anything is slow. Indexes only help so much.</p>
<p>So we're thinking about other ways to do something like this. Things we've considered so far:
- Sharding these tables by something like the timestamp.
- Denormalizing the two tables and merge them into one.
- A combination of the two above.
- Doing something along the lines of serializing each object after a change and storing it in subversion.
- Probably something else, but I can't think of it right now.</p>
<p>The whole problem is that we'd like to have some mechanism for properly storing and searching through transactional data. Yeah you can force feed that into a relational database, but really, it's transactional data and should be stored accordingly.</p>
<p>What is everyone else doing?</p>
|
<p>We have taken the following approach:-</p>
<ol>
<li><p>All objects are serialised (using the standard XMLSeriliser) but we have decorated our classes with serialisation attributes so that the resultant XML is much smaller (storing elements as attributes and dropping vowels on field names for example). This could be taken a stage further by compressing the XML if necessary.</p></li>
<li><p>The object repository is accessed via a SQL view. The view fronts a number of tables that are identical in structure but the table name appended with a GUID. A new table is generated when the previous table has reached critical mass (a pre-determined number of rows)</p></li>
<li><p>We run a nightly archiving routine that generates the new tables and modifies the views accordingly so that calling applications do not see any differences.</p></li>
<li><p>Finally, as part of the overnight routine we archive any old object instances that are no longer required to disk (and then tape).</p></li>
</ol>
|
How can you emulate a mailing list in Django? <p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p>
<p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p>
<p>Now, we can work our way through all these fiddly little details, but I was wondering if anyone had any code which already did this sort of thing that we could crib from, so that we don't have to go through all the trial-and-error ourselves. Specific sections of RFCs that showed us what we should be sending would also be useful.</p>
<p>Thanks,<br/>
Blake.</p>
|
<p>What about <a href="http://labs.freehackers.org/projects/colibri/wiki" rel="nofollow">http://labs.freehackers.org/projects/colibri/wiki</a>
It seems to do what you want: a mailing list manager with a django frontend.</p>
|
Getting directory listing using Flash <p>In flash you can open a file on the user's computer. In flash 9 you can upload and download the file and in flash 10 you can access the contents of the file.</p>
<p>It is secure because the user has to choose the file from a file dialog box to allow flash access to it.</p>
<p>What I would like to do in my application is to get a directory listing of the files/subdirectories in a directory. It's not really any different from uploading a file chosen by the user to list the contents of a directory chosen by the user so I don't see any security implications. I don't need to access the files, just list them,</p>
<p>But there appears to be no way in flash to do this?
Am I right or am I missing something?</p>
<p>I can always use a signed java applet instead if necessary but flash seems more appropriate for my particular application so I thought it worth asking the question.</p>
|
<p>It is insecure, unless, perhaps, you ask the user to point to the wanted directory with a folder browse dialog, if we remain in the above logic...<br />
Even them, users can inadvertently give more information than they should with this mean.<br />
Like when they open all the Documents and Settings folder to P2P networks... :-)</p>
<p>Insecure because then people can get interesting file names, perhaps explore browser caches, etc.</p>
|
Where do you get XML file formats from <p>Looking at questions like <a href="http://stackoverflow.com/questions/77726/xml-or-sqlite-when-to-drop-xml-for-a-database">http://stackoverflow.com/questions/77726/xml-or-sqlite-when-to-drop-xml-for-a-database</a> and <a href="http://stackoverflow.com/questions/44207/what-are-good-alternative-data-formats-to-xml">http://stackoverflow.com/questions/44207/what-are-good-alternative-data-formats-to-xml</a> it is clear that XML is something you best use for exchanging data between systems, organizations, and software programs. For internal use, other formats tend to more compact and scalable, like home-made plain-text formats, regular source code, or using a database. </p>
<p>Once the time comes to move data out to some other program/tool/system/organization in XML: where and how do you define the data format encapsulated in the XML file? It is clear that you need strict rules for what goes where, and then meaning of all nodes in the tree. XML is not self-documenting, that much seems clear. </p>
<p>Do you use somebody else's design, or roll your own? Is there some good guide to how to do the document designs?</p>
<p>/jakob</p>
|
<p>How I handle it:</p>
<ul>
<li>One element wrapping the whole thing (XML standard)</li>
<li>One element within that for each "object".</li>
<li>Attributes on the element for each Property, when they are a reasonable length.</li>
<li>The InnerXml text of that element for a property with lots of text (provided there is just one)</li>
<li>Elements nested within the element if there are several properties with a lot of text.</li>
</ul>
<p>(sorry, the editor just will not let me post XML. The preview and the submitted versions don't even match)</p>
<p>If you write a sample version of the XML file in VisualStudio, there's a toolbar button to click which will have it automatically create a xsd schema for that file. Add a "targetNamespace" attribute to the XSD, and copy it to <code>C:\Program Files\Microsoft Visual Studio 8\Common7\Packages\schemas\xml</code> (varying slightly by VS release). </p>
<p>Then add a xmlns="{your namespace}" attribute to your root element, and VS will give it Intellisense for your tags.</p>
|
Engineer accountability and code review processes <p>In your âenterpriseâ work environment, how are engineers held accountable for performing code inspections and unit testing? What processes do you follow (formal methodology or custom process) to ensure the quality of your software? Do you or have you tried implementing a developer "signoff" sheet for deliverables?</p>
<p>Thanks in advance!</p>
<p>Update: I forgot to mention we are using Code Collaborator to perform our inspections. The problem is getting people to "get it" and buy into doing them outside of a core group of people. As stalbot pointed out below it is a cultural change but the question becomes, how do you change your culture to promote quality initiatives such as reviews/unit tests?</p>
|
<p>⢠Our company uses peer code reviews. We conduct them as Over-The-Shoulder reviews and invite the teamâs tester to participate in the meeting to gain a better understanding of the changes. We use Source Control software that requires check-in, code-review rules to be signed off. Nothing big, just another developer's name that has reviewed the code.</p>
<p>⢠There are definite benefits to code review as several studies have been able to demonstrate. For our company, it was evident that code quality increased as the number of support calls decreased and the number of reported bugs decreased as well. NOTE: Some of the benefits here were the result of implementing Scrum and abandoning Waterfall. More on Scrum below.</p>
<p>⢠The benefits of code review can be a more stable product, more maintainable code as it applies to structure and coding standards, and it allows developers to focus more on new features rather than âfire-fightingâ bugs, and other production issues. There really arenât any drawbacks if code reviews are conducted ârightâ. More on the âright wayâ below.</p>
<p>⢠Some of the hurdles to overcome while implementing code reviews are the idea that âbig brotherâ is watching me and the idea that not having perfect code means torture and pain. Getting developers to trust each other is difficult sometimes, especially when it involves âpecking orderâ or the âholier than thouâ attitudes and putting your hard work under a microscope. Trust is the key to resolving these issues. A developer must trust that they will not be punished by peers or management for mistakes in code. It happens to everyone. Make a note of the issue, get it resolved and move on.</p>
<p><strong>Scrum</strong>
One of the benefits of using the Scrum methodology is that a development cycle (âsprintâ) is short. The time-frame of the âsprintâ is determined by what works best for your organization and will need some trial and error, but really shouldnât be longer than four week iterations. The benefit is that it requires the developers communicate daily and communicate problems early on in the project. This was initially adopted by our development department and has spread to all areas of our company as the benefits of scrum are far reaching. For more information, see: <a href="http://en.wikipedia.org/wiki/SCRUM" rel="nofollow">http://en.wikipedia.org/wiki/SCRUM</a> or <a href="http://www.scrumalliance.org/" rel="nofollow">http://www.scrumalliance.org/</a> . As the development iterations are smaller, the code review process reviews smaller pieces of code, making the review more likely to find problems than hours or days of formal reviews.</p>
<p><strong>âRight Wayâ</strong>
Code Reviews done the âright wayâ is completely subjective. However, I personally believe that they should be informal, over-the-shoulder reviews. All of the participants in a review should avoid personally attacking the person being reviewed with statements such as âwhy did you do it that way?â or âwhat were you thinking?â etc. These types of comments diminish the trust between peers, leading to animosity, hours of arguing over the best/right way to code a solution. Keep in mind that developers do not think or code exactly the same, and there are many solutions to a problem.
Just a little clarification on over-the-shoulder reviews; these can be conducted via remote desktop sharing (pick flavor here), or in person. However, they shouldnât be limited to the developers only. We typically invite our entire scrum team which consists of two developers per team, a tester, a documentation person, and product owner. All non-developers are there to gain a better understanding of the changes or new functionality being made. They are free to ask questions or provide input, but not to make coding decisions or comments. This has been effective as certain questions will be asked that may change the direction of the project as the initial requirements may have missed a scenario, but that is what agile is all about, change.</p>
<p><strong>Suggestion</strong>
I would highly recommend researching scrum and code reviews, before mandating them. Create the basic rules for each and implement them as part of your culture to achieve a better quality product. It must become part of your culture so that it is part of a natural process and integrated at all levels, as it is a paradigm shift from poor quality, missed deadlines and frustration to better quality products, less frustration, and more on-time deliverables.</p>
|
BCP out Error in SQL2000: SQLState = 37000, NativeError = 4060 <p>I have created a proc that grabs all the user tables in a local DB on my machine. I want to be able to create a flat file of all my tables using BCP and SQL. Its a dummy database in SQL 2000 connecting through windows authentication. I have set my enviroment path variable in WinXP SP2. I have created new users to access the db, switched off my firewall, using trusted connection. I have tried dozens of forums, no luck. </p>
<p>In dos command prompt I get the same error. </p>
<p>SQLState = 37000, NativeError = 4060
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database requested in login '[HelpDesk-EasyPay'. Login fails.</p>
<p>Here is my SP: </p>
<pre><code>@Path VARCHAR(100),
@UserName VARCHAR(15),
@PassWord VARCHAR(15),
@ServerName VARCHAR(15)
AS
set quoted_identifier off
set nocount on
declare @n int
declare @db varchar(40)
set @db=DB_NAME()
declare @TableName varchar(15)
declare @bcp varchar(200)
select identity(int,1,1) as tblNo,name tblname into #T from Sysobjects where xtype='u'
select @n=COUNT(*) from #T
WHILE (@n>0)
BEGIN
SELECT @TableName=tblname FROM #T WHERE tblno=@n
PRINT 'Now BCP out for table: ' + @TableName
SET @bcp = "master..xp_cmdshell 'BCP " + "[" + @db + ".." + @TableName + "]" + " OUT" + @Path + "" + @TableName+".txt -c -U" + @UserName + " -P" + @PassWord + " -S" + @ServerName + " -T" + "'"
EXEC(@bcp)
SET @n=@n-1
END
DROP TABLE #T
</code></pre>
<p>Can anyone advise. This seems to be a connection problem or BCP ? Not sure. </p>
<p>edit: I am running this from query analyzer because I have 118 tables to output to flat file. I seem to agree that its an authentication issue because I tried connecting to master db with username sa password root. which is what its set to and I get the same error: SQLState = 37000, NativeError = 4060</p>
<p>Thanking you in advance.
EJ</p>
|
<p>Your brackets are extending over the entire qualified table name - only the individual components should be bracketed:</p>
<pre><code>bcp [HelpDesk-EasyPay].dbo.[customer] out d:\MSSQL\Data\customer.bcp -N -Utest -Ptest -T
</code></pre>
<p>should work, so you want:</p>
<pre><code>SET @bcp = "master..xp_cmdshell 'BCP " + "[" + @db + "]..[" + @TableName + "]" + " OUT" + @Path + "" + @TableName+".txt -c -U" + @UserName + " -P" + @PassWord + " -S" + @ServerName + " -T" + "'"
</code></pre>
<p>in your code. It looks like the error message you gave was truncated, otherwise you would have been able to see that it was attempting to open database "[HelpDesk-EasyPay.dbo.customer]" which, of course, does not exist, and even if it did, you would then get an error that no table was specified.</p>
|
How to determine which Child Page is being displayed from Master Page? <p>I'm writing code on the master page, and I need to know which child (content) page is being displayed. How can I do this programmatically? </p>
|
<p>I use this:</p>
<pre><code>string pageName = this.ContentPlaceHolder1.Page.GetType().FullName;
</code></pre>
<p>It retuns the class name in this format "ASP.default_aspx", but I find that easy to parse for most purposes.</p>
<p>Hope that helps!</p>
|
Is there a Python library function which attempts to guess the character-encoding of some bytes? <p>I'm writing some mail-processing software in Python that is encountering strange bytes in header fields. I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a <code>UnicodeDecodeError </code>.</p>
<p>So, I'm looking for a function that takes a <code>str</code> and optionally some hints and does its darndest to give me back a <code>unicode</code>. I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.</p>
<p>I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".</p>
|
<p>You may be interested in <a href="http://pypi.python.org/pypi/chardet">Universal Encoding Detector</a>.</p>
|
How do you use Ruby/DL? Is this right? <p>I am trying to write an interface between RSPEC (ruby flavoured BDD) and a Windows application. The application itself is written in an obscure language, but it has a C API to provide access. I've gone with Ruby/DL but am having difficulties getting even the most basic call to a DLL method to work. Here is what I have so far, in a file called gt4r.rb:</p>
<pre><code>require 'dl/import'
module Gt4r
extend DL::Importable
dlload 'c:\\gtdev\\r321\\bin\\gtvapi'
# GTD initialization/termination functions
extern 'int GTD_init(char *[], char *, char *)'
extern 'int GTD_initialize(char *, char *, char *)'
extern 'int GTD_done(void)'
extern 'int GTD_get_error_message(int, char **)'
end
</code></pre>
<p>My reading so far suggests that this is all I need to get going, so I wrote up a RSPEC example:</p>
<pre><code>require 'gt4r'
@@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini"
@@normal_user = "BMCHARGUE"
describe Gt4r do
it 'initializes' do
rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment
rv.should == 0
end
end
</code></pre>
<p>And when run...</p>
<pre><code>C:\code\GraphTalk>spec -fs -rgt4r gt4r_spec.rb
Gt4r
- initializes (FAILED - 1)
1)
'Gt4r initializes' FAILED
expected: 0,
got: 13 (using ==)
./gt4r_spec.rb:9:
Finished in 0.031 seconds
1 example, 1 failure
</code></pre>
<p>The return value (13) is an actual return code, meaning an error, but when I try to add the gTD_get_error_message call to my RSPEC, I can't get the parameters to work.</p>
<p>Am I heading in the right direction and can anyone point to the next thing I can try?</p>
<p>Thanks,
Brett</p>
<hr>
<p>A follow up to this question, showing the part that fails when I try to get the error message from my target library:</p>
<pre><code>require 'gt4r'
@@test_environment = "INCLUDE=C:\\graphtalk\\env\\aiadev\\config\\aiadev.ini"
@@normal_user = "BMCHARGUE"
describe Gt4r do
it 'initializes' do
rv = Gt4r.gTD_initialize @@normal_user, @@normal_user, @@test_environment
Gt4r.gTD_get_error_message rv, @msg
@msg.should == ""
rv.should == 0
end
end
</code></pre>
<p>I expect the error message to be returned in @msg, but when run I get the following:</p>
<pre><code>Gt4r
(eval):5: [BUG] Segmentation fault
ruby 1.8.6 (2008-08-11) [i386-mswin32]
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
</code></pre>
<p>And this if I use a symbol (:msg) instead:</p>
<pre><code>C:\code\GraphTalk\gt4r_dl>spec -fs -rgt4r gt4r_spec.rb
Gt4r
- initializes (ERROR - 1)
1)
NoMethodError in 'Gt4r initializes'
undefined method `to_ptr' for :msg:Symbol
(eval):5:in `call'
(eval):5:in `gTD_get_error_message'
./gt4r_spec.rb:9:
Finished in 0.046 seconds
1 example, 1 failure
</code></pre>
<p>Clearly I am missing something about passing parameters between ruby and C, but what?</p>
|
<p>The general consensus is you want to avoid DL as much as possible. The (english) documentation is quite sketchy and the interface is difficult to use for anything but trivial examples.</p>
<p>Ruby native C interface is MUCH easier to program against. Or you could use FFI, which fills a similiar niche to DL, originally comes from the rubinius project and has recently been ported to "normal" ruby. It has a nicer interface and is much less painful to use:</p>
<p><a href="http://blog.headius.com/2008/10/ffi-for-ruby-now-available.html">http://blog.headius.com/2008/10/ffi-for-ruby-now-available.html</a></p>
|
.NET Runtime 2.0 Error in a service <p>We have a custom service that writes to a DB (SQL 2005). This is a full 64-bit environment (DB, .NET service). On one of our servers we crash every morning when we have a spike in our volume of data. On another server we run fine. The only differences that I've been able to notice between the two machines is that the one experiencing the crash has .NET 3.5 also installed.</p>
<p>Has anyone else seen this type of behavior?</p>
<p>Here is the event log entry from the crash today:</p>
<p>Event Type: Error<br />
Event Source: .NET Runtime 2.0 Error Reporting<br />
Event Category: None<br />
Event ID: 1000<br />
Date: 11/6/2008<br />
Time: 09:35:03<br />
User: N/A<br />
Computer: RDDARWIN02<br />
Description:<br />
Faulting application servicehost.exe, version 2.0.6.6, stamp 48eb7b7a, faulting module kernel32.dll, version 5.2.3790.4062, stamp 462643a7, debug? 0, fault address 0x0000000000027d8d. </p>
<p>For more information, see Help and Support Center at <a href="http://go.microsoft.com/fwlink" rel="nofollow">http://go.microsoft.com/fwlink</a> /events.asp.<br />
Data:<br />
0000: 41 00 70 00 70 00 6c 00 A.p.p.l.<br />
0008: 69 00 63 00 61 00 74 00 i.c.a.t.<br />
0010: 69 00 6f 00 6e 00 20 00 i.o.n. .<br />
0018: 46 00 61 00 69 00 6c 00 F.a.i.l.<br />
0020: 75 00 72 00 65 00 20 00 u.r.e. .<br />
0028: 20 00 73 00 65 00 72 00 .s.e.r.<br />
0030: 76 00 69 00 63 00 65 00 v.i.c.e.<br />
0038: 68 00 6f 00 73 00 74 00 h.o.s.t.<br />
0040: 2e 00 65 00 78 00 65 00 ..e.x.e.<br />
0048: 20 00 32 00 2e 00 30 00 .2...0.<br />
0050: 2e 00 36 00 2e 00 36 00 ..6...6.<br />
0058: 20 00 34 00 38 00 65 00 .4.8.e.<br />
0060: 62 00 37 00 62 00 37 00 b.7.b.7.<br />
0068: 61 00 20 00 69 00 6e 00 a. .i.n.<br />
0070: 20 00 6b 00 65 00 72 00 .k.e.r.<br />
0078: 6e 00 65 00 6c 00 33 00 n.e.l.3.<br />
0080: 32 00 2e 00 64 00 6c 00 2...d.l.<br />
0088: 6c 00 20 00 35 00 2e 00 l. .5...<br />
0090: 32 00 2e 00 33 00 37 00 2...3.7.<br />
0098: 39 00 30 00 2e 00 34 00 9.0...4.<br />
00a0: 30 00 36 00 32 00 20 00 0.6.2. .<br />
00a8: 34 00 36 00 32 00 36 00 4.6.2.6.<br />
00b0: 34 00 33 00 61 00 37 00 4.3.a.7.<br />
00b8: 20 00 66 00 44 00 65 00 .f.D.e.<br />
00c0: 62 00 75 00 67 00 20 00 b.u.g. .<br />
00c8: 30 00 20 00 61 00 74 00 0. .a.t.<br />
00d0: 20 00 6f 00 66 00 66 00 .o.f.f.<br />
00d8: 73 00 65 00 74 00 20 00 s.e.t. .<br />
00e0: 30 00 30 00 30 00 30 00 0.0.0.0.<br />
00e8: 30 00 30 00 30 00 30 00 0.0.0.0.<br />
00f0: 30 00 30 00 30 00 32 00 0.0.0.2.<br />
00f8: 37 00 64 00 38 00 64 00 7.d.8.d.<br />
0100: 0d 00 0a 00 .... </p>
|
<p>Have you tried to attache a debugger to the running code before the crash? Maybe you can track down where the problem is.</p>
<p>You could also use adplus to get a dump of the process and then use that dump in windbg to help track down the problem. Something like this should give you the dump file you are looking for:</p>
<p>adplus -crash -pn servicehost.exe</p>
|
Access savedThis property in Function <p>When I'm in the flash debugger, and I have some callbacks saved, I can see that the functions have a property named <code>savedThis</code> that is very usefull to know where that callback came from.</p>
<p>I'm trying to access that property from code, but for some reason I can't.</p>
<p><code>callback.savedThis</code> throws an Error because it can't find the property, probable because it's private.</p>
<p>So I tried to add a method to the Function class that would give me access to it:</p>
<pre><code>Function.prototype.getSavedThis = function()
{
return this.savedThis
}
</code></pre>
<p>But it gives me the same error about not finding the property, even though I can see it in the debugger.
Is there a way to access it?</p>
<p><strong>Note</strong>: I'm not planing on using this in production code, I'm making some classes to help me with debugging by automating some data gathering, and it would be incredible useful to get this information without having to add code to every callback saved informing of the this object.</p>
|
<p>You can get a reference to a calling function by using the '<em>arguments.callee</em>' property.
<br/>For example:<br/></p>
<p><hr /></p>
<pre><code>bar( arguments.callee );
public function bar( caller:Function ) : void { trace( caller ); }
</code></pre>
|
Understanding JDBC internals <p>[1] In JDBC, why should we first load drivers using Class.forName("some driver name").
Why SUN didnt take care of loading driver within the getConnection() method itself.If I pass driver name as a parameter to the getConnection() method. </p>
<p>[2] I want to understand JBDC internals.Any pointers towards it are appreciated. </p>
|
<p>With JDBC 4, you no longer need to use Class.forName(...) see <a href="http://www.artima.com/lejava/articles/jdbc_four.html" rel="nofollow">here</a> for one article explaining this:</p>
<blockquote>
<p>Connection to a database requires that a suitable JDBC database driver be loaded in the client's VM. In the early days of JDBC, it was common to load a suitable driver via Class.forName(), passing in the name of the class implementing the JDBC Driver interface. The DriverManager class later offered a more flexible means of managing JDBC drivers in a client application. For a driver to become available, DriverManager's registerDriver() had to be invoked with the driver's class name. Alternatively, you could specify the drivers to load via the jdbc.drivers system property. When DriverManager initializes, it attempts to load the drivers associated with that property.</p>
<p>JDBC 4 adds the <strong><em>J2SE Service Provider</em></strong> mechanism as another means to specify database drivers. For this to work, driver JAR files must include the file META-INF/services/java.sql.driver. That file must contain a single line with the name of the JDBC driver's implementation of the Driver interface. Invoking getConnection() on DriverManager will load a driver so packaged, if needed. Upon loading the driver, an instance of the driver is created, and then registerDriver() is invoked to make that driver available to clients. </p>
</blockquote>
<p>Have a look at <a href="http://java.sun.com/products/jdbc/download.html" rel="nofollow">Sun's JDBC link</a> for more information on JDBC. The JDBC 4.0 Specification is relatively a nice read compared to some other specs...</p>
|
Opening an application inside a form - C# or VB.NET <p>I am writing an application and I would like to be able to display another application inside it. (Think like a windows form with a small box, or a tab that is displaying a totally seperate application.)</p>
<p>Is that something that can be done? If so, can anyone give some direction on how to go about doing it? </p>
<p>I am looking for something in the C# or VB.NET world.</p>
<p>THANKS! </p>
|
<p>You need a hWnd (handle) of window from another application.
Then you need a hWnd of container control in you application (System.Windows.Forms.Control.Handle property).</p>
<p>Then you need use a Win32API function <a href="http://www.pinvoke.net/default.aspx/user32/SetParent.html">SetParent</a>, and that all you need.
On the SetParent page is little sample, which should do what you need.</p>
|
.Net Data Handling Suggestions <p>I am just beginning to write an application. Part of what it needs to do is to run queries on a database of nutritional information. What I have is the USDA's <a href="http://www.ars.usda.gov/Services/docs.htm?docid=17478" rel="nofollow">SR21 Datasets</a> in the form of flat delimited ASCII files.</p>
<p>What I need is advice. I am looking for the best way to import this data into the app and have it easily and quickly queryable at run time. I'll be using it for all the standard things. Populating controls dynamically, Datagrids, calculations, etc. I will also need to do user specific persistent data storage as well. This will not be a commercial app, so hopefully that opens up the possibilities. I am fine with .Net Framework 3.5 so Linq is a possibility when accessing the data (just don't know if it would be the best solution or not). So, what are some suggestions for persistent storage in this scenario? What sort of gotchas should I be watching for? Links to examples are always appreciated of course. </p>
|
<p>It looks pretty small, so I'd work out an appropriate object model, load the whole lot into memory, and then use LINQ to Objects.</p>
<p>I'm not quite sure what you're asking about in terms of "persistent storage" - aren't you just reading the data? Don't you already have that in the text files? I'm not sure why you'd want to introduce anything else.</p>
|
How to validate .NET dialog items when using automatic DialogResult? <p>At the moment I have setup a custom ok cancel dialog with a drop down in c#. The ok and cancel buttons use the DialogResult property so no code behind it. What I now need to do is validate the drop down to check it isn't left empty before posting back a dialogresult.</p>
<p>Is this possible?</p>
|
<p>From <a href="http://www.functionx.com/vcsharp2003/Lesson06.htm" rel="nofollow">here</a></p>
<p>Double-click the Closing field, and implement it as follows:</p>
<pre><code>private void Second_Closing(object sender,
System.ComponentModel.CancelEventArgs e)
{
// When the user attempts to close the form, don't close it...
e.Cancel = (dropdown.selecteditemindex >= 0);
}
</code></pre>
|
How to Fix This MySQL Query So It Works? <p>I have the following query:</p>
<pre><code>UPDATE lessonstatus
INNER JOIN user ON lessonstatus.user_id = user.user_id
SET user_id = (SELECT user_id FROM user WHERE username = 'too_many_accounts')
WHERE last_name = 'stupid'
AND first_name = 'user'
AND username != 'too_many_accounts'
AND lessonstatus.lesson_id NOT IN (SELECT lesson_id FROM lessonstatus WHERE user_id = 1);
</code></pre>
<p>However, I get the following error when trying to execute it:</p>
<pre><code>Error Code : 1093
You can't specify target table 'lessonstatus_rtab' for update in FROM clause
</code></pre>
<p>How would I fix this query so that it works?</p>
|
<p>You can't <code>SELECT</code> from a table (even in a subquery) that you're updating in the same query. That's what the error "can't specify target table" means.</p>
<p>But you can join <code>user</code> and <code>lessonstatus</code> multiple times in the <code>UPDATE</code> statement, and use the join criteria creatively to pick out the individual row you want.</p>
<p>The way to simulate <code>NOT IN</code> with a join is to do a <code>LEFT OUTER JOIN</code>. Where the right side of that join is not matched, that's where <code>NOT IN</code> would be true.</p>
<pre><code>UPDATE lessonstatus l1
INNER JOIN user u1 ON (l1.user_id = u1.user_id)
INNER JOIN user u2 ON (u2.username = 'too_many_accounts')
LEFT OUTER JOIN lessonstatus l2
ON (l1.lesson_id = l2.lesson_id AND l2.user_id = 1)
SET l1.user_id = u2.user_id
WHERE u1.last_name = 'stupid' AND u1.first_name = 'user'
AND u1.username != 'too_many_accounts'
AND l2.lesson_id IS NULL; -- equivalent to "l NOT IN l2"
</code></pre>
<p><strong>nb:</strong> I have tested this query for syntax, but not with real data. Anyway, it should get you started.</p>
|
Emacs and cygwin <p>How can I change my GNUemacs to open up a cygwin terminal rather then a cmd one with the shell command?</p>
<blockquote>
<p><strong>Closed</strong> as duplicate of <a href="http://stackoverflow.com/questions/235254/how-can-i-run-cygwin-bash-shell-from-within-emacs">How can I run Cygwin Bash Shell from within Emacs?</a>.</p>
</blockquote>
|
<p>See question <a href="http://stackoverflow.com/questions/235254/how-can-i-run-cygwin-bash-shell-from-within-emacs">How can I run Cygwin Bash Shell from within Emacs?</a>. </p>
|
Does OCaml have general map()/reduce() functions? <p>In Python map() works on any data that follows the sequence protocol. It does The Right Thing^TM whether I feed it a string or a list or even a tuple.</p>
<p>Can't I have my cake in OCaml too? Do I really have no other choice but to look at the collection type I'm using and find a corresponding List.map or an Array.map or a Buffer.map or a String.map? Some of these don't even exist! Is what I'm asking for unusual? I must be missing something.</p>
|
<p>The closest you will get to this is the module <a href="http://batteries.forge.ocamlcore.org/doc.preview/batteries-alpha1/batteries/html/api/Data.Mutable.Enum.html"><code>Enum</code></a> in <a href="http://batteries.forge.ocamlcore.org/">OCaml Batteries Included</a> (formerly of <a href="http://ocaml-extlib.googlecode.com/">Extlib</a>). <code>Enum</code> defines maps and folds over <code>Enum.t</code>; you just have to use a conversion to/from <code>Enum.t</code> for your datatype. The conversions can be fairly light-weight, because <code>Enum.t</code> is lazy.</p>
<p>What you really want is Haskell-style <a href="http://en.wikipedia.org/wiki/Type_class">type classes</a>, like <code>Foldable</code> and <code>Functor</code> (which generalizes "maps"). The Haskell libraries define instances of <code>Foldable</code> and <code>Functor</code> for lists, arrays, and trees. Another relevant technique is the <a href="http://www.cs.vu.nl/boilerplate/">"Scrap Your Boilerplate" approach</a> to generic programming. Since OCaml doesn't support type classes or <a href="http://lambda-the-ultimate.org/node/2579">higher-kinded polymorphism</a>, I don't think you'd be able to express patterns like these in its type system.</p>
|
Scope of Oracle transactions when used from ADO.NET and involving triggers? <p>I am told by someone that when calling Oracle from ADO.net, when calling multiple inserts in a loop, where each insert causes a trigger to fire that includes within it's PL-Sql a Commit statement, that it is impossible to stop that commit from actually commiting the transaction.</p>
<p>i.e., I want my ADO.Net code to begin a transaction before the loop starts, and, when the loop exits, only commit all the inserts if and only if every insert in the loop was successful. My source is telling me that the way Oracle works, if these triggers include COmmit statements, then this is impossible.. </p>
<p>As this seems to be an very common requirement, and I know it is possible in SQL Server, this does not seem right to me. </p>
<p>Is this correct? </p>
|
<p>Your informant is wrong, if he is talking about Oracle database triggers:</p>
<p>1) You <strong>cannot</strong> put a COMMIT in an Oracle trigger that is not autonomous:</p>
<pre><code>SQL> create trigger this_wont_work
2 after insert on emp
3 begin
4 commit;
5 end;
6 /
Trigger created.
SQL> insert into emp (empno) values (123)
2 /
insert into emp (empno) values (123)
*
ERROR at line 1:
ORA-04092: cannot COMMIT in a trigger
ORA-06512: at "TONY.THIS_WONT_WORK", line 2
ORA-04088: error during execution of trigger 'TONY.THIS_WONT_WORK'
</code></pre>
<p>2) If the trigger is autonomous (i.e. has PRAGMA AUTONOMOUS_TRANSACTION in its declaration section) then it can only commit any changes it (the trigger) makes.</p>
<p>There is no danger whatsoever of a trigger committing work you did outside of that trigger.</p>
<p>Note: the use of autonomous transactions in triggers is dangerous except for certain cases, because actions performed by the autonomous trigger will be committed even if the triggering statement is rolled back. This can easily lead to data corruption if mis-used.</p>
|
JavaScript: Ci is not defined <p>I just spent half an one our to find out what caused the Error-Message "Ci is not defined" in my JavaScript code. I finally found the reason:</p>
<p>It should be (jQuery):</p>
<pre><code>$("asd").bla();
</code></pre>
<p>It was:</p>
<pre><code>("asd").bla();
</code></pre>
<p>(Dollar sign gone missing)</p>
<p>Now after having fixed the problem I'd like to understand the message itself: What does Firefox mean when it tells me that "Ci" is not defined. What's "Ci"?</p>
<p><hr></p>
<p>Update:
I'm using the current version of Firefox (3.0.3).</p>
<p>To reproduce, just use this HTML code:</p>
<pre><code><html><head><title>test</title>
<script>
("asd").bla();
</script>
</head><body></body></html>
</code></pre>
<p>To make it clear: I know what caused the error message. I'd just like to know what Firefox tries to tell me with "Ci"...</p>
|
<p>I don't know which version of FF you are using, but regardless, the message is probably referring to the fact that <code>bla()</code> is not a function available on the String object. Since you were missing the <code>$</code>, which means you were missing a function, <code>("asd")</code> would evaluate to a string, and then the JavaScript interpreter would try to call <code>bla()</code> on that object. So, if you had the following code in your project:</p>
<pre><code>String.prototype.bla = function() {};
// now this next line will execute without any problems:
("asd").bla();
</code></pre>
<p>So, it is possible that <code>Ci</code> is some internal Firefox symbol that simply refers to the idea of a function. That is my guess, I imagine you are going to need someone that knows something about Firefox's internals to get a better answer to this question...</p>
<p><hr /></p>
<p>UPDATE: I am running your example code in the <em>exact</em> same version of FF as you are, but it reports the error as:</p>
<blockquote>
<p>Error: "asd".bla is not a function<br />
Source File: file:///C:/test.html<br />
Line: 3</p>
</blockquote>
<p>Perhaps you have an extension/plug-in running that does something with this? Maybe some Greasemonkey script or something?</p>
|
Iterate through generic list of unknown type at runtime in VB.Net <p>Does anyone know how to iterate over a generic list if the type of that list isn't known until runtime?</p>
<p>For example, assume <code>obj1</code> is passed into a function as an <code>Object</code>:</p>
<pre><code>Dim t As Type = obj1.GetType
If t.IsGenericType Then
Dim typeParameters() As Type = t.GetGenericArguments()
Dim typeParam As Type = typeParameters(0)
End If
</code></pre>
<p>If <code>obj</code> is passed as a <code>List(Of String)</code> then using the above I can determine that a generic list (<code>t</code>) was passed and that it's of type <code>String</code> (<code>typeParam</code>). I know I am making a big assumption that there is only one generic parameter, but that's fine for this simple example.</p>
<p>What I'd like to know is, based on the above, how do I do something like this:</p>
<pre><code>For Each item As typeParam In obj1
'do something with it here
Next
</code></pre>
<p>Or even something as simple as getting <code>obj1.Count()</code>.</p>
|
<p>The method that iterates over your list can specify a generic type:</p>
<pre><code>Public Sub Foo(Of T)(list As List(Of T))
For Each obj As T In list
..do something with obj..
Next
End Sub
</code></pre>
<p>So then you can call:</p>
<pre><code>Dim list As New List(Of String)
Foo(Of String)(list)
</code></pre>
<p>This method makes the code look a little hairy, at least in VB.NET. </p>
<p>The same thing can be accomplished if you have the objects that are in the list implement a specific interface. That way you can populate the list with any object type as long as they implement the interface, the iteration method would only work on the common values between the object types.</p>
|
Kill Derby DB Network Server on background <p>I'm looking for a good way to run a Apache Derby server in network mode. I'm using the NetworkServerControl to start the server and it's working great.</p>
<p>I start the server like this:</p>
<pre><code>/**
* starts the network server
* @return true if sucessfull
*/
public boolean start()
{
try
{
// just to be sure that we don't start two servers
this.stop();
server = new NetworkServerControl();
server.start( null );
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
</code></pre>
<p>And stop it like this:</p>
<pre><code>/**
* stops the server
*
* @return true if there were no problems stopping the server
*/
public boolean stop()
{
try
{
if ( server == null )
{
server = new NetworkServerControl();
}
server.shutdown();
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
</code></pre>
<p>On the main() I have this so the process doesn't die while the server is running</p>
<pre><code>(...)
clsDB.start();
while( clsDB.testForConnection() )
{
Thread.sleep( 60000 );
}
</code></pre>
<p>testForConnection() looks like this:</p>
<pre><code>/**
* Try to test for a connection
*
* @return true if the server is alive
*/
public boolean testForConnection()
{
try
{
server.ping();
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
</code></pre>
<p>My problem is that when a new instace of my JAR is called the old one will still be running (unless I'm really really lucky and the test is made before the new server is started).</p>
<p>I know I could just test if the server is already running and then I wouldn't start again, but I would like for start to work like a restart if the server is already there.</p>
|
<p>I did a project awhile ago with derby (including running in network mode), and I seem to remember that there is some SQL you can execute on the server which shuts derby down.</p>
<p>So, assuming that's the case (no time to google for it atm sorry) you could, on start up, look for your network instance. If it exists, run this SQL on it. Once you have determined that it's finally shut down (polling that it exists I suppose) you can then start it up again.</p>
<p><strong>Edit:</strong> Oh, it wasn't SQL, it's connecting to the DB with 'shutdown=true' as a parameter. See <a href="http://db.apache.org/derby/docs/dev/devguide/tdevdvlp40464.html" rel="nofollow">here</a>:</p>
<pre><code>DriverManager.getConnection(
"jdbc:derby:sample;shutdown=true");
</code></pre>
|
Tests Projects In Solution <p>In .NET should you place unit test projects in with the rest of the solution? Or should there be a test solution that houses all the test projects?</p>
<p>We have all the test projects in with our code base solution...it seems a bit cumbersome. </p>
<p>What do you usually do?</p>
|
<p>In our current project we decided to put all unit tests in separate projects. The application code and tests are in the same solution, but at least we can build (and deploy) a version without the unit test code.</p>
<p>The downside of this -so far- has been that sometimes your unit tests can't reach certain members of the application code (protected and internals), but that usually lead us to discover that our design could be improved.</p>
<p>And I guess I should point out a similar thread <a href="http://stackoverflow.com/questions/271808/write-unit-tests-into-an-assembly-or-in-a-separate-assembly">Here</a> with more answers on the same/similar topic.</p>
|
Is it possible to change headers on an S3 object without downloading the entire object? <p>I've uploaded a bunch of images to Amazon S3, and now want to add a Cache-Control header to them. </p>
<p>Can the header be updated without downloading the entire image? If so, how?</p>
|
<p>It's beta functionality, but you can specify new meta data when you <a href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTObjectCOPY.html">copy an object</a>. Specify the same source and destination for the copy, and this has the effect of just updating the meta data on your object.</p>
<pre><code>PUT /myObject HTTP/1.1
Host: mybucket.s3.amazonaws.com
x-amz-copy-source: /mybucket/myObject
x-amz-metadata-directive: REPLACE
x-amz-meta-myKey: newValue
</code></pre>
|
SetSecurityDescriptorSddlForm(string sddlForm) <p>I dont find any usefull website according to this API.</p>
<p>What's the format of the String? The content?</p>
<p>Thanks</p>
|
<p>The Security Descriptor String Format is defined <a href="http://msdn.microsoft.com/en-us/library/aa379570(VS.85).aspx" rel="nofollow">here</a></p>
|
Difference between a LinkedList and a Binary Search Tree <p>What are the main differences between a Linked List and a BinarySearchTree? Is BST just a way of maintaining a LinkedList? My instructor talked about LinkedList and then BST but did't compare them or didn't say when to prefer one over another. This is probably a dumb question but I'm really confused. I would appreciate if someone can clarify this in a simple manner.</p>
|
<p>Linked List:</p>
<pre><code>Item(1) -> Item(2) -> Item(3) -> Item(4) -> Item(5) -> Item(6) -> Item(7)
</code></pre>
<p>Binary tree:</p>
<pre><code> Node(1)
/
Node(2)
/ \
/ Node(3)
RootNode(4)
\ Node(5)
\ /
Node(6)
\
Node(7)
</code></pre>
<p>In a linked list, the items are linked together through a single next pointer.
In a binary tree, each node can have 0, 1 or 2 subnodes, where (in case of a binary search tree) the key of the left node is lesser than the key of the node and the key of the right node is more than the node. As long as the tree is balanced, the searchpath to each item is a lot shorter than that in a linked list.</p>
<p>Searchpaths:</p>
<pre><code>------ ------ ------
key List Tree
------ ------ ------
1 1 3
2 2 2
3 3 3
4 4 1
5 5 3
6 6 2
7 7 3
------ ------ ------
avg 4 2.43
------ ------ ------
</code></pre>
<p>By larger structures the average search path becomes significant smaller:</p>
<pre><code>------ ------ ------
items List Tree
------ ------ ------
1 1 1
3 2 1.67
7 4 2.43
15 8 3.29
31 16 4.16
63 32 5.09
------ ------ ------
</code></pre>
|
Finding Unique Table/Column Combinations Across SQL Databases <p>I have 4 databases with similar schema's, and I'm trying to create a query to return just the table, column pairs that exist ONLY in database 1 and do not exist in database 2, 3, or 4.</p>
<p>Currently I can return the symmetric difference between database 1 and 2 via the following query...</p>
<pre><code>select table_name, column_name from (
select table_name, column_name from [Database1].information_schema.columns
union all
select table_name, column_name from [Database2].information_schema.columns) as tmp
group by table_name, column_name having count(*) = 1
</code></pre>
<p>However, in trying to isolate just those columns in database 1, and doing the same across all 4 databases, things are getting complicated. What is the cleanest solution for this query?</p>
|
<pre><code>SELECT
D1.table_name,
D1.column_name
FROM
Database1.information_schema.columns D1
LEFT OUTER JOIN Database2.information_schema.columns D2 ON
D2.table_name = D1.table_name AND
D2.column_name = D1.column_name
LEFT OUTER JOIN Database3.information_schema.columns D3 ON
D3.table_name = D1.table_name AND
D3.column_name = D1.column_name
LEFT OUTER JOIN Database4.information_schema.columns D4 ON
D4.table_name = D1.table_name AND
D4.column_name = D1.column_name
WHERE
D2.table_name IS NULL AND
D3.table_name IS NULL AND
D4.table_name IS NULL
</code></pre>
|
<%# Eval("State") %> or <%# DataBinder.Eval(Container.DataItem, "state")%> <p>What is the difference between having</p>
<pre class="lang-java prettyprint-override"><code><%# Eval("State") %>
</code></pre>
<p>in your <code>aspx</code> page, versus having</p>
<pre class="lang-java prettyprint-override"><code><%# DataBinder.Eval(Container.DataItem, "State") %>
</code></pre>
<p>in your <code>aspx</code> page?</p>
|
<p>Eval("State") is a simplified form of the DataBinder.Eval(Container.DataItem, "State") syntax. It only works inside of data-bound template controls.</p>
<p>For more info, see <a href="http://msdn.microsoft.com/en-us/library/ms178366.aspx">the MSDN documentation</a>.</p>
|
Help getting QTP to identify a control <p>We're trying to use QTP (QuickTest Professional) to auto-test a legacy C++ application.</p>
<p>However, the main window for the app is composed of several IDENTICAL panels. Each panel has a unique title.</p>
<p>If I view the window in Spy++ (comes with DevStudio), I see:</p>
<pre><code>+ Window <hwnd> "Window Title" taskwindowclass
+ Window <hwnd> "Panel A" childwindowclass
+ Window <hwnd> "OK" Button
+ Window <hwnd> "Panel B" childwindowclass
+ Window <hwnd> "OK" Button
</code></pre>
<p>In QTP's Object Spy however, the hierarchy shows as:</p>
<pre><code>+ Window: Window Title
+ WinButton: OK
</code></pre>
<p>It doesn't even show that there is an intermediate panel.</p>
<p>Does anybody know a way to get the window "path" in order to identify each control?
i.e. so the controls identify as:</p>
<pre><code>Button A: "Window Title/Panel A/OK"
Button B: "Window Title/Panel B/OK"
</code></pre>
|
<p>You could use descriptive programming to bypass the object map. QTP will ignore panel objects by default. You could try to get a reference to the panel object dynamically, then search the ChildObjects collection to find the ok button. Another option might be to simply add an ordinal identifier to the ok buttons. </p>
<ul>
<li>Button A: "Window Title/OK index #1"</li>
<li>Button B: "Window Title/OK index #2"</li>
</ul>
|
Is there some list of input's IDs or names of Form after the script was sent? <p>Let's imagine I got this:</p>
<p>index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php</p>
<pre><code><form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>
</code></pre>
<p>Script.php:</p>
<p>Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.</p>
<p>Is there a way to do this?</p>
|
<p>i may be missing something in your question, but the <code>$_POST</code> variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:</p>
<pre><code>print_r($_POST);
// contains:
array
(
[1] => 1
[24] => 2233
[55] => 231321
)
// example access:
foreach($_POST as $name => $value) {
print "Name: {$name} Value: {$value} <br />";
}
</code></pre>
|
Lambda Expressions in Delphi Prism/Oxygene <p>I have been experimenting with Lambda expressions in Oxygene. Very simple recursive lambda expression to calculate a fibonacci number :</p>
<pre><code>var fib : Func<int32, int32>;
fib := n -> iif(n > 1, fib(n - 1) + fib(n - 2), n);
fib(3);
</code></pre>
<p>When I run this code I get a nullreferenceexception. Any ideas as to what I'm doing wrong?</p>
|
<p>You aren't doing anything wrong. If anything, the compiler should warn you about using fib, an unassigned variable, inside the body of the lambda.</p>
<p>However the compiler ought to be capturing fib as a location, so that when the assignment completes and the delegate is later invoked, fib is properly assigned and recursion should work as expected.</p>
<p>The most obvious possible reason for the failure is that Prism isn't capturing locations, but values, which would be grossly unintuitive and at odds with every other closure implementation in non-pure languages.</p>
<p>For example, try this code in JavaScript (contrary to Craig's assertion in the comments to this post, JavaScript also captures locations, not values):</p>
<pre><code><html>
<head>
<script language='javascript'>
function main()
{
var x = 1;
var f = function() { return x; };
alert(f());
x = 2;
alert(f());
}
</script>
</head>
<body>
<input type=button onclick="javascript:main()"></input>
</body>
</html>
</code></pre>
<p>The alert boxes after you click on the button show 1 and 2 respectively, while following Prism/Oxygene semantics they would show 1 both times.</p>
|
jquery round corners <p>This probably sounds really stupid but I have noo idea how to implement jquery's rounded corners (<a href="http://www.methvin.com/jquery/jq-corner-demo.html" rel="nofollow">http://www.methvin.com/jquery/jq-corner-demo.html</a>). My javascript-fu is complete fail and I can't seem to get it to work on my page. Can anyone show me a simple example of the HTML and JavaScript you would use to get them to show? Apologies for my idiocy.</p>
|
<ol>
<li>This thing does not work in Safari & Google Chrome.</li>
<li><p>You need to include <a href="http://jqueryjs.googlecode.com/files/jquery-1.2.6.js" rel="nofollow">jquery.js</a> in your page. Don't forget to have a separate closing tag.</p>
<p><code><script type="text/javascript" src="jquery.js"></script></code></p></li>
<li><p>You need to include the jQuery Corner Plugin JavaScript file (<a href="http://www.methvin.com/jquery/jquery.corner.js" rel="nofollow">jquery.corner.js</a>) in your page as well.</p>
<p><code><script type="text/javascript" src="jquery.corner.js"></script></code></p></li>
<li><p>Somewhere in your page you should have the <code><div></code> you want to have corners:</p>
<p><code><div id="divToHaveCorners" style="width: 200px; height: 100px; background-color: #701080;">Hello World!</div></code> </p></li>
<li><p>Somewhere else in your page, preferably not before the div itself, issue the following JavaScript command. This will execute the inner function when the page is loaded and is ready to be manipulated.</p>
<p><code><script type="text/javascript">$(function() { $('#divToHaveCorners').corner(); } );</script></code></p></li>
<li><p>You're done! If not, let me know.</p></li>
</ol>
|
SQL Deletion Cascading Help (Specific Question) <p>I have two tables (renamed/refactored for illustrative purposes) with a Many-To-Many relationship in an HSQL database. I want everything to be wiped out when I delete from one side of a Many-to-Many relationship (without querying the table; this is performance critical)</p>
<p>Here are my main tables:</p>
<pre><code>CREATE TABLE PERSON
(
PERSON_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
NAME VARCHAR(50)
)
CREATE TABLE JOB
(
JOB_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
NAME VARCHAR(50)
)
</code></pre>
<p>Here is my join table:</p>
<pre><code>CREATE TABLE JOB_PERSON
(
PERSON_ID INTEGER,
JOB_ID INTEGER
)
</code></pre>
<p>Here are my constraints:</p>
<pre><code>ALTER TABLE JOB_PERSON ADD
CONSTRAINT FK_PERSON_JOB FOREIGN KEY(PERSON_ID)
REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE JOB_PERSON ADD
CONSTRAINT FK_JOB_PERSON FOREIGN KEY(JOB_ID)
REFERENCES JOB ON DELETE CASCADE ON UPDATE CASCADE
</code></pre>
<p>I basically want to do this: "delete from person where person_id=0" and have it delete everything from PERSON, JOB_PERSON and JOB if the JOB entity will be orphaned (no longer referenced in the many to many table)</p>
<p>Is this possible without querying the database? When I delete, it only deletes from PERSON and JOB_PERSON. As you can probably tell, my sql skills are lacking.</p>
<p>Here is the dummy data I have been playing around with:</p>
<pre><code>insert into person values(null,'Arthur');
insert into person values(null,'James');
insert into job values(null, 'Programmer')
insert into job values(null, 'Manager')
insert into job_person values(0,0);
insert into job_person values(0,1);
insert into job_person values(1,1);
</code></pre>
<p>So if I enter both of these statements: </p>
<pre><code>delete from person where person_id=0
delete from person where person_id=1
</code></pre>
<p>I would like to have everything in all 3 tables deleted. Possible?</p>
|
<p>Create a Store Procedure where you pass the ID, then simply DELETE the proper row in the order you need to.</p>
<p>This way your app isn't tied to the exact order, which might change in the future with DB redesigns. You also gain the added bonus that Stored Procs are faster then sending a bunch of queries.</p>
<p>Although if you absolutely wanted a way to delete the dependent tables when you try to delete that entry, you have to use triggers, but the rule for triggers are, avoid them whenever possible, if another solution exists, use it. So ultimately, using a Stored Proc is the best solution.</p>
|
How to encrypt in VBScript using AES? <p>I am looking to encrypt some data using <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard">Rijndael/AES</a> in <a href="http://en.wikipedia.org/wiki/VBScript">VBScript</a> using a specific key and <a href="http://en.wikipedia.org/wiki/Initialization_vector">IV</a> value. Are there any good function libraries or COM components that would be good to use?</p>
<p>I looked at <a href="http://en.wikipedia.org/wiki/CAPICOM">CAPICOM</a>; it allows a passphrase only, and won't allow setting specific key and IV values.</p>
|
<p>One response suggested wrapping the <code>RijndaelManaged</code> class in COM. You could also wrap some other AES implementation in COM. I just tried <a href="http://code.google.com/p/slowaes" rel="nofollow">SlowAES</a>, which is a JavaScript implementation of AES. Wrapping it in COM via a Windows Script Component makes it callable from VBScript. I would recommend this only if you cannot use the .NET approach; I would guess the AES for .NET will be faster than the AES implemented in JavaScript. </p>
<p>In my tests of the COM-wrapped-SlowAEs, I used CBC mode, and the encryption was completely compatible with the RijndaelManaged class in .NET. </p>
<p>Here's the WSC; I left out the 3 .js files provided by SlowAES. You need to insert them unchanged where I marked the file. </p>
<pre><code><?xml version="1.0"?>
<!--
//
// Ionic.COM.SlowAES.wsc
//
// This is a Windows Script Component that exposes the SlowAES
// encryption engine via COM. This AES can be used from any
// COM-capable environment, including Javascript or VBScript.
//
//
// This code is licensed under the Microsoft Public License. See the
// accompanying License.txt file for details.
//
// Copyright 2009 Dino Chiesa
//
-->
<package>
<component id="Ionic.Com.SlowAES">
<comment>
SlowAES is a Javascript implementation of AES.
See http://code.google.com/p/slowaes.
This is a COM package for SlowAES.
</comment>
<?component error="true" debug="true"?>
<registration
description="WSC Component for SlowAES"
progid="Ionic.Com.SlowAES"
version="1.00"
classid="{ba78383f-1bcc-4df6-9fb9-61cd639ebc94}"
remotable="False">
<!-- boilerplate registration/unregistration logic -->
<script language="VBScript">
<![CDATA[
strComponent = "Ionic SlowAES"
Function Register
MsgBox strComponent & " - registered."
End Function
Function Unregister
MsgBox strComponent & " - unregistered."
End Function
]]>
</script>
</registration>
<public>
<method name="EncryptString">
<parameter name="plainText"/>
</method>
<method name="DecryptBytes">
<parameter name="cipherText"/>
</method>
<method name="DecryptBytesToString">
<parameter name="cipherText"/>
</method>
<method name="DecryptHexString">
<parameter name="hexStringCipherText"/>
</method>
<method name="DecryptCommaDelimitedStringToString">
<parameter name="cipherText"/>
</method>
<property name="Key">
<put/>
</property>
<property name="Mode">
<put/>
<get/>
</property>
<property name="IV">
<put/>
<get/>
</property>
<property name="KeySize">
<put/>
<get/>
</property>
</public>
<script language="JavaScript">
<![CDATA[
// ...insert slowAES code here... //
// defaults
var _keysize = slowAES.aes.SIZE_128;
var _mode = slowAES.modeOfOperation.CBC;
var _iv = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
var _key;
/*
* byteArrayToHexString
* convert a byte array to hex string.
*/
function byteArrayToHexString(a)
{
try { hexcase } catch(e) { hexcase=0; }
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var r= "";
for (var i = 0; i < a.length; i++)
{
var b = hex_tab.charAt((a[i] >> 4) & 0x0F) +
hex_tab.charAt(a[i] & 0x0F);
r+= b;
}
return r;
}
/*
* hexStringToByteArray
* convert a string of hex byts to a byte array
*/
function hexStringToByteArray(s)
{
var r= Array(s.length/2);
for (var i = 0; i < s.length; i+=2)
{
r[i/2] = parseInt(s.substr(i,2),16);
}
return r;
}
function EncryptString(plainText)
{
var bytesToEncrypt = cryptoHelpers.convertStringToByteArray(plainText);
var result = slowAES.encrypt(bytesToEncrypt,
_mode,
_key,
_keysize,
_iv);
return result['cipher'];
}
function DecryptBytesToString(cipherText)
{
var d = DecryptBytes(cipherText);
var s = cryptoHelpers.convertByteArrayToString(d);
s[cipherText.length]= 0;
return s;
}
function DecryptHexString(hexStringCipherText)
{
var cipherText = hexStringToByteArray(hexStringCipherText);
return DecryptBytesToString(cipherText);
}
function DecryptCommaDelimitedStringToString(cipherText)
{
var c = [];
var atoms = cipherText.split(",");
for (i=0; i < atoms.length; i++)
{
c.push(parseInt(atoms[i], 10));
}
var d = DecryptBytes(c);
return cryptoHelpers.convertByteArrayToString(d);
}
function DecryptBytes(cipherText)
{
if (cipherText == undefined) return null;
var originalSize = cipherText.length;
var result = slowAES.decrypt(cipherText,
originalSize,
_mode,
_key,
_keysize,
_iv);
return result;
}
function put_Key(keyString)
{
_key = hexStringToByteArray(keyString);
}
function put_KeySize(size)
{
if (size == 128) _keysize = slowAES.aes.keySize.SIZE_128;
else if (size == 192) _keysize = slowAES.aes.keySize.SIZE_192;
else if (size == 256) _keysize = slowAES.aes.keySize.SIZE_256;
else
throw "Unsupported key size. Must be one of { 128, 192, 256 }.";
}
function get_KeySize()
{
if (_keysize == slowAES.aes.keySize.SIZE_128) return 128;
else if (_keysize == slowAES.aes.keySize.SIZE_192) return 192;
else if (_keysize == slowAES.aes.keySize.SIZE_256) return 256;
else return -1;
}
function put_IV(ivString)
{
_iv = hexStringToByteArray(ivString);
}
function get_IV()
{
return byteArrayToHexString(_iv);
}
function put_Mode(mode)
{
if (mode == "CBC") _mode= slowAES.modeOfOperation.CBC;
else if (mode == "OFB") _mode= slowAES.modeOfOperation.OFB;
else if (mode == "CFB") _mode= slowAES.modeOfOperation.CFB;
else throw "Unsupported mode. Must be one of {CBC, OFB, CFB}";
}
function get_Mode()
{
if (_mode == slowAES.modeOfOperation.CBC) return "CBC";
if (_mode == slowAES.modeOfOperation.OFB) return "OFB";
if (_mode == slowAES.modeOfOperation.CFB) return "CFB";
return "???";
}
]]>
</script>
</component>
</package>
</code></pre>
<p>Save that to a file called SlowAES.wsc. Register it with "regsvr32 SlowAES.wsc."
Here's some VBScript code that uses the component.</p>
<pre><code>' '
' byteArrayToHexString'
' convert a byte array to hex string.'
' '
Function byteArrayToHexString(a)
Dim r,b,i
r = ""
For i = 0 To UBound(a)
b = Hex( (a(i) And &HF0) / 16) & Hex(a(i) And &HF)
r= r & b
Next
byteArrayToHexString= r
End Function
' '
' hexStringToByteArray'
' convert a string of hex byts to a byte array'
' '
Function hexStringToByteArray(s)
Dim r()
ReDim r(Len(s)/2-1)
Dim x
For i = 0 To Len(s)-2 Step 2
x= "&H" & Mid(s,i+1,2)
r(i/2) = CInt(x)
Next
hexStringToByteArray= r
End Function
Function DemoEncryption()
WScript.echo "Testing Ionic.Com.SlowAES..."
WScript.echo "key: " & byteArrayToHexString(key)
WScript.echo "iv: " & byteArrayToHexString(iv)
WScript.echo "key length: " & keyLengthInBytes & " bytes"
WScript.echo "key length: " & (keyLengthInBytes*8) & " bits"
WScript.echo "plaintext: " & plaintext
WScript.echo "plaintext.length: " & Len(plaintext)
WScript.echo "instantiate Ionic.Com.SlowAES"
Dim aes
set aes = CreateObject("Ionic.Com.SlowAES")
WScript.echo "keysize"
aes.KeySize = keyLengthInBytes * 8
WScript.echo "key"
aes.Key = byteArrayToHexString(key)
WScript.echo "iv "
aes.IV= byteArrayToHexString(iv)
WScript.echo "mode "
aes.Mode = "CBC"
WScript.echo "encrypting... "
Dim result
result= aes.EncryptString(plaintext)
' result is a comma-separated string '
' if we Eval() on it we convert it to an array '
Dim expr
expr = "Array(" & result & ")"
result= Eval( expr )
WScript.echo "Cryptotext/Eval: " & byteArrayToHexString(result)
WScript.echo "Cryptotext.length: " & UBound(result)+1
WScript.echo "decrypting... "
Dim decrypted
'The javascript way to do this is to pass the byte array.'
' Like so:'
' var decrypted = aes.DecryptBytesToString(result);'
' '
'This does not work from VBScript. So, convert to a hexstring,'
'pass the hex string, and then convert back, in the COM component.'
decrypted= aes.DecryptHexString(byteArrayToHexString(result))
WScript.echo "decrypted: " & decrypted
End Function
dim plaintext, iv, key, keyLengthInBytes
plaintext= "Hello. This is a test. of the emergency broadcasting system."
' iv must be a hexstring representation of an array of bytes, length=16'
iv = hexStringToByteArray("feedbeeffeedbeefbaadf00dbaadf00d")
' key must be a hexstring representation of an array of bytes, length=16 or 32'
key = hexStringToByteArray("cafebabe0099887766554433221100AA")
keyLengthInBytes= UBound(key)+1
If Err.Number <> 0 Then Err.Clear
Call DemoEncryption
If (Err.Number <> 0) Then WScript.echo("Error: " & Err.Description)
</code></pre>
<p>If you also want a password-based key derivation capability, then you can grab <a href="http://anandam.name/pbkdf2/" rel="nofollow">the very succint JavaScript code for PBKDF2 here</a>, and <a href="http://cheeso.members.winisp.net/srcview.aspx?dir=AES-example&file=Ionic.Com.PBKDF2.wsc" rel="nofollow">create another WSC for that</a>, without too much trouble.</p>
<hr>
<p><strong>EDIT</strong>: I did what I described - grabbed the source for PBKDF2 and integrated it into the code for SlowAES. I also produced a second, independent implementation in C# that uses the built-in .NET class libraries to do the RFC 2898-key derivation and AES encryption. </p>
<p>The result is 3 test applications, one in C#, one in JavaScript and another in VBScript. <a href="http://cheeso.members.winisp.net/srcview.aspx?dir=AES-example" rel="nofollow">The source is available</a>. They all take the same set of arguments. They each use a <a href="http://tools.ietf.org/html/rfc2898" rel="nofollow">RFC 2898</a>-compliant key derivation function. You can specify the password, <a href="http://en.wikipedia.org/wiki/Salt_%28cryptography%29" rel="nofollow">salt</a>, <a href="http://en.wikipedia.org/wiki/Initialization_vector" rel="nofollow">IV</a>, and plaintext, as well as the number of RFC 2898 iterations to use in the <a href="http://en.wikipedia.org/wiki/PBKDF2" rel="nofollow">PBKDF2</a>. You can easily verify that the ciphertext is the same for each of these test programs. Maybe this example will be useful for someone. </p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.