instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I'm looking for a list of win32 API in some "database"/XML format. </p>
<p>I'd need it to easily create a "conversion layer" between win32 API and the higher level language I'm using (harbour/xharbour). Since this runs Pcode, it is necessary to transform parameters to C standard...</p>
<p>Instead of doing manual code write, I'd like to automate the process...</p>
<p>just for example, the windows API definition (taken from MSDN)</p>
<pre><code>DWORD WINAPI GetSysColor(
__in int nIndex
);
</code></pre>
<p>should be transformed in</p>
<pre><code>HB_FUNC( GETSYSCOLOR )
{
hb_retnl( (LONG) GetSysColor( hb_parni( 1 ) ) );
}
</code></pre>
|
<p>AFAIK, pinvoke.net only stores text data with the PInvoke definition for the call. Not very useful if what you want is something to use as a pre-parsed database of APIs.</p>
<p>Probably you could create an small parser that will take the include file and translate it to what you need. In that case, I'd recommend using <a href="http://www.cs.virginia.edu/~lcc-win32/" rel="nofollow noreferrer">lcc-win32</a>'s include files, as they are pretty much fat-free/no-BS version of the SDK headers (they don't come with a bunch of special reserved words you'd have to ignore, etc.)</p>
|
<p>About the closest thing I know of would be: <a href="http://pinvoke.net/" rel="nofollow noreferrer">http://pinvoke.net/</a>
Maybe they would share their data with you?
They have a VS tool that accesses this data, so it may be a webservice. You might even be able to sniff that out.</p>
| 13,962
|
<p>Sometimes you have strings that must fit within a certain pixel width. This function attempts to do so efficiently. Please post your suggestions or refactorings below :)</p>
<pre><code>function fitStringToSize(str,len) {
var shortStr = str;
var f = document.createElement("span");
f.style.display = 'hidden';
f.style.padding = '0px';
document.body.appendChild(f);
// on first run, check if string fits into the length already.
f.innerHTML = str;
diff = f.offsetWidth - len;
// if string is too long, shorten it by the approximate
// difference in characters (to make for fewer iterations).
while(diff > 0)
{
shortStr = substring(str,0,(str.length - Math.ceil(diff / 5))) + '&hellip;';
f.innerHTML = shortStr;
diff = f.offsetWidth - len;
}
while(f.lastChild) {
f.removeChild(f.lastChild);
}
document.body.removeChild(f);
// if the string was too long, put the original string
// in the title element of the abbr, and append an ellipsis
if(shortStr.length < str.length)
{
return '<abbr title="' + str + '">' + shortStr + '</abbr>';
}
// if the string was short enough in the first place, just return it.
else
{
return str;
}
}
</code></pre>
<p>UPDATE:
@some's solution below is much better; please use that. </p>
<p>Update 2:
Code now posted as a <a href="https://gist.github.com/24261/7fdb113f1e26111bd78c0c6fe515f6c0bf418af5" rel="noreferrer">gist</a>; feel free to fork and submit patches :)</p>
|
<p>There are a couple of problems with your code.</p>
<ul>
<li>Why <code>/ 5</code> ? The width of the characters depends on <code>font-family</code> and <code>font-size</code>.</li>
<li>You must escape <code>str</code> in the abbr title (or else an " will make the code invalid).</li>
<li><code>diff</code> is not declared and ends up in the global scope</li>
<li>The <code>substring</code> is not supposed to work like that. What browser are you using?</li>
<li><code>hidden</code> is not a valid value of <code>style.display</code>. To hide it you should use the value <code>none</code> but then the browser don't calculate the <code>offsetWidth</code>. Use <code>style.visibility="hidden"</code> instead.</li>
<li>The search for the right length is very inefficient.</li>
<li>Must escape <code>&lt;/abbr&gt;</code>"</li>
</ul>
<p>I rewrote it for you and added <code>className</code> so you can use a style to set the <code>font-family</code> and <code>font-size</code>. Mr Fooz suggested that you use a mouseover to show the whole string. That is not necessary since modern browsers do that for you (tested with FF, IE, Opera and Chrome)</p>
<pre><code> function fitStringToSize(str,len,className) {
var result = str; // set the result to the whole string as default
var span = document.createElement("span");
span.className=className; //Allow a classname to be set to get the right font-size.
span.style.visibility = 'hidden';
span.style.padding = '0px';
document.body.appendChild(span);
// check if the string don't fit
span.innerHTML = result;
if (span.offsetWidth > len) {
var posStart = 0, posMid, posEnd = str.length;
while (true) {
// Calculate the middle position
posMid = posStart + Math.ceil((posEnd - posStart) / 2);
// Break the loop if this is the last round
if (posMid==posEnd || posMid==posStart) break;
span.innerHTML = str.substring(0,posMid) + '&hellip;';
// Test if the width at the middle position is
// too wide (set new end) or too narrow (set new start).
if ( span.offsetWidth > len ) posEnd = posMid; else posStart=posMid;
}
//Escape
var title = str.replace("\"","&#34;");
//Escape < and >
var body = str.substring(0,posStart).replace("<","&lt;").replace(">","&gt;");
result = '<abbr title="' + title + '">' + body + '&hellip;<\/abbr>';
}
document.body.removeChild(span);
return result;
}
</code></pre>
<p>Edit:
While testing a little more I found a couple of bugs.</p>
<ul>
<li><p>I used <code>Math.ceil</code> instead of the
intended <code>Math.floor</code> (I blame this on
that English isn't my native
language)</p></li>
<li><p>If the input string had html-tags
then the result would be undefined
(it's not good to truncate a tag in
the middle or to leave open tags)</p></li>
</ul>
<p>Improvements:</p>
<ul>
<li>Escape the string that is copied to the span on all places. You can still use html-entities, but no tags are allowed (<code><</code> and <code>></code> will be displayed)</li>
<li>Rewrote the <code>while</code>-statement (it is a
little faster, but the main reason
was to get rid of the bug that
caused extra rounds and to get rid
of the break-statement)</li>
<li>Renamed the function to <code>fitStringToWidth</code></li>
</ul>
<p>Version 2:</p>
<pre><code>function fitStringToWidth(str,width,className) {
// str A string where html-entities are allowed but no tags.
// width The maximum allowed width in pixels
// className A CSS class name with the desired font-name and font-size. (optional)
// ----
// _escTag is a helper to escape 'less than' and 'greater than'
function _escTag(s){ return s.replace("<","&lt;").replace(">","&gt;");}
//Create a span element that will be used to get the width
var span = document.createElement("span");
//Allow a classname to be set to get the right font-size.
if (className) span.className=className;
span.style.display='inline';
span.style.visibility = 'hidden';
span.style.padding = '0px';
document.body.appendChild(span);
var result = _escTag(str); // default to the whole string
span.innerHTML = result;
// Check if the string will fit in the allowed width. NOTE: if the width
// can't be determined (offsetWidth==0) the whole string will be returned.
if (span.offsetWidth > width) {
var posStart = 0, posMid, posEnd = str.length, posLength;
// Calculate (posEnd - posStart) integer division by 2 and
// assign it to posLength. Repeat until posLength is zero.
while (posLength = (posEnd - posStart) >> 1) {
posMid = posStart + posLength;
//Get the string from the beginning up to posMid;
span.innerHTML = _escTag(str.substring(0,posMid)) + '&hellip;';
// Check if the current width is too wide (set new end)
// or too narrow (set new start)
if ( span.offsetWidth > width ) posEnd = posMid; else posStart=posMid;
}
result = '<abbr title="' +
str.replace("\"","&quot;") + '">' +
_escTag(str.substring(0,posStart)) +
'&hellip;<\/abbr>';
}
document.body.removeChild(span);
return result;
}
</code></pre>
|
<p>Luckily, <a href="http://www.css3.info/preview/text-overflow/" rel="nofollow noreferrer">CSS3 text-overflow</a> should eventually take care of that.</p>
<p>If anyone is using ASP.NET and is interested in a server-side solution, check this blog post:</p>
<p><a href="http://waldev.blogspot.com/2010/09/truncate-text-string-aspnet-fit-width.html" rel="nofollow noreferrer">http://waldev.blogspot.com/2010/09/truncate-text-string-aspnet-fit-width.html</a></p>
| 35,818
|
<p>I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.</p>
<p>In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.</p>
|
<p>As a completion to nertzy's answer you can add the ability for detecting IE versions using this:</p>
<pre><code>Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;
</code></pre>
<p>On the other hand you have to detect user agent details on the server side, too.
Anyways browser detection is a seriously flawed strategy for writing cross-browser scripts, that's just to be used when browser feature detection fails. It's pretty easy for a user to alter his/her user agent details.</p>
|
<pre><code> <script type="text/JavaScript">
function getBrowserVersion()
{
var msg = "Not Recognised Browser";
if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
{
var ffversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ffversion == i)
{
msg = "FF" + i + "x";
break;
}
}
}
else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
{
var ieversion = new Number(RegExp.$1)
for (var i = 1; i < 20; i++)
{
if (ieversion == i)
{
msg = "IE" + i + "x";
break;
}
}
}
alert(msg); // return msg;
}
</script>
</code></pre>
| 25,648
|
<p>Why does C++ Builder 6 always compile all files? </p>
<p>I make some changes on one file but BCB 6 compiles all files when I start the app. Any idea? I use Windows XP SP2.</p>
|
<p>try this plugin for BCB compiler:
<a href="http://andy.jgknet.de/cpp/" rel="nofollow noreferrer">Bcc32Pch IDE Plugin</a></p>
|
<p>Make sure you are using the "make" command and not the "build" command, unless it is required.</p>
<p>Making a project with the Borland tools has always seemed to have that issue -- that it doesn't necessarily notice which ones have changed and starts to compile everything.</p>
<p>Look at the Pre-Compiled Headers options, which may help speed things up. </p>
<p>When Borland/CodeGear, starting in C++Builder 2007, switched to the MSBuild system, the compilations have gone much faster and are more efficient.</p>
| 11,760
|
<p>Simple question, but one that I've been curious about...is there a functional difference between the following two commands?</p>
<pre><code>String::class
String.class
</code></pre>
<p>They both do what I expect -- that is to say they return <code>Class</code> -- but what is the difference between using the <code>::</code> and the <code>.</code>?</p>
<p>I notice that on those classes that have constants defined, IRB's auto-completion will return the constants as available options when you press tab after <code>::</code> but not after <code>.</code>, but I don't know what the reason for this is...</p>
|
<p>The <code>.</code> operator basically says "send this message to the object". In your example it is calling that particular member. The <code>::</code> operator "drills down" to the scope defined to the left of the operator, and then calls the member defined on the right side of operator.</p>
<p>When you use <code>::</code> you have to be referencing members that are defined. When using <code>.</code> you are simply sending a message to the object. Because that message could be anything, auto-completion does not work for <code>.</code> while it does for <code>::</code>.</p>
|
<p>Actually, auto-completion does work for <code>.</code>. The completion options are found by calling <code>#methods</code> on the object. You can see this for yourself by overriding <code>Object.methods</code>:</p>
<pre><code>>> def Object.methods; ["foo", "bar"]; end
=> nil
>> Object.[TAB]
Object.foo Object.bar
>> Object.
</code></pre>
<p>Note that this only works when the expression to the left of the <code>.</code> is a literal. Otherwise, getting the object to call <code>#methods</code> on would involve evaluating the left-hand side, which could have side-effects. You can see this for yourself as well:</p>
<pre><code>[continuing from above...]
>> def Object.baz; Object; end
=> nil
>> Object.baz.[TAB]
Display all 1022 possibilities? (y or n)
</code></pre>
<p>We add a method <code>#baz</code> to <code>Object</code> which returns <code>Object</code> itself. Then we auto-complete to get the methods we can call on <code>Object.baz</code>. If IRB called <code>Object.baz.methods</code>, it would get the same thing as <code>Object.methods</code>. Instead, IRB has 1022 suggestions. I'm not sure where they come from, but it's clearly a generic list which isn't actually based on context.</p>
<p>The <code>::</code> operator is (also) used for getting a module's constants, while <code>.</code> is not. That's why <code>HTTP</code> will show up in the completion for <code>Net::</code>, but not for <code>Net.</code>. <code>Net.HTTP</code> isn't correct, but <code>Net::HTTP</code> is.</p>
| 6,473
|
<p>Using something like this:</p>
<pre><code>try:
# Something...
except Exception as excep:
logger = logging.getLogger("component")
logger.warning("something raised an exception: " + excep)
logger.info("something raised an exception: " + excep)
</code></pre>
<p>I would rather not have it on the error-level cause in my special case it is not an error.</p>
|
<p>From the <a href="http://docs.python.org/library/logging.html#logging.Logger.debug" rel="noreferrer">logging documentation</a>:</p>
<blockquote>
<p>There are three keyword arguments in <code>kwargs</code> which are inspected: <code>exc_info</code>, <code>stack_info</code>, and <code>extra</code>.</p>
<p>If <code>exc_info</code> does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by <a href="https://docs.python.org/3/library/sys.html#sys.exc_info" rel="noreferrer"><code>sys.exc_info()</code></a>) or an exception instance is provided, it is used; otherwise, <a href="https://docs.python.org/3/library/sys.html#sys.exc_info" rel="noreferrer"><code>sys.exc_info()</code></a> is called to get the exception information.</p>
</blockquote>
<p>So do:</p>
<pre><code>logger.warning("something raised an exception:", exc_info=True)
</code></pre>
|
<p>You can try this:</p>
<pre><code>from logging import getLogger
logger = getLogger('warning')
try:
# Somethings that is wrong.
except Exception as exp:
logger.warning("something raised an exception: " , exc_info=True)
logger.warning("something raised an exception: {}".format(exp)) # another way
</code></pre>
| 23,368
|
<p>How can I detect, or be notified, when windows is logging out in python?</p>
<p>Edit:
Martin v. Löwis' answer is good, and works for a full logout but it does not work for a 'fast user switching' event like pressing win+L which is what I really need it for.
<br /><br />Edit: im not using a gui this is running as a service</p>
|
<p>You can detect fast user switching events using the Terminal Services API, which you can access from Python using the <code>win32ts</code> module from <a href="http://sourceforge.net/projects/pywin32/" rel="noreferrer">pywin32</a>. In a GUI application, call <a href="http://msdn.microsoft.com/en-us/library/aa383841.aspx" rel="noreferrer">WTSRegisterSessionNotification</a> to receive notification messages, <a href="http://msdn.microsoft.com/en-us/library/aa383847.aspx" rel="noreferrer">WTSUnRegisterSessionNotification</a> to stop receiving notifications, and handle the <a href="http://msdn.microsoft.com/en-us/library/aa383828.aspx" rel="noreferrer"><code>WM_WTSSESSION_CHANGE</code></a> message in your window procedure.</p>
<p>If you're writing a Windows service in Python, use the <a href="http://msdn.microsoft.com/en-us/library/ms685058.aspx" rel="noreferrer"><code>RegisterServiceCtrlHandlerEx</code></a> function to detect fast user switching events. This is available in the pywin32 library as the <code>RegisterServiceCtrlHandler</code> function in the <code>servicemanager</code> module. In your <a href="http://msdn.microsoft.com/en-us/library/ms683241.aspx" rel="noreferrer">handler function</a>, look for the <code>SERVICE_CONTROL_SESSIONCHANGE</code> notification. See also the <a href="http://msdn.microsoft.com/en-us/library/aa383828.aspx" rel="noreferrer"><code>WM_WTSSESSION_CHANGE</code></a> documentation for details of the specific notification codes.</p>
<p>There's some more detail in <a href="http://mail.python.org/pipermail/python-win32/2008-January/006736.html" rel="noreferrer">this thread</a> from the python-win32 mailing list, which may be useful.</p>
<p>I hope this helps!</p>
|
<p>In a console application, you can use win32api.SetConsoleCtrlHandler and look for CTRL_LOGOFF_EVENT. In a GUI application, you need a window open and wait for the WM_QUERYENDSESSION message. How precisely that works (and if it works at all) depends on your GUI library.</p>
| 47,657
|
<p>How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want. </p>
|
<p><strong>There's no easy way to find out the memory size of a python object</strong>. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead and internal structures related to object types and garbage collection. Finally, some python objects have non-obvious behaviors. For instance, lists reserve space for more objects than they have, most of the time; dicts are even more complicated since they can operate in different ways (they have a different implementation for small number of keys and sometimes they over allocate entries).</p>
<p>There is a <a href="http://code.activestate.com/recipes/544288/" rel="noreferrer">big chunk of code</a> (and an <a href="http://code.activestate.com/recipes/546530/" rel="noreferrer">updated big chunk of code</a>) out there to try to best approximate the size of a python object in memory. </p>
<p>You may also want to check some <a href="http://mail.python.org/pipermail/python-list/2002-March/135223.html" rel="noreferrer">old description about PyObject</a> (the internal C struct that represents virtually all python objects).</p>
|
<p>For big objects you may use a somewhat crude but effective method:
check how much memory your Python process occupies in the system, then delete the object and compare.</p>
<p>This method has many drawbacks but it will give you a very fast estimate for very big objects.</p>
| 5,415
|
<p>Is it a simple case of just never using the this.XYZ construct?</p>
|
<p>It's only considered poor style if it violates your style guidelines. Sometimes using <code>this</code> is necessary to qualify a member variable over a local variable:</p>
<pre><code>public MyType(int arg)
{
this.arg = arg;
}
</code></pre>
<p>This problem can also be mitigated with style guidelines. For example, prefix members with "_":</p>
<pre><code>public MyType(int arg)
{
_arg = arg;
}
</code></pre>
|
<p>I wouldn't say it's poor style - but it's not particularly idiomatic.</p>
<p>My almost sole use of <code>this.foo</code> is when copying parameters into fields:</p>
<pre><code>public Person (string name, string occupation)
{
this.name = name;
this.occupation = occupation;
}
</code></pre>
| 39,836
|
<p>I have a python script that I would like to add a "Shutdown when done" feature to.</p>
<p>I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).</p>
<p>I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.</p>
<p>Any ideas how I can achieve this?</p>
<p>Thanks in advance,
Ashy.</p>
|
<p>gksudo should have a timeout, I believe it's from the time you last executed a gksudo command.</p>
<p>So I think I'd just throw out a "gksudo echo meh" or something every minute. Should reset the timer and keep you active until you reboot.</p>
|
<p>Escalate priority, spawn (<code>fork (2)</code>) a separate process that will <code>wait (2)</code>, and drop priority in the main process.</p>
| 33,029
|
<p>I am looking for a clear, complete example of programmatically deleting all documents from a specific document library, via the Sharepoint object model. The doclib does not contain folders. I am looking to delete the documents completely (ie I don't want them in the Recycle Bin).</p>
<p>I know of SPWeb.ProcessBatchData, but somehow it never seems to work for me.</p>
<p>Thanks!</p>
|
<p>I would persevere with the ProcessBatchData approach, maybe this will help:</p>
<blockquote>
<p><a href="http://blog.thekid.me.uk" rel="noreferrer">Vincent Rothwell</a> has covered this
best:
<a href="http://blog.thekid.me.uk/archive/2007/02/24/deleting-a-considerable-number-of-items-from-a-list-in-sharepoint.aspx" rel="noreferrer">http://blog.thekid.me.uk/archive/2007/02/24/deleting-a-considerable-number-of-items-from-a-list-in-sharepoint.aspx</a></p>
</blockquote>
<p>Otherwise I'm not sure the other recommendation will work, as a Foreach loop will not like that the number of items in the collection changes with each delete. </p>
<p>You are probably best placed doing a reverse for loop (I didn't test this code, just an example):</p>
<pre><code>for (int i = SPItems.Length - 1; i >= 0; i--)
{
SPListItem item = SPItems[i];
item.File.Delete();
}
</code></pre>
|
<p>Powershell way:</p>
<pre><code>function ProcessFolder {
param($folderUrl)
$folder = $web.GetFolder($folderUrl)
foreach ($file in $folder.Files) {
#Ensure destination directory
$destinationfolder = $destination + "/" + $folder.Url
if (!(Test-Path -path $destinationfolder))
{
$dest = New-Item $destinationfolder -type directory
}
#Delete file by deleting parent SPListItem
$list.Items.DeleteItemById($file.Item.Id)
}
}
#Delete root Files
ProcessFolder($list.RootFolder.Url)
#Delete files from Folders or Document Sets
foreach ($folder in $list.Folders) {
ProcessFolder($folder.Url)
}
</code></pre>
| 31,797
|
<p>I have a <code>XmlDocument</code> in java, created with the <code>Weblogic XmlDocument</code> parser.</p>
<p>I want to replace the content of a tag in this <code>XMLDocument</code> with my own data, or insert the tag if it isn't there.</p>
<pre><code><customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
</code></pre>
<p>For example I want to insert a URL in the location tag:</p>
<pre><code><location>http://something</location>
</code></pre>
<p>but otherwise leave the XML as is.</p>
<p>Currently I use a <code>XMLCursor</code>:</p>
<pre><code> XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
</code></pre>
<p>I tried to find a "quick" <code>xquery</code> way to do this since the <code>XmlDocument</code> has an <code>execQuery</code> method, but didn't find it very easy. </p>
<p>Do anyone have a better way than this? It seems a bit elaborate.</p>
|
<p>How about an XPath based approach? I like this approach as the logic is super-easy to understand. The code is pretty much self-documenting.</p>
<p>If your xml document is available to you as an org.w3c.dom.Document object (as most parsers return), then you could do something like the following:</p>
<pre><code>// get the list of customdata nodes
NodeList customDataNodeSet = findNodes(document, "//customdata" );
for (int i=0 ; i < customDataNodeSet.getLength() ; i++) {
Node customDataNode = customDataNodeSet.item( i );
// get the location nodes (if any) within this one customdata node
NodeList locationNodeSet = findNodes(customDataNode, "location" );
if (locationNodeSet.getLength() > 0) {
// replace
locationNodeSet.item( 0 ).setTextContent( "http://stackoverflow.com/" );
}
else {
// insert
Element newLocationNode = document.createElement( "location" );
newLocationNode.setTextContent("http://stackoverflow.com/" );
customDataNode.appendChild( newLocationNode );
}
}
</code></pre>
<p>And here's the helper method findNodes that does the XPath search.</p>
<pre><code>private NodeList findNodes( Object obj, String xPathString )
throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile( xPathString );
return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );
}
</code></pre>
|
<p>You should be able to do this with <code>query</code></p>
<p>try </p>
<pre><code> fn:replace(string,pattern,replace)
</code></pre>
<p>I am new to xquery myself and I have found it to be a painful query language to work with, but it does work quiet well once you get over the initial learning curve. </p>
<p>I do still wish there was an easier way which was as efficient? </p>
| 3,670
|
<p>Let's say I woke up today and wanted to create a clone of StackOverflow.com, and reap the financial windfall of millions $0.02 ad clicks. Where do I start?</p>
<p>My understanding of web technologies are:</p>
<ul>
<li>HTML is what is ultimately displayed</li>
<li>CSS is a mechanism for making HTML look pleasing </li>
<li>ASP.NET lets you add functionality using .NET(?)</li>
<li>JavaScript does stuff</li>
<li>AJAX does asyncronous stuff</li>
<li>... and the list goes on!</li>
</ul>
<p>To write a good website to I just need to buy seven books and read them all? Are Web 2.0 sites really the synergy of all these technologies? </p>
<p>Where does someone go to get started down the path to creating professional-looking web sites, and what steps are there along the way. </p>
|
<p>While I have built my knowledge largely based on using the internet to search out what I want to know (w3schools.com helped a lot, as did A List Apart), a few good books have helped me along the way, though they have been platform/language-specific, so I'll avoid mentioning them unless someone is curious. For me, at least, having a book open so that I don't have to resize windows or switch between them is very valuable.</p>
<p>The first part of your list is ok, but the last few items need tweaking. ASP.NET adds <em>server-side</em> functionality (for the most part) to your application. This lives outside of the browser and is thus quite powerful and easily shared with a variety of end-users.</p>
<p>The problem (some say) with server-side processing is that your application must make a new HTTP request when you ask for an action to be performed. So if you click on a link to a page that yields a new set of data, you don't get instant results. The page reloads, or loads a separate page.</p>
<p>Javascript solves this to a degree--it allows you to respond to user input instantaneously. Do you want to display the sum of two numbers when the user clicks a button? You can do it with Javascript.</p>
<p>The problem with Javascript is that it can't talk directly to databases, or explore your server's file system, or other stuff like that. It lives in the browser--period.</p>
<p>AJAX bridges the gap between your user's browser and your server. With AJAX, <em>Javascript</em> makes the HTTP request without refreshing your page or loading a new one. Javascript talks to a server-side script (not necessarily ASP, either--works with PHP, Rails, Coldfusion, etc.) and sends and receives information. And because Javascript isn't dependent on page loads, a quick, snappy AJAX script can almost give the feeling of a common desktop application, in which you don't have to wait for HTTP requests when performing simple actions on your application's data.</p>
|
<p>I would recommend this book:<br>
<a href="https://rads.stackoverflow.com/amzn/click/com/0735623341" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/MCTS-Self-Paced-Training-Exam-70-528/dp/0735623341/ref=sr_1_1?ie=UTF8&s=books&qid=1218830714&sr=8-1</a></p>
<p>I have just read it to take the exam, and although I knew the web theory part, I found it to be of great value.<br>
This of course is a ASP.NET specific book, but that is what I would recommend learning anyways. </p>
<p>After you learn all the ASP.NET stuff, I would suggest reading up on <a href="http://jquery.com/" rel="nofollow noreferrer">JQuery</a>.</p>
<p>Happy coding :)</p>
| 3,377
|
<p>I'm trying to run a LINQ to SQL query that returns a result in a grid view in a search engine style listing. </p>
<p>In the simplified example below, is it possible to populate the collection with a comma-separated list of any children that the parent has (NAMESOFCHILDREN) in a single query?</p>
<pre><code>var family = from p in db.Parents
where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"])
join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId
join c in db.Children on pcl.ChildId equals c.ChildId
select new
{
Family = "Name: " + p.ParentName + "<br />" +
"Children: " + NAMESOFCHILDREN? + "<br />"
};
</code></pre>
<p>Thanks in advance.</p>
|
<p>Your joins are going to screw up your cardinality! You don't have a list of Parents!</p>
<p>Here's some untested free-hand code. Adding the relationships in the Linq designer gives you relationship properties. String.Join will put the list together.</p>
<p>I've added two optional method calls.</p>
<p><em>Where ... Any</em> will filter the parents to only those parents that have children. I'm unsure of string.Join's behavior on an empty array.</p>
<p><em>ToList</em> will yank Parents into memory, the children will be accessed by further database calls. This may be necessary if you get a runtime <em>string.Join is not supported by SQL translator</em> exception. This exception would mean that LINQ tried to translate the method call into something that SQL Server can understand - and failed.</p>
<pre><code>int parentID = Convert.ToInt32(Request.QueryString["parentId"]);
List<string> result =
db.Parents
.Where(p => p.ParentId == parentID)
//.Where(p => p.ParentChildLookup.Children.Any())
//.ToList()
.Select(p =>
"Name: " + p.ParentName + "<br />" +
"Children: " + String.Join(", ", p.ParentChildLookup.Children.Select(c => c.Name).ToArray() + "<br />"
)).ToList();
</code></pre>
<p>Also note: generally you do not want to mix data and markup until the data is properly escaped for markup.</p>
|
<p>you could try as follow: </p>
<pre><code>var family = from p in db.Parents
where p.ParentId == Convert.ToInt32(Request.QueryString["parentId"])
join pcl in db.ParentChildLookup on p.ParentId equals pcl.ParentId
select new {
Family = "Name: " + p.ParentName + "<br />" + string.Join(",",(from c in db.Children where c.ChildId equals pcl.ChildId select c.ChildId.ToString()).ToArray());
};
</code></pre>
| 14,132
|
<p>I am looking to store 2D arrays of 900x100 elements in a database. Efficient recall and comparison of the arrays is important. I could use a table with a schema like [A, x, y, A(x,y)] such that a single array would compromise 90,000 records. This seems like an ~ok~ table design to store the array, and would provide for efficient recall of single elements, but inefficient recall of a whole array and would make for very inefficient array comparisons.</p>
<p>Should I leave the table design this way and build and compare my arrays in code? Or is there a better way to structure the table such that I can get efficient array comparisons using database only operations?</p>
<p>thanks</p>
|
<p>If the type of data allows, store it in a concatenated format and compare in memory after it has been de-concatenated. The database operation will be much faster and the in-memory operations will be faster than database retrievals as well.</p>
<p>Who knows, you may even be able to compare it without de-concatenating.</p>
|
<p>900 x 100 elements is actually very small (even if the elements are massive 1K things that'd only be 90 MB). Can't you just compare in memory when needed and store on disk in some serialized format?</p>
<p>It doesn't make sense to store 2D arrays in the database, especially if it is immutable data.</p>
| 18,318
|
<p>Platform: Windows XP
Development Platform: VB6</p>
<p>When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed.</p>
<p>Does anyone have a workaround or fix for this? </p>
<hr>
<p>Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) . </p>
<p>Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string. </p>
<p>I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB. </p>
|
<h2>One solution using the Windows API</h2>
<p><br/>
<strong>Disclaimer</strong>: <em>IMHO this seems like overkill just to meet the requirement stated in the question, but in the spirit of giving a (hopefully) complete answer to the problem, here goes nothing...</em></p>
<p>Here is a working version I came up with after looking around in MSDN for awhile, until I finally came upon an article on vbAccelerator that got my wheels turning.</p>
<ul>
<li>See the <a href="http://www.vbaccelerator.com/home/VB/Tips/Get_System_Display_Fonts_and_Non-Client_Area_Sizes/article.asp" rel="nofollow noreferrer">vbAccelerator</a> page for the original article (not directly related to the question, but there was enough there for me to formulate an answer)</li>
</ul>
<p>The basic premise is to first calculate the width of the form's caption text and then to use <strong>GetSystemMetrics</strong> to get the width of various bits of the window, such as the border and window frame width, the width of the Minimize, Maximize, and Close buttons, and so on (I split these into their own functions for readibility/clarity). We need to account for these parts of the window in order to calculate an accurate new width for the form.</p>
<p>In order to accurately calculate the width ("extent") of the form's caption, we need to get the system caption font, hence the <strong>SystemParametersInfo</strong> and <strong>CreateFontIndirect</strong> calls and related goodness.</p>
<p>The end result all this effort is the <strong>GetRecommendedWidth</strong> function, which calculates all of these values and adds them together, plus a bit of extra padding so that there is some space between the last character of the caption and the control buttons. If this new width is greater than the form's current width, GetRecommendedWidth will return this (larger) width, otherwise, it will return the Form's current width.</p>
<p>I only tested it briefly, but it appears to work fine. Since it uses Windows API functions, however, you may want to exercise caution, especially since it's copying memory around. I didn't add robust error-handling, either. </p>
<p>By the way, if someone has a cleaner, less-involved way of doing this, or if I missed something in my own code, please let me know.</p>
<p><strong>To try it out, paste the following code into a new module</strong></p>
<pre><code>Option Explicit
Private Type SIZE
cx As Long
cy As Long
End Type
Private Const LF_FACESIZE = 32
'NMLOGFONT: This declaration came from vbAccelerator (here is what he says about it):'
' '
' For some bizarre reason, maybe to do with byte '
' alignment, the LOGFONT structure we must apply '
' to NONCLIENTMETRICS seems to require an LF_FACESIZE '
' 4 bytes smaller than normal: '
Private Type NMLOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE - 4) As Byte
End Type
Private Type LOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE) As Byte
End Type
Private Type NONCLIENTMETRICS
cbSize As Long
iBorderWidth As Long
iScrollWidth As Long
iScrollHeight As Long
iCaptionWidth As Long
iCaptionHeight As Long
lfCaptionFont As NMLOGFONT
iSMCaptionWidth As Long
iSMCaptionHeight As Long
lfSMCaptionFont As NMLOGFONT
iMenuWidth As Long
iMenuHeight As Long
lfMenuFont As NMLOGFONT
lfStatusFont As NMLOGFONT
lfMessageFont As NMLOGFONT
End Type
Private Enum SystemMetrics
SM_CXBORDER = 5
SM_CXDLGFRAME = 7
SM_CXFRAME = 32
SM_CXSCREEN = 0
SM_CXICON = 11
SM_CXICONSPACING = 38
SM_CXSIZE = 30
SM_CXEDGE = 45
SM_CXSMICON = 49
SM_CXSMSIZE = 52
End Enum
Private Const SPI_GETNONCLIENTMETRICS = 41
Private Const SPI_SETNONCLIENTMETRICS = 42
Private Declare Function GetTextExtentPoint32 Lib "gdi32" Alias "GetTextExtentPoint32A" _
(ByVal hdc As Long, _
ByVal lpszString As String, _
ByVal cbString As Long, _
lpSize As SIZE) As Long
Private Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As SystemMetrics) As Long
Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" ( _
ByVal uAction As Long, _
ByVal uParam As Long, _
lpvParam As Any, _
ByVal fuWinIni As Long) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
Private Declare Function CreateFontIndirect Lib "gdi32" Alias "CreateFontIndirectA" (lpLogFont As LOGFONT) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Function GetCaptionTextWidth(ByVal frm As Form) As Long
'-----------------------------------------------'
' This function does the following: '
' '
' 1. Get the font used for the forms caption '
' 2. Call GetTextExtent32 to get the width in '
' pixels of the forms caption '
' 3. Convert the width from pixels into '
' the scaling mode being used by the form '
' '
'-----------------------------------------------'
Dim sz As SIZE
Dim hOldFont As Long
Dim hCaptionFont As Long
Dim CaptionFont As LOGFONT
Dim ncm As NONCLIENTMETRICS
ncm.cbSize = LenB(ncm)
If SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, ncm, 0) = 0 Then
' What should we do if we the call fails? Change as needed for your app,'
' but this call is unlikely to fail anyway'
Exit Function
End If
CopyMemory CaptionFont, ncm.lfCaptionFont, LenB(CaptionFont)
hCaptionFont = CreateFontIndirect(CaptionFont)
hOldFont = SelectObject(frm.hdc, hCaptionFont)
GetTextExtentPoint32 frm.hdc, frm.Caption, Len(frm.Caption), sz
GetCaptionTextWidth = frm.ScaleX(sz.cx, vbPixels, frm.ScaleMode)
'clean up, otherwise bad things will happen...'
DeleteObject (SelectObject(frm.hdc, hOldFont))
End Function
Private Function GetControlBoxWidth(ByVal frm As Form) As Long
Dim nButtonWidth As Long
Dim nButtonCount As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
nButtonCount = 1 'close button is always present'
nButtonWidth = GetSystemMetrics(SM_CXSIZE) 'get width of a single button in the titlebar'
' account for min and max buttons if they are visible'
If frm.MinButton Then nButtonCount = nButtonCount + 1
If frm.MaxButton Then nButtonCount = nButtonCount + 1
nFinalWidth = nButtonWidth * nButtonCount
End If
'convert to whatever scale the form is using'
GetControlBoxWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetIconWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog, vbSizable:
'we have an icon, gets its width'
nFinalWidth = GetSystemMetrics(SM_CXSMICON)
Case Else:
'no icon present, so report zero width'
nFinalWidth = 0
End Select
End If
'convert to whatever scale the form is using'
GetIconWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetFrameWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog:
nFinalWidth = GetSystemMetrics(SM_CXDLGFRAME)
Case vbSizable:
nFinalWidth = GetSystemMetrics(SM_CXFRAME)
End Select
End If
'convert to whatever scale the form is using'
GetFrameWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetBorderWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.Appearance
Case 0 'flat'
nFinalWidth = GetSystemMetrics(SM_CXBORDER)
Case 1 '3D'
nFinalWidth = GetSystemMetrics(SM_CXEDGE)
End Select
End If
'convert to whatever scale the form is using'
GetBorderWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Public Function GetRecommendedWidth(ByVal frm As Form) As Long
Dim nNewWidth As Long
' An abitrary amount of extra padding so that the caption text '
' is not scrunched up against the min/max/close buttons '
Const PADDING_TWIPS = 120
nNewWidth = _
GetCaptionTextWidth(frm) _
+ GetControlBoxWidth(frm) _
+ GetIconWidth(frm) _
+ GetFrameWidth(frm) * 2 _
+ GetBorderWidth(frm) * 2 _
+ PADDING_TWIPS
If nNewWidth > frm.Width Then
GetRecommendedWidth = nNewWidth
Else
GetRecommendedWidth = frm.Width
End If
End Function
</code></pre>
<p><strong>Then place the following in your Form_Load event</strong></p>
<pre><code>Private Sub Form_Load()
Me.Caption = String(100, "x") 'replace this with your caption'
Me.Width = GetRecommendedWidth(Me)
End Sub
</code></pre>
|
<p>It appears that VB6 limits the App.Title property to 40 characters. Unfortunately, I can't locate any documentation on MSDN detailing this behavior. (And unfortunately, I don't have documentation loaded onto the machine where my copy of VB6 still resides.)</p>
<p>I ran an experiment with long titles, and that was the observed behavior. If your title is longer than 40 characters, it simply will get truncated.</p>
| 17,151
|
<p>Where can I find pascal-style railroad diagrams to describe C++ syntax?
(As an alternative to EBNF)</p>
|
<p>There don't exist any, as far as I know. The C++ syntax can't even be expressed in a proper EBNF - it's a context-sensitive grammar, and anything attempting to parse it has to be capable of processing C++ code at least as far as template instantiation and overload resolution (not to mention macros).</p>
|
<p>There isn't one - the C++ grammar is not only <strong>not</strong> context-free, it's undecidable. See <a href="http://yosefk.com/c++fqa/defective.html#defect-2" rel="nofollow noreferrer"><a href="http://yosefk.com/c++fqa/defective.html#defect-2" rel="nofollow noreferrer">http://yosefk.com/c++fqa/defective.html#defect-2</a></a> and the associated links for a more in-depth discussion.</p>
| 39,917
|
<p>I've found that given a form in a HTML page like this:</p>
<pre><code><form name="form">
<input type="image" name="foo"
src="somewhere.gif" alt="image" value="blah"/>
<input type="text" name="bar" value="blah"/>
</form>
</code></pre>
<p>When accessing the elements via the DOM in Javascript, there is <em>no</em> element for the image input! It is just omitted. So, <code>document.forms[0].elements.length</code> is 1, and <code>document.forms[0].element[0].type</code> is "text".</p>
<p>This seems to be the case in Firefox, and IE. I can't find this fact documented anywhere in my reference books or on the web. All I can find is a throwaway comment here:</p>
<p><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=163822#c4" rel="nofollow noreferrer">https://bugzilla.mozilla.org/show_bug.cgi?id=163822#c4</a></p>
<p>Which suggests it "just is like this". If so, well so be it - but is it <em>really</em> not documented anywhere? Is it a historical mistake, or is there a reason for it?</p>
|
<p>It looks like that's the behavior of the <code>elements</code> property in all browsers.</p>
<p>However, you should still be able to access it through the DOM in JavaScript using the <code>childNodes</code> property.</p>
<p>For your example:</p>
<pre><code>document.forms[0].childNodes.length; // equals 5 (2 inputs and 3 text nodes).
document.forms[0].childNodes[1]; // This is your input with type='image'
</code></pre>
|
<p>Interesting... the <a href="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html" rel="nofollow noreferrer">DOM 1</a> spec defines <code>.elements</code> as:</p>
<blockquote>
<p>elements
Returns a collection of all control elements in the form.</p>
</blockquote>
<p>The <a href="http://www.w3.org/TR/REC-html40/interact/forms.html#input-control-types" rel="nofollow noreferrer">HTML 4</a> spec part 17.2.1 doesn't list "image" types, so I guess that's the answer.</p>
| 30,667
|
<p>I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files.</p>
<p>I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.</p>
|
<p>I would suggest mocking out your calls to the database. Mocks are basically objects that look like the object you are trying to call a method on, in the sense that they have the same properties, methods, etc. available to caller. But instead of performing whatever action they are programmed to do when a particular method is called, it skips that altogether, and just returns a result. That result is typically defined by you ahead of time. </p>
<p>In order to set up your objects for mocking, you probably need to use some sort of inversion of control/ dependency injection pattern, as in the following pseudo-code:</p>
<pre class="lang-php prettyprint-override"><code>class Bar
{
private FooDataProvider _dataProvider;
public instantiate(FooDataProvider dataProvider) {
_dataProvider = dataProvider;
}
public getAllFoos() {
// instead of calling Foo.GetAll() here, we are introducing an extra layer of abstraction
return _dataProvider.GetAllFoos();
}
}
class FooDataProvider
{
public Foo[] GetAllFoos() {
return Foo.GetAll();
}
}
</code></pre>
<p>Now in your unit test, you create a mock of FooDataProvider, which allows you to call the method GetAllFoos without having to actually hit the database.</p>
<pre class="lang-php prettyprint-override"><code>class BarTests
{
public TestGetAllFoos() {
// here we set up our mock FooDataProvider
mockRepository = MockingFramework.new()
mockFooDataProvider = mockRepository.CreateMockOfType(FooDataProvider);
// create a new array of Foo objects
testFooArray = new Foo[] {Foo.new(), Foo.new(), Foo.new()}
// the next statement will cause testFooArray to be returned every time we call FooDAtaProvider.GetAllFoos,
// instead of calling to the database and returning whatever is in there
// ExpectCallTo and Returns are methods provided by our imaginary mocking framework
ExpectCallTo(mockFooDataProvider.GetAllFoos).Returns(testFooArray)
// now begins our actual unit test
testBar = new Bar(mockFooDataProvider)
baz = testBar.GetAllFoos()
// baz should now equal the testFooArray object we created earlier
Assert.AreEqual(3, baz.length)
}
}
</code></pre>
<p>A common mocking scenario, in a nutshell. Of course you will still probably want to unit test your actual database calls too, for which you will need to hit the database.</p>
|
<p>You could use <strong>mocking frameworks</strong> to abstract out the database engine. I don't know if PHP/Python got some but for typed languages (C#, Java etc.) there are plenty of choices</p>
<p>It also depends on how you designed those database access code, because some design are easier to unit test than other like the earlier posts have mentioned.</p>
| 5,058
|
<p>I keep getting asked about AppDomains in interviews, and <a href="http://en.wikipedia.org/wiki/Appdomain" rel="noreferrer">I know the basics</a>: </p>
<ul><li>they are an isolation level within an application (making them different from applications)</li>
<li>they can have threads (making them different from threads)</li>
<li>exceptions in one appdomain do not affect another</li>
<li>appdomains cannot access each other's memory</li>
<li>each appdomain can have different security</li></ul>
<p>I still don't get what makes them necessary. I'm looking for a reasonable concrete circumstance when you would use one.</p>
<p>Answers:</p>
<ul>
<li>Untrusted code</li>
<ul>
<li>Core application protected<br />
Untrusted/3rd party plugins are barred from corrupting shared memory and non-authorized access to registry or hard drive by isolation in separate appdomain with security restrictions, protecting the application or server. e.g. ASP.NET and SQL Server hosting component code</li>
</ul>
<li>Trusted code</li>
<ul>
<li>Stability<br />
Application segmented into safe, independent features/functionality</li>
<li>Architectural flexibility<br />
Freedom to run multiple applications within a single CLR instance or each program in its own.</li>
</ul>
</ul>
<p>Anything else?</p>
|
<p>Probably the most common one is to load assemblies that contain plug-in code from untrusted parties. The code runs in its own AppDomain, isolating the application.</p>
<p>Also, it's not possible to unload a particular assembly, but you can unload AppDomains.</p>
<p>For the full rundown, Chris Brumme had a massive blog entry on this:</p>
<p><strike><a href="http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/cbrumme/archive/2003/06/01/51466.aspx</a></strike></p>
<p><a href="https://devblogs.microsoft.com/cbrumme/appdomains-application-domains/" rel="nofollow noreferrer">https://devblogs.microsoft.com/cbrumme/appdomains-application-domains/</a></p>
|
<p>If you create an application that allows 3rd-party plug-ins, you can load those plug-ins in a separate AppDomain so that your main application is safe from unknown code.</p>
<p>ASP.NET also uses separate AppDomains for each web application within a single worker process.</p>
| 12,291
|
<p>Our situation is as follows, but I'm curious about this problem in any situation.</p>
<p>We have a framework consisting of 4 projects:</p>
<ul>
<li>beans</li>
<li>util</li>
<li>framework</li>
<li>web</li>
</ul>
<p>We also have modules that need a version and depend on a version of beans and util.</p>
<p>Finally we have a customer project that consists of a specific version of the core projects and one or more modules.</p>
<p>Is there a standard way to version these projects?</p>
<p>What seems simple to me is becoming really complicated as we try to deliver releases to QA and then manage our ongoing development with the maintenance of the release (release = tag and possible branch).</p>
<p>I kind of prefer the following:</p>
<p>1.2.0 - major and minor versions + release.</p>
<p>1.2.1 - next release</p>
<p>1.2.0_01 - bug fix in 1.2.0 release (branch)</p>
<p>etc.</p>
<p>Any ideas?</p>
|
<p>We use major.minor.bugfix. A major release only happens for huge changes. A minor release is called for when there is an API change. All other releases are bugfix releases. There's definitely utility in having a build or revision number there too for troubleshooting, although if you've got really rigorous CM you might not need to include it.</p>
<p>Coordinating among the versions of all these projects can be done really well with help from tools like Apache Ivy or Maven. The build of one project, with its own version number, can involve the aggregation of specific versions of (the products of) other projects, and so your build files provide a strict mapping of versions from the bottom up. Save it all in [insert favorite version control tool here] and you have a nice history recorded.</p>
|
<p>Currently we have no real versioning. We use the svn build number and the release date.
(tag name is like release_081010_microsoft e.g.)</p>
<p>Older Products use major.minor.sub version numbering</p>
<p>Major never changed
Minor changes on every release/featurerelease every 6 months.
Sub is everything which doesn't affect the feature set - mostly bugfixes.</p>
| 23,242
|
<p>I am writing an application where I will be accessing the database from django and from a stand alone application. Both need to do session verification and the session should be the same for both of them. Django has a built in authentication/session verification, which is what I am using, now I need to figure out how to reuse the same session for my stand alone application.</p>
<p>My question is how can I look up a session_key for a particular user?</p>
<p>From what it looks there is nothing that ties together auth_user and django_session</p>
|
<p>Modifying the <code>django_session</code> table to add an explicit <code>user_id</code> can make life a lot easier. Assuming you do that (or something similar), here are four approaches to munging things to your liking:</p>
<p>Fork the <code>django.contrib.session</code> code. I know, I know, that's a horrible thing to suggest. But it's only 500 lines including all backends and minus the tests. It's pretty straightforward to hack. This is the best route only if you are going to do some serious rearranging of things.</p>
<p>If you don't want to fork, you could try connecting to the <code>Session.post_save</code> signal and munge there.</p>
<p>Or you could MonkeyPatch <code>contrib.session.models.Session.save()</code>. Just wrap the existing method (or create a new one), breakout/synthesize whatever values you need, store them in your new fields, and then <code>super(Session, self).save()</code>.</p>
<p>Yet another way of doing this is to put in 2 (yes, two) middleware classes -- one before and one after <code>SessionMiddleware</code> in your <em>settings.py</em> file. This is because of the way middleware is processed. The one listed after <code>SessionMiddleware</code> will get, on the inbound request, a request with the session already attached to it. The one listed before can do any processing on the response and/or change/resave the session.</p>
<p>We used a variation on this last technique to create pseudo-sessions for search engine spiders to give them special access to material that is normally member-only. We also detect inbound links where the <code>REFERER</code> field is from the associated search engine and we give the user full access to that one article.</p>
<p><strong>Update:</strong></p>
<p>My answer is now quite ancient, although it still is mostly correct. See @Gavin_Ballard's much more recent answer (9/29/2014) below for yet another approach to this problem.</p>
|
<p>Peter Rowell, thanks for your response. It was a tremendous help. This is what I did to get it working. Only had to change one file in djang.contrib.sessions.</p>
<p>In django/contrib/sessions/models.py, add the user_id to the table (add to DB table manually or drop table and run manage.py syncdb).</p>
<pre><code>class Session(models.Model):
...
user_id = models.IntegerField(_('user_id'), null=True)
...
def save(self, *args, **kwargs):
user_id = self.get_decoded().get('_auth_user_id')
if ( user_id != None ):
self.user_id = user_id
# Call the "real" save() method.
super(Session, self).save(*args, **kwargs)
</code></pre>
<p>Now in your view where you do login (if you use django's base login, you will have to override it)</p>
<pre><code># On login, destroy all prev sessions
# This disallows multiple logins from different browsers
dbSessions = Session.objects.filter( user_id = request.user.id )
for index, dbSession in enumerate( dbSessions ):
if ( dbSession.session_key != request.session.session_key ):
dbSession.delete()
</code></pre>
<p>This worked for me.</p>
| 29,197
|
<p>I am trying to have a tooltip on multiple lines. how do i do this?</p>
|
<p>Put a newline (use <code>Environment.NewLine</code>) into the actual tooltip text. </p>
|
<p>To avoid <a href="https://en.wikipedia.org/wiki/Escape_character" rel="nofollow noreferrer">escaping</a> special characters as newline, easiest is to use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.format" rel="nofollow noreferrer">String.Format()</a> syntax to insert linebreaks in one or multiple places. In this case the last parameter {3}, <em>Environment.NewLine</em>, is inserted in two locations.</p>
<pre><code>tipText = String.Format("{0:HH:mm}{3}{1:0.00}{3}{2}", ADateTime, ADouble, AString, Environment.NewLine);
</code></pre>
| 45,161
|
<p>When the .net 2.0 framework first came out, the provider model was all the rage. 2.0 even shipped with a bunch of default providers (Membership, sitemap, role). Since the release of 2.0, the hype has died down, and whilst I still use providers day to day, it seems to get far less press.</p>
<p>I was wondering if this is because people are using something other than providers and they've been superseded, or is it simply because the take up wasn't as big as other IoC methods? </p>
|
<p>It actually hasn't died down. DI is still big. There are many DI frameworks out there to choose from. Yes, it's not hard-baked into <strong>every part</strong> framework <strong>like it should absolutely be</strong>, but its still a very good practice to follow. For instance, I was using the P&P's custom application blocks to do DI. Until they ditched it for Unity. Now I'm using unity. </p>
<p>A lightweight DI framework is a good idea for any large extensible application.</p>
|
<p>I think that as these tools become more standard within .NET the hype around them becomes less, but their use does not. Certainly the Membership and role providers are very important to our new application that we are developing and will save us significant amounts of code.</p>
<p><a href="http://msdn.microsoft.com/en-us/practices/default.aspx" rel="nofollow noreferrer">Microsoft Patterns and Practices</a> is the birthplace of tools like the Enterprise Library, which is heavily involved with the provider patterns (particularly with membership) in regards to the Security Applicaiton block and the model appears to be used throughout the blocks.</p>
| 18,842
|
<p>I am wondering how you would approach this problem</p>
<p>I have two Taxrates that can apply to my products. I specifically want to avoid persisting the Taxrates into the database while still being able to change them in a central place (like Taxrate from 20% to 19% etc).</p>
<p>so I decided it would be great to have them just compiled into my application (It's internal). The problem is that I want to not only to know the Rate but also the Name of the Taxrate.</p>
<p>I could go with an Enum that maps to the value. But then I'd have to create some method that retrieves the German Name of that Taxrate for the English enum-value (I write my code in english, the App is in german).</p>
<p>I thought about just using hardcoded objects to reflect this,</p>
<pre><code>public interface Taxrate
{
string Name { get; }
decimal Rate { get; }
}
public class NormalTaxRate : Taxrate
{
public string Name
{ get { return "Regelsteuersatz"; } }
public decimal Rate
{ get { return 20m; } }
}
</code></pre>
<p>But then I'd have to create some sort of list that holds two instances of those two objects. Doing it static may work, but still I'd have to keep some sort of list.
Also I'd have to find a way to map my POCO Domain Object to this, because I doubt NHibernate can instantiate the right Object depending on a value in a field.</p>
<p>It doesn't really feel right, and I think I'm missing something here. Hope somebody has a better solution, I can't think of one.</p>
<p>greetings, Daniel</p>
<p><em>Ps: also please retag this question if you find something fitting, I can't think of more meaningful tags right now.</em></p>
|
<p>EDIT: Note that the code here could easily be abbreviated by having a private constructor taking the tax rate and the name. I'm assuming that in real life there might be actual behavioral differences between the tax rates.</p>
<p>It sounds like you want something like Java's enums.</p>
<p>C# makes that fairly tricky, but you can do it to some extent using private constructors and nested classes:</p>
<pre><code> public abstract class TaxRate
{
public static readonly TaxRate Normal = new NormalTaxRate();
public static readonly TaxRate Whatever = new OtherTaxRate();
// Only allow nested classes to derive from this - and we trust those!
private TaxRate() {}
public abstract string Name { get; }
public abstract decimal Rate { get; }
private class NormalTaxRate : TaxRate
{
public override string Name { get { return "Regelsteuersatz"; } }
public override decimal Rate { get { return 20m; } }
}
private class OtherTaxRate : TaxRate
{
public override string Name { get { return "Something else"; } }
public override decimal Rate { get { return 120m; } }
}
}
</code></pre>
<p>You'd probably want some sort of static method in TaxRate to return the right instance based on name or whatever.</p>
<p>I don't know how easily this fits in with NHibernate, but hopefully it will help to some extent...</p>
<p>As noted in the comments, it's pretty ugly - or at least can get pretty ugly when you've got lots of different values. Partial classes can help here:</p>
<pre><code>// TaxRate.cs
public partial abstract class TaxRate
{
// All the stuff apart from the nested classes
}
// TaxRate.Normal.cs
public partial abstract class TaxRate
{
private class NormalTaxRate : TaxRate
{
public override string Name { get { return "Regelsteuersatz"; } }
public override decimal Rate { get { return 20m; } }
}
}
// TaxRate.Other.cs
public partial abstract class TaxRate
{
private class OtherTaxRate : TaxRate
{
public override string Name { get { return "Something else"; } }
public override decimal Rate { get { return 120m; } }
}
}
</code></pre>
<p>You can then munge the project file to show the nested classes as children of the outer class, as shown in <a href="https://stackoverflow.com/questions/223249/">this SO question</a>.</p>
|
<p>Why not store the tax rates in application configuration, eg in the web.config or app.config file? These are simple XML files, which have a section called where you can specify custom parameters with a key and a value. For example:</p>
<pre><code><appSettings>
<add key="BaseTaxRate" value=20"/>
<add key="HigherTaxRate" value=40"/>
</appSettings>
</code></pre>
<p>You can then retrieve these in your application simply:</p>
<pre><code>string baseTaxRate = ConfigurationSettings.AppSettings["BaseTaxRate"];
</code></pre>
<p>This way, they are easily changed, and won't require re-compilation and re-deployment of your application.</p>
<p>Obviously, you can also store the names of the tax rates as extra settings in the config file.</p>
| 42,154
|
<p>I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.</p>
<p>So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions.</p>
<p>This public <a href="http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&cm_cat=rss&par=LWO_rss" rel="noreferrer">weather.com RSS feed</a> is a good example of what we'd be parsing (<em>our actual weather.com feed contains additional information because of a partnership w/them</em>).</p>
<p>In a nutshell, how should we convert XML to JSON using Python?</p>
|
<p><a href="https://github.com/martinblech/xmltodict" rel="noreferrer">xmltodict</a> (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this <a href="http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html" rel="noreferrer">"standard"</a>. It is <a href="http://docs.python.org/library/pyexpat.html" rel="noreferrer">Expat</a>-based, so it's very fast and doesn't need to load the whole XML tree in memory.</p>
<p>Once you have that data structure, you can serialize it to JSON:</p>
<pre><code>import xmltodict, json
o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>')
json.dumps(o) # '{"e": {"a": ["text", "text"]}}'
</code></pre>
|
<p>This stuff here is actively maintained and so far is my favorite: <a href="https://github.com/hay/xml2json" rel="nofollow noreferrer">xml2json in python</a></p>
| 23,264
|
<p>This is a bit of a long shot, but if anyone can figure it out, you guys can...</p>
<p>In Windows XP, is there any meta-data that comes with a cut and paste action, from which I can ascertain the application that provided the clipboard contents?</p>
<p>Bonus question... if there is such information, is there any way I can access it through a Java app?</p>
|
<p>That depends on the clipboard format. If it is plain-text, then no. Unless you want to install global hooks on the clipboard.</p>
<p>Which you cannot do from Java.</p>
|
<p>That depends on the clipboard format. If it is plain-text, then no. Unless you want to install global hooks on the clipboard.</p>
<p>Which you cannot do from Java.</p>
| 4,146
|
<p>How Can I put information in a outputstream from tapestry5 ?</p>
<p>I need a page when a user enters it open a dialog for save or open the file with the outputstream information.</p>
<p>I write the next code:</p>
<p>public class Index {</p>
<pre><code>@Inject
private RequestGlobals requestGlobals;
@OnEvent("activate")
public void onActivate() {
try {
HttpServletResponse response = requestGlobals.getHTTPServletResponse();
response.setContentType("text/txt");
PrintWriter out = response.getWriter();
out.println("hellooooooo");
out.flush();
} catch (IOException ex) {
Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
}
}
</code></pre>
<p>}</p>
<p>I hope that the result is only "helloooooooo" but is ("helloooooooo" + my html raw page)</p>
|
<p>Your method should have a return type of StreamResponse. You return an implementation of the interface StreamResponse, which simply returns the data you want with the content type you want.</p>
<p>Look it up here:</p>
<p><a href="http://tapestry.apache.org/tapestry5/apidocs/" rel="nofollow noreferrer">http://tapestry.apache.org/tapestry5/apidocs/</a></p>
<p>more info here:</p>
<p><a href="http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html" rel="nofollow noreferrer">http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html</a></p>
|
<p>If you are dealing with large response streams, using <a href="http://tapestry.apache.org/tapestry5/apidocs/org/apache/tapestry5/StreamResponse.html" rel="nofollow">StreamResponse</a> can be somewhat inconvenient and inefficient (because you have to return an <a href="http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html" rel="nofollow">InputStream</a>). Better would be to write response directly to <a href="http://download.oracle.com/javase/6/docs/api/java/io/OutputStream.html" rel="nofollow">OutputStream</a>.</p>
<p>Fortunately, in Tapestry Wiki, there is a page for solving exactly this: <a href="http://wiki.apache.org/tapestry/Tapestry5HowToCreateAComponentEventResultProcessor" rel="nofollow">Tapestry5: How To Create A Component Event Result Processor</a>.</p>
| 36,717
|
<p>I'm using xsd.exe to make the C# classes for our settings. I have a setting that is per-server and per-database, so I want the class to behave like Dictionary<string, string[][]>. So I want to be able to say</p>
<pre><code>string serverName = "myServer";
int databaseId = 1;
FieldSettings fieldSettings = getFieldSettings();
string[] fields = fieldSettings[serverName][databaseId];
</code></pre>
<p>how do I represent that in XSD?</p>
|
<p>xsd defines the data structure, not really the access approach. I don't think you can express "this is a lookup" in xsd : everything is either values or set of values/entities.</p>
<p>If you want specific handling, you might consider custom serialization - or alternatively consider your DTOs and your <em>working</em> classes as separate things, and simply translate between the two.</p>
<p>[edit] As leppie notes - you can write your own indexer (typically in a partial class if generating cs from the xsd) that loops over the list to find the item: this will give you the caller usage, but not really the full dictionary experience (uniqueness, O(1) retrieval, etc)</p>
|
<p>This not what <code>xsd</code> is used for. You can always just add your own indexer to a partial class, and mark it with <code>[XmlIgnore]</code></p>
| 26,017
|
<p>We're looking at using Oracle Hierarchical queries to model potentially very large tree structures (potentially infinitely wide, and depth of 30+). My understanding is that hierarchal queries provide a method to write recursively joining SQL but they it does not provide any real performance enhancements over if you were to manually write an equivalent query... is this the case? What sort of experiences have people had, performance wise, with using oracle hierarchical queries?</p>
|
<p>Well the short answer is that without the hierarchical extension (connect by) you couldn't write a recursive query. You could programmitically issue many queries which were recurisively linked.</p>
<p>The rule of thumb with everything database is, especially oracle, is that if you can issue your result in a single query it will almost always be faster than doing it programatically.</p>
|
<p>I've seen that using connect by can be slow but compared to what? There isn't really another option except building a result set using recursive PL/SQL calls (slower) or doing it on your client side.</p>
<p>You could try separating your data into a mapping (hierarchy definition) and lookup tables (the display data) and then joining them back together. I guess I wouldn't expect much of a gain assuming you are getting the hierarchy data from indexed fields but its worth a try.</p>
<p>Have you tried it using the connect by yet? I'm a big fan of trying different variations.</p>
| 30,169
|
<p>Consider the following file</p>
<pre><code>var1 var2 variable3
1 2 3
11 22 33
</code></pre>
<p>I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:</p>
<pre><code>variable_names = char('var1', 'var2', 'variable3');
</code></pre>
<p>I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option. </p>
<p>Note that there can be an arbitrary number of variables (columns)</p>
|
<p>I suggest <strong>importdata</strong> for operations like this:</p>
<pre><code>d = importdata('filename.txt');
</code></pre>
<p>The return is a struct with the numerical fields in a member called 'data', and the column headers in a field called 'colheaders'.</p>
<p>Another useful interface for importing manipulating data like these is the 'dataset' class available in the Statistics Toolbox.</p>
|
<p>Just use textscan with different format specifiers.</p>
<pre><code>fid = fopen(filename,'r');
heading = textscan(fid,'%s %s %s',1);
fgetl(fid); %advance the file pointer one line
data = textscan(fid,'%n %n %n');%read the rest of the data
fclose(fid);
</code></pre>
<p>In this case 'heading' will be a cell array containing cells with each column heading inside, so you will have to change them into cell array of strings or whatever it is that you want. 'data' will be a cell array containing a numeric array for each column that you read, so you will have to cat them together to make one matrix.</p>
| 32,488
|
<p>I'm trying to determine how to open/edit existing SQL Server Reporting Services (SSRS) 2005 report projects (.rptproj) and reports (.rdl) with Visual Studio 2008, <em>without</em> having to install SQL Business Intelligence Development Studio (BIDS) 2005.</p>
|
<p>You cannot. Check this <a href="http://social.msdn.microsoft.com/forums/en-US/sqlreportingservices/thread/9a7a78a0-bf5c-458a-9cb0-bc82004501f7" rel="nofollow noreferrer">forum posting</a> which has a reponse from Microsoft. </p>
<blockquote>
<p>Yes, it was an active decision that
the 2008 design evironments would not
support continuous backwards
compatability but would rather be a
one way upgrade. This was not a
casual decision and it is understood
how it can be an impact.</p>
</blockquote>
<p>You can read the entire posting for more details on why you are unable to use VS2008 for SSRS 2005 projects. Very annoying, but I guess I can understand why they had to make that decision. Just about the only reason I have VS2005 on my dev machine now is for Reporting Services projects since our company is not going to be upgrading to SQL Server 2008 anytime soon. </p>
|
<p>Wow this would be a lot easier to swallow if purchasing VS2008 gave you, by default, rights to all previous versions.</p>
<p>Oh well, long live the internet, the eula, corporate greed and other American inventions...</p>
| 22,245
|
<p>I'm trying to get Cruisecontrol.NET running with Server 2008/IIS7 and when I try and navigate to the dashboard I get the following error:
HTTP Error 404.17 - Not Found
The requested content appears to be script and will not be served by the static file handler.</p>
<p>I'm a bit lost in IIS7 so it could be something pretty straightforward. They (cc.net) do some funny stuff with http handlers in the web.config which may be related to the problem:</p>
<p>
</p>
<p>Anyone have any pointers?</p>
|
<p>Is the dashboard set up as an application in IIS?</p>
<p>I've not used IIS7, but I know in IIS6 you need to enable an application and assign it to an app pool before you can run ASPX code.</p>
<p><strong>EDIT:</strong> This works in IIS6.</p>
<p>Open the IISAdmin tool on the web server. Expand the web sites folder. Find the virtual directory (directories?) for CruiseControl. Right-click on it and look at properties. On the directory tab, create a new application and give it a suitable name. Enable the application to execute "scripts only". Assign it to an application pool (you may want to create a new one just for this application -- consult the help documentation for this). You may also need to change the ASP.NET version You can do this on the ASP.NET tab -- choose either v1.1 or v2.0, whichever CruiseControl requires.</p>
|
<p>I just had this same issue when I installed CCNET 1.5 under Windows 7/IIS 7.5</p>
<p>You need to configure the app pool for the ccnet site. Under the Basic Settings for the application pool, set 'Managed pipeline mode' to 'Integrated'.</p>
| 42,373
|
<p>I would like to create a Crystal Reports report using pre-existing LINQ classes that live in a different project than where the report lives. I can't find a way to do this. I'm using VS2008.</p>
<p>Whenever I expand the "Project Data" tree, I see only classes in my current project. The "History" tree shows me the last 5 class in the OTHER project, but I need more than those 5. I found the "Make New Connection" option under "ADO.NET", but it looks like it's looking for XML sources and DLLs.</p>
|
<p>How about a private helper method in the test fixture</p>
<pre><code>private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()
</code></pre>
|
<p>I can add Dave to the Wamu and the Woodforest account when Dave is created like this: </p>
<pre><code> public Dave()
{
FirstName = "Dave";
LastName = "Allen";
// add accounts for Dave
Wamu wamu = new Wamu();
wamu.AddUser(this);
Woodforest woodforest = new Woodforest();
woodforest.AddUser(this);
}
</code></pre>
<p>The accounts are added the List collection in the User object from which Dave inherits. </p>
| 19,428
|
<p>Should I expose a strongly typed dataset from a webservice and bind it directly in a client? or are there more sensible ways for asmx web services? I am doing CRUD operations (Create, Read, Update, Delete). </p>
<p>I find working with datasets to be frustrating and difficult to work with when for example when inserting into a table within it for instance. It doesn't seem logical to ship a whole dataset to and forth when only inserting one record or when only getting one record from a particular table within the dataset.</p>
<p>Is there a better way?</p>
<p>Should I perhaps be converting to objects and use objects over the webservice? Doing conversions all over the place to get objects passed around is perhaps just as tedious?</p>
|
<p>It depends on your interoperability requirements. Although it's entirely possible to process the DataSet XMLs from practically any environment it can get unwieldly. If you're not interoperating I'd definitely recommend the typed dataset route because it's insanely simple to use from C# and "just works".</p>
|
<p>I agree with Joannes... stick with objects and specific methods for the types of operations you want to expose.</p>
| 14,187
|
<p>As a beginning programmer, I'm trying to settle on a standard naming convention for myself. I realize that it's personal preference, but I was trying to get some ideas from some of you (well a LOT of you) who are much smarter than myself.</p>
<p>I'm not talking about camel notation but rather how do you name your variables, etc. IMHO, var_Quantity is much more descriptive than Q or varQ. However, how do you keep the variable from becoming too long. I've tried to be more descriptive with naming my controls, but I've ended up with some like "rtxtboxAddrLine1" for a RadTextBox that holds address line 1. Too me,that is unmanageable, although it's pretty clear what that control is.</p>
<p>I'm just curious if you have some guides that you follow or am I left up to my own devices?</p>
|
<p>Some <a href="http://msdn.microsoft.com/en-us/library/ms229045.aspx" rel="nofollow noreferrer">basic rules can be found here</a>. And <a href="http://msdn.microsoft.com/en-us/library/ms229002.aspx" rel="nofollow noreferrer">much more extended rules can be found here</a>. These are the official guidelines from the Microsoft framework designers.</p>
<p>As for your example, the variable should should be called simply <code>quantity</code>.</p>
|
<p>The more descriptive the better, you will find that the length isn't as important as remembering what that control/variable did five years down the road.</p>
| 39,480
|
<p>I'm working on a C#/ASP.NET project that has all the javascript files in a /Javascript folder. If I refer to the JS file using this syntax: src="/Javascript/jsfile.js" then the file is correctly picked up if the project is deployed to the root of the URL.</p>
<p>However, if this "web site" is deployed to a sub-folder of the main url this won't work. So the solution could be to use relative urls - but there's a problem with that as well because the master pages reference many of the javascript files and these master pages can be used by pages in the root and in subfolders many levels deep.</p>
<p>Does anybody have any ideas for resolving this?</p>
|
<p>If you reference the JS-file in a section that is "runat=server" you could write src="~/Javascript/jsfile.js" and it will always work.</p>
<p>You could also do this in your Page_Load (In your masterpage):</p>
<pre><code>Page.ClientScript.RegisterClientScriptInclude("myJsFile", Page.ResolveClientUrl("~/Javascript/jsfile.js"))
</code></pre>
|
<p>@Jared: IE needs that /script . FF doesn't care.</p>
| 6,481
|
<p>In Javascript, I have an object:</p>
<pre><code>obj = { one: "foo", two: "bar" };
</code></pre>
<p>Now, I want do do this</p>
<pre><code>var a = 'two';
if(confirm('Do you want One'))
{
a = 'one';
}
alert(obj.a);
</code></pre>
<p>But of course it doesn't work. What would be the correct way of referencing this object dynamically?</p>
|
<p>short answer: <code>obj[a]</code></p>
<p>long answer: <code>obj.field</code> is just a shorthand for <code>obj["field"]</code>, for the special case where the key is a constant string without spaces, dots, or other nasty things. in your question, the key wasn't a constant, so simply use the full syntax.</p>
|
<p>As a side note, global variables are attached to the "window" object, so you can do</p>
<pre><code>var myGlobal = 'hello';
var a = 'myGlobal';
alert(window[a] + ', ' + window.myGlobal + ', ' + myGlobal);
</code></pre>
<p>This will alert "hello, hello, hello"</p>
| 20,486
|
<p>I have created a class library in VB .NET. Some code in the library connects to the database. I want to create a config file that would hold the connection string.
<br /><br />
I have created a "Settings.settings" file and stored the connection string in there.
<br /><br />
When a class library having a settings file is built, it generates a ".dll.config" file which has the key value pairs defined in the settings file.
<br /><br />
Problem with this is when i change the connection string in the ".dll.config" file, the library does not references these changes. I would still need to recompile the class library which would then overwrite my changes in the .dll.config file.
<br /><br />
I need to be able to change the connection strings on the fly without having to recompile the library.
<br /><br />
Is there a mechanism in VB.NET class library (.NET 2.0) that would let me do this?
<br /><br />
Passing the connection string to the class library from the web page that uses its method is not a option.
<br /> <br>
I have listed a sample below, this is how i would access the string.</p>
<pre>
Public Function getsettings(ByVal Setting As String) As String
If Setting = "Demo" Then
Return My.Settings.Demo
Else
Return My.Settings.Live
End If
End Function
</pre>
|
<p>If you have an application which uses your library called MyApp, then the connection string defined in MyApp.exe.config will be available to your library. Generally speaking the client program should set the configuration environment, not the library.</p>
<pre><code>If GetApplicationSetting("connectionString") Is Nothing Then
Throw New Exception("Could not retrieve connection string from .config file")
Else
Return ConfigurationManager.AppSettings.Item("connectionString")
End If
</code></pre>
<p>Make sure you have the System.Configuration framework loaded to access the ConfigurationManager.</p>
<p>EDIT 1: If you are using it in a web-application, then set the connection string in web.config.</p>
<p>EDIT 2: If you set the connection string in the ConnectionStrings section of the .exe.config or web.config you can access it using :</p>
<pre><code>ConfigurationManager.ConnectionStrings("MyConnectionString")
</code></pre>
|
<p>Config files are specific to the application. So if your DLL is used by an application, the app.config or web.config needs to have the entries you are trying to use in the DLL config. </p>
<p>Unfortunately the "Not an option" is probably the correct option. </p>
| 46,489
|
<p>Is it possible using a server side XML parser to have it create an HTML blob that is then included in an existing HTML page?</p>
|
<p>Is the existing HTML page already being served by the same server? If so, then yes - arguably that's a rough description of what almost all web frameworks do, to a greater or lesser extent: insert some dynamic content within a static template.</p>
<p>Which bit are you concerned about?</p>
|
<p>Most languages should have XML libraries or parsers available to facilitate this. </p>
<p>For example, PHP has <a href="http://ca3.php.net/xml" rel="nofollow noreferrer">an XML parser</a>.</p>
<p>Write a function using this to take a given XML feed, pretty it up, and spit it out. Then call this function in your HTML page.</p>
| 24,672
|
<p>I have to add either an embed tag for Firefox or an object tag for Internet Explorer with JavaScript to address the appropriate ActiveX / Plugin depending on the browser. The plugin could be missing and needs to get downloaded in this case. The dynamically added embed tag for Firefox works as expected. The dynamically added object tag for Internet Explorer seems to do nothing at all. The object tag needs the following attributes to function properly.</p>
<p><code>id ="SomeId"
classid = "CLSID:{GUID}"
codebase = "http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1"</code></p>
<p>Even a general working idea or method would be nice.</p>
<p>Thanks!</p>
|
<p>I needed to do this same thing and simply place all of the HTML needed for the OBJECT tag in a string in JavaScript and simply replace the innerHTML of a div tag with the OBJECT HTML and it works in IE just fine.</p>
<pre><code>// something akin to this:
document.getElementById(myDivId).innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
</code></pre>
<p>That should work, it does just fine for me - I use it to embed Windows Media Player in a page.</p>
<hr>
<p>UPDATE: You would run the above code after the page loads via an event handler that either runs on the page's load event or maybe in response to a user's click. The only thing you need to do is have an empty DIV tag or some other type of tag that would allow us to inject the HTML code via that element's <code>innerHTML</code> property.</p>
<hr>
<p>UPDATE: Apparently you need more help than I thought you needed? Maybe this will help:</p>
<p>Have your BODY tag look like this: <code><body onload="loadAppropriatePlugin()"></code></p>
<p>Have somewhere in your page, where you want this thing to load, an empty DIV tag with an <code>id</code> attribute of something like "Foo" or whatever.</p>
<p>Have code like this in a <code><script></code> tag in your <code><head></code> section:</p>
<pre><code>function getIEVersion() { // or something like this
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
return ((msie > 0) ? parseInt(ua.substring(msie+5, ua.indexOf(".", msie))) : 0);
}
function loadAppropriatePlugin() {
if(getIEVersion() != 0) { // this means we are in IE
document.getElementById("Foo").innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
} else {
// if you want to maybe do the same for FF and load that stuff...
}
}
</code></pre>
<p>Does that help?</p>
|
<p>Two ways.</p>
<p>1) Just do a document.write where ever you want it</p>
<pre><code><script type="text/javascript">
<!--
document.write("<object id=\"SomeId\" classid=\"CLSID:{GUID}\" codebase=\"http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1\"></object>");
-->
</script>
</code></pre>
<p>2) Edit a tag's innerHTML property.</p>
<pre><code><div id="my-div"></div>
<script type="text/javascript">
<!--
document.getElementById("my-div").innerHTML = "<object id=\"SomeId\" classid=\"CLSID:{GUID}\" codebase=\"http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1\"></object>";
-->
</script>
</code></pre>
<p><strong>EDIT:</strong> Just a note, it is best to not use JavaScript to do this, since people with JavaScript enabled will never see the object. It would be better to just place it in your HTML.</p>
| 35,578
|
<p>Given the following class, what is your opinion on the best way to handle create/edit where Attributes.Count can be any number.</p>
<pre><code>public class Product {
public int Id {get;set;}
public string Name {get;set;}
public IList<Attribute> Attributes {get;set;}
}
public class Attribute {
public string Name {get;set;}
public string Value {get;set;}
}
</code></pre>
<p>The user should be able to edit both the Product details (Name) and Attribute details (Name/Value) in the same view, including adding and deleting new attributes.</p>
<p>Handling changes in the model is easy, what's the best way to handle the UI and ActionMethod side of things?</p>
|
<p>Look at Steve Sanderson’s blog post <a href="http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/" rel="noreferrer">Editing a variable length list, ASP.NET MVC 2-style</a>.</p>
<h2>Controller</h2>
<p>Your action method receives your native domain model <code>Product</code> and stays pretty simple:</p>
<pre><code>public ActionResult Edit(Product model)
</code></pre>
<h2>View</h2>
<p><strong>Edit.aspx</strong></p>
<pre><code><!-- Your Product inputs -->
<!-- ... -->
<!-- Attributes collection edit -->
<% foreach (Attribute attr in Model.Attributes)
{
Html.RenderPartial("AttributeEditRow", attr);
} %>
</code></pre>
<p><strong>AttributeEditRow.ascx</strong></p>
<p>Pay your attention to helper extension <code>Html.BeginCollectionItem(string)</code></p>
<pre><code><% using(Html.BeginCollectionItem("Attributes")) { %>
<!-- Your Attribute inputs -->
<% } %>
</code></pre>
<p>Adding and editing of new attributes is possible too. See the post.</p>
|
<p>Depends on the experience you are looking to create for the user. I have implemented something similar for tagging content. In the model, Tags are represented as IList, but the UI shows a comma delimited list in a single text field. I then handle merging the items in the list into a string to populate the text field, and I split the input to put items back into the IList in the model.</p>
<p>In my DAL, I then deal with converting the List into LINQ entities, handle inserts and deletes, etc.</p>
<p>It isn't the most straight forward code, but it isn't too difficult to manage and it gives the user an expected interface.</p>
<p>I'm sure there are other ways to handle it but I would focus on what would work best for the user and then work out the mapping details based on that.</p>
| 36,802
|
<p>I want to shift the contents of an array of bytes by 12-bit to the left.</p>
<p>For example, starting with this array of type <code>uint8_t shift[10]</code>:</p>
<pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xBC}
</code></pre>
<p>I'd like to shift it to the left by 12-bits resulting in:</p>
<pre><code>{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAB, 0xC0, 0x00}
</code></pre>
|
<p>Hurray for pointers! </p>
<p>This code works by looking ahead 12 bits for each byte and copying the proper bits forward. 12 bits is the bottom half (nybble) of the next byte and the top half of 2 bytes away.</p>
<pre><code>unsigned char length = 10;
unsigned char data[10] = {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0A,0xBC};
unsigned char *shift = data;
while (shift < data+(length-2)) {
*shift = (*(shift+1)&0x0F)<<4 | (*(shift+2)&0xF0)>>4;
shift++;
}
*(data+length-2) = (*(data+length-1)&0x0F)<<4;
*(data+length-1) = 0x00;
</code></pre>
<blockquote>
<p>Justin wrote:<br>
@Mike, your solution works, but does not carry. </p>
</blockquote>
<p>Well, I'd say a normal shift operation does just that (called overflow), and just lets the extra bits fall off the right or left. It's simple enough to carry if you wanted to - just save the 12 bits before you start to shift. Maybe you want a circular shift, to put the overflowed bits back at the bottom? Maybe you want to realloc the array and make it larger? Return the overflow to the caller? Return a boolean if non-zero data was overflowed? You'd have to define what carry means to you.</p>
<pre><code>unsigned char overflow[2];
*overflow = (*data&0xF0)>>4;
*(overflow+1) = (*data&0x0F)<<4 | (*(data+1)&0xF0)>>4;
while (shift < data+(length-2)) {
/* normal shifting */
}
/* now would be the time to copy it back if you want to carry it somewhere */
*(data+length-2) = (*(data+length-1)&0x0F)<<4 | (*(overflow)&0x0F);
*(data+length-1) = *(overflow+1);
/* You could return a 16-bit carry int,
* but endian-ness makes that look weird
* if you care about the physical layout */
unsigned short carry = *(overflow+1)<<8 | *overflow;
</code></pre>
|
<p>@Joseph, notice that the variables are 8 bits wide, while the shift is 12 bits wide. Your solution works only for N <= variable size.</p>
<p>If you can assume your array is a multiple of 4 you can cast the array into an array of uint64_t and then work on that. If it isn't a multiple of 4, you can work in 64-bit chunks on as much as you can and work on the remainder one by one.
This may be a bit more coding, but I think it's more elegant in the end.</p>
| 4,909
|
<p>How can you implement trackbacks on a custom-coded blog (written in C#)?</p>
|
<p>The TrackBack specification was created by Six Apart back in the day for their <a href="http://www.movabletype.org/" rel="nofollow noreferrer">Movable Type</a> blogging system. After some corporate changes it seems to be no longer available, but here's an archived version:</p>
<p><a href="http://web.archive.org/web/20081228043036/http://www.sixapart.com/pronet/docs/trackback_spec" rel="nofollow noreferrer">http://web.archive.org/web/20081228043036/http://www.sixapart.com/pronet/docs/trackback_spec</a></p>
|
<p>If you're custom coding your own blog you have too much time on your hands. Start with something like <a href="http://www.dasblog.info/" rel="nofollow noreferrer">dasBlog</a> or <a href="http://subtextproject.com/" rel="nofollow noreferrer">SubText</a> and customize that to your needs. Then you get trackbacks for free.</p>
| 5,321
|
<p>I have a list of items that I am displaying in a floated list, with each item in the list at a fixed width so that there's two per row. What is the best practice to prevent this horrible thing from happening:</p>
<p><a href="http://x01.co.uk/floated_items.gif">alt text http://x01.co.uk/floated_items.gif</a></p>
<p>Possibilites:</p>
<ul>
<li>Trim to a specified number of characters before displaying the data. Requires guesswork on how many characters will be "safe".</li>
<li>Overflow: hidden. Hacky.</li>
<li>Remove the background and just have a top border on each item.</li>
</ul>
<p>Possible but silly:</p>
<ul>
<li>Have a scrollbar in each item by doing overflow: auto, this will look horrendous.</li>
<li>Add a background image to the container. It's not guaranteed that there's always an equal number of items so this option is out.</li>
</ul>
<p>Any help on this irritating issue appreciated!</p>
|
<p>Are you using a fixed font size, i.e. specified in px? If not you also need to consider the various text size options of each browser which is probably going to make the concept of trimming the string redundant. If it is fixed then perhaps seeing how many Ws you can fit in and restricting your text to that -3 and appending an ellipsis, not sure what this list is for so that's one approach.</p>
<p>Personally I'd probably use overflow:hidden as that covers all eventualities and ensures that it'll always keep your layout consistent.</p>
<p>I guess the last option would be to keep a tight control over what can be added to the list and prevent the problem occuring in the first place. Prevention better than cure as they say, although probably unhelpfully.</p>
|
<p>One solution would be to have a alpha-based PNG that would slowly fade the text to the backgroundcolor of your container, on the last 10px or so. That would look good if some text are considerebly shorter than the long ones, however in the case where the text would be equal to the container it could look kinda silly.</p>
<p>Of course, in combination with display: hidden and white-space: no-wrap</p>
| 33,823
|
<p>Printer: FDM printer (FDM == Fusion Deposition Modelling).</p>
<p>Raw Material: Thermoplastics.</p>
<p>How do I do multicolor printing? What changes should I make to the printing process/to the raw material used?</p>
<p>(Answer in the context of printing a basic 3X3 Rubix cube)</p>
<hr>
<p>Bonus: What are the best practises while doing multi-colour printing? (<-- This is opinion based and/or broad, so pl add an answer to this point as an extra to your answers if you can. It would greatly help people getting started/practising with multi-colour printing) </p>
|
<p>There are a few different approaches I've seen which you could look into.</p>
<p>The easiest and most common is multiple extruders, each with a different color of thermoplastic. Tools like Pronterface and Slic3r have built-in support for multiple extruders. With multiple extruders you can get one color per extruder; there's no clear way to mix colors and get a color between the input materials' colors.</p>
<p>Another, more complicated approach is to use a single extruder with three inputs, like <a href="http://www.aliexpress.com/item/Diamond-hotend-Prusa-i3-Extruder-Full-kit-E3D-V6-Brass-Multi-Color-Nozzle-3-IN-1/32516521911.html">this one</a>, where thermoplastic from the three inputs can be mixed in varying amounts to get color gradients between the input colors. With red, yellow, and blue filament, you could get a rainbow of colors...albeit without any control over value (white to black) or saturation (bright vs dull color).</p>
|
<p>If you are trying to print something like a Rubic's Cube in the correct colors without using paint or stickers, there are only a couple of options.</p>
<p>Assuming that you are using a printer with only a single extruder and no fancy gadgets, you will need to print each color cube you will need to print in a lot of pieces and then put them together. You can't use tricks like changing the filament manually at a certain level for most of the cubes because most of the cubes are corner cubes with 3 colors.</p>
<p>Assuming that you have some sort of multi-material system, then you just use STL files that are made with the proper colors. And I'm talking any sort of multi-material system, including multiple extruders, the fancy extruder described by @Martin Carney, or the MMS from prusia3d.com which has 4 inputs to a single extruder with the disadvantage of no mixing and having to automatically waste filament when changing colors.</p>
<p>There is another system used by the <a href="https://techcrunch.com/2017/08/31/xyzprinting-announces-a-3000-full-color-3d-printer/" rel="nofollow noreferrer">da Vinchi Full Color 3d Printer</a> which sprays ink onto the filament as its printing.</p>
<p>Since the standard STL file doesn't have color definitions, the normal thing to do is to break up the original file into several STL files each with their own color. This requires Meshmixer or a 3d modeling program.</p>
<p>I've done a lot of research on this, but haven't had a chance to try yet because my Original Prusia 3d and its Multi-Material kit haven't arrived yet. :(</p>
| 124
|
<p>Better yet, how can I make My Computer always open in Explorer as well?</p>
<p>I usually make a shortcut to my programming directories on my quick launch bar, but I'd love for them to open in Explorer.</p>
|
<p>explorer -d c:\path</p>
|
<p>Have you considered the win+e hotkey? It isn't quite what you want, but might be close enough.</p>
| 7,676
|
<p>Why would one choose <a href="http://yaml.org/" rel="noreferrer">YAML</a> over XML or any other formats?</p>
|
<p>I agree with Sergio; YAML provides a format which is easily editable by humans, but also a good way to cleanly represent data structures.</p>
<p>YAML tends to be much more human-readable, IMO.</p>
<p>YAML is more of a data serialisation technique, rather than a markup language.</p>
|
<p>I use YAML as a cheap and easy replacement to writing a domain-specific language (particularly in cases where other developers will be doing maintenance; I'm not sure I'd use it when non-developers would be maintaining it)</p>
| 10,623
|
<p>I'm faced with writing a framework to simplify working with a large and complex object library (<a href="http://resources.esri.com/help/9.3/ArcGISDesktop/ArcObjects/ao_start.htm" rel="noreferrer">ArcObjects</a>). What guidelines would you suggest for creating a framework of this kind? Are static methods preferred? How do you handle things like logging? How do you future proof your framework code from changes that a vendor might introduce?</p>
<p>I think of all of the various wrappers and helpers I've seen for NHibernate, log4net, and code I've read from projects like NLog and <a href="http://code.google.com/p/nettopologysuite/" rel="noreferrer" title="NetTopologySuite">NetTopologySuite</a> and I see so many good approaches, but honestly I'm at a loss where to start.</p>
<p>BTW - I'm working in C# 3.5 but it's more about recommended approach rather than language.</p>
|
<p>Brad Abrams' <a href="https://rads.stackoverflow.com/amzn/click/com/0321246756" rel="noreferrer" rel="nofollow noreferrer">Framework Design Guidelines</a> book is all about this. Might be worth a look.</p>
|
<p>I think that you're consistent is more important than what conventions you go with. As far as future-proofing yourself, that's a matter of the code that you're making a framework for. It's a lot easier to build on a brick house than a sand one.</p>
| 4,905
|
<p>I've always just FTPed files down from sites, edited them and put them back up when creating sites, but feel it's worth learning to do things properly.</p>
<p>I've just commited everything to a SVN repo, and have tried sshing into the server and checking out a tagged build, as well as updating that build using switch.</p>
<p>All good, but it's a lot lot slower than my current process.</p>
<p>What's the best way to set something like this up? Most of my time is just bug fixes or small changes rather than large rewrites, so I'm frequently updating things.</p>
|
<p>You don't necessarily need to use SVN to deploy the files to the server. Keep using FTP for that and just use SVN for revision history.</p>
|
<p>What I do at work, is use FTP to upload changes to a test server. Then when I am finished with the section of the site that I was working on, I commit the changes and update both. Sometimes, if I am working on something and I change a lot of files in different directories, I commit it and update the test server. But I don't update the production server. But I am the only programmer here, I wouldn't recommend committing possibally buggy code if there is more than one programmer.</p>
| 14,278
|
<ul>
<li>I have an Oracle database backup file (.dmp) that was created with <code>expdp</code>.</li>
<li>The .dmp file was an export of an entire database.</li>
<li>I need to restore 1 of the schemas from within this dump file.</li>
<li>I don't know the names of the schemas inside this dump file.</li>
<li>To use <code>impdp</code> to import the data I need the name of the schema to load.</li>
</ul>
<p>So, I need to inspect the .dmp file and list all of the schemas in it, how do I do that?</p>
<hr />
<p><em>Update (2008-09-18 13:02) - More detailed information:</em></p>
<p>The impdp command i'm current using is:</p>
<pre><code>impdp user/password@database directory=DPUMP_DIR
dumpfile=EXPORT.DMP logfile=IMPORT.LOG
</code></pre>
<p>And the DPUMP_DIR is correctly configured.</p>
<pre><code>SQL> SELECT directory_path
2 FROM dba_directories
3 WHERE directory_name = 'DPUMP_DIR';
DIRECTORY_PATH
-------------------------
D:\directory_path\dpump_dir\
</code></pre>
<p>And yes, the EXPORT.DMP file is in fact in that folder.</p>
<p>The error message I get when I run the <code>impdp</code> command is:</p>
<pre><code>Connected to: Oracle Database 10g Enterprise Edition ...
ORA-31655: no data or metadata objects selected for the job
ORA-39154: Objects from foreign schemas have been removed from import
</code></pre>
<p>This error message is mostly expected. I need the <code>impdp</code> command be:</p>
<pre><code>impdp user/password@database directory=DPUMP_DIR dumpfile=EXPORT.DMP
SCHEMAS=SOURCE_SCHEMA REMAP_SCHEMA=SOURCE_SCHEMA:MY_SCHEMA
</code></pre>
<p>But to do that, I need the source schema.</p>
|
<p><code>impdp</code> exports the DDL of a <code>dmp</code> backup to a file if you use the <a href="https://docs.oracle.com/cd/B19306_01/server.102/b14215/dp_import.htm#sthref354" rel="noreferrer"><code>SQLFILE</code> parameter</a>. For example, put this into a text file </p>
<pre><code>impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt
</code></pre>
<p>Then check <code>ddl_dump.txt</code> for the tablespaces, users, and schemas in the backup.</p>
<p>According to the documentation, this does not actually modify the database:</p>
<blockquote>
<p>The SQL is not actually executed, and the target system remains unchanged.</p>
</blockquote>
|
<p>The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.</p>
<p>Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g. </p>
<pre><code>select value_t
from SYS_IMPORT_TABLE_01
where name = 'CLIENT_COMMAND'
and process_order = -59;
col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
object_schema,
object_name,
object_type,
object_tablespace,
process_order,
duplicate,
processing_status,
processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/
</code></pre>
<p><a href="http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf" rel="nofollow">http://download.oracle.com/otndocs/products/database/enterprise_edition/utilities/pdf/oow2011_dp_mastering.pdf</a></p>
| 12,113
|
<p>When I log into a remote machine using ssh X11 forwarding, Vista pops up a box complaining about a process that died unexpectedly. Once I dismiss the box, everything is fine. So I really don't care if some process died. How do I get Vista to shut up about it?</p>
<hr>
<p>Specifically, the message reads:</p>
<pre><code>sh.exe has stopped working
</code></pre>
<p>So it's not ssh itself that died, but some sub-process.</p>
<p>The problem details textbox reads:</p>
<pre><code>Problem signature:
Problem Event Name: APPCRASH
Application Name: sh.exe
Application Version: 0.0.0.0
Application Timestamp: 48a031a1
Fault Module Name: comctl32.dll_unloaded
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 4549bcb0
Exception Code: c0000005
Exception Offset: 73dc5b17
OS Version: 6.0.6000.2.0.0.768.3
Locale ID: 1033
Additional Information 1: fc4d
Additional Information 2: d203a7335117760e7b4d2cf9dc2925f9
Additional Information 3: 1bc1
Additional Information 4: 7bc0b00964c4a1bd48f87b2415df3372
Read our privacy statement:
http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409
</code></pre>
<p>I notice the problem occurs when I use the <strong>-Y</strong> option to enable X11 forwarding in an X terminal under Vista.</p>
<p>The dialog box that pops up doesn't automatically gain focus, so pressing Enter serves no purpose. I have to wait for the box to appear, grab it with the mouse, and dismiss it. Even forcing the error to receive focus would be a step in the right direction.</p>
<hr>
<p>Per DrPizza I have sent an <a href="http://cygwin.com/ml/cygwin/2008-08/msg00880.html" rel="nofollow noreferrer">email</a> to the Cygwin mailing list. The trimmed down subject line represents my repeated attempts to bypass an over-aggressive spam filter and highlights the need for something like StackOverflow.</p>
|
<p>The problem is, the process didn't just die, it died unexpectedly. Sounds like there's a bug in your SSH client that Vista is pointing out.</p>
|
<p>I know this is going to be heresy for a cygwin user, but you could just use <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/" rel="nofollow noreferrer">PuTTY</a> instead.</p>
| 5,576
|
<p>This might be a silly question:</p>
<ul>
<li>Does HTTP ever use the User Datagram Protocol? </li>
</ul>
<p><strong>For example:</strong> </p>
<blockquote>
<p>If one is streaming MP3 or video using HTTP, does it internally use UDP for transport?</p>
</blockquote>
|
<p>Typically, no.</p>
<p>Streaming is seldom used over HTTP itself, and HTTP is seldom run over UDP. See, however, <a href="http://en.wikipedia.org/wiki/Real-time_Transport_Protocol" rel="noreferrer">RTP</a>.</p>
<p>For something as your example (in the comment), you're not showing a protocol for the resource. If that protocol were to be HTTP, then I wouldn't call the access "streaming"; even if it in some sense of the word is since it's sending a (possibly large) resource serially over a network. Typically, the resource will be saved to local disk before being played back, so the network transfer is not what's usually meant by "streaming".</p>
<p>As commenters have pointed out, though, it's certainly possible to really stream over HTTP, and that's done by some.</p>
|
<p>UDP is the best protocol for streaming, because it doesn't make demands for missing packages like TCP. And if it doesn't make demands, the flow is far more faster and without any buffering. </p>
<p>Even the stream delay is lesser than TCP. That is because TCP (as a far more secure protocol) makes demands for missing packages, overwriting the existing ones.</p>
<p>So TCP is a protocol too advanced to be used for streaming.</p>
| 41,852
|
<p>I work on a project that was just told we had to incorporate Parasoft C++ unit testing tool into any code changes going forward. The problem I face is that we have methods with very small changes and now it seems we are forced to unit test the whole method. Many of these methods are hundreds or thousands of lines of code. I know for certain that if I have to test the methods entirely then we will run into fixing old issues such as null pointer checks and our budget and manpower can't handle these fixes.</p>
<p>Does anyone know if parasoft allows you to test small portions of a method? or if another unit testing framework would work better.</p>
|
<p>Implement the small change you are making in a new method, test that. Then change the original to call the new method.</p>
<p>You will be testing the change and gotten a little refactor to better code.</p>
|
<p>No unit testing framework allows you to just test portions of a method.</p>
<p>One ugly suggestion is to use #include to include small chunks of code directly into methods, with the same #include used to include that code into a testing method that sets up variables used by that code. </p>
<p>I recommend Michael Feather's book <a href="https://rads.stackoverflow.com/amzn/click/com/0131177052" rel="nofollow noreferrer" rel="nofollow noreferrer">Working Effectively with Legacy Code</a> for advice on how to add testing to a large code base. It's also available online at <a href="http://my.safaribooksonline.com/0131177052" rel="nofollow noreferrer">Safari</a>.</p>
| 35,554
|
<p>I've an MFC application that currently uses CAtlHttpClient to query a web server for some information.</p>
<p>I'd like to change this so that the query goes over securely, with server authentication, using SSL.</p>
<p>Googling reveals that Microsoft has changed the way they support this several times, e.g., WinInet, WinHTTP, but for the life of me I can't figure out how to do the above using MFC under MSVS 2005.</p>
<p>The application is in C++, and if at all possible, I'd like to avoid dragging .Net into the picture.</p>
<p>Any help, hints, suggestions or pointers gratefully appreciated!</p>
<p>Thanks,</p>
<p>ony</p>
|
<p>Back in 2002 I wrote an article for Windows Developer Magazine that showed how to use OpenSSL to provide SSL for MFC's CAsyncSocket. The code and article are here: <a href="http://www.serverframework.com/asynchronousevents/2010/10/using-openssl-with-asynchronous-sockets.html" rel="nofollow noreferrer">http://www.serverframework.com/asynchronousevents/2010/10/using-openssl-with-asynchronous-sockets.html</a> and might help you.You could also do something similar using Microsoft's SChannel but it's a little more involved as OpenSSL does some of the buffering for you so all you need to do is push bytes into it until you get clear text out...</p>
|
<p>What about using the <strong>libeay32.dll</strong> and <strong>ssleay32.dll</strong> files that come as part of <strong>OpenSSL</strong>:</p>
<p><a href="https://code.google.com/p/openssl-for-windows/" rel="nofollow noreferrer">https://code.google.com/p/openssl-for-windows/</a></p>
| 49,568
|
<p>I am not really familiar with Maven program but I've been using Eclipse for quite a while for Unit testing, code coverage, javadoc generation, code style checking, etc. Probably, the only main thing that I didn't really like about Eclipse is the "compilation errors" that it generates when you are running Eclipse and Ant simultaneously. So I am wondering if Maven 2 does the same thing if you are running Ant task.</p>
<p>Lee23 </p>
|
<p>The company I currently work for has a lot of JUnit tests which are run using Maven (1.x). We've never really had any problem and any tests that fail in maven can be debugged using the remote debugger or in Eclipse on their own.</p>
<p>The most important thing is that you take the time and effort to set up the environment properly so that when your tests run they are using the correct directories, variables, etc. This way you shouldn't get the 'compilation errors' that you would get when running Eclipse and Ant.</p>
<p>Maven has the ability to run all your tests for you during the testing cycle of compilation, this should stop the need for any Ant tasks to run the tests. However, if you still need to have scripts for other tasks (generation of code, etc) then be weary of Maven's ability to generate code and not include it in the compiled binaries (jar, war), though this may well be fixed for newer versions of Maven.</p>
<p>At the end of the day it would be best to evaluate Maven 2 and see if it's right for you. It sounds like you're having (sarcasm)a lot of fun (/sarcasm) with Ant and Eclipse already though. :)</p>
|
<p>If you are working with tests and code coverage tools allready, you should look into maven.
Especialy if you start to work with a project team.</p>
<p>Running tests in eclipse is fine as long as you are the only developer.
Using maven will enable you to use continuous intregration tools like <a href="http://continuum.apache.org/" rel="nofollow noreferrer">continuum</a></p>
<p>It might seem you have to invest more time in setting up maven correectly, but it wil ldefinetly pay of fin the long run.</p>
<p>We use continuum here, and we have never seen any problems with compilation errors, as soon as the system was setup corectly.</p>
| 19,510
|
<p>Just wondering if a .NET app can be compiled down to native machine code ahead of time? I'm not planning on doing so even if I could; I'm just curious.</p>
<p>Thanks</p>
|
<p>You can use NGen to compile it ahead of time, but this still depends on the .NET framework. Remotesoft's Salamander (a commercial app) can make a framework-less app.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx" rel="nofollow noreferrer">ngen</a> can be used to 'pre-JIT' an image, so it is available on disk in native form to reduce application start up time.</p>
| 23,018
|
<p>Let me start off with a bit of background.</p>
<p>This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem.</p>
<p>A now, for the actual question.</p>
<p>Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing.</p>
<p>I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way.</p>
<pre><code>from difflib import SequenceMatcher
spybot = open("spybotsd160.exe", "rb").read()
testuff = open("TestuffSetup.exe", "rb").read()
s = SequenceMatcher(None, spybot, testuff)
print s.find_longest_match(0, len(spybot), 0, len(testuff))
</code></pre>
<p>Is there a better library for Python or for another language that can do this?
A completely different way to tackle the problem is welcome as well.</p>
|
<p>See <a href="http://en.wikipedia.org/wiki/Longest_common_substring_problem" rel="noreferrer">the longest common substring problem</a>. I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays.</p>
<p>Using perl <a href="http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm" rel="noreferrer">Tree::Suffix</a> might be easiest solution. Apparently it gives all common substrings in a specified length range:</p>
<pre><code>@lcs = $tree->lcs;
@lcs = $tree->lcs($min_len, $max_len);
@lcs = $tree->longest_common_substrings;
</code></pre>
|
<p>I suspect that looking for binary strings isn't going to help you. An install program is likely to be doing some 'suspicious' things. </p>
<p>You probably need to talk to CA and spybot about white-listing your installer, or about what is triggering the alert.</p>
| 14,548
|
<p>I just moved to a new hosting company and now whenever a string gets escaped using:</p>
<pre><code>mysql_real_escape_string($str);
</code></pre>
<p>the slashes remain in the database. This is the first time I've ever seen this happen so none of my scripts use</p>
<pre><code>stripslashes()
</code></pre>
<p>anymore.</p>
<p>This is on a CentOS 4.5 64bit running php 5.2.6 as fastcgi on a lighttpd 1.4 server. I've ensured that all magic_quotes options are off and the mysql client api is 5.0.51a.</p>
<p>I have the same issue on all 6 of my webservers.</p>
<p>Any help would be appreciated.</p>
<p>Thanks.</p>
<h3>Edit:</h3>
<h3>Magic Quotes isn't on. Please don't recommend turning it off. THIS IS NOT THE ISSUE.</h3>
|
<p>The host that you've moved probably has <code>magic_quotes_runtime</code> turned on. You can turn it off with <code>set_magic_quotes_runtime(0)</code>.</p>
<p>Please turn off <code>magic_quotes_runtime</code>, and then change your code to use bind variables, rather than using the string escaping.</p>
|
<p><code>mysql_real_escape_string($str);</code> is supposed to do exactly that. it is meant to add backslashes to special characters especially when you want to pass the query to mysql. Take note that it also takes into account the character set of mysql.</p>
<p>For safer coding practices it would be good to edit your code and use <code>stripslashes()</code> to read out the data and remove the slashes.</p>
| 20,866
|
<p>Im currently working on a PPC application that I would like to test in the PPC emulator "USA Windows mobile 5.0 PC R2 Emulator" without using Active Sync. Somewhere in my back head I think I have been able to just do that: But when I start a debug session with Visual Studio, it can not deploy the application to the emulator. All I get in the build log is:</p>
<pre><code>9>------ Deploy started: Project: DLL1, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------
9>There are no more files.
9>
10>------ Skipped Deploy: Project: DLL2, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------
10>Project not selected to build for this solution configuration
11>------ Deploy started: Project: DLL3, Configuration: Debug Salsa ARMv4 Windows Mobile 5.0 Pocket PC SDK (ARMV4I) ------
11>There are no more files.
11>
========== Build: 0 succeeded, 0 failed, 7 up-to-date, 5 skipped ==========
========== Deploy: 3 succeeded, 2 failed, 7 skipped ==========
</code></pre>
<p>If I cradle it (Using Device Emulator manager) and let the device sync through ActiveSync, then Visual Studio can deploy and debug. But I would like to debug some connectivity issues without being connected thorugh ActiveSync. How can I do that?</p>
|
<p>The actual problem was that I had different target devices when I built the project and tried to deploy it. At the end VS would deploy one file to an ActiveSync device, one to the emulator and so forth. It was not suprisngly that it didnt work. If I changed the target device for the current project, it would not change it for the other projects...</p>
<p>So if you have problems deploying using Visual Studio and having multiple projects in a solution, make sure that they all go the same target device. </p>
|
<p>From your build log, you are targetting the <strong>ARMv4</strong> processor. You need to target <strong>Win32 (WCE emulator)</strong> in order to use and debug through the emulator.</p>
| 31,058
|
<p>I have been reading a lot of XQuery tutorials on the website. Almost all of them are teaching me XQuery syntax. Let's say I have understood the XQuery syntax, how am I going to actually implement XQuery on my website?</p>
<p>For example, I have <strong>book.xml</strong>:</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<books>
<book>
<title>Doraemon</title>
<authorid>1</authorid>
</book>
<book>
<title>Ultraman</title>
<authorid>2</authorid>
</book>
</books>
</code></pre>
<p>Then, I have <strong>author.xml</strong></p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<authors>
<author id="1">Mr A</author>
<author id="2">Mr B</author>
</authors>
</code></pre>
<p>I want to generate HTML which looks like following:</p>
<pre><code><table>
<tr> <td>Title</td> <td>Author</td> </tr>
<tr> <td>Doraemon</td> <td>Mr A</td> </tr>
<tr> <td>Ultraman</td> <td>Mr B</td> </tr>
</table>
</code></pre>
<p>Please show me some examples. Or any website that I can do reference. Thanks very much.</p>
|
<pre><code>(: file: titles.xqy :)
<table>
<tr><th>title</th><th>author</th></tr>
{
let $books-doc := doc("books.xml")
let $authors-doc := doc("authors.xml")
for $b in $books-doc//book,
$a in $authors-doc//author
where $a/@id = $b/authorid
return
<tr>
<td>{$b/title/text()}</td>
<td>{$a/text()}</td>
</tr>
}
</code></pre>
<p></p>
|
<pre><code><table>
<tr><td>Title<td><td>Author<td></tr>
{
let $authordoc := fn:doc("author.xml")
for $book in fn:doc("book.xml")/books/book
return
<tr>
<td>{ $book/title }</td>
<td>{ $authordoc/authors/author/[@id eq $book/authorid] }</td>
</tr>
}
</table>
</code></pre>
<p>ps: haven't tested/executed it, but this is how one solution could look like</p>
| 10,631
|
<p>I have Ramps 1.4 and would like to get answer on extrusion in Marlin firmware. I have NEMA 17 stepper motor 1.8 deg, set to 1/16 step. Mk7 direct drive.
38 teeth in extruder drive gear. I bought it from <a href="https://www.robotics.org.za/RDKIT-00?search=extru" rel="nofollow noreferrer">this website</a>.</p>
<p>Here are my current settings:</p>
<pre><code>#define DEFAULT_AXIS_STEPS_PER_UNIT { 80,80, 4000, 180 }
#define DEFAULT_MAX_FEEDRATE { 500, 500, 3, 45 }
#define DEFAULT_MAX_ACCELERATION { 9000, 9000, 100, 300 }
</code></pre>
<p>I am using ABS 1.75 filament and a 0.4 nozzle.</p>
|
<p>According to the description, the drive gear you have has a <code>10.8mm</code> diameter. This means that (in the ideal case) one full rotation of the drive gear will advance a length of filament equal to its circumference, which is <code>pi x 10.8mm</code> or approximately <code>33.93mm</code>.</p>
<p>Your motor rotates <code>1.8</code> degrees per step, so it takes <code>360 / 1.8 = 200 steps</code> for a full rotation. Since you are using 16x microstepping, this is multiplied to <code>200 x 16 = 3200 steps</code>.</p>
<p>You thus end up with a steps per mm value of <code>3200 / 33.93 = 94.31 steps/mm</code>.</p>
<p>You might need to calibrate this further, for instance by extruding a set length of filament (e.g. 100mm) and measuring how much is actually extruded, and then compensating the steps/mm value to get you closer to the desired 100mm. A simple way to measure this is to put a mark on your filament at 150mm from the extruder, and then (after extruding 100mm) measure how close the mark is to the extruder (which should be 50mm) However, this theoretically computed value should be a good starting point. Note that the speed you do this test at should be close to your normal printing speed, since extruding at a much higher (resp. lower) speed will falsely lead you to believe you are underextruding (resp. overextruding).</p>
|
<p>Simplest way to calculate your extrusion is:</p>
<p>Set your number of perimeters walls 1
top and bottom layer 0
infill 0%
and print simple 20x20x20 cube
look at the wall thickness with caliper and compare your extrusion width value on your slicer software</p>
| 656
|
<p>It is obviosly some Perl extensions. Perl version is 5.8.8.</p>
<p>I found Error.pm, but now I'm looking for Core.pm. </p>
<p>While we're at it: how do you guys search for those modules. I tried Google, but that didn't help much. Thanks.</p>
<hr>
<p>And finally, after I built everything, running: </p>
<pre><code>./Build install
</code></pre>
<p>gives me:</p>
<pre><code>Running make install-lib
/bin/ginstall -c -d /usr/lib/perl5/site_perl/5.8.8/i486-linux-thread-multi/Alien/SVN --prefix=/usr
/bin/ginstall: unrecognized option `--prefix=/usr'
Try `/bin/ginstall --help' for more information.
make: *** [install-fsmod-lib] Error 1
installing libs failed at inc/My/SVN/Builder.pm line 165.
</code></pre>
<p>Looks like Slackware's 'ginstall' really does not have that option. I think I'm going to Google a little bit now, to see how to get around this.</p>
|
<p>It should be compatible. The <a href="http://bbbike.radzeit.de/~slaven/cpantestersmatrix.cgi?dist=Error+0.17015" rel="nofollow noreferrer">CPAN Tester's matrix</a> shows no failures for Perl 5.8.8 on any platform.</p>
<p>Per the <a href="https://metacpan.org/source/SHLOMIF/Error-0.17022/README" rel="nofollow noreferrer">README</a>, you can install it by doing:</p>
<pre><code>perl Makefile.pl
make
make test
make install
</code></pre>
|
<p>What do you mean by "does not seem to be compatible"? Can you post the error message?</p>
<p>If the latest version does not work, you can select an older version in the "other releases" drop down and download that.</p>
<p>Edit: to those reading this, the author updated the question, so my answer seems a bit out of left field :)</p>
| 11,275
|
<p>How can I determine if a Win32 thread has terminated?</p>
<p>The documentation for <strong><a href="http://msdn.microsoft.com/en-us/library/ms683190(VS.85).aspx" rel="noreferrer">GetExitCodeThread</a></strong> warns to not to use it for this reason since the error code STILL_ACTIVE can be returned for other reasons.</p>
<p>Thanks for the help! :)</p>
|
<p>MSDN mentions that "When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object".</p>
<p>So, you can check for whether a thread has terminated by checking the state of the thread handle - whether it's signaled or not:</p>
<pre><code>DWORD result = WaitForSingleObject( hThread, 0);
if (result == WAIT_OBJECT_0) {
// the thread handle is signaled - the thread has terminated
}
else {
// the thread handle is not signaled - the thread is still alive
}
</code></pre>
|
<p>The documentation you link to warns against using <code>STILL_ACTIVE</code> as a return code, since it can't be distinguished from the return value used to indicate an active thread. <em>So don't use it as a return value and you won't have this problem.</em></p>
| 38,602
|
<p>I'm looking for some "Best Practices" for automating the deployment of Stored Procedures/Views/Functions/Table changes from source control. I'm using StarTeam & ANT so the labeling is taken care of; what I am looking for is how some of you have approached automating the pull of these objects from source - not necessarily StarTeam.</p>
<p>I'd like to end up with one script that can then be executed, checked in, and labeled.</p>
<p>I'm NOT asking for anyone to write that - just some ideas or approaches that have (or haven't) worked in the past.</p>
<p>I'm trying to clean up a mess and want to make sure I get this as close to "right" as I can.</p>
<p>We are storing the tables/views/functions etc. in individual files in StarTeam and our DB is SQL 2K5.</p>
|
<p>We use SQL Compare from redgate (<a href="http://www.red-gate.com/" rel="nofollow noreferrer">http://www.red-gate.com/</a>).</p>
<p>We have a production database, a development database and each developer has their own database.</p>
<p>The development database is synchronised with the changes a developer has made to their database when they check in their changes. </p>
<p>The developer also checks in a synchronisation script and a comparison report generated by SQL Compare.</p>
<p>When we deploy our application we simply synchronise the development database with the production database using SQL Compare.</p>
<p>This works for us because our application is for in-house use only. If this isn't your scenario then I would look at SQL Packager (also from redgate).</p>
|
<p>I prefer to separate views, procedures, and triggers (objects that can be re-created at will) from tables. For views, procedures, and triggers, just write a job that will check them out and re-create the latest.</p>
<p>For tables, I prefer to have a database version table with one row. Use that table to determine what new updates have not been applied. Then each update is applied and the version number is updated. If an update fails, you have only that update to check and you can re-run know that the earlier updates will not happen again.</p>
| 7,586
|
<p>Starting new .NET projects always involves a bit of work. You have to create the solution, add projects for different tiers (Domain, DAL, Web, Test), set up references, solution structure, copy javascript files, css templates and master pages etc etc.</p>
<p>What I'd like is <strong>an easy way of cloning any given solution</strong>. </p>
<p>If you use copy/paste, the problem is that you need to then go through renaming namespaces, assembly names, solution names, GUIDs etc. </p>
<p>Is there a way of automating this?</p>
<p>Something like this would be great:</p>
<pre><code>solutionclone.exe --solution=c:\code\abc\template.sln --to=c:\code\xyz --newname=MySolution
</code></pre>
<p>I'm aware that Visual Studio has project templates, but I've not seen solution templates.</p>
|
<p>I have created a small application for this. It works just like the previously mentioned Solutionclone app, except that it is both a command line application as well as a WPF application.</p>
<p>Cloney copies a source folder to a target one, without any Git or Svn integration. It will also replace the old namespace everywhere (in file names as well as within files) with the new namespace (the name of the target folder) and exclude certain files (e.g. *.suo, *.user, *.vssscc) and folders (e.g. .git, .svn).</p>
<p>You can grab the source code or download an executable at <a href="https://github.com/danielsaidi/cloney" rel="nofollow">https://github.com/danielsaidi/cloney</a>.</p>
<p>Cloney can also be added to the Windows Explorer context menu, which makes it possible to clone .NET solutions by just right-clicking the .sln file.</p>
|
<p>I believe the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=B91066B3-D1D6-4990-A45F-34CF8DBDC60C&displaylang=en" rel="nofollow noreferrer">Guidance Automation Toolkit</a> allows you to do this, but may not be an "easy" way.</p>
<p>I have the same problem as you and intend to look at it in detail "real soon now".</p>
| 20,057
|
<p>I am working on cleaning up a bug in a large code base where no one was paying attention to local time vs. UTC time. </p>
<p>What we want is a way of globally ignoring time zone information on DateTime objects sent to and from our ASP.NET web services. I've got a solution for retrieve operations. Data is only returned in datasets, and I can look for DateTime columns and set the DateTimeMode to Unspecified. That solves my problem for all data passed back and forth inside a data set.</p>
<p>However DateTime objects are also often passed directly as parameters to the web methods. I'd like to strip off any incoming time zone information. Rather than searching through our client code and using DateTime.SpecifyKind(..) to set all DateTime vars to Undefined, I'd like to do some sort of global ASP.NET override to monitor incoming parameters and strip out the time zone information.</p>
<p>Is such a thing possible? Or is there another easier way to do what I want to do?</p>
<p>Just to reiterate -- I don't care about time zones, everyone is in the same time zone. But a couple of users have machines badly configured, wrong time zones, etc. So when they send in July 1, 2008, I'm getting June 30, 2008 22:00:00 on the server side where it's automatically converting it from their local time to the server's local time.</p>
<p><strong>Update:</strong> One other possibility would be if it were possible to make a change on the client side .NET code to alter the way DateTime objects with Kind 'Undefined' are serialized.</p>
|
<p>I have dealt with this often in many applications, services, and on different platforms (.NET, Java, etc.). Please believe me that you do NOT want the long term consequences of pretending that you don't care about the time zone. After chasing lots of errors that are enormously difficult and expensive to fix, you will wish you had cared.</p>
<p>So, rather than stripping the time zone, you should either capture the correct time zone or force a specific time zone. If you reasonably can, get the various data sources fixed to provide a correct time zone. If they are out of your control, then force them either to the server's local time zone or to UTC.</p>
<p>The general industry convention is to force everything to UTC, and to set all production hardware clocks to UTC (that means servers, network devices like routers, etc.). Then you should translate to/from the user's local time zone in the UI.</p>
<p>If you fix it correctly now, it can be easy and cheap. If you intentionally break it further because you think that will be cheaper, then you will have no excuses later when you have to untangle the awful mess.</p>
<p>Note that this is similar to the common issue with Strings: there is not such thing as plain text (a String devoid of a character encoding) and there is no such thing as a plain (no time zone) time/date. Pretending otherwise is the source of much pain and heartache, and embarrassing errors.</p>
|
<p>I've had issues with the time zone information as well. The problem is I'm already providing the datetime fields in UTC. Then the serialization occurs and the local offset becomes part of the date/time. The dates/times for our vendor in a different timezone were pretty messed up. I got around this problem by using the tsql convert function on the datetime fields in my select statement I used to populate my datasets. This converted the fields to a string variable, which translates nicely to a datetime value automatically on the client side. If you just want to pass the date, you can use the 101 code to provide just the date. I used 126 to provide the date and time exactly how it appears in my database columns, with the timezone information stripped out.</p>
| 42,945
|
<p>I'm looking for the best way to interpret the standard (well, standardish) Ethernet PHY registers, to determine the speed that an Ethernet link is actually running at. (e.g. 10/100/1000 and full/half-duplex)</p>
<p>I daresay that this is to be found in the source of things like Linux, and I'm just off to look there now, but if anyone has a good reference I'd be interested.</p>
<p>What I'm interested in is if it actually linked and what it linked at, rather than the vast sea of possibilities that each end has advertised at the outset.</p>
|
<p>How about this:</p>
<pre><code>select id, first, last from mytable
where first != upper(first) or last != upper(last);
</code></pre>
|
<p>for SQL server where the DB collation setting is Case insensitive use the following:</p>
<pre><code>SELECT * FROM tbl_user WHERE LEFT(username,1) COLLATE Latin1_General_CS_AI <> UPPER(LEFT(username,1))
</code></pre>
| 41,019
|
<p>I have a fairly huge database with a master table with a single column GUID (custom GUID like algorithm) as primary key and 8 child tables that have foreign key relationships with this GUID column. All the tables have approximately 3-8 million records. None of these tables have any BLOB/CLOB/TEXT or any other fancy data types just normal numbers, varchars, dates, and timestamps (about 15-45 columns in each table). No partitions or other indexes other than the primary and foreign keys.</p>
<p>Now, the custom GUID algorithm has changed and though there are no collisions I would like to migrate all the old data to use GUIDs generated using the new algorithm. No other columns need to be changed. Number one priority is data integrity and performance is secondary.</p>
<p>Some of the possible solutions that I could think of were (as you will probably notice they all revolve around one idea only)</p>
<ol>
<li>add new column ngu_id and populate with new gu_id; disable constraints; update child tables with ngu_id as gu_id; renaname ngu_id->gu_id; re-enable constraints</li>
<li>read one master record and its dependent child records from child tables; insert into the same table with new gu_id; remove all records with old gu_ids</li>
<li>drop constraints; add a trigger to the master table such that all the child tables are updated; start updating old gu_id's with new new gu_ids; re-enable constraints</li>
<li>add a trigger to the master table such that all the child tables are updated; start updating old gu_id's with new new gu_ids</li>
<li>create new column ngu_ids on all master and child tables; create foreign key constraints on ngu_id columns; add update trigger to the master table to cascade values to child tables; insert new gu_id values into ngu_id column; remove old foreign key constraints based on gu_id; remove gu_id column and rename ngu_id to gu_id; recreate constraints if necessary;</li>
<li>use <code>on update cascade</code> if available?</li>
</ol>
<p>My questions are:</p>
<ol>
<li>Is there a better way? (Can't burrow my head in the sand, gotta do this)</li>
<li>What is the most suitable way to do this? (I've to do this in Oracle, SQL server and mysql4 so, vendor-specific hacks are welcome)</li>
<li>What are the typical points of failure for such an exercise and how to minimize them?</li>
</ol>
<p>If you are with me so far, thank you and hope you can help :)</p>
|
<p>Your ideas should work. the first is probably the way I would use. Some cautions and things to think about when doing this:<br>
Do not do this unless you have a current backup.<br>
I would leave both values in the main table. That way if you ever have to figure out from some old paperwork which record you need to access, you can do it.
Take the database down for maintenance while you do this and put it in single user mode. The very last thing you need while doing something like this is a user attempting to make changes while you are in midstream. Of course, the first action once in single user mode is the above-mentioned backup. You probably should schedule the downtime for some time when the usage is lightest.
Test on dev first! This should also give you an idea as to how long you will need to close production for. Also, you can try several methods to see which is the fastest.<br>
Be sure to communicate in advance to users that the database will be going down at the scheduled time for maintenance and when they can expect to have it be available again. Make sure the timing is ok. It really makes people mad when they plan to stay late to run the quarterly reports and the database is not available and they didn't know it.<br>
There are a fairly large number of records, you might want to run the updates of the child tables in batches (one reason not to use cascading updates). This can be faster than trying to update 5 million records with one update. However, don't try to update one record at a time or you will still be here next year doing this task.<br>
Drop indexes on the GUID field in all the tables and recreate after you are done. This should improve the performance of the change. </p>
|
<p>Create a new table with the old and the new pk values in it. Place unique constraints on both columns to ensure you haven't broken anything so far.</p>
<p>Disable constraints.</p>
<p>Run an updates against all the tables to modify the old value to the new value.</p>
<p>Enable the PK, then enable the FK's.</p>
| 39,412
|
<p>I have been tasked with creating a new frontend for a legacy website.</p>
<p>It is written in php (pre-oo), and uses a MySQL database. The hosting provides a .Net package, but does not offer Ms Sql Server. </p>
<p>This is fine, as the database is working fine, but I really want to use Asp.net for the pages. However, most tutorials I've seen on connecting to MySQL from C# require installing an ODBC Driver specifically for MySQL. Not controlling the hosting env, I doubt I'll be able to do just that :)</p>
<p>Have you got any insight to share on this issue?</p>
|
<p>MySql does have <a href="http://dev.mysql.com/downloads/connector/net/5.2.html" rel="nofollow noreferrer">connector</a> for .Net. You do not need to use ODBC,</p>
<p>MySql Connector will let you interact with your MySql database and is fully managed ADO.Net provider. You have the binary (dll) or the source code if you desire. It's pretty simple, once you have imported the dll you just need a connexion string (username,password,location) and you will be setup!</p>
<p>Here is a sample of code (ref: <a href="http://bitdaddys.com/MySQL-ConnectorNet.html" rel="nofollow noreferrer">bitdaddy.com</a>):</p>
<pre><code>string MyConString = "SERVER=localhost;" +
"DATABASE=mydatabase;" +
"UID=testuser;" +
"PASSWORD=testpassword;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "select * from mycustomers";
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
string thisrow = "";
for (int i= 0;i<Reader.FieldCount;i++)
thisrow+=Reader.GetValue(i).ToString() + ",";
listBox1.Items.Add(thisrow);
}
connection.Close();
</code></pre>
<p>I suggest you to do not put your code and persistance in the same place and to place your connexion string in you App.Config, but I think this show you how to do it.</p>
|
<p>Agree with Patrick Desjardins, plus would like to add that easiest way to interact with MySQL is</p>
<ol>
<li>Get the <a href="http://dev.mysql.com/downloads/connector/net/6.0.html" rel="nofollow noreferrer">MySQL connector for .Net
v6.0</a> - this has support for
<a href="http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx" rel="nofollow noreferrer">Entity Framework</a></li>
<li>Create a Data Model layer using
ADO.Net Entity Model to interact
with database</li>
</ol>
<p>OR</p>
<p>You could also take a look at <a href="http://code2code.net/Linq_Mysql/" rel="nofollow noreferrer">Linq to MySQL provider</a> implementation - it's pretty good.</p>
<p>I went with the former option, when I had a similar requirement.</p>
| 46,955
|
<p>Considering the following table</p>
<p>I have a large table from which I can query to get the following table</p>
<pre><code>type no of times type occurs
101 450
102 562
103 245
111 25
112 28
113 21
</code></pre>
<p>Now suppose I wanted to get a table which shows me the sum of no of times type occurs
for type starting with 1 then starting with 10,11,12,13.......19 then starting with 2, 20,21, 22, 23...29 and so on.</p>
<p>Something like this </p>
<pre><code>1 1331 10 1257
11 74
12 ..
13 ..
.. ..
2 ... 20 ..
21 ..
</code></pre>
<p>Hope I am clear
Thanks </p>
|
<p>We have solved this by overriding the ControlTemplate of the ScrollViewer embedded in the DocumentViewer control. Insert the Style below in "Window.Resources":</p>
<pre><code><Style TargetType="{x:Type ScrollViewer}" x:Key="CustomScrollPresenter">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ScrollViewer}">
<Grid Background="{TemplateBinding Panel.Background}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Rectangle Grid.Column="1" Grid.Row="1" Fill="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
<ScrollContentPresenter
PreviewMouseLeftButtonDown="ScrollContentPresenter_PreviewMouseLeftButtonDown"
Grid.Column="0"
Grid.Row="0"
Margin="{TemplateBinding Control.Padding}"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
CanContentScroll="{TemplateBinding ScrollViewer.CanContentScroll}" />
<ScrollBar
x:Name="PART_VerticalScrollBar"
Grid.Column="1"
Grid.Row="0"
Minimum="0"
Maximum="{TemplateBinding ScrollViewer.ScrollableHeight}"
ViewportSize="{TemplateBinding ScrollViewer.ViewportHeight}"
Value="{Binding Path=VerticalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}"
Visibility="{TemplateBinding ScrollViewer.ComputedVerticalScrollBarVisibility}"
Cursor="Arrow" AutomationProperties.AutomationId="VerticalScrollBar" />
<ScrollBar
x:Name="PART_HorizontalScrollBar"
Orientation="Horizontal" Grid.Column="0" Grid.Row="1" Minimum="0"
Maximum="{TemplateBinding ScrollViewer.ScrollableWidth}" ViewportSize="{TemplateBinding ScrollViewer.ViewportWidth}" Value="{Binding Path=HorizontalOffset, Mode=OneWay, RelativeSource={RelativeSource Mode=TemplatedParent}}" Visibility="{TemplateBinding ScrollViewer.ComputedHorizontalScrollBarVisibility}" Cursor="Arrow" AutomationProperties.AutomationId="HorizontalScrollBar" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>Then override the Style of ScrollViewer with it in the ControlTemplate for DocumentViewer:</p>
<pre><code> <Style
x:Key="MyDVStyleExtend"
BasedOn="{StaticResource {x:Type DocumentViewer}}"
TargetType="{x:Type DocumentViewer}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="DocumentViewer">
<Border BorderThickness="2,2,2,2"
BorderBrush="SlateBlue" Focusable="False">
<Grid Background="{StaticResource GridBackground}"
KeyboardNavigation.TabNavigation="Local">
<Grid.ColumnDefinitions>
<ColumnDefinition Width ="*"/>
</Grid.ColumnDefinitions>
<ScrollViewer Style="{StaticResource CustomScrollPresenter}" Grid.Column ="0"
CanContentScroll="True"
HorizontalScrollBarVisibility="Auto"
x:Name="PART_ContentHost"
IsTabStop="True"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>Then create a function for the "PreviewMouseLeftButtonDown="ScrollContentPresenter_PreviewMouseLeftButtonDown"" attribute stated in the CustomScrollPresenter style.</p>
<pre><code> private void ScrollContentPresenter_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
</code></pre>
|
<p>Implement the following code in xaml.cs part (DocumentViewerInstance x:Name of your DocumentViewer in your xaml.) </p>
<pre><code>DocumentViewerInstance.GetType().GetProperty("IsSelectionEnabled", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(DocumentViewerInstance, false, null);
</code></pre>
<p>You can use the <code>IsFocusable=false</code> or <code>IsHitTestVisible = false</code> or handle any preview event (for example in accepted answer) for disable selection but the hyperlinks won't work! If you set IsSelectionEnabled = false, the selection will be disabled but hyperlinks will work too. (Warning! IsSelectionEnabled can be changed for true value after you set false, so you should check the value often.)</p>
| 48,070
|
<p>Calling addChild with an empty string as the value (or even with whitespace) seems to cause a redundant SimpleXml node to be added inside the node instead of adding just the node with no value.</p>
<p>Here's a quick demo of what happens:</p>
<pre><code>[description] => !4jh5jh1uio4jh5ij14j34io5j!
</code></pre>
<p>And here's with an empty string:</p>
<pre><code>[description] => SimpleXMLElement Object ( [0] => )
</code></pre>
<p>The workaround I'm using at the moment is pretty horrible - I'm doing a str_replace on the final JSON to replace !4jh5jh1uio4jh5ij14j34io5j! with an empty string. Yuck. Perhaps the only answer at this point is 'submit a bug report to simplexml'...</p>
<p>Does anyone have a better solution?</p>
|
<p>I think I figured out what is going on. Given code like this:</p>
<pre><code>$xml = new SimpleXMLElement('<xml></xml>');
$xml->addChild('node','value');
print_r($xml);
$xml = new SimpleXMLElement('<xml></xml>');
$xml->addChild('node','');
print_r($xml);
$xml = new SimpleXMLElement('<xml></xml>');
$xml->addChild('node');
print_r($xml);
</code></pre>
<p>The output is this:</p>
<pre><code>SimpleXMLElement Object
(
[node] => value
)
SimpleXMLElement Object
(
[node] => SimpleXMLElement Object
(
[0] =>
)
)
SimpleXMLElement Object
(
[node] => SimpleXMLElement Object
(
)
)
</code></pre>
<p>So, to make it so that in case #2 the empty element isn't created (i.e. if you don't know if the second argument is going to be an empty string or not), you could just do something like this:</p>
<pre><code>$mystery_string = '';
$xml = new SimpleXMLElement('<xml></xml>');
if (preg_match('#\S#', $mystery_string)) // Checks for non-whitespace character
$xml->addChild('node', $mystery_string);
else
$xml->addChild('node');
print_r($xml);
echo "\nOr in JSON:\n";
echo json_encode($xml);
</code></pre>
<p>To output:</p>
<pre><code>SimpleXMLElement Object
(
[node] => SimpleXMLElement Object
(
)
)
Or in JSON:
{"node":{}}
</code></pre>
<p>Is that what you want?</p>
<p>Personally, I never use SimpleXML, and not only because of this sort of weird behavior -- it is still under major development and in PHP5 is missing like 2/3 of the methods you need to do DOM manipulation (like deleteChild, replaceChild etc).</p>
<p>I use DOMDocument (which is standardized, fast and feature-complete, since it's an interface to libxml2).</p>
|
<p>Maybe I'm not understanding the question right but, it seems to me that when you use the addChild method, you're required to have a string as an argument for the name of the node regardless of what content is in the node. The value (second argument) is optional and can be left blank to add and empty node.</p>
<p>Let me know if that helps.</p>
| 30,721
|
<p>I have searched high and low and cannot find a Samsung Omnia SDK.</p>
<p>I know its possible to use the .net framework for development , but i want more , specifically being able to access the motion sensor and maybe the GPS as well.</p>
<p>Any idea or directions are welcome.</p>
|
<p>XSLT is your friend for converting the XML database file to the format you want to display on the web-page. You create an XSL template that includes all the HTML you want for each record and then iterate through the XML file with a for-each statement. I'll give a rough overview and can help with more details if needed.</p>
<p>Here's the generic PHP file I use to do XSLT (process an XML file with an XSL file) via AJAX. This one is setup to work with required (and optional, if desired) inputs passed in a GET call from the browser. p#n and p#v (see comments at top of code below) are parameter and value pairs to be passed into the XSL document in cases where you want to use some input parameter to affect the output. In this case output is echoed back to the browser. Here's the PHP to run the XML database through and XSLT transformation to create the HTML for your web display (table, or whatever you put in the XSL file template):</p>
<pre><code><?php
//REQUIRED INPUTS:
// - xml: path to xml document
// - xsl: path to xsl style sheet
// - pCount: number of parameters to be passed to xslt (send zero '0' if none)
//OPTIONAL INPUTS (must have as many as specified in pCount, increment '1' in
//names below up a number for each iteration):
// - p1n: name of first parameter
// - p1v: value of first parameter
//SET Paths
$xmlPath = $_GET['xml'];
$xslPath = $_GET['xsl'];
// Load the XML source
$xml = new DOMDocument;
$xml->load($xmlPath);
$xsl = new DOMDocument;
$xsl->load($xslPath);
// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules
//Set Parameter(s), if present
$xslParamCount = $_GET['pCount']; //Check number of xsl parameters specified in GET
for ($i=1; $i<=$xslParamCount; $i++){
$xslParamName = $_GET['p'.$i.'n'];
$xslParamValue = $_GET['p'.$i.'v'];
$proc->setParameter( '', $xslParamName, $xslParamValue); //Set parameters for XSLTProcessor
}
// TRANSFORM
echo $proc->transformToXML($xml);
// SET Mime Type
$mime = "application/xhtml+xml";
$charset = "iso-8859-1";
header("Content-Type: $mime;charset=$charset");
?>
</code></pre>
<p>Below is an example of an XSL file template taking an XML database document and converting it to HTML for insertion in a web page. Note the HTML span tags. All the xsl tags are processing instructions that determines what goes in and around the HTML tags in the template. In this case, we are filtering results and choosing appropriate data to display based on input parameters passed into the XSL file (see xsl:param items at near top):</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform' version='1.0'>
<xsl:param name='testId'/>
<!--Input options for following param: localUse, notLocalUse, nottestId, or '' (all)-->
<xsl:param name='matchType'/>
<xsl:template match='/'>
<xsl:choose>
<xsl:when test="$matchType='localUse'">
<xsl:for-each select="//test[@id=$testId and @localUse='yes']">
<xsl:sort select="../@id"/>
<div><xsl:if test='../@localPrefTestId=$testId'><xsl:attribute name='class'>preferredTest</xsl:attribute></xsl:if>
<span class='productStockCode'>
<xsl:if test='../@localPrefTestId=$testId'>
<xsl:attribute name='title'>Preferred test for this product</xsl:attribute>
</xsl:if>
<xsl:if test='../@localPrefTestId!=$testId'>
<xsl:attribute name='title'>Alternate (not preferred) test for this product - see note to right</xsl:attribute>
</xsl:if>
<xsl:value-of select='../@id'/>
</span>
<span class='productStockName'>
<xsl:if test='../@localPrefTestId=$testId'>
<xsl:attribute name='title'>Preferred test for this product</xsl:attribute>
</xsl:if>
<xsl:if test='../@localPrefTestId!=$testId'>
<xsl:attribute name='title'>Alternate (not preferred) test for this product - see note to right</xsl:attribute>
</xsl:if>
<xsl:value-of select='../@name'/>
</span>
<span class='producttestNote'>
<xsl:value-of select='child::localPrefNote'/>
</span>
<span class='productDeleteButton'>
<input onClick='remProdLink(this)' title='Click to remove link to this product' type='image' src='button_tiny_X_grey.bmp'></input>
</span>
</div>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<p>Server Error: GET must specify matchType parameter value of 'localUse', 'notLocalUse', 'nottestId', or '' (for all)</p>
<p>matchType received: <xsl:value-of select='$matchType'/></p>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<!--Note the output method="html" below is required for this to insert correctly into a web page; without this it may nest improperly if any divs are empty-->
<xsl:output method="html" omit-xml-declaration="yes"/>
</xsl:stylesheet>
</code></pre>
<p>Note that all the xsl tests are XPath expressions.</p>
<p>To delete a row you can have a button on that row that calls a JavaScript function with the "this" argument (see onClick='remProdLink(this)' in code above) to reference the row, and then grab the unique identifier of the row in JavaScript something like this:</p>
<pre><code>function remProdLink(obj){
//get unique id via Dom from passed in object reference
//edit everything after "obj" below to get to the unique id in the record
var testCode = obj.parentNode.parentNode.firstChild.nextSibling.innerHTML;
//code to send AJAX POST to server with required information goes here
}
</code></pre>
<p>On the server end, your PHP receives the AJAX POST with the unique identifier, loads the XML database file into simpleXml, finds the node via XPath, and removes it, something like this:</p>
<pre><code><?php
//Move url encoded post data into variables
$testCode = $_POST['testCode']; //$testCode should be a unique id for the record
//load xml file to edit
$xml = simplexml_load_file('yourDatabase.xml');
//find target node for removal with XPath
$targets = $xml->xpath("//testCode[@id=$testCode]");
//import simpleXml reference into Dom to do removal
$dom2 = dom_import_simplexml($targets[0]);
$dom2->parentNode->removeChild($dom2);
//format xml to save indented tree (rather than one line) and save
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
$dom->save('yourDatabase.xml');
?>
</code></pre>
<p>As for editing an item, you can have another JavaScript function called similarly to the one for deleting as noted above, create a form under that item on the web page with a save changes button, and when that button is pressed call another JavaScript function to AJAX POST to the server, again similarly to deleting. Only this time your POST will need to include all the information that could have been edited in the record along with the record's unique ID. PHP file will find the appropriate record (same as for deleting), and then you can either edit parts of that record in PHP, or just remove it and the create and append the new version of the record.</p>
<p>I'm not sure how many details you need. Hopefully this gives you a good start. Please comment on my answer if you need more details on any part of it. Good luck!</p>
|
<p>You can use a native XML database to facilitate creating, adding, updating and retrieving xml documents and nodes. I've used <a href="http://www.oracle.com/database/berkeley-db/xml/index.html" rel="nofollow noreferrer">BerkeleyDBXML</a> (now part of Oracle) in the past with success. There's is a PHP library available as well.</p>
| 49,453
|
<p>Just like it reads.</p>
|
<p>The simplest and shortest explanation that I have found is: "The Semantic Web is to Machines what the World Wide Web is to Humans".</p>
<p>And as to why you would want that: for the same reasons why you let your Machine compute Pi to the quadrillionth digit instead of doing that yourself. So you can focus on <em>interesting</em> problems and leave the menial work to the Machine.</p>
|
<p><a href="http://en.wikipedia.org/wiki/Semantic_Web" rel="nofollow noreferrer">From wikipedia:</a></p>
<blockquote>
<p>The Semantic Web is an evolving
extension of the World Wide Web in
which the semantics of information and
services on the web is defined, making
it possible for the web to understand
and satisfy the requests of people and
machines to use the web content. It
derives from World Wide Web Consortium
director Sir Tim Berners-Lee's vision
of the Web as a universal medium for
data, information, and knowledge
exchange.</p>
</blockquote>
| 14,246
|
<p>When we perform a fork in Unix, open file handles are inherited, and if we don't need to use them we should close them. However, when we use libraries, file handles may be opened for which we do not have access to the handle. How do we check for these open file handles?</p>
|
<p>If the libraries are opening files you don't know about, how do you know they don't need them after a fork? Unexported handles are an internal library detail, if the library wants them closed it will register an atfork() handler to close them. Walking around behind some piece of code closing its file handles behind its back will lead to subtle hard to debug problems since the library will error unexpectedly when it attempts to work with a handle it knows it opened correctly, but did not close.</p>
|
<p>Reasonable libraries will always have functions which free whatever resources (eg. file handles) they have allocated.</p>
| 33,595
|
<p>I encounter an error of the form: "The model item passed into the dictionary is of type FooViewData but this dictionary requires a model item of type bar" even though I am passing in an object of the correct type (bar) for the typed user control.</p>
|
<p>What @MattMitchell said is probably the reason you're seeing this error.</p>
<p>If you want to know <em>why</em>; it is because when you pass null as the controlData parameter when using RenderUserControl(), the framework will try to pass the view data from the current view context onto the user control instead (see UserControlExtensions.DoRendering method in System.Web.Mvc).</p>
|
<p>What has probably happened is that the object provided when rendering the user control is actually null.</p>
| 2,744
|
<p>In HTML, I can find a file starting from the <strong>web server's</strong> root folder by beginning the filepath with "/". Like:</p>
<pre><code>/images/some_image.jpg
</code></pre>
<p>I can put that path in any file in any subdirectory, and it will point to the right image.</p>
<p>With PHP, I tried something similar:</p>
<pre><code>include("/includes/header.php");
</code></pre>
<p>...but that doesn't work.</p>
<p>I think that that <a href="http://us2.php.net/manual/en/ini.core.php#ini.include-path" rel="noreferrer">this page</a> is saying that I can set <code>include_path</code> once and after that, it will be assumed. But I don't quite get the syntax. Both examples start with a period, and it says:</p>
<blockquote>Using a . in the include path allows for relative includes as it means the current directory.</blockquote>
<p>Relative includes are exactly what I <strong>don't</strong> want.</p>
<p><strong>How do I make sure that all my includes point to the <code>root/includes</code> folder?</strong> (Bonus: what if I want to place that folder outside the public directory?)</p>
<h2>Clarification</h2>
<p>My development files are currently being served by XAMPP/Apache. Does that affect the absolute path? (I'm not sure yet what the production server will be.)</p>
<h2>Update</h2>
<p>I don't know what my problem was here. The <code>include_path</code> thing I referenced above was exactly what I was looking for, and the syntax isn't really confusing. I just tried it and it works great.</p>
<p>One thing that occurs to me is that some people may have thought that "/some/path" was an "absolute path" because they assumed the OS was Linux. This server is Windows, so an absolute path would have to start with the drive name.</p>
<p>Anyway, problem solved! :)</p>
|
<p>What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;</p>
<pre><code>define( 'ROOT_DIR', dirname(__FILE__) );
</code></pre>
<p>Then in all files, I know what the root of my project is and can do stuff like this</p>
<pre><code>require_once( ROOT_DIR.'/include/functions.php' );
</code></pre>
<p>Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.</p>
|
<p>Not directly answering your question but something to remember:</p>
<blockquote>
<p>When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.</p>
</blockquote>
<p>from: <a href="http://us2.php.net/manual/en/function.include.php#84052" rel="nofollow noreferrer">http://us2.php.net/manual/en/function.include.php#84052</a></p>
| 44,798
|
<p>I am new to any scripting language. But, still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, what is the best online resource to learn Perl?</p>
|
<p>If you already know a bit of perl, <a href="http://www.perlmonks.org/" rel="noreferrer">PerlMonks</a> is a great online resource. You can ask questions in their <a href="http://www.perlmonks.org/?node=Seekers%20of%20Perl%20Wisdom" rel="noreferrer">Seekers of Perl Wisdom</a> section and the answers are often of very high quality. Many people who keep up with the latest developments in Perl hang out there.</p>
<p>As an added bonus, if you ask a clear question, many times the people there take the time to look at the underlying problem and will point out alternate approaches rather than simply taking your question at face value.</p>
|
<p>If you are a beginner, I would suggest you take a look at the cookbook provided by PLEAC. You can find it at <a href="http://pleac.sf.net" rel="nofollow noreferrer">http://pleac.sf.net</a>. There you can find cookbooks for most languages.</p>
| 9,599
|
<p>I just want to enable or disable the button inside a ControlTemplate for a WPF Editor that I'm using.</p>
|
<p>I agree with Joel that the preferred method would be to trigger the setting of the button's Enabled property with xaml markup, either through a trigger or by binding the Enabled value to another dependency property, possibly on a parent element, likely with the help of a ValueConverter.</p>
<p>However, if you have to do it explicitly in C#, you can use the FindName() method on the template property of the button. There's an MSDN 'how to' <a href="http://msdn.microsoft.com/en-us/library/bb613586.aspx" rel="nofollow noreferrer">linked here</a>.</p>
|
<p>I had an issue with buttons in controlTemplates & dataTemplates. I find triggers are often too cumbersome to provide exactly what my clients want, I ended up with too many converters. The method I first tried was to define these more difficult templates inline so they could be bound to commands (& codebehind events) on my screens ViewModel.</p>
<p>if you are templating your own control, I should mention the easiest method is to simply name the button then use something like this:</p>
<pre><code>hourHand = this.Template.FindName( "PART_HourHand", this ) as Rectangle;
</code></pre>
<p>Recently however, I've changed tact (back to indevidual files.. RE-USE!) but started adding a ViewModel (of sorts) which I suffix <code>...TemplateCommandStore</code> to all my templates that get a bit complex. I even use this when templating my customcontrols (for consistency, mostly)</p>
<pre><code>public class BookingDetailsTemplateCommandStore
{
public OpenWindowCommand_Command OpenWindowCommand_Command { get; set; }
public BookingDetailsTemplateCommandStore()
{
OpenWindowCommand_Command = new OpenWindowCommand_Command( this );
}
}
</code></pre>
<p>I can then happily use this command in a template. You can also pass control references into the command store by binding a (dependancy?) property to it to capture events & excise more precise control over your templates.</p>
<pre><code><DataTemplate DataType="{x:Type LeisureServices:BookingSummary}">
<Border Height="50" otherStyling="xyz">
<Border.Resources>
<local:BookingDetailsTemplateCommandStore x:Key="CommandStore" />
</Border.Resources>
<DockPanel>
<Button otherStyling="xyz"
Command="{Binding Source={StaticResource CommandStore},
Path=OpenWindowCommand_Command}" />
</code></pre>
<p><em>MVVM:</em> I find that so long as graphical logic is just that, and completely distinct from business logic, this methodology doesn't interfere with MVVM. In essence I add consistent C# code-ability to Templates, which anyone who spent too much time in winforms might miss as much as I do.</p>
| 22,361
|
<p>I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python?
Thanks!</p>
|
<p>If you specifically want to avoid downloading the content, you'll need to use the HEAD request method. I believe the <code>urllib</code> and <code>urllib2</code> libraries do not support HEAD requests, so you'll have to use the lower-level <code>httplib</code> library:</p>
<pre><code>import httplib
h = httplib.HTTPConnection('www.example.com')
h.request('HEAD', '/')
response = h.getresponse()
// Check for 30x status code
if 300 <= response.status < 400:
// It's a redirect
location = response.getheader('Location')
</code></pre>
|
<p>When you open the URL with <code>urllib2</code>, and you're redirected, you get a status 30x for redirection. Check the info to see the location to which you're redirected. You don't need to read the page to read the <code>info()</code> that's part of the response.</p>
| 42,994
|
<p>How do I copy a directory including sub directories excluding files or directories that match a certain regex on a Windows system?</p>
|
<p>I'd do something like this:</p>
<pre><code>use File::Copy;
sub copy_recursively {
my ($from_dir, $to_dir, $regex) = @_;
opendir my($dh), $from_dir or die "Could not open dir '$from_dir': $!";
for my $entry (readdir $dh) {
next if $entry =~ /$regex/;
my $source = "$from_dir/$entry";
my $destination = "$to_dir/$entry";
if (-d $source) {
mkdir $destination or die "mkdir '$destination' failed: $!" if not -e $destination;
copy_recursively($source, $destination, $regex);
} else {
copy($source, $destination) or die "copy failed: $!";
}
}
closedir $dh;
return;
}
</code></pre>
|
<p>I don't know how to do an exclusion with a copy, but you could work something up along the lines of:</p>
<pre><code>ls -R1 | grep -v <regex to exclude> | awk '{printf("cp %s /destination/path",$1)}' | /bin/sh
</code></pre>
| 28,173
|
<p>I've created a map system for a game that runs on the principle of drawing the picture of the map from tiles. There are many reasons for this which I won't go into here but if you really want to know then I'm sure you can find out how to contact me ;)</p>
<p>I have <a href="http://woarl.com/board/rob.php?mode=map&x=-1&y=9&w=2&h=2" rel="noreferrer">made the latest version live</a> so you can see exactly where the problem lies and the source. The issue is the line between the top 2 tiles and the bottom 2 tiles, I can't figure out why it's gone like this and any help would be appreciated.</p>
<p>In the source is a marker called "stackoverflow", if you search for "stackoverflow" when viewing source then it should take you to the table in question.</p>
<p>I have also uploaded an <a href="http://woarl.com/badMap.png" rel="noreferrer">image of the issue</a>.</p>
|
<p>I think you need to use <code>display: block</code> on your images. When images are <code>inline</code> there's a little extra space for the line spacing.</p>
|
<p>I haven't looked up the whole thing, but the problem lies somewhere in the style sheets.</p>
<p>If you copy out only the table part of it, it is displaying the map correctly.</p>
<p>If you remove the final <code></span></code> tag from this part, it is also working (however the page gets mixed):</p>
<pre><code><div class="inner"><span class="corners-top"><span></span></span>
<div class="content" style="font-size: 1.1em;">
<!-- Stackoverflow findy thingy -->
<table border="0" cellspacing="0" cellpadding="0">
</code></pre>
<p>So either try from the beginning with the css or try to remove one-by-one them, to see, which is causing the problem.</p>
| 4,202
|
<p>Or would a conventional client-server VCS be more appropriate? I'm currently using TortoiseSVN, but I'm interested in a DVCS, but I'm not sure if it's even a good idea to try to use something like that solo.</p>
|
<p>Since you can still push to another machine also running Git/Mercurial/Bzr/etc you still have the multi-computer backup safety, which you'd hopefully have either way. However if you ever code while traveling, having full repository access can be a huge plus, then just resync to your server when you have a net connection again/get home/etc.</p>
|
<p>For a single developer, every VCS will do. I would choose one, that is easy to setup and demands little to no config at all. I personally like <a href="http://en.wikipedia.org/wiki/Monotone_(software)" rel="nofollow noreferrer">Monotone</a>. It was one of the first and I still consider it one of the best ones.</p>
<p>Actually, the most fun I ever had was when using <a href="http://en.wikipedia.org/wiki/Darcs" rel="nofollow noreferrer">darcs</a>, but it's written in a rather ugly language (Haskell) and it was actually already quite a pain to build it on Mac OS X from source.</p>
<p>Git is said to be a good system, but I dislike that it consists out of multiple binaries and scripts and so on. What I really like about systems like darcs and Monotone is, there is one binary... and that's it. No clutter of binaries, no scripts in this or that language, on binary and it does it all.</p>
| 21,604
|
<p>How to find out size of session in ASP.NET from web application?</p>
|
<p>If you're trying to get the size of Session during runtime rather than in debug tracing, you might want to try something like this:</p>
<pre><code>long totalSessionBytes = 0;
BinaryFormatter b = new BinaryFormatter();
MemoryStream m;
foreach(var obj in Session)
{
m = new MemoryStream();
b.Serialize(m, obj);
totalSessionBytes += m.Length;
}
</code></pre>
<p>(Inspired by <a href="http://www.codeproject.com/KB/session/exploresessionandcache.aspx" rel="noreferrer">http://www.codeproject.com/KB/session/exploresessionandcache.aspx</a>)</p>
|
<p>I think you can find that information by adding <strong>Trace="true"</strong> to the page directive of a aspx page. Then when the page loads you can see a large number of details regarding the page request, including session information i think.</p>
<p>You can also enable tracing in your entire application by adding a line to your web.config file. Something like:</p>
<pre><code><trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime"
localOnly="true"/>
</code></pre>
| 24,121
|
<p>I want to use LabVIEW's Call Library Function Node to access a DLL function, and have this function return a string to displayed on my VI. How would I go about doing this? I am quite happy returning numbers from my DLL, but am really struggling to find any examples of how to return a string.</p>
|
<p>I assume from your question that you already have a DLL that can return numbers to Labview. To return a string from the DLL, I have created a DLL with the following C++ function</p>
<pre><code>void returnString(char myString[])
{
const char *aString = "test string";
memcpy(myString, aString, 12);
}
</code></pre>
<p>In Labview I then use the Call Library Function Node and configure it as follows </p>
<pre>
Library Name or Path: c:\path\to\my\custom.dll
Function Name: returnString
Calling Convention: C
Parameters:
Parameter: return type
type: void
Parameter: arg1
type: String
string format: C String Pointer
Function prototype:
void returnString(CStr arg1);
</pre>
<p>After connect the arg1 output in the block diagram to a string indicator and run. The string "test string" should appear in the front panel. </p>
<p>I tried to have the returnString function be of type CStr as in</p>
<pre><code>CStr returnString()
{ ...
}
</code></pre>
<p>but I got build errors when compiling the DLL project.</p>
Update
<p>Thanks to @bk1e comment don't forget to pre-allocate space in Labview for the string.</p>
|
<p>There are at least a few ways to return a string from a Call Library Function Node:</p>
<ol>
<li><p>Return a C string pointer from your DLL function, and configure the Call Library Function Node to have a return type of "C String Pointer". Note that the returned string must be valid after the function returns, so it can't be a pointer to a string allocated on the stack. It must be one of the following: allocated on the heap, statically allocated, a constant string literal, etc.</p>
<p>It looks like <code>examples/dll/regexpr/Regular Expression Solution/VIs/Get Error String.vi</code> in the LabVIEW directory takes this approach.</p>
</li>
<li><p>Allocate a string in your VI, pass it to the Call Library Function Node using a "C String Pointer" parameter as Azim suggested, and overwrite its contents in the DLL. One way to allocate the string is to use Initialize Array to create a u8 array of the desired size, and then use Byte Array To String to convert it to a string.</p>
<p>Be sure that the string you pass in is large enough to hold the contents of your string, and make sure to pass the string length to the DLL so that it knows how large the buffer is. I believe that the default parameter is an empty string. Figuring out the right string length may require calling into the DLL twice, if your VI's first guess isn't large enough.</p>
</li>
<li><p>Pass the string to the Call Library Function Node using a "String Handle" parameter, and use LabVIEW functions in your DLL to resize the string as necessary. This requires your DLL to be specifically designed to interface with LabVIEW and requires linking against a static library that is provided with LabVIEW.</p>
<p>An example of this method ships with LabVIEW as <code>examples/dll/hostname/hostname.vi</code>.</p>
</li>
</ol>
| 33,785
|
<p>I have a C program with an embedded Perl interpreter. I want to be able to precompile some Perl code from within the program. How do I do that?</p>
<p>Rationale (if anyone is interested) is to be able to compile it once, store the parse tree, and execute many times (as long as the compiled code does not change).</p>
<p>Thanks!
Madhu</p>
<p>PS: I am using Perl-5.8, though it would be good to know if Perl-6.0 makes this easier in any way.</p>
|
<p>This is the default behavior when you <a href="http://perldoc.perl.org/perlembed.html" rel="noreferrer">embed the Perl interpreter in a C program</a>. After you've run perl_parse() to parse the Perl program, you can use perl_run() and call_argv() over and over with the same parsed Perl program.</p>
|
<p>In reference to Perl 6, it's not complete. But 5.10.0 might have some bug fixes over 5.8.</p>
| 32,549
|
<p>I just ran across the following error (and found the solution online, but it's not present in Stack Overflow):</p>
<blockquote>
<p>(.gnu.linkonce.[stuff]): undefined
reference to [method] [object
file]:(.gnu.linkonce.[stuff]):
undefined reference to `typeinfo for
[classname]'</p>
</blockquote>
<p>Why might one get one of these "undefined reference to typeinfo" linker errors?</p>
<p>(Bonus points if you can explain what's going on behind the scenes.)</p>
|
<p>One possible reason is because you are declaring a virtual function without defining it.</p>
<p>When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).</p>
<p>An example of defining the virtual function is:</p>
<pre><code>virtual void fn() { /* insert code here */ }
</code></pre>
<p>In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.</p>
<p>The line</p>
<pre><code>virtual void fn();
</code></pre>
<p>declares <code>fn()</code> without defining it and will cause the error message you asked about.</p>
<p>It's very similar to the code:</p>
<pre><code>extern int i;
int *pi = &i;
</code></pre>
<p>which states that the integer <code>i</code> is declared in another compilation unit which must be resolved at link time (otherwise <code>pi</code> can't be set to it's address).</p>
|
<p>Check that your dependencies were compiled without <code>-f-nortti</code>.</p>
<p>For some projects you have to set it explicitly, like in RocksDB:</p>
<pre><code>USE_RTTI=1 make shared_lib -j4
</code></pre>
| 39,553
|
<p>I am getting this error but only very occasionally. 99.9% of the time it works fine:</p>
<p>Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.</p>
<p>Does anyone have any idea on what the cause could be? I only use that datatable for viewing and not updating so is it possible to easily turn off all constraints somehow?</p>
|
<p>This typically happens when the schema on your dataset is enforcing something that your database is not.</p>
<p>Visual Studio will automatically read schema and try and set up some primary keys on your dataset, but if you are using a view that can possibly return multiple rows it will fail. It is easy enough to remove these constraints from the DataSet itself by deleting the constraint in the designer.</p>
<p>Check to ensure that your dataset is not enforcing a primary key in a situation where you could possibly have two rows with the same key, like in a View that joins two tables together and therefore duplicates the rows in the parent table. VS by default will try and create the primary key of the parent table as a unique constraint on the dataset, but the view itself enforces no such constraint.</p>
|
<p>This error can also present if you're using an XSD DataSet to define your schema and the maximum length of a variable-length field (varchar, varbinary, etc) is increased in the database but the XSD is not regenerated.</p>
<p>In my case, I had a <code>varchar(100)</code> database field with a text value 60 characters in length. The XSD expected this field to have a maximum length of 50 (you can see this in the <code>InitClass()</code> method of the Designer.cs file). When this record was loaded I received the "Failed to enable constraints" error message. Updating the record to reduce the field below 50 removed the error.</p>
| 18,848
|
<p>I'm trying to get some ideas about how to develop a web login screen. I'm using DynamicData Webforms, so most of powerful frameworks offers a lot of options, but I'll be very grateful to read your suggestions.</p>
<p>Thanks in advance</p>
<p>Edited:
beyond the functionality, I'll want to read your view-point about the presentation model, i said, im using fx3.5 so improve more than 2 textbox for a single login or using the login aspx control, i have in mind use silverlight but is possible to "light my webapp" that is build in webforms and dynamicdata with out change all the presentation layer?</p>
<p>More Undestandable: Example of using Extjs as Presentation Framework for View Layer, but my project is webforms so this will be nice for MVC.net i said cause is more flexible in json concerns</p>
<p><a href="http://rodotelmi.rebstech.com/wp-content/uploads/2008/07/picture-1.png" rel="nofollow noreferrer">alt text http://rodotelmi.rebstech.com/wp-content/uploads/2008/07/picture-1.png</a></p>
|
<p>Please have a look at 65+ examples of login screen for some inspiration...</p>
<p><a href="http://www.smileycat.com/design_elements/login_forms/" rel="noreferrer">65+ Login form design</a></p>
|
<ul>
<li>Have 2 textboxes : email (or username) and password. </li>
<li>A button to submit. </li>
<li>A link for "Forget your password".</li>
<li>A checkbox to "remember me".</li>
</ul>
| 47,379
|
<p>I was just wondering how I could <em>automatically</em> increment the build (and version?) of my files using Visual Studio (2005). </p>
<p>If I look up the properties of say <code>C:\Windows\notepad.exe</code>, the Version tab gives "File version: 5.1.2600.2180". I would like to get these cool numbers in the version of my dll's too, not version 1.0.0.0, which let's face it is a bit dull.</p>
<p>I tried a few things, but it doesn't seem to be out-of-box functionality, or maybe I'm just looking in the wrong place (as usual).</p>
<p>I work with mainly web projects....</p>
<p>I looked at both:</p>
<ol>
<li><a href="http://www.codeproject.com/KB/dotnet/Auto_Increment_Version.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/Auto_Increment_Version.aspx</a></li>
<li><a href="http://www.codeproject.com/KB/dotnet/build_versioning.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/build_versioning.aspx</a></li>
</ol>
<p>and I couldn't believe it so much effort to do something is standard practice.</p>
<p>EDIT:
<strong>It does not work in VS2005 as far I can tell (<a href="http://www.codeproject.com/KB/dotnet/AutoIncrementVersion.aspx" rel="noreferrer">http://www.codeproject.com/KB/dotnet/AutoIncrementVersion.aspx</a>)</strong></p>
|
<p>In visual Studio 2008, the following works.</p>
<p>Find the AssemblyInfo.cs file and find these 2 lines:</p>
<pre><code>[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
</code></pre>
<p>You could try changing this to:</p>
<pre><code>[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
</code></pre>
<p>But this won't give you the desired result, you will end up with a Product Version of <strong>1.0.*</strong> and a File Version of <strong>1.0.0.0</strong>. Not what you want!</p>
<p>However, if you remove the second of these lines and just have:</p>
<pre><code>[assembly: AssemblyVersion("1.0.*")]
</code></pre>
<p>Then the compiler will set the File Version to be equal to the Product Version and you will get your desired result of an automatically increment product and file version which are in sync. E.g. <strong>1.0.3266.92689</strong></p>
|
<p>Each time I do a build it auto-increments the least-significant digit.</p>
<p>I don't have any idea how to update the others, but you should at least be seeing that already...</p>
| 46,484
|
<p>Has anyone had any luck of using Oracle from .Net on a 64 bit machine, and using the UDT capabilities of Oracle?</p>
<p>I've been able to use an x64 ODP.Net client, but cannot find one with any support for UDTs.</p>
<p>Thanks</p>
<p>Nick</p>
<p>[Edit]
I've posted an answer below. The latest (as of December 2008) release is 11.1.0.7. This has support for 64 bit and UDT.</p>
|
<p>You need to use 11.1.0.7 release. This has UDT support and works with 32 and 64 bit.</p>
|
<p>I've been trying for some time to get the 64-bit edition of Windows Server 2003 to connect to an Oracle 8i instance. It doesn't seem to be possible other than doing it through a 32-bit VM.</p>
<p>Forced upgrading can really suck!</p>
| 8,138
|
<p>I'd like to run some C++ code while the Windows Mobile PocketPC is (or seems) being suspended. An example what I mean is the HTC Home plugin that shows (among others) a tab where the HTC Audio Manager can be used to play back mp3 files. When I press the on/off button, the display goes black, but the audio keeps playing. The only button to switch back on is the on/off button, as expected.</p>
<p>What I tried so far is to capture hardware button presses (works) and switch off the video display (works). What doesn't work with this approach is that when (accidentally) pressing any key on the device, the video display is switched on. I think this isn't the approach taken in the HTC Audio Manager.</p>
<p>I'm guessing on some low-level API magic for this to work, or that the code to play back audio runs at some interrupt level, or the device goes into a different suspend mode.</p>
|
<p>I found sourcecode on the <a href="http://forum.xda-developers.com/archive/index.php/t-379366.html" rel="nofollow noreferrer">xda-developers forum</a> that explains what to do, and it works as thought. The main points are:</p>
<ul>
<li>Set the device to send a notification when going into "unattended" mode. This is done with <code>PowerPolicyNotify(PPN_UNATTENDEDMODE, TRUE)</code></li>
<li>For every device that you need during unattended mode, call <code>SetPowerRequirement(L"gpd0:", D0, POWER_NAME|POWER_FORCE, NULL, NULL)</code>; The "gpd0:" device is the GPS Intermediate driver; replace or duplicate call with any device you need, e.g. "wav1:" for audio, "dsk1:" for memory card or "com1:" for serial port 1.</li>
<li>Create a message queue and request power notifications using <code>RequestPowerNotifications(hMsgQueue, PBT_POWERINFOCHANGE | PBT_TRANSITION)</code></li>
<li>Every time a power notification is sent, the message queue is filled with a struct of type <code>POWER_BROADCAST</code>.</li>
<li>Look for <code>PBT_TRANSITION</code> message type. The field <code>pPwrBrodcast->SystemPowerState</code> then contains a string "unattended" when the device is shut off, e.g. by the user pressing the off button</li>
<li>In this transition, just call <code>SystemIdleTimerReset()</code> to tell the device to not shut off</li>
<li>Repeat when the transition occurs again</li>
<li>When shutting down, call <code>PowerPolicyNotify()</code> to leave unattended mode, release any devices with <code>ReleasePowerRequirement()</code> and stop receiving power notifications with <code>StopPowerNotifications()</code>.</li>
</ul>
|
<p>At first have a look at this <a href="http://blogs.msdn.com/windowsmobile/archive/2005/08/10/450186.aspx" rel="nofollow noreferrer">blog entry</a> in order to understand the various power states. What you basically need is to force the ScreenOff state. Have a look at the SetSystemPowerState function.</p>
| 43,686
|
<p>I'm looking for the simplest, most straightforward way to implement the following:</p>
<ul>
<li>The main program instantiates worker
threads to do a task.</li>
<li>Only <code>n</code> tasks can be running at once.</li>
<li>When <code>n</code> is reached, no more workers
are started until the count of
running threads drops back below <code>n</code>.</li>
</ul>
|
<p>I think that <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)" rel="nofollow noreferrer">Executors.newFixedThreadPool</a> fits your requirements. There are a number of different ways to use the resulting ExecutorService, depending on whether you want a result returned to the main thread, or whether the task is totally self-contained, and whether you have a collection of tasks to perform up front, or whether tasks are queued in response to some event. </p>
<pre><code> Collection<YourTask> tasks = new ArrayList<YourTask>();
YourTask yt1 = new YourTask();
...
tasks.add(yt1);
...
ExecutorService exec = Executors.newFixedThreadPool(5);
List<Future<YourResultType>> results = exec.invokeAll(tasks);
</code></pre>
<p>Alternatively, if you have a new asynchronous task to perform in response to some event, you probably just want to use the ExecutorService's simple <code>execute(Runnable)</code> method.</p>
|
<p>If you want to roll your own:</p>
<pre><code>private static final int MAX_WORKERS = n;
private List<Worker> workers = new ArrayList<Worker>(MAX_WORKERS);
private boolean roomLeft() {
synchronized (workers) {
return (workers.size() < MAX_WORKERS);
}
}
private void addWorker() {
synchronized (workers) {
workers.add(new Worker(this));
}
}
public void removeWorker(Worker worker) {
synchronized (workers) {
workers.remove(worker);
}
}
public Example() {
while (true) {
if (roomLeft()) {
addWorker();
}
}
}
</code></pre>
<p>Where Worker is your class that extends Thread. Each worker will call this class's removeWorker method, passing itself in as a parameter, when it's finished doing it's thing.</p>
<p>With that said, the Executor framework looks a lot better.</p>
<p>Edit: Anyone care to explain why this is so bad, instead of just downmodding it?</p>
| 15,233
|
<h2>solution structure [Plain Winforms + VS 2008 Express Edition]</h2>
<ul>
<li>CoffeeMakerInterface (NS CoffeeMaker)</li>
<li>CoffeeMakerSoftware (NS CoffeeMakerSoftware)</li>
<li>TestCoffeeMaker (NS TestCoffeeMaker)</li>
</ul>
<p>CoffeeMakerSoftware proj references CoffeeMakerInterface.
TestCoffeeMaker proj references CoffeeMakerInterface and CoffeeMakerSoftware.</p>
<p>Now the thing that is driving me nuts. I can't get this to build. <strong>If I remove CoffeeMakerSoftware project reference from TestCoffeeMaker it builds (??!!).. as soon as I add the second project reference, it throws build errors</strong> claiming that types declared in first reference 'can't be found.. are you missing an assembly ref'</p>
<p>At first I had the first 2 assemblies having the same namespace CoffeeMaker.. I then made them distinct (although I think having classes belonging to the same NS across assemblies should be possible) but even that doesn't seem to be it.</p>
<p>Calling more eyeballs. Any pointers.. </p>
|
<p>I broke my 'Don't code when you're tired' dictum. I zipped it up, went to sleep and looked at it today.. found the issue by looking at the output window. <em>(FWIW everything was CopyLocal=True and nothing in GAC. This is Bob Martin's OOD problem from the Agile PPnP book.. coming up with good names was particularly hard)</em></p>
<pre><code>1. CoffeeMaker > CoffeeMakerInterfaces
2. [X] > CoffeeMaker > CoffeeMakerSoftware
3. [X] > TestCoffeeMaker
</code></pre>
<p>That's how I added and renamed the projects in chronological order. Apparently renaming the Assembly via solution explorer, doesn't change the name of the produced binary or throw up a warning. As a result, #1 and #2 both were producing CoffeeMaker.dll as the output.
Adding Reference#2 to the TestCoffeeMaker rendered all the types defined in reference#1 as unknown with the ever popular </p>
<blockquote>
<p>"Error 2 The type or namespace name
'CoffeeMaker' could not be found (are
you missing a using directive or an
assembly reference?) C:\Documents and
Settings\pillaigi\Desktop\CoffeeMaker\TestCoffeeMaker\FakeCoffeeMakerDevice.cs 4 7 TestCoffeeMaker"</p>
</blockquote>
<p><strong>Solution: Open Project properties and examine if the "Assembly name:" in project properties for each (ref or otherwise) project is unique and doesn't clash.</strong></p>
<p>Maybe not enough people do this.. the IDE or compiler could easily catch this one 'If referenced assemblies have the same binary name... please fix it.. you will anyway'
I've done this to myself once before.. Making a BIG note to myself this time. Now excuse me while I wear my Dunce cap and sit in the corner. </p>
|
<p>A few things to check:</p>
<ul>
<li>Ensure "copy local" is TRUE for all project references</li>
<li>If any are set to false, check the GAC for old builds of your libraries</li>
</ul>
<p>If all this fails, remove all projects from the solution, create a new solution and add the projects back. Yeah, it's voodoo, but this has got me past silly mistakes before. ;-)</p>
| 32,094
|
<p>I have an existing htaccess that works fine:</p>
<pre><code>RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule (.*) /default.php
DirectoryIndex index.php /default.php
</code></pre>
<p>I wish to modify this so that all urls that start with /test/ go to /test/default.php.</p>
<p>Example: <a href="http://www.x.com/hello.php" rel="nofollow noreferrer">http://www.x.com/hello.php</a> -- > <a href="http://www.x.com/default.php" rel="nofollow noreferrer">http://www.x.com/default.php</a>
Example: <a href="http://www.x.com/test/hello.php" rel="nofollow noreferrer">http://www.x.com/test/hello.php</a> -- > <a href="http://www.x.com/test/default.php" rel="nofollow noreferrer">http://www.x.com/test/default.php</a></p>
|
<p>Basically, just put <code>/test/</code> in front of your expression. Also, the parentheses are unnecessary here:</p>
<pre><code>RewriteRule ^/test/ /test/default.php
</code></pre>
|
<p>If you need to pass on information from the URL you can capture it (with parentheses) and send it to default.php (with $1) as follows:</p>
<pre><code>RewriteRule ^/test/(.*)$ /test/default.php/$1
</code></pre>
<p>so that http//..../test/foo/bar/ would result in /test/default.php/foo/bar/ . Your script can then access the extra information.</p>
| 42,011
|
<p><a href="http://en.wikipedia.org/wiki/Greenspun%27s_Tenth_Rule" rel="nofollow noreferrer">Greenspunning</a>. We've all had occasion to hack around a language's missing features to get what we need. Implementing pseudo-monadic patterns in Java, Y Combinators in Javascript, variable immutability in C... </p>
<p>What do you consider your most impressive workaround in search of greater functionality? In hindsight, was it worth the hack? Even better: did it, like Ruby's <a href="http://weblog.raganwald.com/2007/10/stringtoproc.html" rel="nofollow noreferrer">string#to_proc</a>, become an accepted feature of a later version of the language?</p>
|
<p>You need the Toolkit version <a href="http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=11121" rel="nofollow noreferrer">1.0.20229.20821</a>, <em>AjaxControlToolkit.zip</em> the dll's are targeted to .NET 2.0 and you need also the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en" rel="nofollow noreferrer">ASP.NET AJAX Extensions 1.0 for .NET 2.0</a>.</p>
|
<p>You need the Toolkit version <a href="http://www.codeplex.com/AjaxControlToolkit/Release/ProjectReleases.aspx?ReleaseId=11121" rel="nofollow noreferrer">1.0.20229.20821</a>, <em>AjaxControlToolkit.zip</em> the dll's are targeted to .NET 2.0 and you need also the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en" rel="nofollow noreferrer">ASP.NET AJAX Extensions 1.0 for .NET 2.0</a>.</p>
| 27,221
|
<p>I have several RequiredFieldValidators in an ASP.NET 1.1 web application that are firing on the client side when I press the Cancel button, which has the CausesValidation attribute set to "False". How can I get this to stop? </p>
<p>I do not believe that Validation Groups are supported in 1.1.</p>
<p>Here's a code sample: </p>
<pre><code><asp:TextBox id="UsernameTextBox" runat="server"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="UsernameTextBoxRequiredfieldvalidator" ControlToValidate="UsernameTextBox"
runat="server" ErrorMessage="This field is required."></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="UsernameTextBoxRegExValidator" runat="server" ControlToValidate="UsernameTextBox"
Display="Dynamic" ErrorMessage="Please specify a valid username (6 to 32 alphanumeric characters)."
ValidationExpression="[0-9,a-z,A-Z, ]{6,32}"></asp:RegularExpressionValidator>
<asp:Button CssClass="btn" id="addUserButton" runat="server" Text="Add User"></asp:Button>
<asp:Button CssClass="btn" id="cancelButton" runat="server" Text="Cancel" CausesValidation="False"></asp:Button>
</code></pre>
<p><strong>Update:</strong> There was some dynamic page generating going on in the code behind that must have been messing it up, because when I cleaned that up it started working.</p>
|
<p>Validation Groups were not added to ASP.NET until version 2.0. This is a 1.1 question. </p>
<p>Double check your setting and make sure you are not overwriting it in the code behind. </p>
|
<p>Are they in separate validation groups (the button and validator controls)?</p>
<p>You're not manually calling the JS to do the client validation are you?</p>
| 10,857
|
<p>I have backed up an encrypted DB (symmetric key/certificate) and
restored it on a different server. </p>
<p>Unfortuantely we're having problems with the decryption... hoping
someone can help. </p>
<p>In the restored db, I can see the Symmetric Key and the Certificate in
SSMS, but when I try to Open the key using the cert ( open symmetric
key KeyA decryption by certificate CertB )I get the
following <em>very descriptive</em> error: </p>
<p>Msg 15466, Level 16, State 1, Line 1
An error occurred during decryption. </p>
<p>Any ideas?</p>
<p>Thanks in advance.</p>
|
<p><a href="http://blogs.msdn.com/lcris/archive/2007/11/16/sql-server-2005-restoring-the-backup-of-a-database-that-uses-encryption.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/lcris/archive/2007/11/16/sql-server-2005-restoring-the-backup-of-a-database-that-uses-encryption.aspx</a> answers this:</p>
<p>"When you restore a database that uses encryption features, there is only one thing you need to take care off - if the database master key (DbMK) needs a service master key (SMK) encryption, you need to regenerate this encryption. Note that this encryption is made by default when you create the DbMK, but it may be intentionally dropped, if you want tighter control of access to the encrypted data. Anyway, if you did have such SMK encryption for the DbMK, the steps to regenerate it are the following:</p>
<p>OPEN MASTER KEY DECRYPTION BY PASSWORD = 'password'
ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY
CLOSE MASTER KEY</p>
<p>That's it - the database encryption features should now work as when the backup was taken. Also note that it doesn't matter if you restore the database on the server where the backup was taken or elsewhere. The only thing that matters for this procedure is that you know one of the passwords protecting the DbMK "</p>
|
<p>The problem you are probably experiencing is that the Database Master Key for the servers is different. To my understanding the other keys are based off of this and it could cause problems when trying to decrypt the data. Check out the <a href="http://msdn.microsoft.com/en-us/library/ms189586.aspx" rel="nofollow noreferrer">encryption hierarchy</a> for a description of the steps that go into data encryption.</p>
<p>I hope this answer helps and isn't too off-track. :)</p>
| 25,771
|
<p><strong>The situation:</strong></p>
<p>I need to convert our current development environment from Windows XP 32-bit to Windows Vista 64-bit (*). Naturally, I've run into plenty of places in our build system where hardcoded paths were problematic (e.g. "<code>C:\Program Files</code>" becoming "<code>C:\Program Files (x86)</code>"). Fortunately, there is a <code>%ProgramFiles%</code> environment variable which maps to the proper directory based on the source process (32-bit or 64-bit). So I updated the build scripts with <code>%ProgramFiles%</code>, and I was sure it'd be the end of that.</p>
<p>The build environment is called from the command-line (<code>C:\Windows\System32\cmd.exe</code>).</p>
<p><b>The problem:</b>
On one specific machine (namely my dev machine at work), it turns out that <code>C:\Windows\System32\cmd.exe</code> is actually a 32bit process, so the scripts find the <code>x86</code> version of the <code>Program Files</code> directory and everything works great.</p>
<p>On every other 64bit machine I can find (including my home machine), <code>C:\Windows\System32\cmd.exe</code> is the 64bit version, and the 32bit version is in <code>C:\Windows\SysWow64\cmd.exe</code>. So the build scripts can't find anything they're looking for and fail.</p>
<p>I understand now that the 32bit <code>cmd.exe</code> should be called explicitly if that's what you need, and by default you get a 64bit <code>cmd.exe</code>. Typical case of <code>WORKSFORME</code>...</p>
<p><b>The question is</b>, what happened to the machine where this is not true? Why am I getting a 32bit <code>cmd.exe</code> by default on one machine but not on others? In all cases I am explicitly executing <code>C:\Windows\System32\cmd.exe</code> from the <code>Start|Run</code> menu but getting different results <em>on one machine only</em>. All are running the same edition of Vista 64bit.</p>
<p>Any thoughts or insight?</p>
<p>(*) Please accept that I <em>must</em> do this. I am not at liberty to say <em>why</em> I am doing this. Re-installing the OS and everything from scratch would probably work, but it is surely overkill. Besides, it was hard enough convincing our IT department to give out Vista machines!</p>
|
<p>I have finally found the problem, and as expected it is quite simple: user error. Explorer (which is itself a 64-bit process on Windows Vista 64-bit) launches 64-bit command prompts by default. If you want a 32-bit <code>CMD.EXE</code>, you must explicitly reference <code>C:\Windows\SysWoW64\CMD.EXE</code>.</p>
<p>The reason this worked fine on my system is that I use Far Manager for most of my command-line usage, which is 32-bit (therefore it launches 32-bit command prompts). When I verified I must have confused a 32-bit window for a 64-bit window (after all they look the same!) and asked a stupid question.</p>
<p>Die in Sente, the problem with <code>%ProgramFiles(x86)%</code> is that it doesn't exist on Windows Vista 32-bit, because that would have really been simpler.</p>
<p>Ah, there is nothing like a public posting to make a fool of yourself... :)</p>
|
<p>Instead of <code>%ProgramFiles%</code>, isn't there a <code>%Programfiles(x86)%</code> that always goes where you want, regardless of which cmd.exe is running? My Windows XP 64-bit systems all have that; excuse me for not taking the time to boot up a Vista system.</p>
| 48,827
|
<p>I'm working on an iphone application (not web app) and I'd like to build a form asking a user to indicate a price range. Instead of using two text fields, I would prefer to use a double slider to set the minimum and the maximum price. I know that it is possible de use a simple slider (sound control for exemple) but i've never seen a double one. Can anyone help ?</p>
|
<p>This is not possible without creating a custom control. You'll need to inherit from UIControl or UIView and provide a custom drawRect method. You'll also need to respond to touch and drag events to update the state of the control. I have not done this myself, but I would be prepared for a fairly significant amount of work to get everything to respond and display as expected.</p>
<p>I'm curious as to why you need to have both values specified on a single slider? Why not use two sliders either side-by-side or stacked? It would not require any more input steps than a double slider, and would conform more to standard UI guidelines.</p>
|
<p>I <em>think</em> you can specify multiple thumbs for a single slider if you subclass UISlider, at least I vaguely remember that being possible in MacOSX. But Code Addict is right, you'll probably be better off using the standard controls - a double-thumbed slider seems like it'd be pretty difficult to deal with in the touchscreen environment.</p>
| 13,853
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.