instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>Is it possible to use a TabContainer inside a templated FormView like so:
</p>
<pre><code> <ItemTemplate>
<cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabPanel ID="Tab1" runat="server">
<HeaderTemplate>Tab One</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="Tab2" runat="server">
<HeaderTemplate>Tab 2</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
</ItemTemplate>
<EditTemplate>
<cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabPanel ID="Tab1" runat="server">
<HeaderTemplate>Tab One</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="Tab2" runat="server">
<HeaderTemplate>Tab 2</HeaderTemplate>
<ContentTemplate>
... bound fields
</ContentTemplate>
</cc1:TabPanel>
</cc1:TabContainer>
</EditTemplate>
</code></pre>
<p>
</p>
<p>Everything works fine for only one template view at a time; for example if ItemTemplate works then EditTemplate won't. ASP.NET will complain about duplicate bound field IDs.</p>
<p>Has anybody tried doing what I'm trying to do?</p>
<p>Thanks.- Gene</p>
<p>EDIT :</p>
<p><em>I don't think the tab containers with the same IDs is the issue here since they are both inside separate Template elements and only one Template gets rendered at a time.</em></p>
<p>UPDATE:</p>
<p><em>I didn't manage to find a solution, and I think it's not possible. So, just moved on and use unique IDs. Being lazy, I wrote some code to automate the dreaded naming process. I hope someone out there has a better answer to share. Anyway, I'm too poor to afford to put a bounty on it.</em> ;-)</p>
|
<p>Haven't used the Tab container much but you need to define unique ID's for each element on the page. </p>
<pre><code><cc1:TabContainer ID="TabContainer1" runat="server">
<cc1:TabContainer ID="TabContainer2" runat="server">
</code></pre>
|
<p>I solved this the hard way, by, changing the duplicate field names in each of the tabs.</p>
| 37,250
|
<p>How do I have two effects in jQuery run in <code>sequence</code>, not simultaneously? Take this piece of code for example:</p>
<pre><code>$("#show-projects").click(function() {
$(".page:visible").fadeOut("normal");
$("#projects").fadeIn("normal");
});
</code></pre>
<p>The <code>fadeOut</code> and the <code>fadeIn</code> run simultaneously, how do I make them run one after the other?</p>
|
<p>You can supply a callback to the effects functions that run after the effect has completed.</p>
<pre><code>$("#show-projects").click(function() {
$(".page:visible").fadeOut("normal", function() {
$("#projects").fadeIn("normal");
});
});
</code></pre>
|
<p>Does there have to be a target? surely you can use a random target to queue events sequentially so long as the target is constant...below I'm using the parent of an animation target to store the queue.</p>
<pre><code>//example of adding sequential effects through
//event handlers and a jquery event trigger
jQuery( document ).unbind( "bk_prompt_collapse.slide_up" );
jQuery( document ).bind( "bk_prompt_collapse.slide_up" , function( e, j_obj ) {
jQuery(j_obj).queue(function() {
//running our timed effect
jQuery(this).find('div').slideUp(400);
//adding a fill delay to the parent
jQuery(this).delay(400).dequeue();
});
});
//the last action removes the content from the dom
//if its in the queue then it will fire sequentially
jQuery( document ).unbind( "bk_prompt_collapse.last_action" );
jQuery( document ).bind( "bk_prompt_collapse.last_action" , function( e, j_obj ) {
jQuery(j_obj).queue(function() {
//Hot dog!!
jQuery(this).remove().dequeue();
});
});
jQuery("tr.bk_removing_cart_row").trigger(
"bk_prompt_collapse" ,
jQuery("tr.bk_removing_cart_row")
);
</code></pre>
<p>Not sure if its possible but it seems like you could bind .dequeue() to fire when another jquery event fires, instead of firing inline in my example above? effectively halting an animation queue?</p>
| 10,072
|
<p>I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than <a href="http://en.wikipedia.org/wiki/ROT13" rel="noreferrer">ROT13</a> or <a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64</a>.</p>
<p>I'd prefer something that is already included in the <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> framework 2.0, so I don't have to worry about any external dependencies.</p>
<p>I really don't want to have to mess around with public/private keys, etc. I don't know much about encryption, but I do know enough to know that anything I wrote would be less than worthless... In fact, I'd probably screw up the math and make it trivial to crack.</p>
|
<p>Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays. </p>
<p>NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be <= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use <a href="https://www.random.org/bytes/" rel="noreferrer">https://www.random.org/bytes/</a> to generate a new set easily:</p>
<ul>
<li><a href="https://www.random.org/cgi-bin/randbyte?nbytes=32&format=d" rel="noreferrer">generate <code>Key</code></a></li>
<li><a href="https://www.random.org/cgi-bin/randbyte?nbytes=16&format=d" rel="noreferrer">generate <code>Vector</code></a></li>
</ul>
<p>Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place.</p>
<hr>
<pre><code>using System;
using System.Data;
using System.Security.Cryptography;
using System.IO;
public class SimpleAES
{
// Change these keys
private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });
// a hardcoded IV should not be used for production AES-CBC code
// IVs should be unpredictable per ciphertext
private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 });
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleAES()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
static public byte[] GenerateEncryptionKey()
{
//Generate a Key.
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateKey();
return rm.Key;
}
/// Generates a unique encryption vector
static public byte[] GenerateEncryptionVector()
{
//Generate a Vector
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateIV();
return rm.IV;
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue));
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString));
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return UTFEncoder.GetString(decryptedBytes);
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
</code></pre>
|
<p>I think this is the worlds simplest one !</p>
<pre><code>string encrypted = "Text".Aggregate("", (c, a) => c + (char) (a + 2));
</code></pre>
<p>Test</p>
<pre><code> Console.WriteLine(("Hello").Aggregate("", (c, a) => c + (char) (a + 1)));
//Output is Ifmmp
Console.WriteLine(("Ifmmp").Aggregate("", (c, a) => c + (char)(a - 1)));
//Output is Hello
</code></pre>
| 20,026
|
<p>I would like to know if there is some way to share a variable or an object between two or more Servlets, I mean some "standard" way. I suppose that this is not a good practice but is a easier way to build a prototype.</p>
<p>I don't know if it depends on the technologies used, but I'll use Tomcat 5.5</p>
<hr>
<p>I want to share a Vector of objects of a simple class (just public attributes, strings, ints, etc). My intention is to have a static data like in a DB, obviously it will be lost when the Tomcat is stopped. (it's just for Testing)</p>
|
<p>I think what you're looking for here is request, session or application data.</p>
<p>In a servlet you can add an object as an attribute to the request object, session object or servlet context object:</p>
<pre><code>protected void doGet(HttpServletRequest request, HttpServletResponse response) {
String shared = "shared";
request.setAttribute("sharedId", shared); // add to request
request.getSession().setAttribute("sharedId", shared); // add to session
this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context
request.getRequestDispatcher("/URLofOtherServlet").forward(request, response);
}
</code></pre>
<p>If you put it in the request object it will be available to the servlet that is forwarded to until the request is finished:</p>
<pre><code>request.getAttribute("sharedId");
</code></pre>
<p>If you put it in the session it will be available to all the servlets going forward but the value will be tied to the user:</p>
<pre><code>request.getSession().getAttribute("sharedId");
</code></pre>
<p>Until the session expires based on inactivity from the user.</p>
<p>Is reset by you:</p>
<pre><code>request.getSession().invalidate();
</code></pre>
<p>Or one servlet removes it from scope:</p>
<pre><code>request.getSession().removeAttribute("sharedId");
</code></pre>
<p>If you put it in the servlet context it will be available while the application is running:</p>
<pre><code>this.getServletConfig().getServletContext().getAttribute("sharedId");
</code></pre>
<p>Until you remove it:</p>
<pre><code>this.getServletConfig().getServletContext().removeAttribute("sharedId");
</code></pre>
|
<p>Here's how I do this with Jetty.</p>
<p><a href="https://stackoverflow.com/a/46968645/1287091">https://stackoverflow.com/a/46968645/1287091</a></p>
<p>Uses the server context, where a singleton is written to during startup of an embedded Jetty server and shared among all webapps for the life of the server. Can also be used to share objects/data between webapps assuming there is only one writer to the context - otherwise you need to be mindful of concurrency.</p>
| 15,041
|
<p>I have an executable on Linux that loads <code>libfoo.so.1</code> (that's a <code>SONAME</code>) as one of its dependencies (via another shared library). It also links to another system library, which, in turn, links to a <strong>system</strong> version, <code>libfoo.so.2</code>. As a result, <strong>both</strong> <code>libfoo.so.1</code> and <code>libfoo.so.2</code> are loaded during execution, and code that was supposed to call functions from library with version 1 ends up calling (binary-incompatible) functions from a newer system library with version 2, because some symbols stay the same. The result is usually stack smashing and a subsequent segfault.</p>
<p>Now, the library which links against the older version is a closed-source third-party library, and I can't control what version of <code>libfoo</code> it compiles against. Assuming that, the only other option left is rebuilding a bunch of system libraries that currently link with <code>libfoo.so.2</code> to link with <code>libfoo.so.1</code>.</p>
<p>Is there any way to avoid replacing system libraries wiith local copies that link to older <code>libfoo</code>? Can I load both libraries and have the code calling correct version of symbols? So I need some special symbol-level versioning?</p>
|
<p>You may be able to do some version script tricks:</p>
<p><a href="http://sunsite.ualberta.ca/Documentation/Gnu/binutils-2.9.1/html_node/ld_26.html" rel="noreferrer">http://sunsite.ualberta.ca/Documentation/Gnu/binutils-2.9.1/html_node/ld_26.html</a></p>
<p>This may require that you write a wrapper around your lib that pulls in libfoo.so.1 that exports some symbols explicitly and masks all others as local. For example:</p>
<p>MYSYMS {
global:
foo1;
foo2;
local:
*;
};</p>
<p>and use this when you link that wrapper like:</p>
<p>gcc -shared -Wl,--version-script,mysyms.map -o mylib wrapper.o -lfoo -L/path/to/foo.so.1</p>
<p>This should make libfoo.so.1's symbols local to the wrapper and not available to the main exe.</p>
|
<p>I can only come up with a work-around. Which would be to statically link a version of the "system library" that you are using. For your static build, you could make it link against the same old version as the third-party library. Given that it does not rely on the newer version...</p>
<p>Perhaps it is also possible to avoid these problems with not linking to the third-party library the ordinary way. Instead, your program could load it at execution time. Perhaps then it could be shadowed against the rest. But I don't know much about that.</p>
| 28,232
|
<p>I'm looking for a way to generate a set of random sided, but regular, polygons, inside a given rectangle or sector of a circle. To better explain, my given 2d space should have a random arrangement of regular polygons with various numbers of sides, so, e.g, if two hexagons are separated by a rectangle equal in length to their sides, the whole space cannot be filled with only more hexagons, some triangles may be required, etc.</p>
<p>I'm looking for one segment of a sort of kaleidoscope effect. </p>
|
<p>Another approach, I can think of:
First decide on how many objects you want. Say 'N'</p>
<p>Randomly Select 3 Points in your 2D Space.</p>
<p>Make use of 3 points to get a virtual triangle. </p>
<p>Now Select another point such a way that the point is outside the virtual triangle. Now form another virtual triangle by joining this point to 2 points from previous virtual triangle and then recurisevely form "N" virtual trianlges. Incase virtual triangles crossed, then you ignore the bigger trianlge and take triangles which had formed because of crossing points as new virtualtriangles</p>
<p>Now Generate a INSCRIBED Circle virtually to all virtual triangles which will never be able to intersect another virtual triangle since all virtual triangles are formed by without crossing any of the triangles as expalined above. </p>
<p>Make use of virtual circles to form any number of regular sides by dividing 360 degress to equal slices.
Now You can draw random regular polygons</p>
|
<p>Generate N random points on a plane and extract the convex hull of the object (that is, if all polygons should be convex).</p>
<p>You can trivially reject before generating the convex hull if one of the points is inside another polygon. If it's not you still need to test the generated polygon against other polygons near it. (If you need to do this often, a spatial data structure is probably a something to look into).</p>
| 46,920
|
<p>I'm planning to write a simple J2SE application to aggregate information from multiple web sources.</p>
<p>The most difficult part, I think, is extraction of meaningful information from web pages, if it isn't available as RSS or Atom feeds. For example, I might want to extract a list of questions from stackoverflow, but I absolutely don't need that huge tag cloud or navbar.</p>
<p>What technique/library would you advice?</p>
<p><strong>Updates/Remarks</strong></p>
<ul>
<li>Speed doesn't matter — as long as it can parse about 5MB of HTML in less than 10 minutes.</li>
<li>It sould be really simple.</li>
</ul>
|
<p>You could look at how httpunit does it. They use couple of decent html parsers, one is nekohtml.
As far as getting data you can use whats built into the jdk (httpurlconnection), or use apache's </p>
<p><a href="http://hc.apache.org/httpclient-3.x/" rel="nofollow noreferrer">http://hc.apache.org/httpclient-3.x/</a></p>
|
<p>In short, you may either parse the whole page and pick things you need(for speed I recommend looking at SAXParser) or running the HTML through a regexp that trims of all of the HTML... you can also convert it all into DOM, but that's going to be expensive especially if you're shooting for having a decent throughput.</p>
| 9,701
|
<p>I know it's by design that you can't control what happens when an object is destroyed. I am also aware of defining some class method as a finalizer.</p>
<p>However is the ruby idiom for C++'s RAII (Resources are initialized in constructor, closed in destructor)? How do people manage resources used inside objects even when errors or exceptions happen?</p>
<p>Using <em>ensure</em> works:</p>
<pre><code>f = File.open("testfile")
begin
# .. process
rescue
# .. handle error
ensure
f.close unless f.nil?
end
</code></pre>
<p>but users of the class <strong>have to remember to do the whole begin-rescue-ensure chacha</strong> everytime the open method needs to be called. </p>
<p>So for example, I'll have the following class:</p>
<pre><code>class SomeResource
def initialize(connection_string)
@resource_handle = ...some mojo here...
end
def do_something()
begin
@resource_handle.do_that()
...
rescue
...
ensure
end
def close
@resource_handle.close
end
end
</code></pre>
<p>The resource_handle won't be closed if the exception is cause by some other class and the script exits.</p>
<p>Or is the problem more of I'm still doing this too C++-like?</p>
|
<p>So that users don't "<em>have to remember to do the whole begin-rescue-ensure chacha</em>" combine <code>rescue</code>/<code>ensure</code> with <code>yield</code>.</p>
<pre><code>class SomeResource
...
def SomeResource.use(*resource_args)
# create resource
resource = SomeResource.new(*resource_args) # pass args direct to constructor
# export it
yield resource
rescue
# known error processing
...
ensure
# close up when done even if unhandled exception thrown from block
resource.close
end
...
end
</code></pre>
<p>Client code can use it as follows:</p>
<pre><code>SomeResource.use(connection_string) do | resource |
resource.do_something
... # whatever else
end
# after this point resource has been .close()d
</code></pre>
<p>In fact this is how <code>File.open</code> operates - making the first answer confusing at best (well it was to <em>my</em> work colleagues).</p>
<pre><code>File.open("testfile") do |f|
# .. process - may include throwing exceptions
end
# f is guaranteed closed after this point even if exceptions are
# thrown during processing
</code></pre>
|
<p>See <a href="http://www.rubycentral.com/pickaxe/tut_exceptions.html" rel="nofollow noreferrer">http://www.rubycentral.com/pickaxe/tut_exceptions.html</a></p>
<p>In Ruby, you would use an <code>ensure</code> statement:</p>
<pre><code>f = File.open("testfile")
begin
# .. process
rescue
# .. handle error
ensure
f.close unless f.nil?
end
</code></pre>
<p>This will be familiar to users of Python, Java, or C# in that it works like try / catch / finally.</p>
| 26,382
|
<p>There are certain common components that are used across projects:</p>
<ol>
<li>User Authentication and Authorization</li>
<li>Exception Handling</li>
<li>Logging</li>
<li>E-mail</li>
<li>DataBase Access</li>
<li>Caching etc</li>
</ol>
<p>Is there a consistent design pattern that can be used for each of these common modules? By the way, the framework can vary like JAAS/JNDI for User Authentication and Authorization, log4j/java logging for logging, JavaMail for E-mai, JDBC/Hibernate for DataBase access. </p>
<p>For example there is DAO for database access. Is there any good design pattern that can be used for User Authentication and Authorization no matter what framework is used(JAAS/JNDI/SSO)?</p>
|
<p>Perhaps not a pattern per se, but I've always thought that the spring annotations approach was quite clever. Essentially you annotate the methods that need to be secured. Providing that you have a nice tiered architecture then this should make things pretty straightforward! It does all of the hard work for you. <a href="http://www.acegisecurity.org/" rel="nofollow noreferrer" title="Acegi web site">Check it out here</a>. The <a href="http://www.acegisecurity.org/faq.html" rel="nofollow noreferrer" title="FAQ">FAQ is pretty good</a>. </p>
<p>I've only used this in really elementary stuff as part of my spring training with Rod Johnson.</p>
|
<p>I don't know for design patterns for the user authentication/authorization but... if you want to be able to mock them easily, in .NET we use Providers.</p>
<p>We can then configure which component we use for the authentication and authorization directly through our configuration file.</p>
<p>What do you think?</p>
| 29,528
|
<p>I was just wondering, since the <strong>sealed</strong> keyword's existence indicates that it's the class author's decision as to whether other classes are allowed to inherit from it, why aren't classes sealed by default, with some keyword to mark them explicitly as extensible?</p>
<p>I know it's somewhat different, but access modifiers work this way. With the default being restrictive and fuller access only being granted with the insertion of a keyword.</p>
<p>There's a large chance that I haven't thought this through properly, though, so please be humane!</p>
|
<p>I'd say it was just a mistake. I know many people (including myself) who believe that classes should indeed be sealed by default. There are at least a couple of people in the C# design team in that camp. The pendulum has swung somewhat away from inheritance since C# was first designed. (It has its place, of course, but I find myself using it relatively rarely.)</p>
<p>For what it's worth, that's not the only mistake along the lines of being too close to Java: personally I'd rather Equals and GetHashCode weren't in object, and that you needed specific Monitor instances for locking too...</p>
|
<p>For the same reason why objects are not private by default</p>
<p>or</p>
<p>to be consistent with the object analogue, which is objects are not private by default</p>
<p>Just guessing, coz at the end of the day it's a language's design decision and what the creators say is the canon material.</p>
| 31,431
|
<p>Is it possible to run more than one website on IIS 5.1 (Windows XP)?</p>
<p>I'm able to create multiple websites through adminscripts in IIS, but only one website can be active at a time.</p>
<p>Is there is any workaround, trick, or script for this limitation?</p>
<p>Thanks,</p>
|
<p>As far as I know, you can only have one active at any one time, but see <a href="http://www.codinghorror.com/blog/archives/000329.html" rel="nofollow noreferrer">this link</a> by Jeff for more info on how to uncripple IIS.</p>
|
<p>Check the Port No for each website you created, By default you get port no 80. But here if you dont have Host Headers for the Application then you have to create Each website with each port no like 80, 8080, 8081...etc and try.</p>
| 31,025
|
<p>Is it possible to configure Visual Studio 2008 to automatically remove whitespace characters at the end of each line when saving a file? There doesn't seem to be a built-in option, so are there any extensions available to do this?</p>
|
<p>CodeMaid is a very popular Visual Studio extension and does this automatically along with other useful cleanups.</p>
<ul>
<li>Download: <a href="https://github.com/codecadwallader/codemaid/releases/tag/v0.4.3" rel="noreferrer">https://github.com/codecadwallader/codemaid/releases/tag/v0.4.3</a></li>
<li>Modern Download: <a href="https://marketplace.visualstudio.com/items?itemName=SteveCadwallader.CodeMaid" rel="noreferrer">https://marketplace.visualstudio.com/items?itemName=SteveCadwallader.CodeMaid</a></li>
<li>Documentation: <a href="http://www.codemaid.net/documentation/#cleaning" rel="noreferrer">http://www.codemaid.net/documentation/#cleaning</a></li>
</ul>
<p>I set it to clean up a file on save, which I believe is the default.</p>
|
<p>This is a really good example of how to remove trailing whitespace. There are a few things that I would change based on what I discovered using this macro. First of all, the macro automatically converts tabs to spaces. This is not always desirable and could lead to making things worse for people that love tabs (typically Linux-based). The tab problem is not really the same as the extra whitespace problem anyways.
Secondly, the macro assumes only one file is being saved at once. If you save multiple files at once, it will not correctly remove the whitespace. The reason is simple. The current document is considered the document you can see.
Third, it does no error checking on the find results. These results can give better intelligence about what to do next. For example, if no whitespace is found and replaced, there is no need to save the file again. In general, I did not like the need for the global flag for being saved or not. It tends to ask for trouble based on unknown states. I suspect the flag had been added solely to prevent an infinite loop.</p>
<pre><code> Private Sub DocumentEvents_DocumentSaved(ByVal document As EnvDTE.Document) _
Handles DocumentEvents.DocumentSaved
Dim result As vsFindResult
'Dim nameresult As String
Try
document.Activate()
' Remove all the trailing whitespaces.
result = DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
":Zs+$", _
vsFindOptions.vsFindOptionsRegularExpression, _
String.Empty, _
vsFindTarget.vsFindTargetCurrentDocument, , , _
vsFindResultsLocation.vsFindResultsNone)
'nameresult = document.Name & " " & Str$(result)
'MsgBox(nameresult, , "Filename and result")
If result = vsFindResult.vsFindResultReplaced Then
'MsgBox("Document Saved", MsgBoxStyle.OkOnly, "Saved Macro")
document.Save()
Else
'MsgBox("Document Not Saved", MsgBoxStyle.OkOnly, "Saved Macro")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.OkOnly, "Trim White Space exception")
End Try
End Sub
</code></pre>
<p>I added debug message boxes to help see what was going on. It made it very clear that multiple file save was not working. If you want to play with them, uncomment those lines.</p>
<p>The key difference is using document.Activate() to force the document into the foreground active current document. If the result is 4, that means that the text was replaced. Zero means nothing happened. You will see two saves for every file. The first will replace and the second will do nothing. Potentially there could be trouble if the save cannot write the file but hopefully this event will not get called if that happens.</p>
<p>Before the original script, I was unaware of how the scripting worked in Visual Studio. It is slightly surprising that it uses Visual Basic as the main interface but it works just fine for what it needs to do.</p>
| 10,865
|
<p>Ruby on Rails has a lot of ways to generate JavaScript. Particularly when it comes to Ajax. Unfortunately, there are a few problems that I often see with the JavaScript that it generates. </p>
<ul>
<li><p>Rails typically uses inline event handling.</p>
<pre><code><a onclick="somejavascript(); return false;" />
</code></pre>
<p>This is generally frowned upon, as it's mixing behavior in with the XHTML. </p></li>
<li><p>The generated JavaScript also relies heavily on Prototype. Personally, I prefer jQuery. </p></li>
<li><p>In my experience, the attitude with a lot of Rails developers has been to write as much of the code in Ruby as possible. The final step is to generate some very procedural and repetitive JavaScript. Often, this code ends up being very inflexible and difficult to debug.</p></li>
</ul>
<p>So, my question is: how much JavaScript do you write manually for your projects and how much of it is generated server-side with Rails/Ruby? Or is there a happy medium where you get the benefits of both? With a subquestion: if you write a lot of the JavaScript manually, what techniques do you use to fit it into the MVC model?</p>
|
<p>If you prefer jQuery you can use the <a href="http://ennerchi.com/projects/jrails" rel="nofollow noreferrer">jQuery on Rails Project</a>. A drop in to replace Prototype with jQuery.</p>
<p>Some of what Rails does with Javascript generation is good and some is bad. In the bad instances, write it yourself and keep it unobtrusive. At any given time you're uncomfortable with the Javascript Rails generates, you can go ahead and write it yourself. </p>
<p>And be sure to check out this great intro to <a href="http://www.railsenvy.com/2008/1/3/unobtrusive-javascript" rel="nofollow noreferrer">unobtrusive Javascript</a> that was done with Rails in mind.</p>
|
<p>Let Rails do as much as possible. Then when you have problems, start rewriting it with hand coded versions.</p>
| 27,644
|
<p>I have a C# .NET application with which I've created a custom image display control. Each image display represents its own display context and draws the image using glDrawPixels (Yes I know it would be better to use textures, I plan to in the futures but this app is already too far along and my time is limited).</p>
<p>I am now trying to have both images pan simultaneously. That is, when one image is moved down ten pixels, the second image moves down ten pixels. Like so:</p>
<pre><code>imageOne.YPan -= 10;
imageTwo.YPan -= 10;
imageOne.Invalidate(); //This forces a redraw.
imageTwo.Invalidate(); //This forces a redraw.
</code></pre>
<p>Alright so here is the problem I am having. Only one of the images displays is redrawing. If I place a pause in between the two Invalidate calls and make the pause duration at least 110 milliseconds both will redraw, but not simultaneously. So it looks as if the second image is always trying to catch up to the first. Plus, a 110 millisecond pause slows down the motion too much. </p>
<p>I have tried placing the updating and invalidating of each image in its own thread but this did not help.</p>
<p>At the beginning of drawing I make the appropriate context is current, and at the end I am calling swapbuffers(). I tried adding a glFinish to the end of the draw function, but there was no change. </p>
<p>Could it be that its the graphics card that is the problem? I am stuck using an integrated gpu that only has openGL 1.4. </p>
<p>Hopefully, I have provided enough detail that the answer to my problem can be found. </p>
|
<p>Its difficult telling what's wrong with what you do since you give so little detail. Here are some pointers which may help.<br>
- before doing something in a context, make sure you make it the current one. If you want to pan two contexts, make the first one current, pan it and then make the second one current and pan it. These is no real reason why this should not work.<br>
- If it looks like there is a timing problem, adding <code>glFinish()</code> at strategic places may help weed the problem out<br>
- As should always be done, on occasions call <code>glError()</code> and see that everything went well.<br>
- I'm not sure how this is done in the framework you're talking about but you should make sure that both contexts get a <code>swapBuffers()</code> call for every frame.</p>
|
<p><code>Invalidate</code> doesn't force an immediate redraw. It marks the window invalid, and when the message queue runs out of other messages, a paint message will be created and processed. But that won't happen until you finish processing the current message and return to the main message loop, and it may be delayed even more than that.</p>
<p>Generally OpenGL animation is an exception to the rule of doing all drawing inside <code>Control.OnPaint</code> (or in a handler for the <code>Control.Paint</code> event).</p>
| 41,302
|
<p>I need to resize PNG, JPEG and GIF files. How can I do this using Java?</p>
|
<p>After loading the image you can try:</p>
<pre><code>BufferedImage createResizedCopy(Image originalImage,
int scaledWidth, int scaledHeight,
boolean preserveAlpha)
{
System.out.println("resizing...");
int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
Graphics2D g = scaledBI.createGraphics();
if (preserveAlpha) {
g.setComposite(AlphaComposite.Src);
}
g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
g.dispose();
return scaledBI;
}
</code></pre>
|
<p>I have developed a solution with the freely available classes ( AnimatedGifEncoder, GifDecoder, and LWZEncoder) available for handling GIF Animation.<br>
You can download the jgifcode jar and run the GifImageUtil class.
Link: <a href="http://www.jgifcode.com" rel="nofollow">http://www.jgifcode.com</a></p>
| 30,267
|
<p>Using LINQ to Entities sounds like a great way to query against a database and get actual CLR objects that I can modify, data bind against and so forth. But if I perform the same query a second time do I get back references to the same CLR objects or an entirely new set? </p>
<p>I do not want multiple queries to generate an ever growing number of copies of the same actual data. The problem here is that I could alter the contents of one entity and save it back to the database but another instance of the entity is still in existence elsewhere and holding the old data.</p>
|
<p>Within the same DataContext, my understanding is that you'll always get the same objects - for queries which return full objects instead of projections.</p>
<p>Different DataContexts will fetch different objects, however - so there's a risk of seeing stale data there, yes.</p>
|
<p>[oops; note that this reply applies to Linq-to-SQL, not Entity Framework.]</p>
<p>I've left it here (rather than delete) because it is partly on-topic, and might be useful.</p>
<hr>
<p>Further to the other replies, note that the data-context also has the ability to avoid doing a round-trip for simply "by primary key" queries - it will check the cache first.</p>
<p>Unfortunately, it was <em><a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=340036" rel="nofollow noreferrer">completely</a></em> broken in 3.5, and is still <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=362313" rel="nofollow noreferrer">half-broken</a> in 3.5SP1, but it works for <em>some</em> queries. This can save a lot of time if you are getting individual objects.</p>
<p>So basically, IIRC you need to use:</p>
<pre><code>// uses object identity cache (IIRC)
var obj = ctx.Single(x=>x.Id == id);
</code></pre>
<p>But not:</p>
<pre><code>// causes round-trip (IIRC)
var obj = ctx.Where(x=>x.Id == id).Single();
</code></pre>
| 35,435
|
<p>Given the following inheritance tree, what would be the best way of implementing it in a way that works?</p>
<pre><code>abstract class Foo<T> : IEnumerable<T>
{
public abstract Bar CreateBar();
}
class Bar<T> : Foo<T>
{
// Bar's provide a proxy interface to Foo's and limit access nicely.
// The general public shouldn't be making these though, they have access
// via CreateBar()
protected Bar(Foo base)
{
// snip...
}
}
class Baz<T> : Foo<T>
{
public Bar CreateBar()
{
return new Bar(this);
}
}
</code></pre>
<p>This fails with: <code>'Bar.Bar()' is inaccessible due to its protection level</code>.</p>
<p>I don't want the constructor being public, only classes that inherit from <code>Foo</code> should be able to create <code>Bar</code>s. <code>Bar</code> is a specialised <code>Foo</code>, and any type of <code>Foo</code> should be able to create one. Public internal is an 'option' here, as the majority of the predefined extensions to <code>Foo</code> will be internal to the DLL, but I consider this a sloppy answer, since anyone who comes along later who wants to create their own type of <code>Foo</code> or <code>Baz</code> (which is likely to happen) will be stuck with a default <code>CreateBar()</code> implementation, which may or may not meet their needs.</p>
<p>Perhaps there is a way of refactoring this to make it work nicely? I'm banging my head on the wall trying to design this so it'll work though.</p>
<p><strong>Edit (More info):</strong></p>
<p>Slightly more concrete: Foo is implementing IEnumerable and long story short, Bar is providing the same interface, but to a limited subset of that enumerable object. All Foo's should be able to create subsets of themselves (ie. Bar) and return it. But I don't want to have everyone who ever wants to implement a Foo to have to worry about this, because Bar will do the proxying and worry about limiting the range, etc.</p>
|
<p>Okay, new answer:</p>
<ol>
<li>Split Bar into an interface and a concrete class.</li>
<li>Express the public abstract method in terms of IBar.</li>
<li>Make Bar a private nested class in Foo, implementing IBar. Give it an internal constructor which you can call from Foo.</li>
<li>Write a protected method in Foo which creates an instance of Bar from itself. Classes deriving from Foo can use this to implement the abstract method if just proxying is good enough, and classes with more complicated needs can just implement IBar directly. You could even change the abstract method to a virtual one, and create a new Bar from "this" by default.</li>
</ol>
<p>EDIT: One variant on this would be to make Bar a <em>protected</em> nested class within Foo, with a public constructor. That way any derived class would be able to instantiate it for themselves, but no unrelated class would be able to "see" it at all. You'd still need to separate the interface from the implementation (so that the interface can be public) but I think that's a good thing anyway.</p>
|
<p>C# doesn't provide a direct equivalent of the C++ friend keyword. Seems like your design is requiring this sort of construct.</p>
<p>In C++ you could designate that a specific class has access to the private/protected members of another class by using "friend". Note: this is not the same as C# internal, modifier which gives access to all classes within the same assembly.</p>
<p>Looking at your design, it seems you are trying to do something along the lines that would require the C++ style friend. Jon Skeet is right, the usual design in C# to make up for this is to use a nested class.</p>
<p>This <a href="http://bytes.com/forum/thread235936.html" rel="nofollow noreferrer">forum post</a> explains further and shows some examples of how to do this.</p>
| 24,397
|
<p>What is the difference between a <code>const_iterator</code> and an <code>iterator</code> and where would you use one over the other?</p>
|
<p><code>const_iterator</code>s don't allow you to change the values that they point to, regular <code>iterator</code>s do.</p>
<p>As with all things in C++, always prefer <code>const</code>, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not <code>const</code> to change the pointed-to value).</p>
|
<p>(as others have said) const_iterator doesn't allow you modify the elements to which it points, this is useful inside of const class methods. It also allows you to express your intent.</p>
| 39,883
|
<p>OK since I am in a holding pattern on this issue perhaps someone has seen these symptoms and can provide some sage advice. (Note: I have learned only enough Active Directory information to build this feature and I only have read access to the Active Directory.)</p>
<p>I updated the company intranet to allow the automatic entry/modification of employee phone/address information; it uses a web service to connect to the company Active Directory so I can call it from multiple locations in the main application. </p>
<p>The AD has two domains (A and B) in the same forest. Each domain has an ‘ADS update user’ group and an ‘ADSupdate’ account (which belongs to ‘ADS update user’).</p>
<p>Problem: Entries in Domain A update fine for Local Development Servers, Test Servers, and Production Servers. Entries in Domain B update only when run from Local Development Servers. When you run the same code (verified multiple times) on either Test or Production you get a (General access denied error).</p>
<p>The domain name is stored in the employee record so the exact same code is called for all employees.</p>
<p>All Local Development Servers, Test, and Production servers reside in Domain A.</p>
<p>This has the Active Directory Admin for Domain B stumped and to be honest I am thankful that the Local Development Servers are able to update the Active Directory entries in domain B. It proves that the code works at least in one location</p>
<p>I have looked at machine permissions, permissions on the group and user, and IIS and I can spot no significant differences.
Any help would be appreciated…</p>
|
<p>Nobody has yet mentioned the obvious and trivial way to stack the letters of an arbitrary string vertically (without rotating them) using pure XAML:</p>
<pre class="lang-xml prettyprint-override"><code><ItemsControl
ItemsSource="Text goes here, or you could use a binding to a string" />
</code></pre>
<p>This simply lays out the text vertically by recognizing the fact that the string is an IEnumerable and so ItemsControl can treat each character in the string as a separate item. The default panel for ItemsControl is a StackPanel, so the characters are laid out vertically.</p>
<p>Note: For precise control over horizontal positioning, vertical spacing, etc, the ItemContainerStyle and ItemTemplate properties can be set on the ItemsControl.</p>
|
<p>I will offer a solution based on the converter:</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;
namespace Converters
{
[ValueConversion(typeof(object), typeof(string))]
public class InsertLineBreakConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter != null)
value = parameter;
if (value == null)
return null;
if (!(value is string str))
str = value.ToString();
return string.Join(Environment.NewLine, (IEnumerable<char>) str);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
public static InsertLineBreakConverter Instance { get; } = new InsertLineBreakConverter();
}
public class InsertLineBreakConverterExtension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
=> InsertLineBreakConverter.Instance;
}
}
</code></pre>
<p>Usage examples:</p>
<pre class="lang-xml prettyprint-override"><code> <TextBlock Text="{Binding Property, Converter={cnvs:InsertLineBreakConverter}}"/>
<TextBlock Text="{Binding Converter={cnvs:InsertLineBreakConverter}, ConverterParameter='Some Text'}"/>
</code></pre>
| 45,527
|
<p>How can I continuously capture images from a webcam?</p>
<p>I want to experiment with object recognition (by maybe using java media framework). </p>
<p>I was thinking of creating two threads</p>
<p>one thread:</p>
<ul>
<li>Node 1: capture live image</li>
<li>Node 2: save image as "1.jpg"</li>
<li>Node 3: wait 5 seconds</li>
<li>Node 4: repeat...</li>
</ul>
<p>other thread:</p>
<ul>
<li>Node 1: wait until image is captured</li>
<li>Node 2: using the "1.jpg" get colors
from every pixle</li>
<li>Node 3: save data in arrays</li>
<li>Node 4: repeat...</li>
</ul>
|
<p>This JavaCV implementation works fine.</p>
<p>Code:</p>
<pre><code>import org.bytedeco.javacv.*;
import org.bytedeco.opencv.opencv_core.IplImage;
import java.io.File;
import static org.bytedeco.opencv.global.opencv_core.cvFlip;
import static org.bytedeco.opencv.helper.opencv_imgcodecs.cvSaveImage;
public class Test implements Runnable {
final int INTERVAL = 100;///you may use interval
CanvasFrame canvas = new CanvasFrame("Web Cam");
public Test() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
public void run() {
new File("images").mkdir();
FrameGrabber grabber = new OpenCVFrameGrabber(0); // 1 for next camera
OpenCVFrameConverter.ToIplImage converter = new OpenCVFrameConverter.ToIplImage();
IplImage img;
int i = 0;
try {
grabber.start();
while (true) {
Frame frame = grabber.grab();
img = converter.convert(frame);
//the grabbed frame will be flipped, re-flip to make it right
cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
//save
cvSaveImage("images" + File.separator + (i++) + "-aa.jpg", img);
canvas.showImage(converter.convert(img));
Thread.sleep(INTERVAL);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Test gs = new Test();
Thread th = new Thread(gs);
th.start();
}
}
</code></pre>
<p>There is also <a href="http://ganeshtiwaridotcomdotnp.blogspot.com/2017/01/javacv-configuration-in-windows.html" rel="nofollow noreferrer">post on configuration for JavaCV</a></p>
<p>You can modify the codes and be able to save the images in regular interval and do rest of the processing you want.</p>
|
<p>I believe the web-cam application software which comes along with the web-cam, or you native windows webcam software can be run in a batch script(windows/dos script) after turning the web cam on(i.e. if it needs an external power supply). In the bacth script , u can add appropriate delay to capture after certain time period. And keep executing the capture command in loop.</p>
<p>I guess this should be possible</p>
<p>-AD</p>
| 34,839
|
<p>Our application executes a long, hairy stored procedure with multiple result sets. The users are experiencing long wait times for this query, so I set out to determine what is causing the delay.</p>
<p>I put a Stopwatch on executing and reading the data, and it takes 6-7 seconds each time. I timed the execution of the stored procedure, expecting that this would be taking all the time. It wasn't - it took 30ms or so.</p>
<p>So I put timers around each of the ~20 result sets. Each "block" took very little time ( < 10ms) except for one in the middle of the processing, which took 5-6 seconds. Upon further research, I discovered it was the "reader.NextResult()" call that took all the time. This long delay happens in the same spot each time.</p>
<p>If I just exec the stored procedure, it seems to run real snappy, so it doesn't APPEAR to be a problem with the query - but I don't know...</p>
<p>How do I interpret this? Is SQL shipping me the result sets as it gets them, and is the result set in question likely to be a problem area in my SQL query? Or is something else possibly causing the delay?</p>
<p>EDIT:</p>
<p>Thanks for the answer and the comments - I am using SQL Server and .NET</p>
<p>What I was most curious about was WHY my delay happens on the "NextResult()" call. Being new to SQL development, I assumed that a delay due to a long stored procedure execution would show up in my application while waiting for the "ExecuteReader()" call to return. It now seems that SQL will start returning data BEFORE the query is complete, and if there is a delay it will delay on the NextResult() call.</p>
<p>I started out thinking my delay was in the stored procedure. When the ExecuteReader() call came back quickly, I thought my delay was in my code's handling of the reader. When the delay ended up being on the NextResult() call, I was confused. I am now back to reviewing the stored procedure.</p>
<p>Thanks to those of you who took the time to review my problem and offered your help.</p>
|
<p>When you execute a stored proc from a .Net command, the results will start streaming as soon as SQL has them ready. </p>
<p>This means that you may start seeing results in your .Net app before the entire stored proc has been executed. </p>
<p>Your bottleneck is probably in the stored procedure, run a sql server trace, and trace all the statements running inside the stored procedure (get the durations). You will be able to track down the exact statement in the proc that is slow and you also will be able to pick up on the params that are being passed to the proc so you can test this in Query Analyzer and look at the plan.</p>
<p>Another point that is missing from the question seems to be the amount of data you are moving, though unlikely, it may be that you have some really large chunks of data (like blobs) that are being sent and the time is being spent on the wire. You really need to expand the question a bit to help with the diagnosis. </p>
|
<p>The answer will be dependent on what RDBMS you are using.</p>
<p>If its SQL Server and .NET then from my experience:</p>
<ol>
<li>Check other open transactions on the same connection which is used to invoke the sproc. They may have row locks on the table one of your selects is executing against. You can try adding "MultipleActiveResultSets=false" to your SQL Server connection string and see if you get an improvement, or more likely an exception (and you can hunt down the problem from an exception). This can also be an effect from an unreset connection returned to the connection pool (something I've ran into since I've started to use <a href="http://www.devx.com/dbzone/Article/30132/1954" rel="nofollow noreferrer">MARS</a>).</li>
<li><p>You may need to specify the NOLOCK (or READUNCOMMITTED, same thing) table hint in your SELECT query if <a href="http://msdn.microsoft.com/en-us/library/ms190805.aspx" rel="nofollow noreferrer">dirty reads are acceptible</a>.</p>
<p>SELECT * FROM [table] WITH NOLOCK</p></li>
</ol>
| 28,553
|
<p>My application pops a form as a child of the main form. On the form is<br>
User Control with a Panel where Graphics are rendered. When executed
from Visual Studio in debug mode the drawing is often rendered as expected,
imagine a simply XY graph. If the panel's graphic aren't drawn then adding
two or three break points to the drawing routines usually fix the problem.</p>
<p>When executed inside Visual Studio in release mode, or from the.exe in any mode,
the graphics are never rendered, although the user control's Paint method is
called. Resizing the form cause the repaint to be called again, of course,
and the image is now rendered correctly.</p>
<p>Can anyone give me some insight as to why there's a difference in the behavior
between Debug and Release modes, from execution within VS and out side VS,
any why are the break points sometimes fixing things? And how can I get the
graphics to be consistently visible.</p>
<p>Thanks,</p>
<p>Rick</p>
<p><a href="http://img160.imageshack.us/my.php?image=profilebeforeresizeti4.png" rel="nofollow noreferrer">alt text http://img160.imageshack.us/my.php?image=profilebeforeresizeti4.png</a><a href="http://img512.imageshack.us/my.php?image=profileafterresizenw2.png" rel="nofollow noreferrer">alt text http://img512.imageshack.us/my.php?image=profileafterresizenw2.png</a></p>
|
<p>Ctrl + Space in immediate if you don't have the intellisense coming up automatically. Like Joel, intellisense seems to come in go in the immed window.</p>
|
<p>When debugging in Visual Studio 2008, you can get intellisense to pop up by pressing ctrl+space. Also, it will pop up in a quick watch window with the same keystroke. Very handy.</p>
| 36,698
|
<p>I'm writing a service that has five different methods that can take between 5 seconds and 5 minutes to run.</p>
<p>The service will schedule these different methods to run at different intervals.</p>
<p>I don't want any of the methods to run concurrently, so how do I have the methods check to see if another method is running and queue itself to run when it finishes?</p>
<p>Anthony</p>
|
<p>If you want <em>simple</em>, and all the methods are in the same class, ou can just use <code>[MethodImpl]</code>:</p>
<pre><code>[MethodImpl(MethodImplOptions.Synchronized)]
public void Foo() {...}
[MethodImpl(MethodImplOptions.Synchronized)]
public void Bar() {...}
</code></pre>
<p>For instance methods, this locks on <code>this</code>; for static methods, this locks on <code>typeof(TheClass)</code>.</p>
<p>As such, these lock objects are public - so there is a remote (but genuine) chance that another bit of code might be locking on them. It is generally considered better practice to create your own lock object:</p>
<pre><code>private readonly object syncLock = new object(); // or static if needed
...
public void Foo() {
lock(syncLock) {
...
}
}
</code></pre>
<p>etc</p>
<hr>
<p>Aside: a curious fact; the ECMA spec doesn't define a specific pattern for [MethodImpl], even including an example of a private lock, as "valid". The MS spec, however, insists on this/typeof.</p>
|
<p>In general, I strongly discourage using the MethodImpl(MethodImplOptions.Synchronized) attribute to do thread synchronization. If you are going to do multi-threaded programming you really should think very carefully about exactly where and how you should be locking.</p>
<p>I may be exaggerating a bit but I find too many similarities between the MethodImpl synchronization method and others such as the use of the End statement in VB. It often signals to me that you don't really know what you are doing and hope that this statement/method/attribute will magically solve your problem.</p>
| 42,430
|
<p>What are the advantages and limitations of dynamic type languages compared to static type languages?</p>
<p><strong>See also</strong>: <a href="https://stackoverflow.com/questions/42934/whats-with-the-love-of-dynamic-languages">whats with the love of dynamic languages</a> (a far more argumentative thread...)</p>
|
<p>The ability of the interpreter to deduce type and type conversions makes development time faster, but it also can provoke runtime failures which you just cannot get in a statically typed language where you catch them at compile time. But which one's better (or even if that's always true) is hotly discussed in the community these days (and since a long time).</p>
<p>A good take on the issue is from <a href="http://www.ics.uci.edu/~lopes/teaching/inf212W12/readings/rdl04meijer.pdf" rel="noreferrer">Static Typing Where Possible, Dynamic Typing When Needed: The End of the Cold War Between Programming Languages</a> by Erik Meijer and Peter Drayton at Microsoft:</p>
<blockquote>
<p>Advocates of static typing argue that
the advantages of static typing
include earlier detection of
programming mistakes (e.g. preventing
adding an integer to a boolean),
better documentation in the form of
type signatures (e.g. incorporating
number and types of arguments when
resolving names), more opportunities
for compiler optimizations (e.g.
replacing virtual calls by direct
calls when the exact type of the
receiver is known statically),
increased runtime efficiency (e.g. not
all values need to carry a dynamic
type), and a better design time
developer experience (e.g. knowing the
type of the receiver, the IDE can
present a drop-down menu of all
applicable members). Static typing
fanatics try to make us believe that
“well-typed programs cannot go wrong”.
While this certainly sounds
impressive, it is a rather vacuous
statement. Static type checking is a
compile-time abstraction of the
runtime behavior of your program, and
hence it is necessarily only partially
sound and incomplete. This means that
programs can still go wrong because of
properties that are not tracked by the
type-checker, and that there are
programs that while they cannot go
wrong cannot be type-checked. The
impulse for making static typing less
partial and more complete causes type
systems to become overly complicated
and exotic as witnessed by concepts
such as “phantom types” [11] and
“wobbly types” [10]. This is like
trying to run a marathon with a ball
and chain tied to your leg and
triumphantly shouting that you nearly
made it even though you bailed out
after the first mile.</p>
<p>Advocates of dynamically typed
languages argue that static typing is
too rigid, and that the softness of
dynamically languages makes them
ideally suited for prototyping systems
with changing or unknown requirements,
or that interact with other systems
that change unpredictably (data and
application integration). Of course,
dynamically typed languages are
indispensable for dealing with truly
dynamic program behavior such as
method interception, dynamic loading,
mobile code, runtime reflection, etc.
In the mother of all papers on
scripting [16], John Ousterhout argues
that statically typed systems
programming languages make code less
reusable, more verbose, not more safe,
and less expressive than dynamically
typed scripting languages. This
argument is parroted literally by many
proponents of dynamically typed
scripting languages. We argue that
this is a fallacy and falls into the
same category as arguing that the
essence of declarative programming is
eliminating assignment. Or as John
Hughes says [8], it is a logical
impossibility to make a language more
powerful by omitting features.
Defending the fact that delaying all
type-checking to runtime is a good
thing, is playing ostrich tactics with
the fact that errors should be caught
as early in the development process as
possible.</p>
</blockquote>
|
<p><strong>Static Typing:</strong>
The languages such as Java and Scala are static typed.</p>
<p>The variables have to be defined and initialized before they are used in a code.</p>
<p>for ex.
int x;
x = 10;</p>
<p>System.out.println(x);</p>
<p><strong>Dynamic Typing:</strong>
Perl is an dynamic typed language.</p>
<p>Variables need not be initialized before they are used in code.</p>
<p>y=10; use this variable in the later part of code</p>
| 15,237
|
<p>Anybody knows how to do this? I got all the information of the email (body, subject, from , to, cc, bcc) and need to generate an .eml file out of it.</p>
|
<p>You can construct <a href="https://javaee-spec.java.net/nonav/javadocs/javax/mail/internet/MimeMessage.html" rel="noreferrer"><code>javax.mail.Message</code></a> object (or have it already constructed from the mail server) and then you can use <a href="https://javaee-spec.java.net/nonav/javadocs/javax/mail/internet/MimeMessage.html#writeTo%28java.io.OutputStream%29" rel="noreferrer"><code>writeTo()</code></a> method to save it to file.
See <a href="http://www.oracle.com/technetwork/java/javamail/index.html" rel="noreferrer">JavaMail API</a> for more information.</p>
|
<p>If you want to add HTML Stuff you have to add </p>
<pre><code>content.setHeader("Content-Type", "text/html");
</code></pre>
<p>(as Marco Sulla said) but also change</p>
<pre><code>message.setContent(multipart);
</code></pre>
<p>to</p>
<pre><code>message.setContent(multipart,"text/html");
</code></pre>
| 19,020
|
<p>I have a view that I would like the user to rotate around its center, by tapping and holding somewhere and just move their finger round and round.</p>
<p>I have all the geometry worked out; What I do is store the initial touch angle relative to the center as offsetAngle, then my touchesMoved method looks like this:</p>
<pre><code>- (void) touchesMoved: (NSSet *)touches withEvent:(UIEvent *)event {
self.transform = CGAffineTransformMakeRotation(0);
CGPoint location = [[touches anyObject] locationInView: self];
CGPoint actualCenter = [self convertPoint: self.center fromView: self.superview];
CGPoint relativeTouch = [MathHelper translatePoint:location relativeTo: actualCenter];
CGPoint zero = CGPointMake(0, 0);
float angle = [MathHelper getAngleForPoint:zero andPoint:relativeTouch];
self.transform = CGAffineTransformMakeRotation(offsetAngle-angle);
}
</code></pre>
<p>The ugly bit is the first line, where I have to restore the rotation in order to get the correct event positions in the view. If I don't that, then the locations jump all over the place as there's no continuity, since the view is rotating...</p>
<p>Another issue is when you want to manipulate a view's frame (eg. moving it down), when the view has a transform applied:</p>
<pre><code>- (IBAction)toggleSettingsView {
BOOL state = [settingsSwitch isOn];
float height = optionsView.bounds.size.height;
CGRect polygonFrame = polygonView.frame;
[UIView beginAnimations:@"advancedAnimations" context:nil];
[UIView setAnimationDuration:0.3];
if (state) {
optionsView.alpha = 1.0;
polygonFrame.origin.y += height;
} else {
optionsView.alpha = 0.0;
polygonFrame.origin.y -= height;
}
polygonView.frame = polygonFrame;
[UIView commitAnimations];
}
</code></pre>
<p>This distorts the view heavily.</p>
<p>I must mention that both the CGTransform and the CALayer transform have the same effect.</p>
<p>This smells like I'm doing something wrong, but I don't know what I should be doing.</p>
|
<p>I would use the coordinate system of the superview, since it is unaffected by the rotation:</p>
<pre><code>- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
CGPoint location = [[touches anyObject] locationInView:self.superview];
CGPoint relativeTouch = [MathHelper translatePoint:location relativeTo:self.center];
CGPoint zero = CGPointMake(0, 0);
float angle = [MathHelper getAngleForPoint:zero andPoint:relativeTouch];
self.transform = CGAffineTransformMakeRotation(offsetAngle-angle);
}</code></pre>
|
<p>Just save the original transform in an ivar and call it a day.</p>
| 38,076
|
<p>I have a table that got into the "db_owner" schema, and I need it in the "dbo" schema.</p>
<p>Is there a script or command to run to switch it over?</p>
|
<p>In SQL Server Management Studio:</p>
<ol>
<li>Right click the table and select modify (it's called "Design" now)<br></li>
<li>On the properties panel choose the correct owning schema.</li>
</ol>
|
<p>You need to firstly stop all connections to the database, change the ownership of the tables that are 'db_owner' by running the command </p>
<pre><code>sp_MSforeachtable @command1="sp_changeobjectowner ""?"",'dbo'"
</code></pre>
<p>where ? is the table name.</p>
| 11,510
|
<p>Is there a practical algorithm that gives "multiplication chains"</p>
<p>To clarify, the goal is to produce a multiplication change of an <b>arbitrary and exact </b> length<br>
Multiplication chains of length 1 are trivial.</p>
<p>A "multiplication chain" would be defined as 2 numbers, {start} and {multiplier}, used in code:</p>
<pre><code> Given a pointer to array of size [{count}] // count is a parameter
a = start;
do
{
a = a * multiplier; // Really: a = (a * multiplier) MOD (power of 2
*(pointer++) = a;
}
while (a != {constant} )
// Postcondition: all {count} entries are filled.
</code></pre>
<p>I'd like to find a routine that takes three parameters<br>
1. Power of 2<br>
2. Stopping {constant}<br>
3. {count} - Number of times the loop will iterate </p>
<p>The routine would return {start} and {multiplier}. </p>
<p>Ideally, a {Constant} value of 0 should be valid.</p>
<p>Trivial example:</p>
<pre><code>power of 2 = 256
stopping constant = 7
number of times for the loop = 1
returns {7,1}
</code></pre>
<p>Nontrivial example: </p>
<pre><code>power of 2 = 256
stopping constant = 1
number of times for the loop = 49
returns {25, 19}
</code></pre>
<p>The maximum {count} for a given power of 2 can be fairly small.<br>
For example, 2^4 (16) seems to be limited to a count of 4 </p>
|
<p>You are asking for nontrivial solutions to the following modular equation:</p>
<pre><code>s * m^N = C (mod 2^D)</code></pre>
<p>where</p>
<ul>
<li>s is the starting constant</li>
<li>m is the multiplier</li>
<li>N is the number of iterations (given by the problem)</li>
<li>C is the final constant (given by the problem)</li>
<li>D is the exponent of the power of 2 (given by the problem)</li>
</ul>
<p>Have a look at <a href="http://en.wikipedia.org/wiki/Euler%27s_theorem" rel="nofollow noreferrer">Euler's theorem</a> in number theory.</p>
<p>For an arbitrary <em>odd</em> m (which is prime with 2^D), you have</p>
<pre><code>m^phi(2^D) = 1 (mod 2^D)</code></pre>
<p>thus</p>
<pre><code>C * m^phi(2^D) = C (mod 2^D)</code></pre>
<p>and finally</p>
<pre><code>C * m^(phi(2^D)-N) * m^N = C (mod 2^D)</code></pre>
<p>Take</p>
<pre><code>s = C * m^(phi(2^D)-N)</code></pre>
<p>and you're done. The <a href="http://en.wikipedia.org/wiki/Euler%27s_totient_function" rel="nofollow noreferrer">Euler's phi function</a> of a power of 2 is <em>half</em> that power of 2, i.e.:</p>
<pre><code>phi(2^D) = 2^(D-1)</code></pre>
<p><strong>Example</strong>. Let</p>
<ul>
<li>N = 5</li>
<li>C = 3</li>
<li>2^D = 16</li>
<li>phi(16) = 8</li>
</ul>
<p>Choose arbitrarily m = 7 (odd), and compute</p>
<pre><code>3 * 7^(8-5) = 1029
s = 1029 mod 16 = 5
</code></pre>
<p>Now</p>
<pre><code>s * m^N = 5 * 7^5 = 84035
84035 mod 16 = 3 == C
</code></pre>
|
<p>Why wouldn't this satisfy the requirements?</p>
<pre><code>start = constant;
multiplier = 1;
</code></pre>
<p>Update: I see now that the number of loops is one of the input parameters. It sounds like this problem is a special case of, or at least related to, the <a href="http://mathworld.wolfram.com/DiscreteLogarithm.html" rel="nofollow noreferrer">discrete logarithm</a> problem.</p>
| 31,884
|
<p>I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me?</p>
<pre><code>LinkedList<Diff_match_patch.Patch> patches = // whatever...
FileOutputStream fileStream = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(patches1);
os.close();
FileInputStream fileInputStream = new FileInputStream("foo.ser");
ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);
Object one = oInputStream.readObject();
LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;
os.close();
</code></pre>
|
<p>Sergio:</p>
<p>You should use <a href="http://docs.oracle.com/javase/6/docs/api/java/sql/Blob.html" rel="noreferrer">BLOB</a>. It is pretty straighforward with JDBC. </p>
<p>The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails.</p>
<p>If you still want to write it down into a String you can encode the bytes using <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html" rel="noreferrer">java.util.Base64</a>. </p>
<p>Still you should use CLOB as data type because you don't know how long the serialized data is going to be.</p>
<p>Here is a sample of how to use it.</p>
<pre><code>import java.util.*;
import java.io.*;
/**
* Usage sample serializing SomeClass instance
*/
public class ToStringSample {
public static void main( String [] args ) throws IOException,
ClassNotFoundException {
String string = toString( new SomeClass() );
System.out.println(" Encoded serialized version " );
System.out.println( string );
SomeClass some = ( SomeClass ) fromString( string );
System.out.println( "\n\nReconstituted object");
System.out.println( some );
}
/** Read the object from Base64 string. */
private static Object fromString( String s ) throws IOException ,
ClassNotFoundException {
byte [] data = Base64.getDecoder().decode( s );
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
private static String toString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
oos.close();
return Base64.getEncoder().encodeToString(baos.toByteArray());
}
}
/** Test subject. A very simple class. */
class SomeClass implements Serializable {
private final static long serialVersionUID = 1; // See Nick's comment below
int i = Integer.MAX_VALUE;
String s = "ABCDEFGHIJKLMNOP";
Double d = new Double( -1.0 );
public String toString(){
return "SomeClass instance says: Don't worry, "
+ "I'm healthy. Look, my data is i = " + i
+ ", s = " + s + ", d = " + d;
}
}
</code></pre>
<p>Output: </p>
<pre><code>C:\samples>javac *.java
C:\samples>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7T
AABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+w
QCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJ
DREVGR0hJSktMTU5PUA==
Reconstituted object
SomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0
</code></pre>
<p><strong>NOTE</strong>: for Java 7 and earlier you can see the original <a href="https://stackoverflow.com/revisions/134918/9">answer here</a></p>
|
<p>you can use UUEncoding</p>
| 16,279
|
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p>
<p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile" rel="noreferrer">execfile</a>:</p>
<ul>
<li><code>script_1.py</code> calls <code>script_2.py</code>. </li>
<li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li>
</ul>
<p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p>
<p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
|
<p>p1.py:</p>
<pre><code>execfile("p2.py")
</code></pre>
<p>p2.py:</p>
<pre><code>import inspect, os
print (inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
</code></pre>
|
<p>I used the approach with __file__<br>
<code>os.path.abspath(__file__)</code><br>
but there is a little trick, it returns the .py file
when the code is run the first time,
next runs give the name of *.pyc file<br>
so I stayed with:<br>
<code>inspect.getfile(inspect.currentframe())</code><br>
or<br>
<code>sys._getframe().f_code.co_filename</code> </p>
| 7,327
|
<p>To complete some testing I need to load the 64 bit version of an assembly even though I am running a 32 bit version of Windows. Is this possible?</p>
|
<p>I'm not sure why you would want to do this, but I suppose you could. If you don't do anything to tell it otherwise, the CLR will load the version of the assembly that is specific to the CPU you are using. That's usually what you want. But I have had an occasion where I needed to load the neutral IL version of an assembly. I used the <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load(VS.71).aspx" rel="nofollow noreferrer">Load method</a> to specify the version. I haven't tried it (and others here suggest it won't work for an executable assembly), but I suppose you can do the same to specify you want to load the 64 bit version. (You'll have to specify if you want the AMD64 or IA64 version.)</p>
|
<p>32 bit Windows can not run 64 bit executables without a VM/emutalor</p>
<p>32 bit Windows can compile for execution on 64 bit Windows</p>
| 13,277
|
<p>In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a <code>std::string</code>).<br>
<a href="http://rapidxml.sourceforge.net/" rel="nofollow noreferrer">RapidXml</a> has been recommended to me, but I can't see how to retrieve the XML back as a text string.<br>
(I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.)<br>
Thank you.</p>
|
<p>Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml:</p>
<pre><code>#include <iostream>
#include <sstream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
int main(int argc, char* argv[]) {
char xml[] = "<?xml version=\"1.0\" encoding=\"latin-1\"?>"
"<book>"
"</book>";
//Parse the original document
rapidxml::xml_document<> doc;
doc.parse<0>(xml);
std::cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
//Insert something
rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, "author", "John Doe");
doc.first_node()->append_node(node);
std::stringstream ss;
ss <<*doc.first_node();
std::string result_xml = ss.str();
std::cout <<result_xml<<std::endl;
return 0;
}
</code></pre>
|
<p>If you aren't yet committed to Rapid XML, I can recommend some alternative libraries:</p>
<ul>
<li><p>Xerces - This is probably the defacto C++ implementation.</p></li>
<li><p>XMLite - I've had some luck with this minimal XML implementation. See the article at <a href="http://www.codeproject.com/KB/recipes/xmlite.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/recipes/xmlite.aspx</a></p></li>
</ul>
| 5,896
|
<p>Specifically this is regarding when using a client session cookie to identify a session on the server.</p>
<p>Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie?</p>
<p>And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie?</p>
<p>If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session?</p>
|
<p>Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed.</p>
<p>The only real solution is HTTPS. If you don't want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not.</p>
<p><strong>EDIT</strong>: This answer was originally written in 2008. It's 2016 now, and there's no reason not to have SSL across your entire site. No more plaintext HTTP!</p>
|
<p>Protect by:</p>
<pre><code>$ip=$_SERVER['REMOTE_ADDER'];
$_SESSEION['ip']=$ip;
</code></pre>
| 4,290
|
<p>I am coding a feature in a program where users can edit documents stored in a database, it saves the document to a temporary folder then uses Process.Start to launch the document into the editing application, let's say Microsoft Word for example.</p>
<p>Then my app needs to wait until they've closed the called process and replace the document in the database with the newly edited copy in the temp folder.</p>
<p>The following code works great as long as the called application isn't already running:</p>
<pre><code>ProcessStartInfo pInfo = new ProcessStartInfo();
pInfo.FileName=TempFolder + Path.DirectorySeparatorChar + f.Name;
Process p = new Process();
p.StartInfo = pInfo;
p.Start();
//p is null at this point if called application was already running
//i.e. Microsoft Word is re-used instead of starting a fresh copy
p.WaitForInputIdle();
p.WaitForExit();
</code></pre>
<p>Is there a way to <em>force</em> starting a completely new process or can anyone think of another way to handle this. I really don't want the users to be able to do anything else in my app until they've closed the called process because I need to know if they edited that file or not at that point in time, not later when all sorts of other problems could creep up.</p>
|
<p>Personally I'm not sure I agree with this approach at all. Displaying a modal form might get you out of this situation, but in most cases when a solution seems hard to find, it's helpful to change the problem you're trying to solve.</p>
<p><strong>Option 1:</strong></p>
<p>In this case, I'd recommend a checkout/checkin model. This would allow users to "checkout" a file to their machine, and then check it in when they have finished updating it. This has a number of benefits:</p>
<ul>
<li>They can edit many documents at once, and perform checkin operations on multiple documents at once.</li>
<li>They can apply comments to checkins.</li>
<li>The user can shutdown their PC, or go offline and still work on their document.</li>
<li>The user can checkout multiple documents locally, then take the work home.</li>
<li>You don't have to try and work out what to do if the PC crashes (or the laptop battery runs out) while a document is open, and how to get it all back together again.</li>
</ul>
<p>The model also fits well with the concept of creating a new document, and adding it to the database. It's the same as a checkin.</p>
<p>You could easily provide reports that display who has what document checked out, and what their "working copy" location is.</p>
<p>I would concede that typically only developers are comfortable with this model, and that you may have to invest in a small amount of re-training. I don't think it would be difficult to setup an automated reminder system that emails people when they've had a document checked out for a long time.</p>
<p><strong>Option 2:</strong></p>
<p>Watch the file using a FileSystemWatcher or equivalent. This would enable you to keep an eye on the file, and when the user performs a save operation, you can commit to the database. After all, it's only if the user actually saved the file that you're interested in updating the database,</p>
|
<p>I'm not sure about the starting a new process, but have you considered this logic for waiting until exit:</p>
<p>while (Process.IsRunning) {}</p>
<p>basically just a holder loop until your process is done.</p>
| 38,973
|
<p>What is the difference in ASP/VBScript between <code>Int()</code> and <code>CInt()</code>?</p>
|
<ul>
<li><a href="http://www.w3schools.com/Vbscript/func_int.asp" rel="noreferrer">Int()</a></li>
</ul>
<blockquote>
<p>The Int function returns the integer part of a specified number.</p>
</blockquote>
<ul>
<li><a href="http://www.w3schools.com/VBScript/func_cint.asp" rel="noreferrer">CInt()</a></li>
</ul>
<blockquote>
<p>The CInt function converts an expression to type Integer.</p>
</blockquote>
<p>And the best answer comes from <a href="http://msdn.microsoft.com/en-us/library/fctcwhw9(VS.85).aspx" rel="noreferrer">MSDN</a></p>
<blockquote>
<p>CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.</p>
</blockquote>
|
<p>Here is another difference:</p>
<p>Script:</p>
<pre><code>wscript.echo 40.91 * 100
wscript.echo Int(40.91 * 100)
wscript.echo CInt(40.91 * 100)
</code></pre>
<p>result:</p>
<pre><code>4091
4090 (????)
4091
</code></pre>
<p>Any thoughts?</p>
| 4,100
|
<p>Let's assume that some developer in my team shelved his changes that he did in branch A. And I am working on branch B. Can I unshelve his changes into branch B? (By GUI or command prompt) </p>
|
<p>The <a href="http://msdn.microsoft.com/en-us/vstudio/bb980963.aspx" rel="noreferrer">Visual Studio Power Tools</a> should let you do this.</p>
<pre><code>C:\src\2\Merlin\Main>tfpt unshelve /?
tfpt unshelve - Unshelve into workspace with pending changes
Allows a shelveset to be unshelved into a workspace with pending changes.
Merges content between local and shelved changes. Allows migration of shelved
changes from one branch into another by rewriting server paths.
Usage: tfpt unshelve [shelvesetname[;username]] [/nobackup]
[/migrate /source:serverpath /target:serverpath]
shelvesetname The name of the shelveset to unshelve
/nobackup Skip the creation of a backup shelveset
/migrate Rewrite the server paths of the shelved items
(for example to unshelve into another branch)
/source:serverpath Source location for path rewrite (supply with /migrate)
/target:serverpath Target location for path rewrite (supply with /migrate)
/nobackup Skip the creation of a backup shelveset
</code></pre>
<p>For example to merge a shelve set called "Shelve Set Name" created on Branch1 to Branch2 use this:</p>
<pre><code>>tfpt unshelve "Shelve Set Name";domain\userName /migrate /source:"$/Project/Branch1/" /target:"$/Project/Branch2/"
</code></pre>
|
<p>I spent good amount of time to get this done and I had few issues to overcome. It is possible but here few issues and few rules to follow to avois these issues </p>
<p>Error:</p>
<blockquote>
<p>unable to determine the workspace</p>
</blockquote>
<p>This particular issue was solved by running the command from <strong>source</strong> branch root folder. This is contrary to some answers on SO where they say to use "target" branch - no, use "source":</p>
<pre><code>cd [your !!source!! branch root]
tfpt unshelve /migrate /source:"$/MyCollection/Development/Maint1.1" /target:"$/MyCollection/Development/Maint1.2" "myShelveset;UserName"
</code></pre>
<p>Second issue appeared after this. Seem that it couldn't connect to TFS server. What I realized, I have multiple VS installed and connected to different TFS servers. I was using VS12 and I had workspace and server connection. But I didn't realize that same connection needs to be replicated in VS13 for TFPT2013 to work. It connects to same server and workspace.</p>
<p>I also tried doing it using TFPT2015 but I installed it and it didn't install TFPT.exe hence it was useless. So I tried from TFPT2013 to TFS2015 and it worked for this particular command. I wonder, why not, if VS12/13 works fine against TFS2015?</p>
<p><strong>To summarize</strong></p>
<ul>
<li>Use CMD or DevCMD - doesn't matter</li>
<li>run command from <strong>source</strong> branch root folder</li>
<li>verify Team Explorer Server connection for specific VS</li>
<li>TF Power Tools 2013 work against TFS v15, at least <em>migrate</em> option works</li>
</ul>
| 14,287
|
<p>I'm very happy with the output from SandCastle, but I would also like to have some search functionality included in the HTML output, is this possible?</p>
|
<p>The Website output from SandCastle Help File Builder contains <strong>index.aspx</strong> and <strong>index.html</strong>.</p>
<p>If you display <strong>index.html</strong> then you don't get the search or index options:
<a href="http://www.ewoodruff.us/shfbdocs/index.html" rel="noreferrer">http://www.ewoodruff.us/shfbdocs/index.html</a></p>
<p>If you display <strong>index.aspx</strong> then you do get the search and index options:
<a href="http://www.ewoodruff.us/shfbdocs/index.aspx" rel="noreferrer">http://www.ewoodruff.us/shfbdocs/index.aspx</a></p>
|
<p>According the the <a href="http://shfb.codeplex.com/" rel="nofollow">site</a> it is, but I have not looked at how to configure it:</p>
<blockquote>
<p>The website output contains an HTML
and an ASP.NET index page with tree
view that can be used to navigate the
table of contents and a full-text
index search feature.</p>
</blockquote>
| 44,723
|
<p>Can you give me some pointers on making C# code and Java code interoperate?
Let's define the interoperation as something simple: allow (from Java code) the instantiantion and method calling of a class defined in C#, and, possibly, the other way around as well.</p>
<p>Is this even possible <em>natively</em>? (i.e. without some proxy/skeleton interface mechanism)</p>
<p>And finally, what proxy mechanisms can be used? (i.e. are supported by both language realms)</p>
|
<p>I've used <a href="http://www.ikvm.net/" rel="nofollow noreferrer">IKVM</a> to accomplish this successfully.</p>
|
<p>There are a few third-party products that can do .NET-Java interop natively. <a href="http://j-integra.intrinsyc.com/" rel="nofollow noreferrer">J-Integra</a> is the one I'm most familiar with (I don't work for them nor do I have any economic interest in them).</p>
<p>If you're ok with proxies and the like, you have a few options like SOAP/Web Services or CORBA.</p>
| 23,270
|
<p>Boost is a very large library with many inter-dependencies -- which also takes a long time to compile (which for me slows down our <a href="http://cruisecontrol.sourceforge.net/" rel="noreferrer"><strong>CruiseControl</strong></a> response time).</p>
<p>The only parts of boost I use are boost::regex and boost::format.</p>
<p>Is there an easy way to extract only the parts of boost necessary for a particular boost sub-library to make compilations faster?</p>
<p>EDIT: To answer the question about why we're re-building boost...</p>
<ol>
<li>Parsing the boost header files still takes a long time. I suspect if we could extract only what we need, parsing would happen faster too.</li>
<li>Our CruiseControl setup builds everything from scratch. This also makes it easier if we update the version of boost we're using. But I will investigate to see if we can change our build process to see if our build machine can build boost when changes occur and commit those changes to SVN. (My company has a policy that everything that goes out the door must be built on the "build machine".)</li>
</ol>
|
<p>First, you can use the bcp tool (can be found in the tools subfolder) to extract the headers and files you are using. This won't help with compile times, though. Second, you don't have to rebuild Boost every time. Just pre-build the lib files once and at every version change, and copy the "stage" folder at build time.</p>
|
<p>Precompiled headers are the word of the day! Include the boost headers you need in your precompiled header - tada!</p>
| 20,890
|
<p>I have some HTML that is generated via a Rich Text Editor outside of my Flex application but would like to display it inside Flex. </p>
<p>The HTML is simple HTML tags, things like styles, anchors, and possibly image tags, is there a control that would let me render this HTML in flex or am I going to have to roll up my sleeves and roll my own?</p>
<p>Any ideas appreciated...Thanks.</p>
|
<p>If the HTML is <em>really</em> simple, you can display it in a normal label or textarea component, If it is more complex, I'll quote what I answered <a href="https://stackoverflow.com/questions/22909/is-there-some-way-to-show-html-content-inside-flash">in this question</a>. The discussion there also has a little more info.</p>
<blockquote>
<p>If it is complex HTML and Javascript, one possible way is <a href="http://drumbeatinsight.com/htmlcomponent" rel="nofollow noreferrer">HTMLComponent</a>, a method that uses an iframe over your flash to make it appear like the HTML is in your app. There are a few downsides to this method however - most of them described in detail <a href="http://www.deitte.com/archives/2008/07/dont_use_iframe.htm" rel="nofollow noreferrer">at Deitte.com</a>.</p>
<p>If this can move offline, you could use Air (it has an mx:HTML component built in). <a href="http://www.deitte.com/archives/2008/07/an_air_version.htm" rel="nofollow noreferrer">Deitte.com</a> has a detail of this technique as well.</p>
</blockquote>
|
<p>@mmattax</p>
<p>Indeed you can display images in a TextArea component. The approach <a href="http://aralbalkan.com/239" rel="nofollow noreferrer">is not entirely without problems though</a>...</p>
| 7,384
|
<p>How do I <code>grep</code> and show the preceding and following 5 lines surrounding each matched line?</p>
|
<p>For <strong>BSD</strong> or <strong>GNU</strong> <code>grep</code> you can use <code>-B num</code> to set how many lines before the match and <code>-A num</code> for the number of lines after the match.</p>
<pre><code>grep -B 3 -A 2 foo README.txt
</code></pre>
<p>If you want the same number of lines before and after you can use <code>-C num</code>.</p>
<pre><code>grep -C 3 foo README.txt
</code></pre>
<p>This will show 3 lines before and 3 lines after.</p>
|
<pre><code>$ grep thestring thefile -5
</code></pre>
<p><code>-5</code> gets you <code>5</code> lines above and below the match 'thestring' is equivalent to <code>-C 5</code> or <code>-A 5 -B 5</code>.</p>
| 3,055
|
<p>Has anyone had a chance to dig into how <a href="http://blogs.msdn.com/andrewkennedy/archive/2008/08/20/units-of-measure-in-f-part-one-introducing-units.aspx" rel="noreferrer">F# Units of Measure</a> work? Is it just type-based chicanery, or are there CLR types hiding underneath that could (potentially) be used from other .net languages? Will it work for any numerical unit, or is it limited to floating point values (which is what all the examples use)?</p>
|
<p>According to a <a href="http://blogs.msdn.com/andrewkennedy/archive/2008/08/22/units-of-measure-in-f-part-two-unit-conversions.aspx#8920660" rel="noreferrer">response</a> on the next related blog post, they are a purely static mechanism in the F# compiler. So there is no CLR representation of the units data.</p>
<p>Its not entirely clear whether it currently works with non-float types, but from the perspective of the type system it is theoretically possible. </p>
|
<p>The best (and I think official) place to find out about this is on Andrew Kennedy's blog.</p>
<p>Here are the (current) relevant posts.</p>
<ul>
<li><a href="https://learn.microsoft.com/en-us/archive/blogs/andrewkennedy/units-of-measure-in-f-part-one-introducing-units" rel="nofollow noreferrer">Units of Measure in F#: Part One, Introducing Units</a></li>
<li><a href="http://web.archive.org/web/20100118052651/http://blogs.msdn.com/andrewkennedy/archive/2008/09/02/units-of-measure-in-f-part-two-unit-conversions.aspx" rel="nofollow noreferrer">Units of Measure in F#: Part Two, Unit Conversions</a></li>
<li><a href="https://learn.microsoft.com/en-us/archive/blogs/andrewkennedy/units-of-measure-in-f-part-three-generic-units" rel="nofollow noreferrer">Units of Measure in F#: Part Three, Generic Units</a></li>
<li><a href="https://learn.microsoft.com/en-us/archive/blogs/andrewkennedy/units-of-measure-in-f-part-four-parameterized-types" rel="nofollow noreferrer">Units of Measure in F#: Part Four, Parameterized Types</a></li>
</ul>
<p>As I said in the post that your answerer referred to, this is most definitely something that you CAN'T do in C# (though I wish you could).</p>
| 6,211
|
<p>What do you think is the best set-up for RoR in a Win Vista environment? I've tried the radrails eclipse plug-in, and it just seemed too bulky for me, I've also started to just use Textpad and the command line, but I'm used to having somewhat of an IDE to work with.</p>
|
<p>I don't know about "best", because that's a subjective question, but I can tell you what setup I use and recommend:</p>
<p><strong>Editor</strong>: <a href="http://e-texteditor.com" rel="noreferrer">E Text Editor</a><br>
TextMate seems to be the editor of choice for Rails on Mac. E Text Editor is essentially TextMate for Windows. Its bundles are broadly compatible with TextMate's including the Rails 2 bundle which is included with the basic install.</p>
<p>Alternatively, if you're into the whole Visual Studio ecosystem, then <a href="http://www.rubyinside.com/ruby-in-steel-pe-free-visual-studio-based-ruby-and-rails-ide-for-windows-1228.html" rel="noreferrer"><strong>Ruby in Steel PE</strong></a> might be a better bet. It's a really nice all-in-one package that actually comes with (a stripped-down version of) Visual Studio now.</p>
<p><strong>Environment</strong>: <a href="http://www.virtualbox.org/" rel="noreferrer">VirtualBox</a> running Ubuntu Server<br>
Deploying a Rails app can be a pain at the best of times; deploying a Rails app from a Windows environment onto a *nix server is even worse. Plus, <a href="http://railsforum.com/viewtopic.php?id=7219" rel="noreferrer">running Rails apps on Windows is slow</a>. Running your tests is slow. So I use VirtualBox to host a VM on my Windows machine that mirrors my target deployment environment as closely as possible. In my case I run Ubuntu Server because there are a really nice set of step-by-step tutorials for getting up-and-running with a full Ubuntu-based Rails stack on the <a href="http://articles.slicehost.com/ubuntu-hardy" rel="noreferrer">SliceHost wiki</a>. </p>
<p>Here are the benefits of developing using a VM:</p>
<ul>
<li>I map a network drive to the VM so that I can edit the code on it directly from Windows using E Text Editor. The VM acts and feels just like a command line window. So you don't feel like you're in a completely alien environment.</li>
<li>It runs Rails and other Ruby scripts (like tests) faster than running it natively in Windows</li>
<li>Everything is contained and <a href="http://servervirtualization.blogs.techtarget.com/2008/06/25/getting-to-know-sun-xvm-virtualbox-snapshots/" rel="noreferrer">snapshottable</a>, so I can experiment and generally play around without worrying about breaking anything. If something does break, I just roll back to a previous good state.</li>
<li>It uses hardly any RAM. It will typically use less that 100MB (it's currently using ~43MB, but I don't have a Rails app spun-up). Contrast this with, say, Firefox which will typically be hogging >200MB and you realize that running a Linux-based VM like this is amazingly efficient.</li>
<li>I can move my environment between machines</li>
<li>I have much more robust deployment workflow</li>
<li>I can limit the VM to have exactly the same amount of RAM as the server I'll be hosting on. E.g., if I'm to be using a SliceHost 256MB slice, I would limit the RAM to 256MB.</li>
<li>I can build a seperate environment for different hosts. If I wanted to host on Joyent, for example, I could build an Open Solaris VM</li>
<li>Gems and other binaries won't need recompiling for your target environment</li>
<li>It's "a good thing"™ to get to grips with the environment your Rails app is likely to be running on. Seeing as most, if not all, commercial Rails hosts run some sort of *nix derivative, you're going to want to be comfortable with the *nix environment.</li>
</ul>
|
<p>You might want to take a look at this:</p>
<p><a href="http://www.sapphiresteel.com/" rel="nofollow noreferrer">http://www.sapphiresteel.com/</a></p>
<p>There's a free personal edition too</p>
<p>(Updated: Assuming that you already have Visual Studio Full Fat Edition)</p>
| 2,554
|
<p>I have a List of strings that is regenerated every 5 seconds. I want to create a Context Menu and set its items dynamically using this list.
The problem is that I don't have even a clue how to do that and manage the Click action for every item generated (which should use the same method with different parameter DoSomething("item_name")).</p>
<p>How should I do this?</p>
<p>Thanks for your time.
Best regards.</p>
|
<p>So, you can clear the items from the context menu with:</p>
<pre><code>myContextMenuStrip.Items.Clear();
</code></pre>
<p>You can add an item by calling:</p>
<pre><code>myContextMenuStrip.Items.Add(myString);
</code></pre>
<p>The context menu has an ItemClicked event. Your handler could look like so:</p>
<pre><code>private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
DoSomething(e.ClickedItem.Text);
}
</code></pre>
<p>Seems to work OK for me. Let me know if I misunderstood your question.</p>
|
<p>Another alternative using a <code>ToolStripMenuItem</code> object:</p>
<pre><code>//////////// Create a new "ToolStripMenuItem" object:
ToolStripMenuItem newMenuItem= new ToolStripMenuItem();
//////////// Set a name, for identification purposes:
newMenuItem.Name = "nameOfMenuItem";
//////////// Sets the text that will appear in the new context menu option:
newMenuItem.Text = "This is another option!";
//////////// Add this new item to your context menu:
myContextMenuStrip.Items.Add(newMenuItem);
</code></pre>
<p><br>
Inside the <code>ItemClicked</code> event of your <code>myContextMenuStrip</code>, you can check which option has been chosen (<em>based on the name property of the menu item</em>)</p>
<pre><code>private void myContextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ToolStripItem item = e.ClickedItem;
//////////// This will show "nameOfMenuItem":
MessageBox.Show(item.Name, "And the clicked option is...");
}
</code></pre>
| 27,857
|
<p>Is there anything out there (for Java specifically) that allow you to automatically test the behavior of an interface? As an example, let's say I have a bunch of tests for the Comparable interface, that should apply to anything that implements Comparable. What I'd like is to be able to include "ComparableTests" automatically in the test fixtures for any of my classes which implement Comparable. Bonus points if this would work with generic interfaces.</p>
<p>I know the .NET framework <a href="http://weblogs.asp.net/astopford/archive/2008/08/25/mbunit-typefixture.aspx" rel="nofollow noreferrer">mbUnit</a> has something similar, and when you're using something like TestNG's generator functions you could set up a test fixture for Comparable and have the generator create an instance of each of your classes that implement Comparable. But I'd rather have it be automatic, and located at the test fixture for each of my classes (since I'll already have them around for testing other parts of that class).</p>
<p><strong>Clarification:</strong> I could definitely build something like this. I was asking if there was anything out there that already enabled this.</p>
|
<p>Based on your last paragraph, what you're trying to do is inject some 'extra methods' into unit testing since you're already testing a specific class. I do not know of a testing harness that allows you to attach tests based on the hierarchy of a class.</p>
<p>However, with your own suggestion of using TestNG for building something similar, I think you might be very close. You could very well incorporate some base code that adds your class to a list of 'default test classes', which are in turn tested if they implement a specific interface.</p>
<p>Still, regarding the general case, I think you're out of luck, since the Java type system is one-way, you can only (easily) find out what interfaces a class implements, not the other way around. Furthermore, the problem is 'where to stop looking': if you have a test that checks all your <code>comparable</code> implementers, do you want it to check the validity of <code>String</code>'s one too, since that is in your Java environment?</p>
|
<p>In .NET it would be pretty simple to set up a method that looks through an assembly and identifies each class's inheritance/implementation hierarchy. I'm sure you could do it in Java, too, if you research the <a href="http://www.onjava.com/pub/a/onjava/2007/03/15/reflections-on-java-reflection.html" rel="nofollow noreferrer">Java reflection API</a>.</p>
<p>You could then create an array of <code>ITargetInterface</code>s and call a test method on each one.</p>
| 13,435
|
<p>This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:</p>
<ul>
<li><p><strong>Firstly</strong>: Given an established C# project, what are some decent ways to speed it up beyond just plain in-code optimization?</p></li>
<li><p><strong>Secondly</strong>: When writing a program from scratch in C#, what are some good ways to greatly improve performance?</p></li>
</ul>
<p><strong>Please stay away from general optimization techniques unless they are <em>C# specific</em>.</strong></p>
<p>This has previously been asked for <a href="https://stackoverflow.com/questions/172720/speeding-up-python">Python</a>, <a href="https://stackoverflow.com/questions/177122/speeding-up-perl">Perl</a>, and <a href="https://stackoverflow.com/questions/179745/speeding-up-java">Java</a>.</p>
|
<p>Off the top of my head:</p>
<ul>
<li>Replace non-generic variants of container classes by their generic counterparts</li>
<li>Cut down on boxing/unboxing. Specifically, use generics where possible and generally avoid passing value types as <code>object</code>.</li>
<li>For dialogs using many dynamic controls: suspend drawing until after inserting all controls by using <code>SuspendLayout</code>/<code>ResumeLayout</code>. This helps especially when using layout containers.</li>
</ul>
|
<p>For Windows Forms on XP and Vista: Turn double buffering on across the board. It does cause transparency issues, so you would definitely want to test the UI:</p>
<pre><code>protected override System.Windows.Forms.CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | 0x2000000;
return cp;
}
}
</code></pre>
| 22,122
|
<p>I've got a WPF browser-like application with a few pages. When I switch between pages, I'd like to set the keyboard focus.</p>
<p>When a page is loaded the first time, this works by calling <code>Control.Focus()</code> in the constructor.</p>
<p>But when I switch between pages this does not work anymore - the focus is just on the first field, and ignores my attempts to change it to anything else :(</p>
<p>The pages have the attribute <code>KeepAlive=true</code> - it would be OK if that would keep the focus alive, too, but just setting the focus to the first field is annoying.</p>
<p>I tried to set the focus in the loaded event, but it did not work, too. It seems the default focus is set after reloading the page.</p>
<p>Is there any way to set the focus on entering a page the second time? <strong>When, how and where should I set the focus when switching between WPF pages in a browserlike application</strong>?</p>
|
<p>Try Adding FocusManager.FocusedElement="{Binding ElementName=[...]}"``
to the first Element in your Page and set [...] to the name of the element which should get the focus.</p>
|
<p>Have you tried setting the focus in the Loaded event handler rather than the constructor? Pages aren't re-constructed when you navigate back to them, but they are reloaded if I recall correctly.</p>
| 21,442
|
<p>There doesn't seem to be much info on this topic so I'm going to outline my specific problem then maybe we can shape the question and the answer into something a bit more universal.</p>
<p>I have this rewrite rule</p>
<pre><code>RewriteEngine On
RewriteBase /bookkeepers/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/?$ index.php?franchise=$1
</code></pre>
<p>Which is changes this URL</p>
<pre><code>http://example.com/location/kings-lynn
</code></pre>
<p>Into this one</p>
<pre><code>http://example.com/location/index.php?franchise=kings-lynn
</code></pre>
<p>The problem I am having is that if I add a trailing slash</p>
<pre><code>http://example.com/location/kings-lynn/
</code></pre>
<p>then the query string is returned as</p>
<pre><code>franchise=kings-lynn/
</code></pre>
<p>and for some reason none of my CSS and Javascript files are being loaded.</p>
<p>Any ideas?</p>
|
<p>As @Paul Tomblin said, the .+ is being greedy; that is, it's matching as much as it can.</p>
<p><code>^(.+[^/])/?$</code> tells it to match anything, followed by a character that isn't a /, then followed by an optional /. This has the effect of not capturing the trailing /.</p>
<p>The most probable reason your CSS and Javascript doesn't work is you're using a relative path, like src="my.js". When there's a trailing slash, it looks like a directory, so your browser will look for /location/kings-lynn/my.js. You can fix this simply by using an absolute path to your files (e.g. /location/my.js).</p>
|
<p>It looks like the (.+) is being greedy matched. In that case, you could try</p>
<pre><code>RewriteRule ^(.+[^/])/?$ index.php?franchise=$1
</code></pre>
<p>This makes sure that the first group (in the brackets) doesn't end in a slash.</p>
| 40,646
|
<p>I'm an application packager trying to make sense of how the COM registry keys (SelfReg) interrelate to the given .dll in Windows.</p>
<p>ProgID's, AppID's, TypeLibs, Extensions & Verbs are all tied around the CLSID right?
Do CLSID's always use Prog/App IDs or could you just have a file extension class?
Which bits are optional? </p>
<p>Some of it seems to be 'like a router' where there's the two interfaces (internal - .dll) and external (the extension etc).</p>
<p>How does this all fit? (The SDK documentation doesn't make sense to me)</p>
<p>I ask as this is all pivotal to application 'healing' with Windows Installer (which packagers are all 'big' on, but there's no nitty-gritty breakdowns since its a coder-thing really)</p>
<p>---Edit:
Am I safe in assuming that for what COM is registered, it must all link back to the CLSID and cannot be a 'dead-end'?
Verbs need extensions which need progid's...</p>
<p>What about the AppId's, TypeLibs and Interfaces? How do they interrelate?</p>
|
<p>The first thing to realise, is that COM dlls register themselves. They will put all the required entries into the correct places in the registry.</p>
<p>I think the answer to your central question about which bits are optional is probably that they are all optional for different types of objects. Automation objects require Prog/AppIDs if they are publicly creatable, but may not if they are only created internally, similarly a non- publicly creatable COM class can be listed. </p>
<p>Many COM objects that do not have automation interfaces (such as many of the COM classes microsoft uses internally in windows will not have any ProgId but will simply have an entry under their CLSID in HKCR\CLSID.</p>
<p>If I understand you correctly you are interested in this from a installer perspective. I would imagine that all you need do is ask the user to specify which dlls are selfregistering and then call</p>
<blockquote>
<p>regsvr32 dllname.dll </p>
</blockquote>
<p>or</p>
<blockquote>
<p>exename.exe /Regserver</p>
</blockquote>
<p>for a out of process server. If something goes wrong you just need to call the opposites.</p>
<blockquote>
<p>regsvr32 /u dllname.dll </p>
</blockquote>
<p>or</p>
<blockquote>
<p>exename.exe /Unregserver</p>
</blockquote>
<p>I hope that this answers your question.</p>
|
<p>I used an answer cos the comments seem so limited. Not sure how SO will interpret this (maybe I'll be deemed mad for talking to myself?)</p>
<blockquote>
<p>"how does it work" question will require a really, really long answer</p>
</blockquote>
<p> Thanks - what I'm trying to acheive is an understanding of that without actually being a developer - this is because of the way packagers attempt to group the COM registry keys with the .dll (in the same component) so that application resiliency works. </p>
<p>This means 'trapping' the COM from the .dll's registration and associating it in the correct advertising tables (CLSID, AppID ...<em>ad nauseum</em>) to the component that holds the .dll. Sometimes this isn't easy to see and sometimes (I'm told) it can break the app from functioning. I'm told that the COM doesn't <strong>need</strong> to be complete (self-referential).</p>
<p>I'm still trying to get my head around it all.
Of course, if the packager captures all the information but doesn't associate the COM info to the .dll, the regkeys are still written at install-time, just the MSI doesn't baby-sit the application if things go wrong (which is almost never)</p>
| 25,981
|
<p>We've developed a Java application and would like to use this application from a C# client. The application has dependencies on Spring, Log4j, ... </p>
<p>What would be the most efficient mechanism - make DLL(s) from Java code, ... - to achieve this ?</p>
|
<p><a href="http://www.ikvm.net/" rel="noreferrer">IKVM!</a></p>
<p>It is really awesome. The only problem is that it DOES add ~30MB to the project.
log4net and Spring .NET are available as well, but if living with existing code, go the ikvm route.</p>
|
<p>alternatively you could write a webservice/xmlrpc layer between the two.</p>
<p>I seem to remember that there is a tool calles grassshopper that will compile your .Net code into JVM bytecode.</p>
<p>I've also heard good things about IKVM</p>
| 15,788
|
<p>I've been trying to get into F# on and off for a while but I keep getting put off. Why?</p>
<p>Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator <code>-></code>.</p>
<p>However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies.</p>
<p>I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back.</p>
<p>Can someone please, explain it or point to a truly accessible resource that explains it?</p>
|
<p>'->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct.</p>
<p>Inside a type, '->' describes function types as people have described above. For example</p>
<pre><code>let f : int -> int = ...
</code></pre>
<p>says that 'f' is a function that takes an int and returns an int.</p>
<p>Inside a lambda ("thing that starts with 'fun' keyword"), '->' is syntax that separates the arguments from the body. For example</p>
<pre><code>fun x y -> x + y + 1
</code></pre>
<p>is an expression that defines a two argument function with the given implementation.</p>
<p>Inside a "match" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in</p>
<pre><code>match someList with
| [] -> 0
| h::t -> 1
</code></pre>
<p>the stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched.</p>
<p>The difficulty in understanding may be rooted in the faulty assumption that '->' is "an operator" with a single meaning. An analogy might be "." in C#, if you have never seen any code before, and try to analyze the "." operator based on looking at "obj.Method" and "3.14" and "System.Collections", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear.</p>
|
<p>The nice thing about languages such as Haskell (it's very similar in F#, but I don't know the exact syntax -- this should help you understand ->, though) is that you can apply only parts of the argument, to create <em>curried</em> functions:</p>
<pre><code>adder n x y = n + x + y
</code></pre>
<p>In other words: "give me three things, and I'll add them together". When you throw numbers at it, the compiler will infer the types of n x and y. Say you write</p>
<pre><code>adder 1 2 3
</code></pre>
<p>The type of 1, 2 and 3 is Int. Therefore:</p>
<pre><code>adder :: Int -> Int -> Int -> Int
</code></pre>
<p>That is, give me three integers, and I will become an integer, eventually, or the same thing as saying:</p>
<pre><code>five :: Int
five = 5
</code></pre>
<p>But, here's the nice part! Try this:</p>
<pre><code>add5 = adder 5
</code></pre>
<p>As you remember, adder takes an int, an int, an int, and gives you back an int. However, that is not the entire truth, as you'll see shortly. In fact, add5 will have this type:</p>
<pre><code>add5 :: Int -> Int -> Int
</code></pre>
<p>It will be as if you have "peeled off" of the integers (the left-most), and glued it directly to the function. Looking closer at the function signature, we notice that the -> are right-associative, i.e.:</p>
<pre><code>addder :: Int -> (Int -> (Int -> Int))
</code></pre>
<p>This should make it quite clear: when you give adder the first integer, it'll evaluate to whatever's to the right of the first arrow, or:</p>
<pre><code>add5andtwomore :: Int -> (Int -> Int)
add5andtwomore = adder 5
</code></pre>
<p>Now you can use add5andtwomore instead of "adder 5". This way, you can apply another integer to get (say) "add5and7andonemore":</p>
<pre><code>add5and7andonemore :: Int -> Int
add5and7andonemore = adder 5 7
</code></pre>
<p>As you see, add5and7andonemore wants exactly another argument, and when you give it one, it will suddenly become an integer!</p>
<pre><code> > add5and7andonemore 9
=> ((add5andtwomore) 7) 9
=> ((adder 5) 7) 9)
<=> adder 5 7 9
</code></pre>
<p>Substituting the parameters to adder (n x y) for (5 7 9), we get:</p>
<pre><code> > adder 5 7 9 = 5 + 7 + 9
=> 5 + 7 + 9
=> 21
</code></pre>
<p><em>In fact</em>, plus is also just a function that takes an int and gives you back another int, so the above is really more like:</p>
<pre><code> > 5 + 7 + 9
=> (+ 5 (+ 7 9))
=> (+ 5 16)
=> 21
</code></pre>
<p>There you go!</p>
| 13,026
|
<p>I have a set of Berkeley DB files on my Linux file system that I'd like to examine.</p>
<p>What useful tools exist for getting a quick overview of the contents? I can write Perl scripts that use BDB modules for examining them, but I'm looking for some CLI utility to be able to take a look inside without having to start writing scripts.</p>
|
<p>Check out the <strong>db-utils</strong> package. If you use apt, you can install it with the following: <code>apt-get install db-util</code> (or <code>apt-get install db4.8-util</code> or whatever version you have or prefer.)</p>
<p>Additional links:</p>
<ul>
<li><a href="http://rpmfind.net/linux/rpm2html/search.php?query=db-utils" rel="nofollow noreferrer">http://rpmfind.net/linux/rpm2html/search.php?query=db-utils</a></li>
<li><a href="http://packages.ubuntu.com/search?keywords=db4.4-util" rel="nofollow noreferrer">https://packages.ubuntu.com/search?suite=default&section=all&arch=any&keywords=db-util&searchon=names</a></li>
<li><a href="http://www.linux.gr/cgi-bin/man/man2html?db4.4_dump+1" rel="nofollow noreferrer">Man page of db4.4_dump</a></li>
</ul>
|
<p>Under Amazon Linux you can install it with:</p>
<p><strong>yum install db43-utils</strong></p>
| 5,841
|
<p>I recall there is a difference between some methods/properties called directly on the <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable(VS.71).aspx" rel="noreferrer">DataTable</a> class, and the identically named methods/properties on the <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.rows(VS.71).aspx" rel="noreferrer">DataTable.Rows</a> property. (Might have been the RowCount/Count property for which I read this.) The difference is one of them disregards <a href="http://msdn.microsoft.com/en-us/library/system.data.datarow.rowstate(VS.71).aspx" rel="noreferrer">DataRow.RowState</a>, and the other respects/uses it.</p>
<p>In this particular case I'm wondering about the difference between <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.clear(VS.71).aspx" rel="noreferrer">DataTable.Clear</a> and <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowcollection.clear(VS.71).aspx" rel="noreferrer">DataTable.Rows.Clear</a>. I can imagine one of them actually removes all rows, and the other one just marks them as deleted.</p>
<p>So my question is, <strong>is there a difference between the two Clear methods, and if so what is the difference?</strong></p>
<p>(Oh, this is for .NET 1.1 btw, in case the semantics changed from one version to another.)</p>
|
<p>In .Net 1.1, <code>DataRowCollection.Clear</code> calls <code>DataTable.Clear</code></p>
<p>However, in .Net 2.0, there is a difference.
If I understand the source correctly, <code>DataTable.Clear</code> will clear unattached rows (created using <code>DataTable.NewRow</code>) whereas DataRowCollection.Clear won't.</p>
<p>The difference is in <code>RecordManager.Clear</code> (source below, from the <a href="http://referencesource.microsoft.com/netframework.aspx" rel="noreferrer">.Net Reference Source</a> for v3.5 SP 0); <code>clearAll</code> is true only when called from <code>DataTable.Clear</code>.</p>
<pre><code> internal void Clear(bool clearAll) {
if (clearAll) {
for(int record = 0; record < recordCapacity; ++record) {
rows[record] = null;
}
int count = table.columnCollection.Count;
for(int i = 0; i < count; ++i) {
//
DataColumn column = table.columnCollection[i];
for(int record = 0; record < recordCapacity; ++record) {
column.FreeRecord(record);
}
}
lastFreeRecord = 0;
freeRecordList.Clear();
}
else { // just clear attached rows
freeRecordList.Capacity = freeRecordList.Count + table.Rows.Count;
for(int record = 0; record < recordCapacity; ++record) {
if (rows[record]!= null && rows[record].rowID != -1) {
int tempRecord = record;
FreeRecord(ref tempRecord);
}
}
}
}
</code></pre>
|
<p>The both do the same thing. One is just an inherited method from the Collections class. And the Table.Clear() just calls that method.</p>
| 20,065
|
<p>I'm making a mini ORM for a Java program I'm writing... there is a class for each table in my db, all inheriting from <code>ModelBase</code>.</p>
<p><code>ModelBase</code> is abstract & provides a bunch of static methods for finding & binding objects from the db, for example:</p>
<pre><code>public static ArrayList findAll(Class cast_to_class) {
//build the sql query & execute it
}
</code></pre>
<p>So you can do things like <code>ModelBase.findAll(Albums.class)</code> to get a list of all persisted albums.
My problem is that in this static context, I need to get the appropriate sql string from the concrete class Album. I can't have a static method like </p>
<pre><code>public class Album extends ModelBase {
public static String getSelectSQL() { return "select * from albums.....";}
}
</code></pre>
<p>because there is no polymorphism for static methods in Java. But I don't want to make <code>getSelectSQL()</code> an instance method in <code>Album</code> because then I need to create an instance of it just to get a string that is really static in behavior.</p>
<p>At the moment, <code>findAll()</code> uses reflection to get the appropriate sql for the class in question:</p>
<pre><code>select_sql = (String)cast_to_class.getDeclaredMethod("getSelectSql", new Class[]{} ).invoke(null, null);
</code></pre>
<p>But that's pretty gross. </p>
<p>So any ideas? It's a general problem I'm having time and time again - the inability to specify abstract static methods in classes or interfaces. I know <em>why</em> static method polymorphism doesn't and can't work, but that doesn't stop me from wanting to use it time again!</p>
<p>Is there any pattern/construct that allows me to ensure that concrete subclasses X and Y implement a class method(or failing that, a class constant!)?</p>
|
<p>Albeit, I totally agree in the point of "Static is the wrong thing to be using here", I kind of understand what you're trying to address here. Still instance behavior should be the way to work, but if you insist this is what I would do:</p>
<p>Starting from your comment "I need to create an instance of it just to get a string that is really static in behaviour" </p>
<p>It is not completely correct. If you look well, you are not changing the behavior of your base class, just changing the parameter for a method. In other words you're changing the data, not the algorithm.</p>
<p>Inheritance is more useful when a new subclass wants to change the way a method works, if you just need to change the "data" the class uses to work probably an approach like this would do the trick.</p>
<pre><code>class ModelBase {
// Initialize the queries
private static Map<String,String> selectMap = new HashMap<String,String>(); static {
selectMap.put( "Album", "select field_1, field_2 from album");
selectMap.put( "Artist", "select field_1, field_2 from artist");
selectMap.put( "Track", "select field_1, field_2 from track");
}
// Finds all the objects for the specified class...
// Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
public static List findAll(Class classToFind ) {
String sql = getSelectSQL( classToFind );
results = execute( sql );
//etc...
return ....
}
// Return the correct select sql..
private static String getSelectSQL( Class classToFind ){
String statement = tableMap.get( classToFind.getSimpleName() );
if( statement == null ) {
throw new IllegalArgumentException("Class " +
classToFind.getSimpleName + " is not mapped");
}
return statement;
}
}
</code></pre>
<p>That is, map all the statements with a Map. The "obvious" next step to this is to load the map from an external resource, such as a properties file, or a xml or even ( why not ) a database table, for extra flexibility.</p>
<p>This way you can keep your class clients ( and your self ) happy, because you don't needed "creating an instance" to do the work.</p>
<pre><code>// Client usage:
...
List albums = ModelBase.findAll( Album.class );
</code></pre>
<p>...</p>
<p>Another approach is to create the instances from behind, and keep your client interface intact while using instance methods, the methods are marked as "protected" to avoid having external invocation. In a similar fashion of the previous sample you can also do this</p>
<pre><code>// Second option, instance used under the hood.
class ModelBase {
// Initialize the queries
private static Map<String,ModelBase> daoMap = new HashMap<String,ModelBase>(); static {
selectMap.put( "Album", new AlbumModel() );
selectMap.put( "Artist", new ArtistModel());
selectMap.put( "Track", new TrackModel());
}
// Finds all the objects for the specified class...
// Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
public static List findAll(Class classToFind ) {
String sql = getSelectSQL( classToFind );
results = execute( sql );
//etc...
return ....
}
// Return the correct select sql..
private static String getSelectSQL( Class classToFind ){
ModelBase dao = tableMap.get( classToFind.getSimpleName() );
if( statement == null ) {
throw new IllegalArgumentException("Class " +
classToFind.getSimpleName + " is not mapped");
}
return dao.selectSql();
}
// Instance class to be overrided...
// this is "protected" ...
protected abstract String selectSql();
}
class AlbumModel extends ModelBase {
public String selectSql(){
return "select ... from album";
}
}
class ArtistModel extends ModelBase {
public String selectSql(){
return "select ... from artist";
}
}
class TrackModel extends ModelBase {
public String selectSql(){
return "select ... from track";
}
}
</code></pre>
<p>And you don't need to change the client code, and still have the power of polymorphism.</p>
<pre><code>// Client usage:
...
List albums = ModelBase.findAll( Album.class ); // Does not know , behind the scenes you use instances.
</code></pre>
<p>...</p>
<p>I hope this helps.</p>
<p>A final note on using List vs. ArrayList. It is always better to program to the interface than to the implementation, this way you make your code more flexible. You can use another List implementation that is faster, or does something else, without changing your client code.</p>
|
<p>I agree with Gizmo: you're either looking at annotations or some sort of configuration file. I'd take a look at Hibernate and other ORM frameworks (and maybe even libraries like log4j!) to see how they handle loading of class-level meta-information.</p>
<p>Not everything can or should be done programmatically, I feel this may be one of those cases.</p>
| 18,293
|
<p>I have seen a few suggestions on making emacs portable (on Windows). I have this in my site-start.el:</p>
<pre><code>(defvar program-dir (substring data-directory 0 -4))
(setq inhibit-startup-message t)
(setenv "HOME" program-dir)
</code></pre>
<p>I changed the HOME variable so that not only my .emacs init files (and other init files) are read, but everything generated by emacs will stay in the program directory, not needing me to specify the path for everything one by one. </p>
<p>Well this works well but the emacs server is not working; I get error message "no connection could be made because target machine actively refused it." If I don't change my HOME var then emacs server works. Is there way to fix this?</p>
|
<p>Quoth <a href="http://www.gnu.org/software/emacs/manual/html_node/emacs/Invoking-emacsclient.html" rel="nofollow noreferrer">the Emacs manual</a>:</p>
<blockquote>When you start the Emacs server (by calling server-start), Emacs creates a file with information about TCP connection to the server: the host where Emacs is running, the port where it is listening, and an authentication string. emacsclient uses this information if it needs to connect to the server via TCP. By default, the file goes in the ~/.emacs.d/server/ directory. You can specify the file name to use with the `-f file' or `--server-file=file' options, or by setting EMACS_SERVER_FILE environment variable to the file name. </blockquote>
<p>In other words: wherever you're calling <code>emacsclient</code> from, you'll have to tell <em>it</em> to use the file in <code>${program-dir}/.emacs.d/server/</code>, either with <code>-f</code> or setting the <code>EMACS_SERVER_FILE</code> environment variable. (In the environment in which you're starting <code>emacsclient</code>, not within Emacs.)<br/>
[You <em>could</em> also tell Emacsclient to look in the right place with <code>-s</code> for "socket", but that doesn't work on Windows. And on Unixes (at least on Mac OS X with Aquamacs) the socket would be somewhere like <code>/tmp/emacs501/server</code> (501 is my UID).]</p>
<p>[Oh, BTW, take a look at this question: <a href="https://stackoverflow.com/questions/350345/how-can-i-have-a-portable-emacs">How can I have a portable Emacs?</a> Maybe something will help you, or maybe you have something to add to it :-)]</p>
|
<p>There is an initial packaging of a Portable Apps version of emacs 23.2 <a href="http://portableapps.com/node/23470" rel="nofollow noreferrer">here.</a> Initial test works here.</p>
| 46,896
|
<p>Whats the normal procedure of clearing a form after POST? Just loop through the textboxes and cleat all text? I have an ASP.NET application with several forms and I am trying to avoid them sending the data twice?</p>
<p>Thanks</p>
|
<p>You can avoid double sending/doing by putting your code inside an if(!isPostBack) block. This will tell the page not to do the specified actions when posting.</p>
|
<p>You can inject some javascript code to execute after postback.</p>
<pre><code>document.forms[0].reset();
document.forms[1].reset();
</code></pre>
<p>From server side, I haven't found an easy way to reset the form contents other than iterating through the controls inside a loop or doing a <a href="http://support.microsoft.com/?kbid=839521" rel="nofollow noreferrer">Server.Transfer</a> back to the same page.</p>
| 32,577
|
<p>I've read in one of my AI books that popular algorithms (A-Star, Dijkstra) for path-finding in simulation or games is also used to solve the well-known "15-puzzle".</p>
<p>Can anyone give me some pointers on how I would reduce the 15-puzzle to a graph of nodes and edges so that I could apply one of these algorithms?</p>
<p>If I were to treat each node in the graph as a game state then wouldn't that tree become quite large? Or is that just the way to do it?</p>
|
<p>A quick Google search turns up a couple papers that cover this in some detail: one on <a href="http://web.archive.org/web/20170329021919/http://www.cse.psu.edu:80/~pxr3/optslides.pdf" rel="nofollow noreferrer">Parallel Combinatorial Search</a>, and one on <a href="http://icaps08.cecs.anu.edu.au/TUTORIALS/Edelkamp-Hansen-Jabbar-Zhou.pdf" rel="nofollow noreferrer">External-Memory Graph Search</a></p>
<p>General rule of thumb when it comes to algorithmic problems: <em>someone has likely done it before you, and published their findings</em>.</p>
|
<p>For my current experience, on how to solve an 8 puzzle.
it is required to create nodes. keep track of each step taken
and get the manhattan distance from each following steps, taking/going to the one with the shortest distance.
update the nodes, and continue until reaches the goal</p>
| 12,057
|
<p>I have a new project which simply put, is an attempt to formalize the look and feel of all of our departmental pages. I Googled around and found many tutorials which discussed the pros and cons of several techniques. And from what I've been reading, the thing I'm ooking for is controls. Basically, I want a common header and footer.</p>
<pre><code><header>
<content>
<footer>
</code></pre>
<p>The content portion would be where I'd place specific content pertaining to the department. I could make a blank template which include both header and footer, which was my original idea. Then, once the time comes to create a new page, I would then copy and template and start filling in the content. Is there a simpler way of doing this pragmatically?</p>
<p>Thank you.</p>
|
<p><a href="http://www.odetocode.com/Articles/419.aspx" rel="nofollow noreferrer">Masterpages</a> would seem to be what you are looking for.</p>
|
<p>Conceptually, I think you're very much on the right track. It's much easier to conceive of a page model in terms of some very simple containers (header, footer, content). You can take it a step further by defining blocks of display logic (top navbar, footer links, left ad bar, etc.) that you can use to populate the larger containers.</p>
<p>Pragmatically, how would you do this? First, it depends on what platform and language you're using. Solutions for .NET, Java, PHP, or flat HTML could be implemented differently depending on where you choose to draw the lines. In flat HTML, one way is to use #include files. In the programming languages, you have to decide what your outermost container structure is going to be and how you're going to define the building blocks (which by default defines how you aggregate them). There are many possible ways to do this.</p>
<p>And are you going to be the person creating & managing the site, or will you be delegating that responsibility to a team of non-technical content owners across your organization? That answer can bear heavily on your design choices.</p>
<p>In many of the content management systems, the idea is to cleanly separate content from presentation. So there is a generic content storage paradigm typically in a database and then there is a dynamic way to present that content out through some display mechanism written in a lightweight platform.</p>
| 42,254
|
<p>Good file comparison tools were already discussed to the pain, but my problem is more exotic. Is there any visual text comparison tool (like WinMerge) that would allow me easily do visual comparison on two sections within the same file?</p>
<p>I have multiple configurations within vcproj file and need to maintain them. It is a pain to do this manually -- splitting windows, scrolling character-by character. On top of that xml is very verbose and takes lots of screen real-estate. I cannot believe there is no tool to do automatic file section comparison, since this sounds like a very common problem.</p>
<p>Please, do not offer me to use property pages, I do not want more complexity, I want less. Splitting manually into files and then comparing them is also too medieval (I am doing this now anyways).</p>
|
<p>I use <a href="http://www.scootersoftware.com/" rel="noreferrer">Beyond Compare</a> (not free, but I think a shareware version is available). You can select the same file for left and right sides, then right-click the beginning of your section on each side and select "Align Manually". This would allow you to compare two sections of the same file relatively easily.</p>
<p>Overall, I highly recommend the product. I haven't tried version 3, which is what they currently have on their Web site, but version 2 is a fabulous tool. A+</p>
|
<p>I use UltraEdit for most of my text editing and they have a product called <a href="http://www.ultraedit.com/products/ultracompare.html" rel="nofollow noreferrer">UltraCompare</a> that does a visual compare.</p>
<hr>
<p><strong>Update by Mofi</strong></p>
<p>UltraCompare Professional supports also a comparison of text snippets in addition to entire files.</p>
<p>After starting UltraCompare, select <strong>Text Compare</strong> in menu <strong>Mode</strong> if not already selected. Select in text editor the first text block which should be compared, press Ctrl+C, switch back to UC and paste with Ctrl+V the block into left text area pane. Switch again to text editor, select the other block in same file, press Ctrl+C, switch back to UC, click into right pane and paste the block with Ctrl+V. The two blocks are immediately compared and the differences are displayed.</p>
<p>Such a text snippet comparison for two blocks in same file can be started also directly from within UltraEdit. Select the first block in file, press Ctrl+C, Ctrl+N, Ctrl+V and Ctrl+A to copy, paste and reselect this block in a new file. Select the second block in file. Execute command <strong>Compare</strong> from menu <strong>File</strong> in UltraEdit with option <em>Compare selected text</em> automatically being enabled and click on button <strong>Compare</strong>. UC Professional is started with just the 2 selected blocks for comparison.</p>
| 47,221
|
<p>It seems that everybody is jumping on the dynamic, non-compiled bandwagon lately. I've mostly only worked in compiled, static typed languages (C, Java, .Net). The experience I have with dynamic languages is stuff like ASP (Vb Script), JavaScript, and PHP. Using these technologies has left a bad taste in my mouth when thinking about dynamic languages. Things that usually would have been caught by the compiler such as misspelled variable names and assigning an value of the wrong type to a variable don't occur until runtime. And even then, you may not notice an error, as it just creates a new variable, and assigns some default value. I've also never seen intellisense work well in a dynamic language, since, well, variables don't have any explicit type.</p>
<p>What I want to know is, what people find so appealing about dynamic languages? What are the main advantages in terms of things that dynamic languages allow you to do that can't be done, or are difficult to do in compiled languages. It seems to me that we decided a long time ago, that things like uncompiled asp pages throwing runtime exceptions was a bad idea. Why is there is a resurgence of this type of code? And why does it seem to me at least, that Ruby on Rails doesn't really look like anything you couldn't have done with ASP 10 years ago?</p>
|
<p>I think the reason is that people are used to statically typed languages that have very limited and inexpressive type systems. These are languages like Java, C++, Pascal, etc. Instead of going in the direction of more expressive type systems and better type inference, (as in Haskell, for example, and even SQL to some extent), some people like to just keep all the "type" information in their head (and in their tests) and do away with static typechecking altogether.</p>
<p>What this buys you in the end is unclear. There are many misconceived notions about typechecking, the ones I most commonly come across are these two.</p>
<p><strong>Fallacy: Dynamic languages are less verbose.</strong> The misconception is that type information equals type annotation. This is totally untrue. We all know that type annotation is annoying. The machine should be able to figure that stuff out. And in fact, it does in modern compilers. Here is a statically typed QuickSort in two lines of Haskell (from <a href="http://haskell.org" rel="nofollow noreferrer">haskell.org</a>):</p>
<pre><code>qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
</code></pre>
<p>And here is a dynamically typed QuickSort in LISP (from <a href="http://swisspig.net/r/post/blog-200603301157" rel="nofollow noreferrer">swisspig.net</a>):</p>
<pre><code>(defun quicksort (lis) (if (null lis) nil
(let* ((x (car lis)) (r (cdr lis)) (fn (lambda (a) (< a x))))
(append (quicksort (remove-if-not fn r)) (list x)
(quicksort (remove-if fn r))))))
</code></pre>
<p>The Haskell example falsifies the hypothesis <em>statically typed, therefore verbose</em>. The LISP example falsifies the hypothesis <em>verbose, therefore statically typed</em>. There is no implication in either direction between typing and verbosity. You can safely put that out of your mind.</p>
<p><strong>Fallacy: Statically typed languages have to be compiled, not interpreted.</strong> Again, not true. Many statically typed languages have interpreters. There's the Scala interpreter, The GHCi and Hugs interpreters for Haskell, and of course SQL has been both statically typed and interpreted for longer than I've been alive.</p>
<p>You know, maybe the dynamic crowd just wants freedom to not have to think as carefully about what they're doing. The software might not be correct or robust, but maybe it doesn't have to be.</p>
<p>Personally, I think that those who would give up type safety to purchase a little temporary liberty, deserve neither liberty nor type safety.</p>
|
<p>Because it's fun fun fun. It's fun to not worry about memory allocation, for one. It's fun not waiting for compilation. etc etc etc</p>
| 6,453
|
<p>I have two tables, we'll call them <code>Foo</code> and <code>Bar</code>, with a one to many relationship where <code>Foo</code> is the parent of <code>Bar</code>. Foo's primary key is an integer automatically generated with a sequence. </p>
<p>Since <code>Bar</code> is fully dependent on <code>Foo</code> how would I setup the primary key of <code>Bar</code> given the following constraints:</p>
<ul>
<li>Records for Bar are programatically
generated so user input can not be
relied upon for an identifier.</li>
<li>Multiple processes are generating
Bar records so anything involving a
<code>Select Max()</code> to generate an <code>ID</code> would
present a race condition.</li>
</ul>
<p>I have come up with two possible solutions that I am not happy with:</p>
<ul>
<li>Treat the tables as if they are a
many to many relationship with a
third table that maps their records
together and have the application
code handle inserting records so
that the mapping between the records
is created correctly. I don't like
this as it makes the database design
misleading and errors in application
code could result in invalid data.</li>
<li>Give Bar two colunms: <code>FooID</code> and
<code>FooBarID</code> and generate a value for
<code>FooBarID</code> by selecting the
<code>max(FooBarID)+1</code> for some <code>FooID</code>, but
as previously stated this creates a
race condition.</li>
</ul>
<p>I appreciate any ideas for an alternative table layout.</p>
|
<p>Give Bar an automatic primary key the same as with Foo. Add a foreign key FooID column to Bar.</p>
<p>Unless I'm missing something, there doesn't seem to be a reason why it wouldn't work.</p>
|
<p>from your description i'm assuming that your database does not support auto-increment identifier fields (MS SQL does, Oracle has 'sequences' which are just as good if not better, I don't remember MySql has).</p>
<p>If it does, then all you need is an auto-increment FooId and an auto-increment BarId, and Bar also has a FooId as a foreign key</p>
<p>If it does not, then you can create a single-row table for allocation as follows:</p>
<pre><code>create table SystemCounter
(
SystemCounterId int identity not null,
BarIdAllocator int
)
--initialize SystemCounter to have one record with SystemCounterId = 1
--and BarIdAllocator = 0
insert into SystemCounter values (1,0)
--id allocator procedure
create procedure GetNextBarId ( @BarId int output ) AS
SET NOCOUNT ON
begin tran
update SystemCounter set
@BarId = BarIdAllocator = BarIdAllocator + 1
where SystemCounterId = 1
commit
GO
</code></pre>
<p>note that if your database does not support the syntax</p>
<pre><code>@BarId = BarIdAllocator = BarIdAllocator + 1
</code></pre>
<p>then you'll need to do it this way instead</p>
<pre><code>begin tran
update SystemCounter set
BarIdAllocator = BarIdAllocator + 1
where SystemCounterId = 1
select
@BarId = BarIdAllocator
from SystemCounter
where SystemCounterId = 1
commit
</code></pre>
<p>EDIT: I missed the Oracle tag originally, so Bill's solution is all that is necessary. Am leaving this answer as an example of how to do it in case someone is using a database that does not support identity or sequence constructs</p>
| 46,559
|
<p>The following Perl statements behave identically on Unixish machines. Do they behave differently on Windows? If yes, is it because of the magic \n?</p>
<pre><code> split m/\015\012/ms, $http_msg;
split m/\015\012/s, $http_msg;
</code></pre>
<p>I got a <a href="http://www.nntp.perl.org/group/perl.cpan.testers/2008/10/msg2450019.html" rel="nofollow noreferrer">failure</a> on one of my CPAN modules from a Win32 smoke tester. It looks like it's an \r\n vs \n issue. One change I made recently was to add //m to my regexes.</p>
|
<p>For these regexes:</p>
<blockquote>
<pre><code>m/\015\012/ms
m/\015\012/s
</code></pre>
</blockquote>
<p>Both /m and /s are meaningless.</p>
<ul>
<li>/s: makes <code>.</code> match <code>\n</code> too.
Your regex doesn't contain <code>.</code></li>
<li>/m: makes <code>^</code> and <code>$</code> match next to embedded <code>\n</code> in the string.
Your regex contains no <code>^</code> nor <code>$</code>, or their synonyms.</li>
</ul>
<p>What is possible is indeed if your input handle (socket?) works in text mode, the <code>\r</code> (<code>\015</code>) characters will have been deleted on Windows.</p>
<p>So, what to do? I suggest making the <code>\015</code> characters optional, and split against </p>
<pre><code>/\015?\012/
</code></pre>
<p>No need for /m, /s or even the leading <code>m//</code>. Those are just cargo cult.</p>
|
<p>Why did you add the <code>/m</code>? Are you trying to split on line? To do that with <code>/m</code> you need to use either <code>^</code> or <code>$</code> in the regex:</p>
<pre><code>my @lines = split /^/m, $big_string;
</code></pre>
<p>However, if you want to treat a big string as lines, just open a filehandle on a reference to the scalar:</p>
<pre><code>open my $string_fh, '<', \ $big_string;
while( <$string_fh> ) {
... process a line
}
</code></pre>
| 26,366
|
<p>Building the same project (without any changes) produces <strong>binary different</strong> exe-files: some small regions of them are different. Empty project, version information (and auto-increment on every build) is turned off.</p>
<p>Why it happens? And is it possible to make delphi produce binary equal files for the same projects?</p>
|
<p>The various structures in the PE executable file format used by Windows include timestamps that are set by the compiler and linker.</p>
<p>It is possible to post-process the file to reset these values to a defined constant (I wrote a tool to do exactly this for a secure product that needed exact hash values), but this should only be done on ready-to-ship executables, as some debuggers rely on the timestamps for source lookup, etc.</p>
|
<p>it may be, that some actual time-stamps are compiled into the exe-file.</p>
| 41,885
|
<p>I have a windows form application that uses a Shared class to house all of the common objects for the application. The settings class has a collection of objects that do things periodically, and then there's something of interest, they need to alert the main form and have it update.</p>
<p>I'm currently doing this through Events on the objects, and when each object is created, I add an EventHandler to maps the event back to the form. However, I'm running into some trouble that suggests that these requests aren't always ending up on the main copy of my form. For example, my form has a notification tray icon, but when the form captures and event and attempts to display a bubble, no bubble appears. However, if I modify that code to make the icon visible (though it already is), and then display the bubble, a second icon appears and displays the bubble properly.</p>
<p>Has anybody run into this before? Is there a way that I can force all of my events to be captured by the single instance of the form, or is there a completely different way to handle this? I can post code samples if necessary, but I'm thinking it's a common threading problem.</p>
<p><strong>MORE INFORMATION:</strong> I'm currently using Me.InvokeRequired in the event handler on my form, and it always returns FALSE in this case. Also, the second tray icon created when I make it visible from this form doesn't have a context menu on it, whereas the "real" icon does - does that clue anybody in?</p>
<p>I'm going to pull my hair out! This can't be that hard!</p>
<p><strong>SOLUTION</strong>: Thanks to nobugz for the clue, and it lead me to the code I'm now using (which works beautifully, though I can't help thinking there's a better way to do this). I added a private boolean variable to the form called "IsPrimary", and added the following code to the form constructor:</p>
<pre><code> Public Sub New()
If My.Application.OpenForms(0).Equals(Me) Then
Me.IsFirstForm = True
End If
End Sub
</code></pre>
<p>Once this variable is set and the constructor finishes, it heads right to the event handler, and I deal with it this way (CAVEAT: Since the form I'm looking for is the primary form for the application, My.Application.OpenForms(0) gets what I need. If I was looking for the first instance of a non-startup form, I'd have to iterate through until I found it):</p>
<pre><code> Public Sub EventHandler()
If Not IsFirstForm Then
Dim f As Form1 = My.Application.OpenForms(0)
f.EventHandler()
Me.Close()
ElseIf InvokeRequired Then
Me.Invoke(New HandlerDelegate(AddressOf EventHandler))
Else
' Do your event handling code '
End If
End Sub
</code></pre>
<p>First, it checks to see if it's running on the correct form - if it's not, then call the right form. Then it checks to see if the thread is correct, and calls the UI thread if it's not. Then it runs the event code. I don't like that it's potentially three calls, but I can't think of another way to do it. It seems to work well, though it's a little cumbersome. If anybody has a better way to do it, I'd love to hear it!</p>
<p>Again, thanks for all the help - this was going to drive me nuts!</p>
|
<p>I think it is a threading problem too. Are you using Control.Invoke() in your event handler? .NET usually catches violations when you debug the app but there are cases it can't. NotifyIcon is one of them, there is no window handle to check thread affinity.</p>
<p>Edit after OP changed question:</p>
<p>A classic VB.NET trap is to reference a Form instance by its type name. Like Form1.NotifyIcon1.Something. That doesn't work as expected when you use threading. It will create a <em>new</em> instance of the Form1 class, not use the existing instance. That instance isn't visible (Show() was never called) and is otherwise dead as a doornail since it is running on thread that doesn't pump a message loop. Seeing a second icon appear is a dead give-away. So is getting InvokeRequired = False when you know you are using it from a thread.</p>
<p>You must use a reference to the existing form instance. If that is hard to come by (you usually pass "Me" as an argument to the class constructor), you can use Application.OpenForms:</p>
<pre><code> Dim main As Form1 = CType(Application.OpenForms(0), Form1)
if (main.InvokeRequired)
' etc...
</code></pre>
|
<p>Use Control.InvokeRequired to determine if you're on the proper thread, then use Control.Invoke if you're not.</p>
| 34,476
|
<p>I am using Visual Studio 2005 and StarTeam 2008 (cross-platform client and VS integration). At some point, I added an 'App.config' to a project. I notice now that this file will not check-in.</p>
<ol>
<li><p>The 'StarTeam Pending Checkins' window in VS reports the file 'Not in View'. Selecting it for check in and clicking 'Check In Files' causes a dialog to appear - 'Any operation... requires completing the pending renames/deletes'. I click 'Yes' to proceed and nothing happens.</p></li>
<li><p>The StarTeam client reports this file as 'Modified'. If I check-in from the client, I get no 'complete pending renames/deletes' dialog and the file quickly appears with a 'Current' status.</p></li>
<li><p>Refreshing StarTeam from VS, I still see the file as 'Not in View'.</p></li>
</ol>
<p>I have tried forcing the check-in. I completely removed my working files and pulled the solution fresh in hopes that the StarTeam status ('Current') would apply in VS.</p>
|
<p>By using reflection you can do that. In C# it looks like that;</p>
<pre><code>PropertyInfo[] propertyInfo = myobject.GetType().GetProperties();
</code></pre>
<hr>
<p>Added a VB.Net translation:</p>
<pre><code>Dim info() As PropertyInfo = myobject.GetType().GetProperties()
</code></pre>
|
<p>You can use reflection... With Reflection you can examine every member of a class (a Type), proeprties, methods, contructors, fields, etc.. </p>
<pre><code>using System.Reflection;
Type type = job.GetType();
foreach ( MemberInfo memInfo in type.GetMembers() )
if (memInfo is PropertyInfo)
{
// Do Something
}
</code></pre>
| 40,568
|
<p>I need to get the Folder size and display the info on a report (SSRS). I need to do this for a number of Databases (loop!). These DB's are websites' backends.</p>
<p>Are any samples available for this? Does xp_filesize and the like the right solution?</p>
|
<p>Looking at the question and Tomalak's response, and I'm assuming the reporting server will be able to reach the folders held in the DB:</p>
<p>Firstly set up the query to get you back the result-set of paths - I assume you'll have no trouble with this part. Next you'll need to add a custom code function to your report: <a href="http://msdn.microsoft.com/en-us/library/ms155798.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms155798.aspx</a> - This function will take the folder path as a parameter, and pass back the size of the folder. You'll have to write in VB.Net if you want to embed the code in the report, or you could code up a DLL and bring that in.</p>
<p>An example VB.Net code block (Remember you may need to prefix objects with System.IO.) <a href="http://www.freevbcode.com/ShowCode.asp?ID=4287" rel="nofollow noreferrer">http://www.freevbcode.com/ShowCode.asp?ID=4287</a></p>
<pre><code>Public Shared Function GetFolderSize(ByVal DirPath As String, _
Optional IncludeSubFolders as Boolean = True) As Long
Dim lngDirSize As Long
Dim objFileInfo As FileInfo
Dim objDir As DirectoryInfo = New DirectoryInfo(DirPath)
Dim objSubFolder As DirectoryInfo
Try
'add length of each file
For Each objFileInfo In objDir.GetFiles()
lngDirSize += objFileInfo.Length
Next
'call recursively to get sub folders
'if you don't want this set optional
'parameter to false
If IncludeSubFolders then
For Each objSubFolder In objDir.GetDirectories()
lngDirSize += GetFolderSize(objSubFolder.FullName)
Next
End if
Catch Ex As Exception
End Try
Return lngDirSize
End Function
</code></pre>
<p>Now, in your report, in your table, you'd have for the cell that shows the folder size an expression something like:</p>
<pre><code>=Code.GetFolderSize(Fields!FolderPath.Value)
</code></pre>
<p>I doubt this approach will be performant for a manually-viewed report, but you might get away with it for small result sets, or a scheduled report delivered by email?</p>
<p>Oh, and this piece suggests you 'may' run into permissions issues using System.IO from within RS: <a href="http://blogs.sqlxml.org/bryantlikes/pages/824.aspx" rel="nofollow noreferrer">http://blogs.sqlxml.org/bryantlikes/pages/824.aspx</a></p>
|
<p>Could you clarify who should do what in your scenario? Do you want SQL Server do get the info or do you want Reporting Server do that? </p>
<p>What exactly do you mean by "folder size"? Is "one folder, sum up each file" enough or does it need to be recursive? Either way, I'd go for a little custom .NET function that uses <code>System.IO.Directory</code> and it's relatives.</p>
| 19,862
|
<p>In Python, if I do this:</p>
<pre><code>print "4" * 4
</code></pre>
<p>I get</p>
<pre><code>> "4444"
</code></pre>
<p>In Perl, I'd get</p>
<pre><code>> 16
</code></pre>
<p>Is there an easy way to do the former in Perl?</p>
|
<pre><code>$ perl -e 'print "4" x 4; print "\n"'
4444
</code></pre>
<p>The x operator is documented in perldoc <a href="http://perldoc.perl.org/perlop.html" rel="noreferrer">perlop</a>. Here binary means an operator taking two arguments, not composed of bits, by the way.</p>
<blockquote>
<p>Binary "x" is the repetition operator. In scalar context or if the
left operand is not enclosed in parentheses, it returns a string consisting
of the left operand repeated the number of times specified by the right
operand. In list context, if the left operand is enclosed in parentheses
or is a list formed by "<code>qw/STRING/</code>", it repeats the list. If the right
operand is zero or negative, it returns an empty string or an empty
list, depending on the context.</p>
</blockquote>
<pre><code> print '-' x 80; # Print row of dashes
print "\t" x ($tab/8), ' ' x ($tab%8); # Tab over
@ones = (1) x 80; # A list of 80 1’s
@ones = (5) x @ones; # Set all elements to 5
</code></pre>
<p><code>perl -e</code> is meant to execute Perl code from the command line:</p>
<pre>
$ perl --help
Usage: perl [switches] [--] [programfile] [arguments]
-e program one line of program (several -e's allowed, omit programfile)
</pre>
|
<p>Came this way looking for an answer. Didn't quite find what I was looking for so I thought I'd share my learning. I wanted to compose dynamic SQL CRUD statements with the appropriate number of placeholders.</p>
<pre><code>$table = "ORDERS";
@fields = ("ORDER_ID", "SALESMAN_ID", "CUSTOMER_ID", "ORDER_DATE", "STATUS");
$sql = "INSERT INTO $table (" . join(',', @fields) . ') VALUES (' . '?,' x (@fields - 1) . '?)';
print $sql;
</code></pre>
<p>The output looks like this...</p>
<pre><code>INSERT INTO ORDERS (ORDER_ID,SALESMAN_ID,CUSTOMER_ID,ORDER_DATE,STATUS) VALUES (?,?,?,?,?)
</code></pre>
| 35,015
|
<p>Is there a better way to negate a boolean in Java than a simple if-else?</p>
<pre><code>if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
</code></pre>
|
<pre><code>theBoolean = !theBoolean;
</code></pre>
|
<p>
Before:</p>
<pre class="lang-java prettyprint-override"><code>boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
</code></pre>
<p>After:</p>
<pre class="lang-java prettyprint-override"><code>boolean result = isresult();
result ^= true;
</code></pre>
| 27,710
|
<p>Suppose I have a non-recurring event that needs to be raised X seconds from now such as a timeout. Intuitively it would make sense to create a System.Timers.Timer, set its interval to X*1000, wire its tick up to the event and start it. Since this is a non-recurring event and you only want it raised once you would then have to stop the timer after it ticks.</p>
<p>The fact that Timers are inherently recurring however makes me distrustful if this is indeed the best way of doing it. Would it be better/more accurate/safer to save the time started, set the timer to tick every second (or even millisecond) and on tick poll the system for time and manually raise the target event only once the requisite time has elapsed?</p>
<p>Can anyone weigh in on which if either method is best (perhaps there is another option I didn't think of too). Does one method become better than the other if the timespan that I need to wait is measured in milliseconds?</p>
|
<p>This <a href="http://msdn.microsoft.com/en-us/library/ah1h85ch.aspx" rel="nofollow noreferrer">constructor</a> for the System.Threading.Timer allows you to specify a <strong>period</strong>. If you set this parameter to -1, it will disable periodic signaling and only execute once.</p>
<pre><code>public Timer(
TimerCallback callback,
Object state,
TimeSpan dueTime,
TimeSpan period
)
</code></pre>
|
<p>just set it to tick after X seconds, and in the code of the tick, do:</p>
<p>timer.enabled = false;</p>
<p>worked for me.</p>
| 17,900
|
<p>I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting. I have a control that currently uses a Repeater control with templates. Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties? </p>
|
<p>Building on the previous answer, a better solution that includes the label for the group box:</p>
<pre><code>groupBox1.Paint += PaintBorderlessGroupBox;
private void PaintBorderlessGroupBox(object sender, PaintEventArgs p)
{
GroupBox box = (GroupBox)sender;
p.Graphics.Clear(SystemColors.Control);
p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0);
}
</code></pre>
<p>You might want to adjust the x/y for the text, but for my use this is just right.</p>
|
<p>This tweak to Jim Fell's code placed the borders a little better for me, but it's too long to add as a comment</p>
<p>...</p>
<pre><code> Rectangle rect = new Rectangle(this.ClientRectangle.X,
this.ClientRectangle.Y + (int)(strSize.Height / 2),
this.ClientRectangle.Width,
this.ClientRectangle.Height - (int)(strSize.Height / 2));
Brush labelBrush = new SolidBrush(this.BackColor);
// Clear text and border
g.Clear(this.BackColor);
int drawX = rect.X;
int drawY = rect.Y;
int drawWidth = rect.Width;
int drawHeight = rect.Height;
if (this._borderWidth > 0)
{
drawX += this._borderWidth / 2;
drawY += this._borderWidth / 2;
drawWidth -= this._borderWidth;
drawHeight -= this._borderWidth;
if (this._borderWidth % 2 == 0)
{
drawX -= 1;
drawWidth += 1;
drawY -= 1;
drawHeight += 1;
}
}
g.DrawRoundedRectangle(borderPen, drawX, drawY, drawWidth, drawHeight, (float)this._borderRadius);
</code></pre>
| 10,209
|
<p>This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.</p>
<p>Original string is <code>'original READ ONLY'</code></p>
<p>I want to replace the <code>'READ ONLY'</code> with <code>'READ WRITE'</code></p>
<p>Any quick answer please? Possibly with a javascript code snippet...</p>
|
<p><code>String.replace()</code> is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the <strong>‘g’</strong> (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want).</p>
<p>An alternative <strong>non-regexp</strong> idiom for simple global string replace is:</p>
<pre><code>function string_replace(haystack, find, sub) {
return haystack.split(find).join(sub);
}
</code></pre>
<p>This is preferable where the <code>find</code> string may contain characters that have an unwanted special meaning in regexps.</p>
<p>Anyhow, either method is fine for the example in the question.</p>
|
<pre><code>stringObject.replace(findstring,newstring)
</code></pre>
| 31,518
|
<p>I am trying to use a Generic Linked List to hold some WorkFlow steps in my application. Here is how I'm persisting it to my database.</p>
<p>OrderID WorkFlowStepID ParentWorkFlowStepID<br/>
178373 1 NULL<br/>
178373 2 1<br/>
178373 3 2<br/></p>
<p>I get this dataset back in a datareader object. I then loop through the datareader and create a WorkFlowStep object that includes a WorkFlowStepID property and a ParentWorkFlowStepID property. I add the first object to my LinkedList by using the .AddFirst() method. My next idea is to create the next object and then insert it after the object in the LinkedList where it's WorkFlowStepID is equal to the new object's ParentWorkFlowStepID. I can't figure out of to find the object in the LinkedList. The find() method is asking for a value, but I don't understand what value it is, or how I can find it.</p>
|
<p>So do you mean you're using the <a href="http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx" rel="nofollow noreferrer">linked list class in the framework</a>?</p>
<p>If so, the <code>Find</code> method doesn't really do what you want it to. Basically you want a version which takes a predicate. This would be easier if the class exposed an iterator of <a href="http://msdn.microsoft.com/en-us/library/ahf4c754.aspx" rel="nofollow noreferrer"><code>LinkedListNode<T></code></a>. Fortunately it's easy to provide an extension method to do that:</p>
<pre><code>public static IEnumerable<LinkedListNode<T>> GetNodes<T>(this LinkedList<T> list)
{
LinkedListNode<T> current = list.First;
while (current != null)
{
yield return current;
current = current.Next;
}
}
</code></pre>
<p>Then you can do (and I stress all of this is untested):</p>
<pre><code>var node = list.GetNodes().FirstOrDefault(x.Value.WorkFlowerStepID = parentWorkFlowStepID);
if (node != null)
{
list.AddAfter(node, newItem);
}
else
{
// Whatever. Add to tail?
}
</code></pre>
|
<p>Define a comparison function and then call the list .Sort() method with the comparison function passed in as a delegate. The function should take 2 objects(e.g. X and Y) and return -1 if X is greater than Y, 0 if they are equal or 1 if Y is greater than X. </p>
| 38,444
|
<p>I have some legacy code that uses VBA to parse a word document and build some XML output; </p>
<p>Needless to say it runs like a dog but I was interested in profiling it to see where it's breaking down and maybe if there are some options to make it faster.</p>
<p>I don't want to try anything until I can start measuring my results so profiling is a must - I've done a little searching around but can't find anything that would do this job easily. There was one tool by brentwood? that requires modifying your code but it didn't work and I ran outa time.</p>
<p>Anyone know anything simple that works?</p>
<p>Update: The code base is about 20 or so files, each with at least 100 methods - manually adding in start/end calls for each method just isn't appropriate - especially removing them all afterwards - I was actually thinking about doing some form of REGEX to solve this issue and another to remove them all after but its just a little too intrusive but may be the only solution. I've found some nice timing code on here earlier so the timing part of it isn't an issue.</p>
|
<p>Using a class and #if would make that "adding code to each method" a little easier...</p>
<p><strong><em>Profiler</em> Class Module:</strong>:</p>
<pre><code>#If PROFILE = 1 Then
Private m_locationName As String
Private Sub Class_Initialize()
m_locationName = "unknown"
End Sub
Public Sub Start(locationName As String)
m_locationName = locationName
MsgBox m_locationName
End Sub
Private Sub Class_Terminate()
MsgBox m_locationName & " end"
End Sub
#Else
Public Sub Start(locationName As String)
'no op
End Sub
#End If
</code></pre>
<p><strong>some other code module:</strong></p>
<pre><code>' helper "factory" since VBA classes don't have ctor params (or do they?)
Private Function start_profile(location As String) As Profiler
Set start_profile = New Profiler
start_profile.Start location
End Function
Private Sub test()
Set p = start_profile("test")
MsgBox "do work"
subroutine
End Sub
Private Sub subroutine()
Set p = start_profile("subroutine")
End Sub
</code></pre>
<p>In Project Properties set <em>Conditional Compilation Arguments</em> to:</p>
<pre><code>PROFILE = 1
</code></pre>
<p>Remove the line for normal, non-profiled versions.</p>
<p>Adding the lines is a pain, I don't know of any way to automatically get the current method name which would make adding the profiling line to each function easy. You could use the VBE object model to inject the code for you - but I wonder is doing this manually would be ultimately faster.</p>
|
<p>Insert a bunch of</p>
<pre><code>Debug.Print "before/after foo", Now
</code></pre>
<p>before and after snippets that you think might run for long terms, then just compare them and voila there you are.</p>
| 30,166
|
<p>What are some good examples of coding guidelines. I'm not really looking for anything specific to a single language.</p>
<p>But what should I be doing/evaluating as I write coding guidelines? Such as how flexible should the guidelines and how much should decisions be left to the programmer or to someone else or even pre-decided by the guidelines.</p>
<p>This set of guidelines that I am working on is supposed to cover a wide range of topics: comments, database design, and even some user interface guidelines.</p>
|
<p>There are generally three purposes for coding standards:</p>
<ul>
<li>Reduce the likelihood of bugs</li>
<li>Reduce the time required to analyze code written by someone else</li>
<li>Give someone a power trip</li>
</ul>
<p>Obviously, the third is a waste of everyone else's time, but you do need to consider it, specifically so you <em>don't</em> go down that road.</p>
<p>Having said that, there are some definite do's and dont's that I've noticed:</p>
<ul>
<li>Enforce consistent whitespace usage. Tabs, 2-spaces, 4-spaces, doesn't matter. Keep it consistent, so indent levels aren't screwed up by people using different editors. I've seen mistakes made because maintenance programmers misinterpreted the nesting level of a block of code.</li>
<li>Enforce consistent logging methodology. It's a huge drain on support staff's time if they aren't able to skim over logs, because everyone's module logs for different reasons, and everyone has a different definition of Info vs. Warning vs. Error.</li>
<li>Enforce consistent error handling. If module A throws exceptions, module B returns error codes, and module C simply logs and moves on, it'll be a pain to integrate them without letting an error slip through the cracks.</li>
<li>Try to avoid petty things like placement of curly-braces. That's going to get a lot of people arguing over their pet style, and in the end, it really doesn't have a huge impact on the readability of code. On the other hand, enforcing the <em>presence</em> of brackets can make a difference.</li>
<li>When integrating disparate code bases, don't be tempted to change everyone's variable naming conventions to match the golden standard. You may have a standard for moving forward, but what's most important is that any localized standards that already exist are preserved consistently. If one module uses <code>m_member</code>, a maintenance programmer should be using <code>m_member2</code> rather than applying any other standard (such as <code>member2_</code> or <code>m_lpcstrMember2</code> or whatever). Local consistency is king.</li>
<li>Filesystem layout is important. Keep it consistent. Make it easy for someone to jump into a library sourcebase and instantly know where are the headers, the Makefile, the sources, etc. If you're working with Java or Python, this is a no-brainer because the package system enforces it. If you're working with C, C++, or any other myriad of scripting languages, you'll need to devise a standard layout yourself and stick with it.</li>
<li>Don't sweat the little stuff. Variable naming conventions, spaces between parentheses or keywords or function names... most of that doesn't matter, because it doesn't reduce the likelihood of a mistake. Every rule you set should have a concrete rationale, and you shouldn't be afraid to change or remove it if you discover it's causing more grief than it's worth.</li>
<li>Don't enforce gratuitous comment blocks everywhere. They'll end up as a waste, and most comments are better off being expressed in the code itself (as variable or function names, for example).</li>
</ul>
<p>Finally, the most important thing is to have regular code reviews between peers. Encourage people to speak up when they see a "code smell." Also be sure people realize that constructive code criticism is not meant to be personal - the source is shared by everone on the team, it doesn't just belong to the original author. In my experience, the most heinous problems have been design problems that wouldn't have been solved by any amount of coding guidelines. Software design is still something of an art form (for better or for worse), and a pool of brains is much better than a single one.</p>
|
<p>Coding guidelines are behavioural rules for your teammembers, so that you can read eachothers code without too much trouble.</p>
<p>It also gets the "bracket on newline or on same line" discussions out of the way at your code review sessions, which saves a lot of time ;-)</p>
<p>When writing code guidelines, make sure that they're there for a reason, and that they actually help your team on writing more readable code.</p>
| 44,507
|
<p>How long should it take to run </p>
<pre><code>ALTER DATABASE [MySite] SET READ_COMMITTED_SNAPSHOT ON
</code></pre>
<p>I just ran it and it's taken 10 minutes.</p>
<p>How can I check if it is applied?</p>
|
<p>You can check the status of the READ_COMMITTED_SNAPSHOT setting using the <strong><code>sys.databases</code></strong> view. Check the value of the <strong><code>is_read_committed_snapshot_on</code></strong> column. Already <a href="https://stackoverflow.com/questions/51969/how-to-detect-readcommittedsnapshot-is-enabled">asked and answered</a>.</p>
<p>As for the duration, Books Online states that there can't be any other connections to the database when this takes place, but it doesn't require single-user mode. So you may be blocked by other active connections. Run <strong><code>sp_who</code></strong> (or <strong><code>sp_who2</code></strong>) to see what else is connected to that database.</p>
|
<p>Try Shut off the other SQL services so that only the SQL server service is running. </p>
<p>Mine ran for 5 minutes then I cancelled it because it was obvious nothing was happening. Its a brand new server so there are no other users connected. I shut off the SQL Reporting Services and then ran it again.. took less than a second to complete. </p>
| 28,754
|
<p>I'm new to this game, and recently upgraded the hotend on my Ender 3 Pro to a <em>clone</em> of an E3D V6, as I'm keen to do nylon prints at some point. I noticed however that this one I got has a teflon liner which seems to negate the advantage of a metal hotend entirely.</p>
<p>I'm wondering what temperature it's safe to run this hot end up to?</p>
<p><a href="https://i.stack.imgur.com/6Uth3.jpg" rel="nofollow noreferrer" title="Teflon insert#2"><img src="https://i.stack.imgur.com/6Uth3.jpg" alt="Teflon insert#1" title="Teflon insert#2" /></a></p>
<p><a href="https://i.stack.imgur.com/QazJ2.jpg" rel="nofollow noreferrer" title="Teflon insert#1"><img src="https://i.stack.imgur.com/QazJ2.jpg" alt="Teflon insert#2" title="Teflon insert#1" /></a></p>
|
<p>There are many types of <a href="https://3dprinting.stackexchange.com/questions/10998/e3d-v6-original-vs-clone/11012#11012">heatbreak clones</a>. In cour case, your clone effectively turns your hotend into an e3d Lite6, not an all-metal e3d v6. To function properly, the PTFE liner needs to butt against the nozzle or you will quickly develop leak and clog issues.</p>
<p>This means, handle it like a Lite6, which has a max of 245 °C listed, but under usual operation should not exceed 230 °C.</p>
|
<p>Long story short, you can print Nylon with a Teflon tube. I've done it. P.S. The nylon absorbs water like nothing you've ever seen. Even after the part is printed, it absorbs water, and expands!</p>
| 1,712
|
<p>I'm working on a new project, a web application, where I need to focus the user on a particular task. Therefore I want to eliminate all other "System Generated Noise", like Browser Menus, Buttons, Address Bar, OS Task Bar and so forth. I have seen implementations like Lightbox, but this modal approach is limited to the size of the browser window.</p>
<p>What I want to do is have the same effect but stretched out beyond de browser so it covers the WHOLE screen. Well, at least that is the effect I'm aiming for.</p>
<p>The application is already on its way, it is being developed with PHP5, XHTML and Javascript/AJAX.</p>
<p>Please, if someone can point me in the right direction I'd greatly appreciate it.</p>
|
<p>this may help you:</p>
<p><a href="http://www.programmersheaven.com/2/FAQ-JavaScript-Maximize-Browser-Window-To-Screen" rel="nofollow noreferrer">http://www.programmersheaven.com/2/FAQ-JavaScript-Maximize-Browser-Window-To-Screen</a></p>
|
<p>OK, so I've been looking around for other options, or alternate ways I can do this. One solution I found, only works with Firefox 2.0+ or IE6+, is to toggle the browsers Full Screen mode. Maybe even do a little pro Open Source and support only Firefox and urge the user to get that browser...but hell, if I'm telling the user to get stuff why not tell it to go and grab Flash o Silverlight, right??</p>
<p>I think it's a thin line between what is possible, what is wanted, and what is right for the user. I've yet to find what is needed to do this. But I think it's a lot more viable option.</p>
<blockquote>
<p>Let us know what browser you make that work in, and I'll be sure to either cripple the functionality or uninstall it if I can't.</p>
</blockquote>
<p>Mmm WTF!? Gonna go ahead and asume that was a nice comment gone bad. Not very constructive though.</p>
| 49,349
|
<p>I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the <code>java.io.Console</code> class to manage output and, more importantly, user input.</p>
<p>The problem is that <code>System.console()</code> returns <code>null</code> when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with.</p>
<p>Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.</p>
|
<p>I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath.</p>
<pre><code>java -cp workspace\p1\bin;workspace\p2\bin foo.Main
</code></pre>
<p>You can debug using the remote debugger and taking advantage of the class files built in your project.</p>
<p>In this example, the Eclipse project structure looks like this:</p>
<pre><code>workspace\project\
\.classpath
\.project
\debug.bat
\bin\Main.class
\src\Main.java
</code></pre>
<p><strong>1. Start the JVM Console in Debug Mode</strong></p>
<p><strong>debug.bat</strong> is a Windows batch file that should be run externally from a <strong>cmd.exe</strong> console.</p>
<pre><code>@ECHO OFF
SET A_PORT=8787
SET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y
java.exe %A_DBG% -cp .\bin Main
</code></pre>
<p>In the arguments, the debug port has been set to <em>8787</em>. The <em>suspend=y</em> argument tells the JVM to wait until the debugger attaches.</p>
<p><strong>2. Create a Debug Launch Configuration</strong></p>
<p>In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new <strong>Remote Java Application</strong> configuration with the following settings:</p>
<ul>
<li><em>Project:</em> your project name</li>
<li><em>Connection Type:</em> Standard (Socket Attach)</li>
<li><em>Host:</em> localhost</li>
<li><em>Port:</em> 8787</li>
</ul>
<p><strong>3. Debugging</strong></p>
<p>So, all you have to do any time you want to debug the app is:</p>
<ul>
<li>set a break point</li>
<li>launch the batch file in a console</li>
<li>launch the debug configuration</li>
</ul>
<hr>
<p>You can track this issue in <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429" rel="noreferrer">bug 122429</a>. You can work round this issue in your application by using an abstraction layer as described <a href="http://illegalargumentexception.blogspot.com/2010/09/java-systemconsole-ides-and-testing.html" rel="noreferrer">here</a>.</p>
|
<p>Let's say your Eclipse workspace is C:\MyWorkspace,
you created your java application inside a maven project MyProject,
and your Java main class is com.mydomain.mypackage.MyClass.</p>
<p>In this case, you can run your main class that uses <code>System.console()</code> on the command line:</p>
<pre><code>java -cp C:\MyWorkspace\MyProject\target\classes com.mydomain.mypackage.MyClass
</code></pre>
<p>NB1: if it's not in a maven project, check the output folder in project properties | Java Build Path | Source. It might not be "target/classes"</p>
<p>NB2: if it is a maven project, but your class is in src/test/java, you'll likely have to use "target\test-classes" instead of "target\classes"</p>
| 12,982
|
<p>Did Installing OneCare cause a "Generating user instances in SQL Server is disabled" error?</p>
<p>The only change that I've made to my computer is uninstalling AVG and installing the trial for Microsoft OneCare. Did OneCare change the SQLServer installation somehow?</p>
<p>This is a very "odd" question but is something I would post on EE in hopes of someone having had the same issue and giving their solution.</p>
|
<p>I would look more at the uninstalling of AVG as the culprit. OneCare does not care or even notice SQL Server instances as far as I can tell where as AVG does. </p>
<p>I would look into your SQL Server instance and check the jobs. One or more may have been added by AVG. You should remove them. You might also want to drop the AVG database. Just to be sure.</p>
<p>Note: I have never <strong>uninstalled</strong> AVG. I just have notice some of what it did to my Database when my SysAdmin installed it. Being an Accidental DBA I haven't had the time to properly evaluate it's actions.</p>
|
<p>I didn't see anything odd in the event viewer or any db's for avg in SQLServer. btw I installed SQL server after AVG. it's curious anyway. I'll just make a VM and do a fresh install of SQLExpress so I can finish a few projects.</p>
<p>it's been over a year so it's time for the annual reformat and reinstall ;-)</p>
| 5,946
|
<p>We have a major VB6 trading application which uses MS Access (Don't ask!) It is always blasting trades into an MS Access database.</p>
<p>The rest of the infrastructure here has moved on considerably and I want to read this Access database periodically and copy any new trades into a SQL server database.</p>
<p>The SQL and C# needed to do this is trivially easy.</p>
<p>BUT I want to make sure I do it in such a way that does not lock the Access database or cause problems for the VB6 app. In other words when populating my DataTable from Access I do NOT want to lock the database and prevent the VB6 app writing to it. I seem to remember from old ADO there were share modes you could use for this purpose.</p>
<p>What sort of connection string should I use from .NET to accomplish this?</p>
|
<p>To build on Matt's answer, I would recommend a combination of adOpenForwardOnly and adLockReadonly: ForwardOnly because you just need to insert those trades into SQL Server, and Readonly so you aren't locking out other processes (what else would hit these tables?). Fortunately, these are the default options. :) </p>
|
<p>Just an idea ... but have you thought about upgrading the database so that the tables themselves are actually stored in SQL Server and Access just become the front end? It's been a little while, but if I remember correctly, Access should have a wizard (yuck!) to help you do this.</p>
<p>With old ADO you could set the cursor or lock type mechanism to one of the following:</p>
<p><strong>Cursor Type</strong></p>
<p><strong><em>adOpenForwardOnly</em></strong> This type of cursor can only be used to move forward through the recordset. This option is used when a list box or combo box is to be populated.</p>
<p><strong><em>adOpenKeyset</em></strong> This is the best type of cursor to use when we expect a large recordset because we are not informed when changes are made to data that can affect our recordset. </p>
<p><strong><em>adOpenDynamic</em></strong> This cursor allows us to see all the changes made by other users that affect our recordset. It is the most powerful type of cursor but the slowest one.</p>
<p><strong><em>adOpenStatic</em></strong> The static cursor is useful when we have a small recordset.</p>
<p><strong>Lock Type</strong></p>
<p><strong><em>adLockReadonly</em></strong> This lock mode is used when no additions, updates or deletions are allowed from recordset</p>
<p><strong><em>adLockPesimistic</em></strong> In pessimistic locking, the record is locked as soon as editing begins and remains locked until editing is completed.</p>
<p><strong><em>adLockOptimistic</em></strong> This occurs when the update method is called on the record. the record is unlocked even while edit but is temporarily locked when the changes are saved to the database </p>
<p><strong><em>adLockBatchOptimistic</em></strong> This option allows us to perform optimistic locking when we are updating a batch of records</p>
<p>Not sure how that exactly translates into the .NET world ... but maybe this can get you pointed in the right direction.</p>
| 37,026
|
<p>I want to add a <em>column</em> to an existing legacy <em>database</em> and write a <em>procedure</em> by which I can assign each record a different value. Something like adding a <em>column</em> and autogenerate the data for it.</p>
<p>Like, if I add a new <em>column</em> called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID <em>column</em> will have records from say <code>1 to 1000</code>.<br>
How do I do that?</p>
|
<p>This will depend on the database but for SQL Server, this could be achieved as follows:</p>
<pre><code>alter table Example
add NewColumn int identity(1,1)
</code></pre>
|
<p>Depends on the database as each database has a different way to add sequence numbers. I would alter the table to add the column then write a db script in groovy/python/etc to read in the data and update the id with a sequence. Once the data has been set, I would add a sequence to the table that starts after the top number. Once the data has been set, set the primary keys correctly.</p>
| 13,360
|
<p>Using the Java URL class, I can connect to an external <code>HTTPS</code> server (such as our production site), but using a local URL I get following exception. </p>
<pre><code>"SunCertPathBuilderException: unable to find valid certification path to requested target".
</code></pre>
<p>How do I get a valid certification path?</p>
<p>EDIT: I'm not using this URL to directly create a connection, I am passing the URL to an <code>itext</code> <code>PDFReader</code>, which is then having the connection issue.</p>
|
<p>Here was my solution that incorporates some of the ideas in this thread and peiced together with code from around the net.
All I do call this function and it sets the default Trust Manager and HostName Verifier for HttpsURLConnection. This might be undesirable for some because it will effect all HttpsURLConnections but I'm just writing a simple proxy so it worked for me.</p>
<pre><code>private void setTrustAllCerts() throws Exception
{
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType ) { }
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType ) { }
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance( "SSL" );
sc.init( null, trustAllCerts, new java.security.SecureRandom() );
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(
new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
});
}
catch ( Exception e ) {
//We can not recover from this exception.
e.printStackTrace();
}
}
</code></pre>
|
<p>The problem it's complaining about is that when you create an SSL connection, the server must present a valid certificate to the client. You can write an appropriate endpoint in Java (HTTPServerSocket will do it I think) but it would require some hacking about to set it up. It's probably easier to set up a local web server with anything that handles SSL correctly --- Apache, lighttp, whatever --- and create a self-signed cert using the openssl tools.</p>
Updated
<p>Here's an example from the Java Almanac. <a href="http://www.exampledepot.com/egs/javax.net.ssl/Server.html" rel="nofollow noreferrer">http://www.exampledepot.com/egs/javax.net.ssl/Server.html</a></p>
<p>An SSL server socket requires certificates that it will send to clients for authentication. The certificates must be contained in a keystore whose location must be explicitly specified (there is no default). Following the example we describe how to create and specify a keystore for the SSL server socket to use.</p>
<pre><code>try {
int port = 443;
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket = ssocketFactory.createServerSocket(port);
// Listen for connections
Socket socket = ssocket.accept();
// Create streams to securely send and receive data to the client
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
// Read from in and write to out...
// Close the socket
in.close();
out.close();
} catch(IOException e) {
}
</code></pre>
<p>Specify the keystore of certificates using the javax.net.ssl.keyStore system property:</p>
<pre><code>> java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456 MyServer
</code></pre>
| 48,849
|
<p>Can someone tell me what Strong typing and weak typing means and which one is better?</p>
|
<p>That'll be the theory answers taken care of, but the practice side seems to have been neglected...</p>
<p>Strong-typing means that you can't use one type of variable where another is expected (or have restrictions to doing so). Weak-typing means you can mix different types. In PHP for example, you can mix numbers and strings and PHP won't complain because it is a weakly-typed language.</p>
<pre><code>$message = "You are visitor number ".$count;
</code></pre>
<p>If it was strongly typed, you'd have to convert $count from an integer to a string, usually with either with casting:</p>
<pre><code>$message = "you are visitor number ".(string)$count;
</code></pre>
<p>...or a function:</p>
<pre><code>$message = "you are visitor number ".strval($count);
</code></pre>
<p>As for which is better, that's subjective. Advocates of strong-typing will tell you that it will help you to avoid some bugs and/or errors and help communicate the purpose of a variable etc. They'll also tell you that advocates of weak-typing will call strong-typing "<em>unnecessary language fluff that is rendered pointless by common sense</em>", or something similar. As a card-carrying member of the weak-typing group, I'd have to say that they've got my number... but I have theirs too, and <em>I</em> can put it in a string :)</p>
|
<p>Weak typing means that you don't specify what type a variable is, and strong typing means you give a strict type to each variable.</p>
<p>Each has its advantages, with weak typing (or dynamic typing, as it is often called), being more flexible and requiring less code from the programmer. Strong typing, on the other hand, requires more work from the developer, but in return it can alert you of many mistakes when compiling your code, before you run it. Dynamic typing may delay the discovery of these simple problems until the code is executed.</p>
<p>Depending on the task at hand, weak typing may be better than strong typing, or vice versa, but it is mostly a matter of taste. Weak typing is commonly used in scripting languages, while strong typing is used in most compiled languages.</p>
| 41,849
|
<p>I'm developing a set of applications that work together to create a system for processing metering data. There's several reasons I want to have them loosely coupled and the system should be extensible by third parties, so the apps will be tied together via messaging.</p>
<p>I'm looking for a messaging system that offers bindings in (at least) C#, Java and Python and supports messaging patterns like Publish-Subscribe, Guaranteed Delivery, Selective Consumer (like Peek in .Net Messaging).</p>
<p>As far as I could find out, there's nothing wrong with JMS or .Net Messaging, it's just that they are for .Net / Java only.</p>
<p>The system should give me control over which transport mechanism (Sockets, Message Queues, etc.) to use when setting up a channel. I want to be able to both scale out to remote machines and speed things up with local transport facilities.</p>
<p>If I can't find anything suitable, I'll have to roll my own. I'd probably use Google's protocol buffers for serialization. If anybody has other recommendations for technology options, fire away.</p>
<p>Oh, yes - and I would like to have optional encryption on a per-channel or per-message basis.</p>
<p><i>ETA: Thanks for all the quick replies. I'm working my way through the docs & propaganda now. Has anybody used the technologies below, and for what / with what results?</i></p>
|
<p>activemq</p>
<p><a href="http://activemq.apache.org/cross-language-clients.html" rel="noreferrer">http://activemq.apache.org/cross-language-clients.html</a></p>
<p>Supports all the following protocols</p>
<ul>
<li>OpenWire</li>
<li>REST</li>
<li>Stomp</li>
<li>WS Notification</li>
<li>XMPP</li>
<li>AMQP</li>
</ul>
<p>Thanks
Paul</p>
|
<p><a href="https://mq.dev.java.net/" rel="nofollow noreferrer">Open Message Queue (Open MQ)</a> is included in the GlassFish application Server and also runs stand-alone. It starts up in a few seconds, and supports Java and C client. Stomp support is currently in development in version 4.4.</p>
| 32,285
|
<p>I want to paint my ABS parts. But I foresee a problem that will arise from 0.16mm layer - those layers will be perfectly visible, even with primer. Sanding them wouldn't be a good idea, because walls are just 0.8-1mm thick, and probably acetone bath isn't right thing too. I want to use some sort of cement or paste, and cover parts with it using some paint scraper or knife before painting. Do cements suitable for this task exist? Would they stick to ABS?</p>
|
<p>The Prusha I3 design uses two rods to guide the Y axis, which moves along the rods on linear bearings. If the rods are not strictly planar, there will be movement of the bed as it moves to and fro. You would not be able to correct this with the leveling screws.</p>
<p>Be sure that the rods are planar, and that there is no torque on the bed from uneven rods. Even if the bed doesn't flex, the frame may flex if the rods are not planar.</p>
|
<p>The Prusha I3 design uses two rods to guide the Y axis, which moves along the rods on linear bearings. If the rods are not strictly planar, there will be movement of the bed as it moves to and fro. You would not be able to correct this with the leveling screws.</p>
<p>Be sure that the rods are planar, and that there is no torque on the bed from uneven rods. Even if the bed doesn't flex, the frame may flex if the rods are not planar.</p>
| 738
|
<p>i have a server - client application that runs on java 1.3; i want to change to java 1.6 step by step, meaning first few clients, than rest of the clients and finally server...
i was wondering could you direct me to some common problems that can come along and what should i look after?</p>
|
<p>Sun tries to keep a high level of backward-compatibility, so you possibly simply can install the new JVM and restart your application with it.</p>
<p>A document describing the backward-incompatibilities from Java 1.6 with earlier version is <a href="http://java.sun.com/javase/6/webnotes/compatibility.html" rel="nofollow noreferrer">here</a>. This document links the compatibility-documents for <a href="http://java.sun.com/j2se/1.5.0/compatibility.html" rel="nofollow noreferrer">Java 1.5</a> and <a href="http://java.sun.com/javase/compatibility_j2se1.4.html" rel="nofollow noreferrer">Java 1.4</a> as well. You probably want to read this documents to learn about possible pitfalls.</p>
<p>Java 1.5 and <a href="https://jdk.dev.java.net/verifier.html" rel="nofollow noreferrer">Java 1.6</a> introduced new class-file-formats. The JVM's will run the old class-files as well, but recompiling your code - especially with JDK 1.6 - will help the new JVM to take advantage of some changes to make your application faster. So you might consider recompiling.</p>
<p>Additionally some new keywords were introduced, namely assert (in 1.4) and enum (in 1.5) (as Yuval already mentioned). If you use these words as identifiers, a recompile will fail, but the old class-files will work. You can provide the switch <code>-source</code> to javac to let it compile: '<code>javac -source 1.3</code>' will compile the code without <em>assert</em> and <em>enum</em> as a keyword.</p>
|
<p>My experience is that the compatibility is quite high. I've only found one app ever that I couldn't get to run on a current version. For whatever reason (not having source, so I didn't dig into it) that one app wouldn't run on anything other than 1.4.2. Everything else I've ever dealt with (some of them quite sizeable) have come up to 1.6 just fine. No modifications required.</p>
<p>YMMV of course, so you'll have to try it and see...</p>
| 32,746
|
<p>Is there a script to display a simple world clock (time in various places around the world) on a *nix terminal?</p>
<p>I was thinking of writing a quick Python script, but I have a feeling that's gonna be more work than I think (e.g. due to config and output format) - not to mention reinventing the wheel...</p>
|
<p>I have this bourne shell script:</p>
<pre><code>#!/bin/sh
PT=`env TZ=US/Pacific date`
CT=`env TZ=US/Central date`
AT=`env TZ=Australia/Melbourne date`
echo "Santa Clara $PT"
echo "Central $CT"
echo "Melbourne $AT"
</code></pre>
|
<p>I like the script <a href="https://stackoverflow.com/users/111036/mivk">mivk</a> provided.
As I want to be able to specify multiple zones without regex, I adapted the script to use bash when I couldn't get bourne shell to deal with arrays.
Anyway, enjoy and thanks for a great forum:</p>
<pre><code>#!/usr/bin/env bash
# Show date and time in other time zones, with multiple args
elements=$@
zoneinfo=/usr/share/zoneinfo
format='%a %F %T'
for search in ${elements[@]}; do
find $zoneinfo -type f \
| grep -i "$search" \
| while read z
do
d=$(TZ=$z date +"$format")
printf "%-34s %23s\n" ${z#$zoneinfo} "$d"
done
done
</code></pre>
<p>Sample output:</p>
<p><code>/usr/local/bin/wdate Sydney Stockholm
/Australia/Sydney Fri 2015-08-14 05:54:26
/Europe/Stockholm Thu 2015-08-13 21:54:26</code></p>
| 48,338
|
<p>I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:</p>
<p>I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.</p>
<p>How do I do this without the use of cursors? Should be an easy one for you sql gurus!</p>
|
<p>This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table. For example:</p>
<pre><code>CREATE TABLE #t (uniqueid int)
INSERT INTO #t EXEC p_YourStoredProc
UPDATE TargetTable
SET a.FlagColumn = 1
FROM TargetTable a JOIN #t b
ON a.uniqueid = b.uniqueid
DROP TABLE #t
</code></pre>
|
<p>An ugly solution would be to have your procedure return the "next" id each time it is called by using the other table (or some flag on the existing table) to filter out the rows that it has already returned</p>
| 17,975
|
<p>Does anyone know of a script to colorize C++ code the same as the default MSVC IDE does?</p>
|
<p>If it's for the web I can recommend you <a href="http://code.google.com/p/google-code-prettify/" rel="nofollow noreferrer">prettify</a>, it's the script that StackOverflow uses for code colorization, and it's really easy to get it working...</p>
|
<p>Notepad++ is pretty good and I use it when I'm on a windows system and doing C++.</p>
<p>Here is the title off the sourceforge page:
Notepad++ is a generic source code editor (it tries to be anyway) and Notepad replacement written in c++ with win32 API. The aim of Notepad++ is to offer a slim and efficient binary with a totally customizable GUI.</p>
<p><a href="http://sourceforge.net/projects/notepad-plus/" rel="nofollow noreferrer">http://sourceforge.net/projects/notepad-plus/</a></p>
| 32,650
|
<p>I'm working on a project where I have 2 web services that need the same entity. The 2 web services are on the same server so on the back-end, they share the same classes. </p>
<p>On the front-end side, my code consumes <em>both</em> web services and sees the entities from both services as separate (in different namespaces) so I can't use the entity across both services.</p>
<p>Does anyone know of a way to allow this to work in .NET 2.0?</p>
<p>I've done this with my entity: </p>
<pre><code>[XmlType(TypeName = "Class1", Namespace = "myNamespace")]
public class Class1
{
public int field;
}
</code></pre>
<p>Hoping that my IDE would somehow "know" that the class is the same on both web services so that it wouldn't create separate entities for both classes, but no luck.</p>
<p>Is this possible to do with .NET 2.0 web services?</p>
|
<p>I think that you can not do that from inside VS but you can manually use the <code>wsdl.exe</code> utility like this:</p>
<pre><code>wsdl.exe /sharetypes http://localhost/MyService1.asmx?wsdl http://localhost/MyService2.asmx?wsdl
</code></pre>
<p>Notice the <code>/sharetypes</code> option which turns on the type sharing feature. This feature creates one code file with a single type definition for identical types shared between different services (the namespace, name, and wire signature must be identical). </p>
<p>More info:</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/7h3ystb6(VS.80).aspx" rel="nofollow noreferrer">Web Services Description Language tool</a></li>
<li><a href="http://weblogs.asp.net/israelio/archive/2005/01/04/346337.aspx" rel="nofollow noreferrer">Framework 2.0 - WebServices Shared Types</a></li>
</ul>
|
<p>Can you check the namespace of the entity? Make sure it is the same in both the web services. </p>
| 21,161
|
<p>I have implemented a YUI split button with a menu. The button with menu appears in a scrolling div between header and a footer divs. When exposing the menu near the footer div, the menu appears behind the div.</p>
<p>I have tried positioning the footer div with a z-index of -1. I have tried positioning the div (within the scrolling div) containing the button with menu using a z-index of 500. The menu always appears behind the footer div.</p>
<p>I am not using a YUI layout. Yet. If I did would it help?></p>
|
<p>In addition to setting the <strong>z-index</strong> property, you also have to change the <strong>position</strong> property. The easiest thing to change it to is <strong>position:relative</strong>.</p>
<p>Try setting both of those properties.</p>
<p>I don't think YUI layout will assist you in this particular problem.</p>
|
<p>I started using YUI layout and my issues no longer exist.</p>
| 30,881
|
<p>I am using sql express 2008 and vs2008, writing in c#.</p>
<p>I have a db table with a Geography column in it, into which I need to put gps data I collected. When I tried creating an Entity-Framework mapping for this table, it just ignored the column with some warning about not being able to map such column types.
I then looked at nHibernate.Spatial project, but it seems like it only translates the Geometry types, not the Geography. No luck there.
I've been told I can use a view with casting the Geography to VarBinary, and then in the created entity class add another Property that deserializes the binary back into Geography. I guess that will work for reading the data from the db, but I also need to insert those rows into my db, and I can't add rows to the view.
Is there some other trick I can use in order to easily read and write Geography data from my db, in my c# code?</p>
|
<p>I don't know much about EF, but NHibernate allows you to extend it's type framework using <code>IUserType</code>. There's a bit about it on <a href="http://www.lostechies.com/blogs/rhouston/archive/2008/03/23/mapping-strings-to-booleans-using-nhibernate-s-iusertype.aspx" rel="nofollow noreferrer">Ray Houston's Blog</a>.</p>
<p>I've successfully used this to create a type for that uses XmlSerialization to an Xml field, based on <a href="http://ayende.com/78/section.aspx/download/98" rel="nofollow noreferrer">Ayende's example</a></p>
|
<p>At this time Entity Framework v1 does not support SQL UDT - 2008 Spacial type is UDT.</p>
<p>You can store your long/lat data using WKB (byte[]/varbinary).</p>
<p>As a side note i did not notice any support for UDT during the Microsoft MIX09 for the next version (1.5 CTP). Perhaps i missed something.</p>
| 25,465
|
<p>I write a large static method that takes a generic as a parameter argument. I call this method, and the framework throws a System.InvalidProgramException. This exception is thrown even before the first line of the method is executed.</p>
<p>I can create a static class which takes the generic argument, and then make this a method of the static class, and everything works fine.</p>
<p>Is this a .NET defect, or is there some obscure generic rule I'm breaking here?</p>
<p>For the sake of completeness, I've included the method which fails, and the method which passes. Note that this uses a number of other classes from my own library (eg GridUtils), and these classes are not explained here. I don't think the actual meaning matters: the question is why the runtime crashes before the method even starts.</p>
<p>(I'm programming with Visual Studio 2005, so maybe this has gone away in Visual Studio 2008.)</p>
<p><b>This throws an exception before the first line is invoked:</b></p>
<pre><code> private delegate void PROG_Delegate<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid<TGridLine>(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate<TGridLine>(PopulateReadOnlyGrid<TGridLine>),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
</code></pre>
<p><b>This works fine:</b></p>
<pre><code> public static class Populator<TGridLine>
{
private delegate void PROG_Delegate(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns);
public static void PopulateReadOnlyGrid(DataGridView dgv, IEnumerable<TGridLine> gridLines, string[] columns)
{
if (dgv.InvokeRequired)
{
dgv.BeginInvoke
(
new PROG_Delegate(PopulateReadOnlyGrid),
new object[] { dgv, gridLines, columns }
);
return;
}
GridUtils.StatePreserver statePreserver = new GridUtils.StatePreserver(dgv);
System.Data.DataTable dt = CollectionHelper.ConvertToDataTable<TGridLine>((gridLines));
dgv.DataSource = dt;
dgv.DataMember = "";
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
GridUtils.OrderColumns<TGridLine>(dgv, columns);
statePreserver.RestoreState();
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
}
}
</code></pre>
|
<p>I would imagine using <code>blur()</code> would do the trick:</p>
<pre><code><script type="text/javascript">
YAHOO.util.Event.onDOMReady(function() {
document.getElementById("input").focus();
document.getElementById("input").blur();
});
</script>
</code></pre>
|
<p>Your idea is right, but there is a little problem.</p>
<pre><code>document.getElementById("main").focus();
<div id="main">
</code></pre>
<p>as shown in your code, actually the div HTMLElement doesn't have a focus method.</p>
<p>so you can call other elements that have a focus method or call <code>blur()</code> on the input element</p>
| 27,155
|
<p>If I have a usercontrol (in Silverlight) that I've written, that uses XAML to define it's appearance, how can I make a customised version of it?</p>
<p>i.e. I have MyControl.xaml & MyControl.xaml.cs</p>
<p>What do I need to do if I want a "SpecialisedControl" child class? I assume I just make a new code file, then inherit from MyControl. But what if I want to change the appearance of the base class - then what do I do?</p>
|
<p>I wrote this thinking you were talking about WPF, rather than Silverlight, but there may be enough overlap for this to be helpful, so I'm posting it, anyway.</p>
<p>If by "change the appearance of the base class" you mean "provide a new template", then what you need is probably a CustomControl, not a UserControl.</p>
<p>The best way to accomplish this is to follow the example set by other Microsoft controls, such as Button or ListBox:</p>
<ol>
<li>Create a class that derives directly from Control (or whatever is closest to your control).</li>
<li>If any properties will need to be exposed to the control (such as text on a button, for example), make sure that you properly define them as DependencyProperties.</li>
<li>As described <a href="http://msdn.microsoft.com/en-us/library/ms745025.aspx" rel="noreferrer">here</a>, create a ResourceDictionary called Themes/generic.xaml and add a style for your class that includes a template (don't give the style a key).</li>
<li>Use TemplateBindings for any properties of elements on your control that need to get values from your control.</li>
<li>If you'll need to attach any event handlers to elements in your template, give them a unique name. Microsoft uses the convention of prefixing these names with "PART_", and I think it's a good thing to do for the sake of consistency, but it's not strictly required.</li>
<li>Again, if you need to attach event handlers, overload OnApplyTemplate(). In this method, you should detach any old event handlers (we certainly don't want any memory leaks!), and look for elements that have the names your provided in your template--when you find them, attach event handlers, as necessary.</li>
</ol>
<p>This is certainly much more work than simply deriving from UserControl, but if you want to be able to totally re-template controls, like you can with the built-in controls, this is the way to do it.</p>
<p><em>On the other hand</em>, if all you want to do is to provide a certain amount of limited customization, such as changing the background, or associating a Command with some user action, then the best thing to do is to expose DependencyProperties, which can then be set in styles for your control, or on instances of your control, itself.</p>
<p>In the case you mentioned of wanting to customize the look in an inherited control, the process is pretty similar: just add a default style for the new control with a new template; if you need to add more event handlers, just be absolutely certain that you call base.OnApplyTemplate(). </p>
|
<p>You can solve this by using a wrapper as described in the link above.
But you can also use the strategy pattern to solve this problem.</p>
<p>In this post I explain how you implement these two methods.
<a href="http://www.lab101.be/2008/07/silverlight-usercontrol-inheritance/" rel="nofollow noreferrer">http://www.lab101.be/2008/07/silverlight-usercontrol-inheritance/</a></p>
| 27,923
|
<h2>Caution: This question is over nine years old!</h2>
<p>Your best option is to search for newer questions, or to search the answers below looking for your specific version of MVC, as many answers here are obsolete now. </p>
<p>If you do find an answer that works for your version, please make sure the answer contains the version of MVC you are using.<br>
<sub><sub>(The original question starts below)</sub></sub></p>
<hr>
<p>This seems a bit bizarre to me, but as far as I can tell, this is how you do it.</p>
<p>I have a collection of objects, and I want users to select one or more of them. This says to me "form with checkboxes." My objects don't have any concept of "selected" (they're rudimentary POCO's formed by deserializing a wcf call). So, I do the following:</p>
<pre><code>public class SampleObject{
public Guid Id {get;set;}
public string Name {get;set;}
}
</code></pre>
<p>In the view:</p>
<pre><code><%
using (Html.BeginForm())
{
%>
<%foreach (var o in ViewData.Model) {%>
<%=Html.CheckBox(o.Id)%>&nbsp;<%= o.Name %>
<%}%>
<input type="submit" value="Submit" />
<%}%>
</code></pre>
<p>And, in the controller, this is the only way I can see to figure out what objects the user checked:</p>
<pre><code>public ActionResult ThisLooksWeird(FormCollection result)
{
var winnars = from x in result.AllKeys
where result[x] != "false"
select x;
// yadda
}
</code></pre>
<p>Its freaky in the first place, and secondly, for those items the user checked, the FormCollection lists its value as "true false" rather than just true. </p>
<p>Obviously, I'm missing something. I think this is built with the idea in mind that the objects in the collection that are acted upon within the html form are updated using <code>UpdateModel()</code> or through a ModelBinder. </p>
<p>But my objects aren't set up for this; does that mean that this is the only way? Is there another way to do it?</p>
|
<p>Html.CheckBox is doing something weird - if you view source on the resulting page, you'll see there's an <code><input type="hidden" /></code> being generated alongside each checkbox, which explains the "true false" values you're seeing for each form element.</p>
<p>Try this, which definitely works on ASP.NET MVC Beta because I've just tried it.</p>
<p>Put this in the view instead of using Html.CheckBox():</p>
<pre><code><% using (Html.BeginForm("ShowData", "Home")) { %>
<% foreach (var o in ViewData.Model) { %>
<input type="checkbox" name="selectedObjects" value="<%=o.Id%>">
<%= o.Name %>
<%}%>
<input type="submit" value="Submit" />
<%}%>
</code></pre>
<p>Your checkboxes are all called <code>selectedObjects</code>, and the <code>value</code> of each checkbox is the GUID of the corresponding object.</p>
<p>Then post to the following controller action (or something similar that does something useful instead of Response.Write())</p>
<pre><code>public ActionResult ShowData(Guid[] selectedObjects) {
foreach (Guid guid in selectedObjects) {
Response.Write(guid.ToString());
}
Response.End();
return (new EmptyResult());
}
</code></pre>
<p>This example will just write the GUIDs of the boxes you checked; ASP.NET MVC maps the GUID values of the selected checkboxes into the <code>Guid[] selectedObjects</code> parameter for you, and even parses the strings from the Request.Form collection into instantied GUID objects, which I think is rather nice.</p>
|
<p>How about something like this?</p>
<pre><code>bool isChecked = false;
if (Boolean.TryParse(Request.Form.GetValues(”chkHuman”)[0], out isChecked) == false)
ModelState.AddModelError(”chkHuman”, “Nice try.”);
</code></pre>
| 27,082
|
<p>For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:</p>
<pre><code>.tables
.dump
</code></pre>
<p>using the Python sqlite3 API. </p>
<p>Is there anything like that?</p>
|
<p>You can fetch the list of tables and schemata by querying the SQLITE_MASTER table:</p>
<pre><code>sqlite> .tab
job snmptarget t1 t2 t3
sqlite> select name from sqlite_master where type = 'table';
job
t1
t2
snmptarget
t3
sqlite> .schema job
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
);
sqlite> select sql from sqlite_master where type = 'table' and name = 'job';
CREATE TABLE job (
id INTEGER PRIMARY KEY,
data VARCHAR
)
</code></pre>
|
<p>I've implemented a sqlite table schema parser in PHP, you may check here: <a href="https://github.com/c9s/LazyRecord/blob/master/src/LazyRecord/TableParser/SqliteTableDefinitionParser.php" rel="nofollow">https://github.com/c9s/LazyRecord/blob/master/src/LazyRecord/TableParser/SqliteTableDefinitionParser.php</a></p>
<p>You can use this definition parser to parse the definitions like the code below:</p>
<pre><code>$parser = new SqliteTableDefinitionParser;
$parser->parseColumnDefinitions('x INTEGER PRIMARY KEY, y DOUBLE, z DATETIME default \'2011-11-10\', name VARCHAR(100)');
</code></pre>
| 39,272
|
<p>The GUI for managing plugins in Eclipse got a bit of an overhaul in version 3.4.0.
This GUI is accessed via the "Software Updates..." option in the Help menu.</p>
<p>The option to remove the selected Mylyn plugin is greyed out. In fact, this is true of virtually every installed plugin. I know that the Mylyn plugins are optional, so why amn't I provided with an option to remove them?</p>
|
<p><strong>The following text is quoted from the Eclipse help docs:</strong></p>
<p>The Uninstall wizard allows you to review and uninstall items in your configuration. This wizard is shown when you select items and press Uninstall... from the Installed Software page. To uninstall software from your system: </p>
<ol>
<li><p>Click <em>Help > About and then click Installation Details...</em> to open a dialog showing pages that provide more detail about your installation. </p></li>
<li><p>Click the <em>Installed Software</em> tab to see a list of the software items that you have installed into your system. </p></li>
<li><p>Select the items that you wish to uninstall. </p>
<p>Click <em>Uninstall...</em></p></li>
</ol>
<p>The <em>Uninstall Details</em> page will show you a list of the items that will be uninstalled. Expanding each item will show what additional items (if any) will be uninstalled as a result of your choice. </p>
<p>If you change your mind about which items should be uninstalled, you may click <em>Back</em> to see a checkmark list of the items you selected before. You may check and uncheck different items in the list, and click <em>Next</em> when you are ready to continue. </p>
<ol start="5">
<li>Click <em>Finish</em> to start the uninstall. </li>
</ol>
<p>Once all of the software is uninstalled successfully, you will be prompted to restart for the Workbench. Click <em>Yes</em> when asked to exit and restart the Workbench for the changes to take effect.</p>
|
<p>I'm running (a relatively fresh copy of) 3.4.1. I was able to select the same plug-in shown in your screen shot (Mylyn Bridge: Java Development) to get an enabled "Uninstall..." button. I'd suggest getting the latest updates and trying again.</p>
| 48,313
|
<p>I have a page that is hitting a webservice every 5 seconds to update the information on the page. I'm using the DynamicPopulateExtender from the Ajax Control Toolkit to just populate a panel with some text.</p>
<p>What I was wanting to do, is if a certain condition is met, to refresh the page completely. </p>
<p>Am I going to be able to do this in the current method that I have? here's my current stuff:</p>
<hr>
<p>ASP.NET</p>
<pre><code><cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server"
ClearContentsDuringUpdate="true" TargetControlID="panelQueue" BehaviorID="dp1"
ServiceMethod="GetQueueTable" UpdatingCssClass="dynamicPopulate_Updating" />
</code></pre>
<p>Javascript</p>
<pre><code>Sys.Application.add_load(function(){updateQueue();});
function updateQueue()
{
var queueShown = document.getElementById('<%= hiddenFieldQueueShown.ClientID %>').value;
if(queueShown == 1)
{
var behavior = $find('dp1');
if (behavior)
{
behavior.populate();
setTimeout('updateQueue()', 5000);
}
}
}
</code></pre>
<p>SERVER (C#)</p>
<pre><code>[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetQueueTable()
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
try
{
// do stuff
}
catch (Exception ex)
{
// do stuff
}
return builder.ToString();
}
</code></pre>
|
<ul>
<li>You can't do anything from your ASMX.</li>
<li>You can refresh the page from JavaScript by using a conventional page reload or by doing a postback that would perform server-side changes and then update via your UpdatePanel or, more simply, a Response.Redirect. </li>
</ul>
|
<p>You can force a Postback from Javascript, see this Default.aspx page for a example:</p>
<hr>
<h2>Default.aspx</h2>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function forcePostback()
{
<%=getPostBackJavascriptCode()%>;
}
</script>
</head>
<body onload="javascript:forcePostback()">
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Postbacking right now..."></asp:Label>
</div>
</form>
</body>
</html>
</code></pre>
<hr>
<h2>Default.aspx.cs</h2>
<pre><code>namespace ForcingApostback
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) Label1.Text = "Done postbacking!!!";
}
protected string getPostBackJavascriptCode()
{
return ClientScript.GetPostBackEventReference(this, null);
}
}
}
</code></pre>
<p>On the client-side, under any condition, you could then call the forcePostback() Javascript function to force the Postback.</p>
| 23,369
|
<p>I use <code>ftp_put / ftp_nb_put</code> to upload files from my PHP server to another machine. I am frequently (90% of the time) getting absurd error messages like:</p>
<pre><code>Warning: ftp_nb_put(): 2 matches total
Warning: ftp_nb_put(): Transfer complete
Warning: ftp_nb_continue(): Opening BINARY mode data connection
</code></pre>
<p>Now errors like "no such directory" or "incorrect password" I could handle, but these "error message" seem to be completely pointless.</p>
<p>Google suggests this to be a Firewall/PASV-related problem. I have tried ftp_pasv(), but to no avail. I have contacted my server admin, but so far he hasn't come up with anything either.</p>
|
<p>The messages where symptoms of some arcane networking problems the server had. PHP does not diagnose such problems correctly and outputs seemingly random snippets from the communication between servers.</p>
<p>Not actually a programming question, rather a "server fault" issue (or rather a "get a better webhoster" issue).</p>
|
<p>This is not extremly helpful, but I also suggest that while you watch the php error log, open the ftp's in another window and try to figure out all things related. Most ftp servers have their own logfiles, or log to syslog.</p>
<p>Maybe you can replicate the environment with a vmware disk image, or in virtualbox (or similar) and debug this faster.</p>
| 49,195
|
<p>I am trying to create a Data Source in SharePoint Designer that connects to a SharePoint List via XML Web Services. I have created the Data Source and connected to the list in question. I can view all the data using GetListItems, and I want to filter it using the query parameter.</p>
<p>The query parameter takes an XmlNode, and when I put this as the value I get an error:</p>
<pre><code><Query>
<Where>
<Eq>
<FieldRef Name="Title" />
<Value Type="Text">Foo</Value>
</Eq>
</Where>
</Query>
</code></pre>
<p>Of course, I have not entered any tabs or newlines, as I only have a one-line entry field in SharePoint Designer. I receive an error with this query:</p>
<blockquote>
<p>The server returned a non-specific
error when trying to get data from the
data source. Check the format and
content of your query and try again.
If the problem persists, contact the
server administrator.</p>
</blockquote>
<p>I simply want to filter the list items resultset to be those with the Title field of "Foo". Can this be done in SharePoint Designer?</p>
<hr>
<p>Update: escaping the < and > in this manner also fails:</p>
<pre><code>&lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name=&quot;Title&quot; /&gt;&lt;Value Type=&quot;Text&quot;&gt;Foo&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;&lt;/Query&gt;
</code></pre>
<hr>
<p>Update: This appears to be a <a href="http://blogs.msdn.com/sharepointdesigner/archive/2008/06/20/data-source-issues-and-workarounds.aspx" rel="nofollow noreferrer">known issue</a> with SoapDataSource components and SOAP calls. Apparently, they are over-encoding the <'s and >'s before they get submitted. The workaround given is to save the data source without a query parameter, and then to add it to the page and create a filter in the Common Data View Tasks dialog. I was able to get this to work using the following filter string:</p>
<pre><code>[@ows_Title = 'Foo']
</code></pre>
<p>Unfortunately, this doesn't help me much as I am adding a Data View (showing the data) rather than a DataSource that I can use to point other controls to (like a drop-down list).</p>
<p>I'm still looking for a good solution on this that lets me place a datasource using SharePoint Designer.</p>
|
<p>There is a bug in SharePoint Designer. You cannot pass a Query object to a SOAPDataSource like this - the XML gets overencoded. Nothing you can do to fix it, except use Visual Studio.</p>
<p>I'll let you know if there's ever a hotfix available.</p>
<p>If anyone wants to quote this answer in a new answer, I'll accept that answer.</p>
|
<p>Having worked with the list Title field, it does not return values for me unless I used "Contains".</p>
<p>This may not fix your error however.</p>
| 46,036
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.