instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>If all you see is the ugly no-char boxes, what tools or strategies do you use to figure out what went wrong?</p>
<p>(The specific scenario I'm facing is no-char boxes within a <select> when it should be showing Japanese chars.)</p>
|
<p>Firstly, "ugly no-char boxes" might not be an encoding problem, they might just be a sign you don't have a font installed that can display the glyphs in the page.</p>
<p>Most character encoding problems happen when strings are being passed from one system to another. For webapps, this is usually between the browser and the application, between the application and the filesystem and between the application and the database.</p>
<p>So you need to check where the mis-encoded data is coming from, what character encoding it has at the source, and what encoding it is being received as. The best way is to send through characters you know the system is having problems with, and examine them at each level of the app. What do they look like inside the app? In the database? When you get them back from the database? When they're displayed in the browser?</p>
<p>Sorry to be so general, but the question doesn't give much more to work with.</p>
|
<p>Redirect the data to disk and use a <a href="https://www.hhdsoftware.com/free-hex-editor" rel="nofollow noreferrer">Hex Editor</a>. Most text editors / viewers do their own conversions behind the scenes, so it is difficult to be sure you are seeing the data in it's true form.</p>
| 4,915
|
<p>Does anyone here know any resources on how to get started writing a plugin for Google's Picasa? I love it for photo management, but I have some ideas for how it could be better.</p>
<ul>
<li>Riya-esque facial search: given a large enough corpus of faces and pictures (people tend to be repeated often in individuals' albums (family, friends), I would think some semi-workable version of this could be done. And with 13+ gigs/7 years of photos, it would be very nice for search.</li>
<li>Upload to Facebook EDIT: <a href="http://apps.new.facebook.com/picasauploader/" rel="nofollow noreferrer">Someone already made a very nice version</a></li>
<li>Upload to any non-Google property, actually.</li>
</ul>
<p>I know there are certain APIs and a Picasa2Flickr plugin out there, and I was wondering if anyone had seen any resources on this topic or had any experience</p>
|
<p>there is a an <a href="http://picasa2flickr.sourceforge.net/index.html#about" rel="nofollow noreferrer">Opensource Project</a> which created a "Upload To FlickR" Plugin. Maybe you could use it as an startingpoint... </p>
|
<p>I would start with the Picasa API:</p>
<p><a href="http://code.google.com/apis/picasaweb/overview.html" rel="nofollow noreferrer">Picasa API</a></p>
| 3,481
|
<p>This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight.</p>
<p>The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow. But you run it from there and it just blazes along, returning in less than a second each time.</p>
<p>My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system.</p>
|
<p>This is what I've learned so far from my research.</p>
<p>.NET sends in connection settings that are not the same as what you get when you log in to management studio. Here is what you see if you sniff the connection with Sql Profiler:</p>
<pre><code>-- network protocol: TCP/IP
set quoted_identifier off
set arithabort off
set numeric_roundabort off
set ansi_warnings on
set ansi_padding on
set ansi_nulls off
set concat_null_yields_null on
set cursor_close_on_commit off
set implicit_transactions off
set language us_english
set dateformat mdy
set datefirst 7
set transaction isolation level read committed
</code></pre>
<p>I am now pasting those setting in above every query that I run when logged in to sql server, to make sure the settings are the same.</p>
<p>For this case, I tried each setting individually, after disconnecting and reconnecting, and found that changing arithabort from off to on reduced the problem query from 90 seconds to 1 second.</p>
<p>The most probable explanation is related to parameter sniffing, which is a technique Sql Server uses to pick what it thinks is the most effective query plan. When you change one of the connection settings, the query optimizer might choose a different plan, and in this case, it apparently chose a bad one.</p>
<p>But I'm not totally convinced of this. I have tried comparing the actual query plans after changing this setting and I have yet to see the diff show any changes.</p>
<p>Is there something else about the arithabort setting that might cause a query to run slowly in some cases?</p>
<p>The solution seemed simple: Just put set arithabort on into the top of the stored procedure. But this could lead to the opposite problem: change the query parameters and suddenly it runs faster with 'off' than 'on'. </p>
<p>For the time being I am running the procedure 'with recompile' to make sure the plan gets regenerated each time. It's Ok for this particular report, since it takes maybe a second to recompile, and this isn't too noticeable on a report that takes 1-10 seconds to return (it's a monster).</p>
<p>But it's not an option for other queries that run much more frequently and need to return as quickly as possible, in just a few milliseconds.</p>
|
<p>Try changing the SelectCommand timeout value:</p>
<pre><code>DataAdapter.SelectCommand.CommandTimeout = 120;
</code></pre>
| 3,127
|
<p>A discussion about Singletons in <strong>PHP</strong> has me thinking about this issue more and more. Most people instruct that you shouldn't make a bunch of DB connections in one request, and I'm just curious as to what your reasoning is. My first thought is the expense to your script of making that many requests to the DB, but then I counter myself with the question: wouldn't multiple connections make concurrent querying more efficient?</p>
<p>How about some answers (with evidence, folks) from some people in the know?</p>
|
<p>Database connections are a limited resource. Some DBs have a very low connection limit, and wasting connections is a major problem. By consuming many connections, you may be blocking others for using the database.</p>
<p>Additionally, throwing a ton of extra connections at the DB doesn't help anything unless there are resources on the DB server sitting idle. If you've got 8 cores and only one is being used to satisfy a query, then sure, making another connection might help. More likely, though, you are already using all the available cores. You're also likely hitting the same harddrive for every DB request, and adding additional lock contention.</p>
<p>If your DB has anything resembling high utilization, adding extra connections won't help. That'd be like spawning extra threads in an application with the blind hope that the extra concurrency will make processing faster. It <em>might</em> in some certain circumstances, but in other cases it'll just slow you down as you thrash the hard drive, waste time task-switching, and introduce synchronization overhead.</p>
|
<p>I would assume that it is because your requests are not being sent asynchronously, since your requests are done iteratively on the server, blocking each time, you have to pay for the overhead of creating a connection each time, when you only have to do it once...</p>
<p>In Flex, all web service calls are automatically called asynchronously, so you it is common to see multiple connections, or queued up requests on the same connection.</p>
<p>Asynchronous requests mitigate the connection cost through faster request / response time...because you cannot <em>easily</em> achieve this in PHP without out some threading, then the performance hit is greater then simply reusing the same connection. </p>
<p>that's my 2 cents...</p>
| 4,821
|
<p>I frequently use <code>git stash</code> and <code>git stash pop</code> to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but <code>git stash pop</code> appears to remove all references to the associated commit.</p>
<p>I know that if I use <code>git stash</code> then <em>.git/refs/stash contains</em> the reference of the commit used to create the stash. And <em>.git/logs/refs/stash contains</em> the whole stash. But those references are gone after <code>git stash pop</code>. I know that the commit is still in my repository somewhere, but I don't know what it was.</p>
<p>Is there an easy way to recover yesterday's stash commit reference?</p>
|
<p>Once you know the hash of the stash commit you dropped, you can apply it as a stash:</p>
<pre class="lang-bash prettyprint-override"><code>git stash apply $stash_hash
</code></pre>
<p>Or, you can create a separate branch for it with</p>
<pre class="lang-bash prettyprint-override"><code>git branch recovered $stash_hash
</code></pre>
<p>After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away.</p>
<h1>Finding the hash</h1>
<p>If you have only just popped it and the terminal is still open, you will <a href="https://stackoverflow.com/questions/89332/recover-dropped-stash-in-git/7844566#7844566">still have the hash value printed by <code>git stash pop</code> on screen</a> (thanks, Dolda).</p>
<p>Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows:</p>
<pre class="lang-bash prettyprint-override"><code>git fsck --no-reflog | awk '/dangling commit/ {print $3}'
</code></pre>
<p>...or using PowerShell for Windows:</p>
<pre><code>git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] }
</code></pre>
<p>This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph.</p>
<p>The easiest way to find the stash commit you want is probably to pass that list to <code>gitk</code>:</p>
<pre class="lang-bash prettyprint-override"><code>gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' )
</code></pre>
<p>...or see <a href="https://stackoverflow.com/questions/89332#34666995">the answer from emragins</a> if using PowerShell for Windows.</p>
<p>This will launch a repository browser showing you <em>every single commit in the repository ever</em>, regardless of whether it is reachable or not.</p>
<p>You can replace <code>gitk</code> there with something like <code>git log --graph --oneline --decorate</code> if you prefer a nice graph on the console over a separate GUI app.</p>
<p>To spot stash commits, look for commit messages of this form:</p>
<p> WIP on <i>somebranch</i>: <i>commithash Some old commit message</i></p>
<p><em>Note</em>: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did <code>git stash</code>.</p>
|
<p>You can follow the below process step by step:</p>
<p>1- use below to list all unreachable commits
git fsck --unreachable</p>
<p>2- to show unreachable commit hash by
git show hash</p>
<p>3- copy all log, you can see log like, unreachable blob, commit, tree.</p>
<p>4- apply git stash with log having commit hash
git stash apply [replace hash]</p>
| 11,489
|
<p>I need my database to be secure in case of the hard drive being stolen.</p>
<p>I have not seen many databases (even mainstream ones) claiming to support encryption. </p>
<ul>
<li>Do you guys know of any databases that support encryption?</li>
<li>If I'm using a database that doesn't support encryption, is it a bad idea to encrypt data natively (using java encryption libraries, for example)? Would this potentially cause a problem for databases with strongly typed fields? </li>
<li>What other solutions are available for encrypting my database?</li>
</ul>
|
<p>Maybe you should think to encrypt your entire hard disk drive. This is done natively at the filesystem level.</p>
<p>It uses the windows credentials to encrypt it. So, even if your entire computer is stolen, your data is protected.</p>
<p>The stealer will have to reformat the drive to use it.</p>
<p>Of course, if your computer use auto-login, it's not an option for you.</p>
<p>HTH, even if it's not really a database encryption solution.</p>
|
<p>SQL Compact DBs offer encryption out of the box by giving them a password.</p>
<p><a href="http://blogs.msdn.com/stevelasker/archive/2008/05/14/security-and-encryption-for-sql-server-compact.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/stevelasker/archive/2008/05/14/security-and-encryption-for-sql-server-compact.aspx</a></p>
| 35,642
|
<p>New to xml. Looking for XPath to search a xml file with python ElementTree format</p>
<pre><code><root>
<child>One</child>
<child>Two</child>
<child>Three</child>
</root>
</code></pre>
<p>to do search for child with "Two" and return true/false</p>
<p>if it was started off like </p>
<pre><code>from elementtree import ElementTree
root = ElementTree.parse(open(PathFile)).getroot()
</code></pre>
<p>how can this be achieved</p>
|
<p>You could use a sampling profiler like Intel's Vtune to obtain a measure of how many CPU cycles are being consumed with a minimum amount of disturbance on the system being measured.</p>
<p>When using threads however the goal is to avoid needless spawning new threads. Look into using the <a href="http://msdn.microsoft.com/en-us/library/ms973903.aspx" rel="nofollow noreferrer">thread pool</a>. This will let you run work items asynchronously, but without having to spawn a new thread for each item.</p>
|
<p>I asked a closely related question a couple of days ago, and have yet not found a way to measure the actual CPU cycle usage of the code:
<a href="https://stackoverflow.com/questions/234411/limiting-assembly-execution-number-of-cpu-cycles">Limiting assembly execution number of cpu cycles</a></p>
<p>In your case, could you not run a profiling of the calculation and see how much time a single calculation takes, and compare that to the aggregate time of spawning a thread that does the calculation and then kill the thread off afterwards?</p>
| 29,526
|
<p>I know very little about the history of 3D printing, except that SLA came first (in the 1980's?), and FDM development was probably held back by patents.</p>
<p>By 2016, very low price kit machines were available to hobbyists, in the <€300 price range, as price-reduced clones of designs which had already seen several iterations.</p>
<p>Was this the start of the break-out of cheap FDM machines (as opposed to the >€2000 semi-professional lab budget prototyping class), or were the earlier iterations of these kit machines also suitable/adopted by hobbyists?</p>
<p>I realise that early popularity would grow exponentially, but I'm thinking particularly at what point people could build a printer without needing to compile their own firmware, solder any boards, etc.</p>
|
<blockquote>
<p>By 2016, very low price kit machines were available to hobbyists [..]</p>
<p>Was this the start of the break-out of cheap FDM machines</p>
</blockquote>
<p>No, not by any means. The <a href="https://en.wikipedia.org/wiki/RepRap_project" rel="noreferrer">RepRap project</a> started in 2005, and by 2008-2010 there were several open-source printer designs out there that were somewhat workable for hobbyists. These designs were still quite expensive, you needed to source all the components yourself and do a very significant amount of troubleshooting.</p>
<p>However, as early as mid-2009 you could buy a <a href="https://gizmodo.com/5286457/makerbot-cupcake-cnc-delivers-diy-3d-printing-for-just-750/" rel="noreferrer">Makerbot Cupcake CNC</a> for \$750 as a kit (which might have involved some soldering) or \$2500 fully assembled (presumably without soldering, but it's conceivable it was plug-and-play). Makerbot went on to become quite a successful company, piggybacking off the RepRap project and could be viewed as the "break-out" you ask about.</p>
<p>I purchased my first printer kit (no soldering or firmware involved) for \$500 (plus around \$150 in shipping and taxes) in February 2014; cheap hobbyist machines were commonplace well before that. </p>
|
<p>The Makerbot Replicator was released in 2012 and was the first 3D consumer-level printer that was sold only as a complete unit, not a kit. They were also well funded and had a famous Maker-Person as a founder. This seemed to coincide with wide-scale coverage of 3D printing in the media, and a big boom in the DIY side of the movement which is continuing to this day.</p>
<p>The unit was still expensive by many standards (US$2500), but it did solve the bootstrap problem... you could just buy one at a store, instead of having to have a specific knowledge set in order to build one.</p>
| 984
|
<p>I know this won't be a popular question, because a lot of web designers want to assume that their craft is difficult and valuable.</p>
<p><strong>IT IS</strong>. But I do not believe that it is difficult because HTML and CSS are difficult to master, I believe its difficult because being a good creative designer is difficult. Please resist the urge to reflexively disagree with me because I consider the language simple.</p>
<p>I suck as a designer, thankfully its not my job. However I can take a photo shopped comp and create a pure HTML/CSS web page from it with ease.</p>
<p>It is my personal believe that <strong>anyone</strong> can become an effective HTML/CSS guru in a week or two's study. There just isn't that much complexity (and this is someone with years of experience talking).</p>
<p>Crossbrowser coding is not as hard as people make it sound. I develop in Firefox, and tweak for IE, and I'm done, a good CSS reset handles 99% of the issues.</p>
<p>Do you disagree with this? Is HTML and CSS impossible to learn well in a week?</p>
<p>EDIT: This has to do with my heavily downvoted answer here: <a href="https://stackoverflow.com/questions/198337/testing-htmlcssjavascript-skills-when-hiring#198344">Testing HTML/CSS/Javascript skills when hiring</a></p>
|
<p>"Is HTML and CSS impossible to learn well in a week?"</p>
<p>In a word, <strong>yes</strong>.</p>
<p>Can you write a basic page by following something like, "Learn html in 24 hours"? Absolutely. Will you know why it does or does not work - probably not.</p>
<p>"...a good CSS reset handles 99% of the issues." Possibly. <strong>Why</strong> it does is likely way beyond <em>one week of study</em>. </p>
<ul>
<li>Finding a generic CSS reset that
handles 99% of issues - free</li>
<li>Handling the other 1% - priceless!</li>
</ul>
|
<p>It's ultimately easier to build a site using semantic markup and good CSS then it is to go back and change the design of a webpage that was designed using 10 layers of nested tables, 1 pixel transparent gifs (for spacing), and nonstandard <code><font></code> tags to alter the way the text looks.</p>
| 24,193
|
<p>I have an xml file which I would like to create a form/table around to add, edit and delete records using PHP. Currently I use simpleXML to load the XML file, and display its content on various pages.</p>
<p>Is there any way I can create a table that shows all results, and allows me to either edit or delete that particular row of the table which represents a full record within the XML file. </p>
<p>When clicking edit I would like the details from the record to appear in a form which the user can change and then save out, updating the XML file and the corresponding web page.</p>
<p>I need this done in PHP, preferably using SimpleXML, though open to suggestions of other ways to do this with PHP.</p>
<p>Cheers</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,452
|
<p>We have a SQL Server 2005 SP2 machine running a large number of databases, all of which contain full-text catalogs. Whenever we try to drop one of these databases or rebuild a full-text index, the drop or rebuild process hangs indefinitely with a MSSEARCH wait type. The process can’t be killed, and a server reboot is required to get things running again. Based on a Microsoft forums post<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1" rel="noreferrer">1</a>, it appears that the problem might be an improperly removed full-text catalog. Can anyone recommend a way to determine which catalog is causing the problem, without having to remove all of them?</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1" rel="noreferrer">1</a> [<a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1]" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2681739&SiteID=1]</a>
“Yes we did have full text catalogues in the database, but since I had disabled full text search for the database, and disabled msftesql, I didn't suspect them. I got however an article from Microsoft support, showing me how I could test for catalogues not properly removed. So I discovered that there still existed an old catalogue, which I ,after and only after re-enabling full text search, were able to delete, since then my backup has worked”</p>
|
<p>Here's a suggestion. I don't have any corrupted databases but you can try this:</p>
<pre><code>declare @t table (name nvarchar(128))
insert into @t select name from sys.databases --where is_fulltext_enabled
while exists(SELECT * FROM @t)
begin
declare @name nvarchar(128)
select @name = name from @t
declare @SQL nvarchar(4000)
set @SQL = 'IF EXISTS(SELECT * FROM '+@name+'.sys.fulltext_catalogs) AND NOT EXISTS(SELECT * FROM sys.databases where is_fulltext_enabled=1 AND name='''+@name+''') PRINT ''' +@Name + ' Could be the culprit'''
print @sql
exec sp_sqlexec @SQL
delete from @t where name = @name
end
</code></pre>
<p>If it doesn't work, remove the filter checking <code>sys.databases</code>.</p>
|
<p>Have you tried running process monitor and when it hangs and see what the underlying error is? Using process moniter you should be able to tell whick file/resource it waiting for/erroring on. </p>
| 6,847
|
<p>Most of my PHP apps have an ob_start at the beginning, runs through all the code, and then outputs the content, sometimes with some modifications, after everything is done.</p>
<pre><code>ob_start()
//Business Logic, etc
header->output();
echo apply_post_filter(ob_get_clean());
footer->output();
</code></pre>
<p>This ensures that PHP errors get displayed within the content part of the website, and that errors don't interfere with <code>header</code> and <code>session_*</code> calls.</p>
<p>My only problem is that with some large pages PHP runs out of memory. How do I stop this from happening?</p>
<p>Some ideas:</p>
<ol>
<li>Write all of the buffered content to a temporary file and output that.</li>
<li>When the buffers reaches a certain size, output it. Although this might interfere with the post filter.</li>
<li>Raise the memory limit (thanx @troelskn).</li>
</ol>
<p>Whats the drawbacks on each of these approaches? Especially raising the memory limit?</p>
|
<p>Can't you raise the memory limit? Sounds like the best solution to me.</p>
<p>Edit: Obviously, raising the memory limit just because a script tops out should raise some red flags, but it sounds to me like this is a legitimate case - eg. the script is actually producing rather large chunks of output. As such, you have to store the output <em>somewhere</em>, and memory seems to be the best pick, for both performance and convenience reasons.</p>
<p>I should note also that the memory limit setting is just that - a limit. Scripts that don't consume much memory, won't consume more just because you raise the limit. The main reason for its existence, is to prevent misbehaving/buggy scripts from taking down the entire server. This is something that is important if you have a lot of amateurs hacking away on a shared host (Something PHP has been used a lot for). So if this is your own server, or at least you generally know what you're doing, there isn't really any benefit from having a low memory-limit.</p>
|
<p>For you to run out of memory due to output you must have a huge amount of data going out or very low memory limits. 4 or so years ago a memory limit of 8mb was common enough, and reasonable. But with the switch to using objects and just better coding styles in general the memory usage of scripts that I've come across have increased.</p>
<p>Hrm... where is it that your scripts run out of memory? If it's always in your output filtering functions maybe they just need to be optimised? <a href="http://www.php.net/memory_get_usage" rel="nofollow noreferrer">memory_get_usage()</a> will return the amount of memory in use by your script at that point.</p>
<p>What's the current memory limit you're running at? Are you running in a shared environment?
At the moment I've got memory limits between 64 and 128 depending on the server. </p>
<p>If it's only a specific subset of scripts you want to increase the limit for then you can do it per script:</p>
<pre><code>ini_set('memory_limit','64M');
</code></pre>
<p>If you want no limit for the script you can set this to -1</p>
| 35,626
|
<p><strong>What?</strong></p>
<p>I have a DLGTEMPLATE loaded from a resource DLL, how can I change the strings assigned to the controls at runtime programmatically?</p>
<p>I want to be able to do this before the dialog is created, such that I can tell that the strings on display came from the resource DLL, and not from calls to SetWindowText when the dialog is initialized.</p>
<p>Google has found examples of creating DLGTEMPLATE in code, or twiddling simple style bits but nothing on editing the strings in memory.</p>
<p><strong>How?</strong></p>
<p>I am doing this by hooking the Dialog/Property Sheet creation API's. Which gives me access to the DLGTEMPLATE before the actual dialog is created and before it has a HWND. </p>
<p><strong>Why?</strong></p>
<p>I want to be able to do runtime localization, and localization testing. I already have this implemented for loading string (including the MFC 7.0 wrapper), menus and accelerator tables, but I am struggling to handle dialog/property sheet creation.</p>
<p>Code examples would be the perfect answer, ideally a class to wrap around the DLGTEMPLATE, if I work out my own solution I will post it.</p>
|
<p>You can't edit the strings in memory. The DLGTEMPLATE structure is a direct file mapping of the relevent bytes of the resource dll. Thats read only.</p>
<p>You are going to need to process the entire DLGTEMPLATE structure and write out a new one with the altered length strings.</p>
<p>It will frankly be easier to just hook the WM_INITDIALOG and alter the strings by interacting with the controls than building a DLGTEMPLATE writer. Because there arn't a lot of those around. Unless you have an additional requirement to actually save altered dialog resources to disk as raw .res files (or attempt to modify the .dll inplace) Id really recommend you avoid this approach.</p>
<p>You say you are already doing this for accellerator tables and menu strings - if you can guarantee that the patched in strings are going to be shorter, then just make a binary copy of the DLGTEMPLATE struct, and write the non trivial scanning code necessary to find each string so you can patch the copy in place.</p>
|
<p>Thanks all, I actually had 24 hours rest on the problem, then went with a global windows hook filtering WM_INITDIALOG which was a much simpler method, worked out just fine, no API hooking required, 2 pages of code down to just a few lines.</p>
<p>Thanks for all the answers.</p>
| 25,002
|
<p>I have a project where I've been using TDD and unit tests as "software vises". In essence I translate the requirements into tests that verify that the code conforms to the requirements. I rarely have to go back and edit the unit tests, which rather is the point: only the "real" code should be modified. At the moment, there are 900 unit tests.</p>
<p>Now some requirements have been changed by the gold-owners. Since the former requirements are so thorougly encoded in the existing unit tests, it seems that changing them to conform to the new requirements would be inviting disaster. How do you adapt your unit test suites to handle this kind of change?</p>
|
<p>Per definition the <a href="http://en.wikipedia.org/wiki/Unit_testing" rel="nofollow noreferrer">unit-tests</a> don't replicate the requirements for the application. They describe the requirements for a module. That's a difference, the module can be reused even in an application with different requirements or isn't used at all. So the changing requirements don't affect real unit-tests (except that you have to write new for new modules or abandon old tests for modules no longer needed for the changed requirements).</p>
<p>On the other hand: <a href="http://en.wikipedia.org/wiki/Acceptance_testing" rel="nofollow noreferrer">acceptance-tests</a> deal with the requirements on application-level. So I think you talk about acceptance-tests.</p>
<p>I would add the new requirements as new acceptance-test. But for the old ones you have to look through them, how they are invalidated by the changed requirements.</p>
|
<p>I have two answers to your question, one philosophical and the other tactical.</p>
<p>On the philosophical front it is important to consider your unit tests as code. That means all the normal traits of good code are usually appropriate for good tests: intention revealing, remove duplication, etc. Many, perhaps most, of the failures that I've seen with unit testing has come because people haven't treated their tests this way, but rather than just coded them and never revisited them to see if they should be refactored.</p>
<p>In my experience, if you've reached a point where your unit tests are a hinderance to change it is because you've got technical debt in your tests.</p>
<p>So my tactical suggestion is that before you attempt to change your requirements you look to refactor you tests. Each test should have a unique reason to pass/fail, and the behavior outside of that should be in shared code. This means that for any given behavior change you'll have two places to change the tests:</p>
<ol>
<li>The test that actually validates that behavior</li>
<li>The places that behavior is used in shared fixture code</li>
</ol>
<p>You might find this article useful: <a href="http://www.developertesting.com/archives/month200508/20050824-Grow-your-harness.html" rel="nofollow noreferrer">Grow Your Harness Naturally</a>. It was really about a reusable test harness for functional testing but I find the ideas very useful in my unit tests as well.</p>
| 40,261
|
<p>I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems. SNMP, WMI, that sort of thing. With most classes I can mock up objects to test them, but how do you deal with unit testing a real system? For example, if my class goes out and gets the Win32_LogicalDisk object for a server, how could I possibly unit test it?</p>
|
<p>Assuming you meant "How do I test against things that are hard/impossible to mock":</p>
<p>If you have a class that "goes out and gets the Win32_LogicalDisk object for a server" AND does something else (consumes the 'Win32_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">Dependency Injection</a> to allow you to mock the 'Win32_LogicalDisk' object. For instance:</p>
<pre><code>class LogicalDiskConsumer(object):
def __init__(self, arg1, arg2, LogicalDiskFactory)
self.arg1=arg1
self.arg2=arg2
self.LogicalDisk=LogicalDiskFactory()
def consumedisk(self):
self.LogicalDisk.someaction()
</code></pre>
<p>Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'.</p>
|
<p>You might create a set of "test stubs" that replace the core library routines and return known values, perhaps after suitable delays.</p>
<p>As an example, I recently needed to develop code to run inside a 3rd-party product. The challenge was that our "partner" would be doing the compiling and integration with their base code: I wasn't allowed to <em>look at</em> their code in any form! My strategy was to build a very simple emulator that did what I <em>thought</em> their code did, based on information from their engineers. We used a language that made it easy to switch various pieces of the emulator in and out of each build, so I could do a tremendous amount of testing before involving our partner to build each new iteration.</p>
<p>I'd use the same method again, as software problems in that particular product are about an order of magnitude fewer than in our next most reliable product!</p>
| 6,607
|
<p>In Scala, is it possible to get the string representation of a type at runtime? I am trying to do something along these lines:</p>
<pre><code>def printTheNameOfThisType[T]() = {
println(T.toString)
}
</code></pre>
|
<h1>Note: this answer is out of date!</h1>
<p><em>Please see answer using TypeTag for Scala 2.10 and above</em></p>
<p>May I recommend #Scala on freenode</p>
<pre><code>10:48 <seet_> http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible?
10:48 <seet_> possible
10:48 <lambdabot> Title: Getting the string representation of a type at runtime in Scala - Stack Overflow,
http://tinyurl.com/53242l
10:49 <mapreduce> Types aren't objects.
10:49 <mapreduce> or values
10:49 <mapreduce> println(classOf[T]) should give you something, but probably not what you want.
</code></pre>
<p><a href="http://www.scala-lang.org/node/109" rel="nofollow noreferrer">Description of classOf</a></p>
|
<p>Please note that this isn't really "the thing:"</p>
<pre><code>object Test {
def main (args : Array[String]) {
println(classOf[List[String]])
}
}
</code></pre>
<p>gives</p>
<pre><code>$ scala Test
class scala.List
</code></pre>
<p>I think you can blame this on erasure</p>
<p>====EDIT====
I've tried doing it with a method with a generic type parameter:</p>
<pre><code>object TestSv {
def main(args:Array[String]){
narf[String]
}
def narf[T](){
println(classOf[T])
}
}
</code></pre>
<p>And the compiler wont accept it. Types arn't classes is the explanation</p>
| 23,101
|
<p>So far I had "designed" my app-icon in the Visual-Studio-Editor. 16-Colors, 4kB.
Now someone created a more sophisticated and up-to-date app-icon for me, which results in a filesize of about 250kB. </p>
<p><strong>Problem:</strong> A user reported, that win2000 is complaining, because it is not able to digest this amount of data for an icon.</p>
<p><strong>Question:</strong> What can be regarded as <em>best practice for application-icons</em>. In detail: which resolutions and which color-depth-variations should be contained in an icon?</p>
|
<p>I've always tried to stick to the following set of sizes to get a reasonable icon on most systems.</p>
<ul>
<li>16 x 16 in 16 colours</li>
<li>16 x 16 in XP Style (true colour with alpha channel info)</li>
<li>32 x 32 in 256 colours</li>
<li>32 x 32 in XP style</li>
<li>48 x 48 in XP style</li>
<li>64 x 64 in XP style</li>
</ul>
<p>This produces an icon of about 35KB in size and seems to work on systems from win95/98 all the way up to Vista. I still develop on a Win2000 machine and these work just fine. </p>
|
<p>In general I wouldn't care about Windows 2000 any more as even Microsoft has begun to stop support for it. For Windows XP <a href="http://msdn.microsoft.com/en-us/library/ms997636.aspx" rel="nofollow noreferrer">this article on MSDN</a> might help you.</p>
| 12,538
|
<p>I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument. </p>
<p>That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP? </p>
<p>Bonus points for doing it in pure PHP (no <code>system('stty')</code>) and replacing the characters with <code>*</code>. </p>
<p><strong>EDIT:</strong></p>
<p>The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that.</p>
<p>Also, for the record, the <code>stty</code> way of doing it is:</p>
<pre><code>echo "Password: ";
system('stty -echo');
$password = trim(fgets(STDIN));
system('stty echo');
// add a new line since the users CR didn't echo
echo "\n";
</code></pre>
<p>I'd prefer to not have the <code>system()</code> calls in there.</p>
|
<p>Found on <a href="http://www.sitepoint.com/blogs/2009/05/01/interactive-cli-password-prompt-in-php/" rel="noreferrer">sitepoint</a>.</p>
<pre><code>function prompt_silent($prompt = "Enter Password:") {
if (preg_match('/^win/i', PHP_OS)) {
$vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
file_put_contents(
$vbscript, 'wscript.echo(InputBox("'
. addslashes($prompt)
. '", "", "password here"))');
$command = "cscript //nologo " . escapeshellarg($vbscript);
$password = rtrim(shell_exec($command));
unlink($vbscript);
return $password;
} else {
$command = "/usr/bin/env bash -c 'echo OK'";
if (rtrim(shell_exec($command)) !== 'OK') {
trigger_error("Can't invoke bash");
return;
}
$command = "/usr/bin/env bash -c 'read -s -p \""
. addslashes($prompt)
. "\" mypassword && echo \$mypassword'";
$password = rtrim(shell_exec($command));
echo "\n";
return $password;
}
}
</code></pre>
|
<p>Why not use an SSH connection? You can abstract the commands away, redirect input/output and have full control.</p>
<p>You can provide someone with a pure clean shell with as little rights as neccesary, and let the password just be POST'ed along with to SSH2::Connect() to open the shell.</p>
<p>I created a nice class to work with the php SSH2 extension, maybe it helps you;
(and it also does secure file transfers)</p>
<pre><code><?php
/**
* SSH2
*
* @package Pork
* @author SchizoDuckie
* @version 1.0
* @access public
*/
class SSH2
{
private $host;
private $port;
private $connection;
private $timeout;
private $debugMode;
private $debugPointer;
public $connected;
public $error;
/**
* SSH2::__construct()
*
* @param mixed $host
* @param integer $port
* @param integer $timeout
* @return
*/
function __construct($host, $port=22, $timeout=10)
{
$this->host = $host;
$this->port = $port;
$this->timeout = 10;
$this->error = 'not connected';
$this->connection = false;
$this->debugMode = Settings::Load()->->get('Debug', 'Debugmode');
$this->debugPointer = ($this->debugMode) ? fopen('./logs/'.date('Y-m-d--H-i-s').'.log', 'w+') : false;
$this->connected = false;
}
/**
* SSH2::connect()
*
* @param mixed $username
* @param mixed $password
* @return
*/
function connect($username, $password)
{
$this->connection = ssh2_connect($this->host, $this->port);
if (!$this->connection) return $this->error("Could not connect to {$this->host}:{$this->port}");
$this->debug("Connected to {$this->host}:{$this->port}");
$authenticated = ssh2_auth_password($this->connection, $username, $password);
if(!$authenticated) return $this->error("Could not authenticate: {$username}, check your password");
$this->debug("Authenticated successfully as {$username}");
$this->connected = true;
return true;
}
/**
* SSH2::exec()
*
* @param mixed $command shell command to execute
* @param bool $onAvailableFunction a function to handle any available data.
* @param bool $blocking blocking or non-blocking mode. This 'hangs' php execution until the command has completed if you set it to true. If you just want to start an import and go on, use this icm onAvailableFunction and false
* @return
*/
function exec($command, $onAvailableFunction=false, $blocking=true)
{
$output = '';
$stream = ssh2_exec($this->connection, $command);
$this->debug("Exec: {$command}");
if($onAvailableFunction !== false)
{
$lastReceived = time();
$timeout =false;
while (!feof($stream) && !$timeout)
{
$input = fgets($stream, 1024);
if(strlen($input) >0)
{
call_user_func($onAvailableFunction, $input);
$this->debug($input);
$lastReceived = time();
}
else
{
if(time() - $lastReceived >= $this->timeout)
{
$timeout = true;
$this->error('Connection timed out');
return($this->error);
}
}
}
}
if($blocking === true && $onAvailableFunction === false)
{
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);
$this->debug($output);
}
fclose($stream);
return($output);
}
/**
* SSH2::createDirectory()
*
* Creates a directory via sftp
*
* @param string $dirname
* @return boolean success
*
*/
function createDirectory($dirname)
{
$ftpconnection = ssh2_sftp ($this->connection);
$dircreated = ssh2_sftp_mkdir($ftpconnection, $dirname, true);
if(!$dircreated)
{
$this->debug("Directory not created: ".$dirname);
}
return $dircreated;
}
public function listFiles($dirname)
{
$input = $this->exec(escapeshellcmd("ls {$dirname}"));
return(explode("\n", trim($input)));
}
public function sendFile($filename, $remotename)
{
$this->debug("sending {$filename} to {$remotename} ");
if(file_exists($filename) && is_readable($filename))
{
$result = ssh2_scp_send($this->connection, $filename, $remotename, 0664);
}
else
{
$this->debug("Unable to read file : ".$filename);
return false;
}
if(!$result) $this->debug("Failure uploading {$filename} to {$remotename}");
return $result;
}
public function getFile($remotename, $localfile)
{
$this->debug("grabbing {$remotename} to {$localfile}");
$result = ssh2_scp_recv($this->connection, $remotename, $localfile);
if(!$result) $this->debug("Failure downloading {$remotename} to {$localfile}");
return $result;
}
/**
* SSH2::debug()
*
* @param mixed $message
* @return
*/
function debug($message)
{
if($this->debugMode)
{
fwrite($this->debugPointer, date('Y-m-d H:i:s')." : ".$message."\n");
}
}
/**
* SSH2::error()
*
* @param mixed $errorMsg
* @return
*/
function error($errorMsg)
{
$this->error = $errorMsg;
$this->debug($errorMsg);
return false;
}
/**
* SSH2::__destruct()
*
* @return
*/
function __destruct()
{
if($this->connection){
$this->connection = null;
}
if($this->debugMode && $this->debugPointer)
{
fclose($this->debugPointer);
}
}
}
</code></pre>
<p>Usage example:</p>
<pre><code>$settings = Settings::Load()->Get("SecureServer");
$ssh = new SSH2($settings['host']);
if( $ssh->connect($settings['username'], $settings['password']))
{
echo $ssh->exec("ls -la ".$settings['path'], false, true);
flush();
}
</code></pre>
| 22,745
|
<p>Why doesn't this work?</p>
<pre><code>DECLARE @temp table
(ShipNo int,
Supplier varchar(10)
)
INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')
Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp
</code></pre>
<p>But if you cast the ShipNo to a varchar in the Case statement it DOES work?</p>
|
<p>I am aware that this is old post but this is for any one who tumbles upon this issue and is looking for a solution:</p>
<pre><code>SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
END
CASE @OrderBy
WHEN 'ShipNo' THEN ShipNo
END
)
</code></pre>
<p>basically you are putting each field in its own case. Do this only when their data type or value inside field differs for both the columns or when you are getting error such as</p>
<p>conversion failed when trying to convert int to varchar or varchar to int..</p>
|
<p>From Books Online:</p>
<pre><code>CASE
WHEN Boolean_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
]
END
</code></pre>
<p>"The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion."</p>
<p>So Supplier and ShipNo must be the same datatype.</p>
| 33,671
|
<p>How do I implement "Exclude these words" feature for a search appliation using Lucene?</p>
<p>Thanks!</p>
|
<p>therefor i can use the stopanalyzer:</p>
<p>StopAnalyzer StopAnalyzer includes the lower-case filter, and also has a filter that drops out any "stop words", words like articles (a, an, the, etc) that occur so commonly in english that they might as well be noise for searching purposes. StopAnalyzer comes with a set of stop words, but you can instantiate it with your own array of stop words.</p>
<p><a href="http://lucene.apache.org/java/2_3_0/api/org/apache/lucene/analysis/StopAnalyzer.html" rel="nofollow noreferrer">http://lucene.apache.org/java/2_3_0/api/org/apache/lucene/analysis/StopAnalyzer.html</a></p>
<p>more information:
<a href="http://www.darksleep.com/lucene/" rel="nofollow noreferrer">http://www.darksleep.com/lucene/</a>
<a href="https://stackoverflow.com/questions/66041/how-to-sort-by-lucene-net-field-and-ignore-common-stop-words-such-as-a-and-the">How to sort by Lucene.Net field and ignore common stop words such as 'a' and 'the'?</a></p>
|
<p>Look at the NOT operator <a href="http://lucene.apache.org/java/2_3_2/queryparsersyntax.html" rel="nofollow noreferrer">here</a>. Just construct your query accordingly or massage if it is a user-generated query.</p>
| 47,493
|
<p>Here's some code I have:</p>
<pre><code>MyClass* MyClass::getInstance()
{
static MyClass instance;
return &instance;
}
</code></pre>
<p>I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.</p>
<p>My question then is how to refer to this <code>instance</code> variable from a global scope. I've tried referring to it as <code>MyClass::getInstance::instance</code> but that doesn't work. I'm guessing <code>getInstance</code> has to be decorated somehow. Anyone know how?</p>
<p>This is in Visual Studio 2008.</p>
|
<p>Well, the function-scoped static <code>instance</code> variable doesn't show up in a <code>.map</code> file generated by <code>cl.exe /Fm</code>, and it doesn't show up when I use <code>x programname!*MyClass*</code> in WinDbg, so the mangled name doesn't seem to contain <code>MyClass</code> at all.</p>
<p><strong>Option 1: Disassemble <code>MyClass::getInstance</code></strong></p>
<p>This approach seems easier:</p>
<pre>
0:000> uf programname!MyClass::getInstance
programname!MyClass::getInstance [programname.cpp @ 14]:
14 00401050 55 push ebp
14 00401051 8bec mov ebp,esp
15 00401053 a160b34200 mov eax,dword ptr [programname!$S1 (0042b360)]
15 00401058 83e001 and eax,1
15 0040105b 7526 jne funcstat!MyClass::getInstance+0x33 (00401083)
programname!MyClass::getInstance+0xd [programname.cpp @ 15]:
15 0040105d 8b0d60b34200 mov ecx,dword ptr [programname!$S1 (0042b360)]
15 00401063 83c901 or ecx,1
15 00401066 890d60b34200 mov dword ptr [programname!$S1 (0042b360)],ecx
15 0040106c b9b0be4200 mov ecx,offset programname!instance (0042beb0)
15 00401071 e88fffffff call programname!ILT+0(??0MyClassQAEXZ) (00401005)
15 00401076 68e03e4200 push offset programname!`MyClass::getInstance'::`2'::`dynamic atexit destructor for 'instance'' (00423ee0)
15 0040107b e8f3010000 call programname!atexit (00401273)
15 00401080 83c404 add esp,4
programname!MyClass::getInstance+0x33 [programname.cpp @ 16]:
16 00401083 b8b0be4200 mov eax,offset programname!instance (0042beb0)
17 00401088 5d pop ebp
17 00401089 c3 ret
</pre>
<p>From this we can tell that the compiler called the object <code>$S1</code>. Of course, this name will depend on how many function-scoped static variables your program has.</p>
<p><strong>Option 2: Search memory for the object</strong></p>
<p>To expand on @gbjbaanb's suggestion, if <code>MyClass</code> has virtual functions, you might be able to find its location the hard way:</p>
<ul>
<li>Make a full memory dump of the process.</li>
<li>Load the full memory dump into WinDbg.</li>
<li>Use the <code>x</code> command to find the address of MyClass's vtable:</li>
</ul>
<pre>
0:000> x programname!MyClass::`vftable'
00425c64 programname!MyClass::`vftable' =
</pre>
<ul>
<li>Use the <code>s</code> command to search the process's virtual address space (in this example, 0-2GB) for pointers to MyClass's vtable:</li>
</ul>
<pre>
0:000> s -d 0 L?7fffffff 00425c64
004010dc 00425c64 c35de58b cccccccc cccccccc d\B...].........
0040113c 00425c64 8bfc458b ccc35de5 cccccccc d\B..E...]......
0042b360 00425c64 00000000 00000000 00000000 d\B.............
</pre>
<ul>
<li>Use the <code>dt</code> command to find the class's vtable offset, and subtract that from the addresses returned from the search. These are possible addresses for the object.</li>
</ul>
<pre>
0:000> dt programname!MyClass
+0x000 __VFN_table : Ptr32
+0x008 x : Int4B
+0x010 y : Float
</pre>
<ul>
<li>Use <code>dt programname!MyClass 0042b360</code> to examine the object's member variables, testing the hypothesis that the object is located at 0042b360 (or some other address). You will probably get some false positives, as I did above, but by inspecting the member variables you may be able to figure out which one is your singleton.</li>
</ul>
<p>This is a general technique for finding C++ objects, and is kind of overkill when you could just disassemble <code>MyClass::getInstance</code>.</p>
|
<p>In gdb, you can put a watchpoint on the mangled name of the variable.</p>
<p>For example, with this function:</p>
<pre><code>int f() {
static int xyz = 0;
++xyz;
return xyz;
}
</code></pre>
<p>I can watch _ZZ1fvE3xyz (as mangled by gcc 3.2.3 or gcc 4.0.1).</p>
| 36,692
|
<ul>
<li>Plastic: Same Matterhacker PLA (filament I use every day)</li>
<li>Printer: Anycubic i3 Mega (the one I use every day)</li>
<li>Slicer: Ultimaker Cura 4.2.1</li>
</ul>
<p>I don't know what's causing it, I haven't changed any slicer settings to my knowledge, I haven't changed anything on the printers end, and I'm using the same filament I've always used. But for some reason, the first layer is simply not sticking. At first I noticed when doing a print the nozzle seemed a little higher than normal for the first layer, but then it started having problems where 0 % of the filament would stick to the bed and it would all just come off and turn into a mess. I've checked and checked, but I see no reason the printer would just start doing this now all the sudden when it's worked perfectly for a year now.</p>
<hr>
<p>EDIT: Something I've noticed since posting this is that older sliced models seem to print just fine, which means there's something about the newser slicer settings that's causing it. I don't know what I would have changed though and/or how to restore to my original settings.</p>
|
<p>There are 3 general factors about print adhesion you always have to keep in mind:</p>
<ul>
<li>Have a sufficient surface for the print to stick. A pyramid printed on the tip can't print properly.</li>
<li>Check the leveling of your bed occasionally and relevel the bed. By removing prints, one can easily unlevel it over time without noticing it.</li>
<li>Clean your print bed from fingerprints and grease every so often. Fats are good separators between the print and the bed. Getting them off with Isopropyl alcohol or other solvents can restore print surfaces in an instant.</li>
</ul>
<p>In this specific case, there are some hints that make the general things less of an issue though: Old sliced items print fine, newer not. This hints that you changed something in the print settings. Among the settings that are good for adhesion, check your old G-code for the following three:</p>
<ul>
<li>Bed temperature. I use 60 °C bed temperature for PLA and have good results on bed adhesion. Others print with 50 °C. However, going too low can make the plastic not stick well anymore.</li>
<li>Extrusion temperature. When the plastic extrudes, it has to be molten enough to push out enough and cold enough to solidify within moments and stick to the surface of the bed. If it is too hot, it would be dragged along, if it's too cold it doesn't get to stick either. I use 190-200 °C for PLA.</li>
<li>The <code>first layer height</code> might be different. I usually use 0.2 mm for this setting, no matter what the actual layer height is, and get good adhesion and not too much trouble with tiny unevenness.</li>
<li>The reason might be a mechanical issue, in that the <a href="https://drucktipps3d.de/wp-content/uploads/2017/11/anycubic_i3_mega_endstop-1024x768.jpg" rel="nofollow noreferrer">Z-endstops</a> (in an Anycubic i3, there are two, hidden in the frame sides) might have bent, moved or misaligned over time. Check its positioning. If the mount is broken, there are <a href="https://www.thingiverse.com/make:441224" rel="nofollow noreferrer">replacement part designs</a>.</li>
</ul>
|
<p>This seems like a long-shot, but I've noticed at this time of year many 3D prints fail. We noticed 4 printers all went dead and had massive non-stick issues last year about this time. Turns out it was mostly around changes in temperature and humidity - the outside temperature changed inside AC settings/wind-flow, etc.</p>
<p>So, you might think through some of the meta-causes of where the printer is, and if temp/air/humidity might be just enough chaos to not make the material stick. Right in September, I start putting a light layer of glue down on the glass bed under each print or increasing the use of rafts...</p>
| 1,463
|
<p>Printer: SecKit Go w/ BMG/v6 and SKR v1.3/TMC2130 Drivers</p>
<p>Slicer: Simplify3d or Cura (problem is much worse in Cura?)</p>
<p>Long story short - after getting this printer running, I have noticed that it will underextrude ONLY on corners on an internal perimeter specifically once we're above bottom layers - and nowhere else. See below:</p>
<p><a href="https://i.stack.imgur.com/J9Y3r.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J9Y3r.jpg" alt="enter image description here"></a></p>
<p>E-Steps have been calibrated, extrusion multiplier has been calibrated (single perimeters are 0.48 mm), linear advance has been calibrated, but here it gets weird. Anything resembling a 'standard' value (suggested between 1-2) results in MASSIVE underextrusion after the speed change. I was able to get a good looking line using the linear advance test with a value of 0.15 (which seems very low).</p>
<p><a href="https://i.stack.imgur.com/VvSl7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VvSl7.jpg" alt="enter image description here"></a></p>
<p>Retraction (1 mm @ 30 mm/s), junction deviation (0.02) and all other settings are off the factory Simplify3d profile. Turning linear advance off makes the problem slightly better but doesn't fix it, going to a value of around 1 results in huge underextrusion after any change in direction.</p>
<p>I am absolutely lost as to what to try next.</p>
|
<p>Unsupported parts need to be printed with support. If your supports are too hard to remove, try the Tree Support setting and make sure that your support structure is set up with a gap to the actual print. As we don't know which slier you use, I can't go into more details here.</p>
|
<p>You could try printing slower and/or increase cooling ( possibly even a cooler bed temp) if you absolutely want to avoid supports, or just use supports with a support interface and tweak support distance.</p>
| 1,606
|
<p>I've written some C# code that checks whether a device is present on any SerialPort by issuing a command on the port and listening for a reply. When I just set the port speed, open the port, get the serial stream and start processing, it works 100% of the time. However, some of our devices work at different speeds and I am trying to probe for a device at various speeds to autonegotiate a connection as well as detect device presence.</p>
<p>When I do all this in a single thread there are no problems. However, 3s timeout at ten speeds is 30s per serial port, and there may be several. Hence the desire to probe all ports concurrently.</p>
<p>Sometimes this works. Sometimes Vista bluescreens. When I use threads to probe all the ports simultaneously it nearly always bluescreens. When I force everything to run in one thread it never happens.</p>
<p>A USB-serial Prolific PL-2303 adaptor is in use with x64 drivers. </p>
<hr>
<p>@Vinko - thanks for the tip on reading minidumps. </p>
<p>As near as I can tell, the crux of the problem is that by starting a new asynchronous I/O operation <em>from a different thread</em> it is possible to give a whole new meaning to overlapped I/O, inducing a race condition inside the driver. Since the driver executes in kernel mode, <strong>BLAM!</strong></p>
<h1>Epilogue</h1>
<p>Except for kicking off, don't use BeginXxx outside of the callback handler and don't call BeginXxx until you've called EndXxx, because you'll induce a race condition in driver code that runs in kernel mode.</p>
<h1>Postscript</h1>
<p>I have found that this also applies to socket streams.</p>
|
<p>Having written Windows drivers for one of these sort of device once, my advice would be not to waste your time with WinDbg trying to prove what you already know - i.e. that the driver you're using is buggy.</p>
<p>If you can find a more up-to-date driver from the PL2302, then try that, but my recommendation is that if you have to use USB->Serial adaptors, the FTDI-based ones are the best. (They're <em>not</em> the one I wrote the drivers for, either...)</p>
|
<p>BSOD usually means buggy drivers.</p>
<p>What kind of HW ports do you use? I've had BSODs with SiLabs CP21xx USB to Serial converters drivers.</p>
| 32,050
|
<p>I am writing a batch script in order to beautify JavaScript code. It needs to work on both <strong>Windows</strong> and <strong>Linux</strong>. </p>
<p>How can I beautify JavaScript code using the command line tools? </p>
|
<p>First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at <a href="http://jsbeautifier.org/" rel="noreferrer"><a href="http://jsbeautifier.org/" rel="noreferrer">http://jsbeautifier.org/</a></a>, because it's what I found first. Downloads its file <a href="https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js" rel="noreferrer">https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js</a></p>
<p>Second, download and install The Mozilla group's Java based Javascript engine, <a href="https://www.mozilla.org/rhino/" rel="noreferrer">Rhino</a>. "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this </p>
<pre><code>java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js
</code></pre>
<p>Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example</p>
<pre><code>//original code
(function() { ... js_beautify code ... }());
//new code
print(global.js_beautify(readFile(arguments[0])));
</code></pre>
<p>Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file. </p>
<p>You'd invoke the above something like </p>
<pre><code>java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js
</code></pre>
<p>You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.</p>
|
<p>I've written an article explaining how to build a <a href="http://blog.shonzilla.com/post/1448821411/command-line-javascript-beautifier" rel="nofollow">command-line JavaScript beautifier implemented in JavaScript</a> in under 5 minutes. YMMV.</p>
<blockquote>
<ol>
<li>Download the latest stable Rhino and unpack it somewhere, e.g. ~/dev/javascript/rhino</li>
<li>Download beautify.js which is referenced from aforementioned jsbeautifier.org then copy it somewhere, e.g. ~/dev/javascript/bin/cli-beautifier.js</li>
<li><p>Add this at the end of beautify.js (using some additional top-level properties to JavaScript):</p>
<pre><code>// Run the beautifier on the file passed as the first argument.
print( j23s_beautify( readFile( arguments[0] )));
</code></pre></li>
<li><p>Copy-paste the following code in an executable file, e.g. ~/dev/javascript/bin/jsbeautifier.sh:</p>
<pre><code>#!/bin/sh
java -cp ~/dev/javascript/rhino/js.jar org.mozilla.javascript.tools.shell.Main ~/dev/web/javascript/bin/cli-beautifier.js $*
</code></pre></li>
<li><p>(optional) Add the folder with jsbeautifier.js to PATH or moving to some folder already there.</p></li>
</ol>
</blockquote>
| 3,950
|
<p>I'm getting the strangest results. I have a class with a composite key.
If i do the following query:</p>
<blockquote>
<p>from LOVEJB l order by l.canonicalId
desc</p>
</blockquote>
<p>my results are not ordered by the '<strong>canonicalId</strong>' column I asked for. Instead, the canonical id result is like:</p>
<blockquote>
<p>823 823 822 823 ,,,</p>
</blockquote>
<p>Can someone give me some pointers on how should I try to crack this? I already messed up with <em>hashcodes</em> and <em>equals</em>, I experimented with a new class, etc. to no avail.</p>
|
<p>I found out. My composite key had columns that were not part of the table's primary key. Thanks all.</p>
|
<p>What's the actual QUERY generated? Order is dictated by RDBMS.
Turn on show_sql in Hib configuration and run that query manually.</p>
| 28,103
|
<p>I need advice on how to have my C# console application display text to the user through the standard output while still being able access it later on. The actual feature I would like to implement is to dump the entire output buffer to a text file at the end of program execution.</p>
<p>The workaround I use while I don't find a cleaner approach is to subclass <code>TextWriter</code> overriding the writing methods so they would both write to a file and call the original stdout writer. Something like this:</p>
<pre><code>public class DirtyWorkaround {
private class DirtyWriter : TextWriter {
private TextWriter stdoutWriter;
private StreamWriter fileWriter;
public DirtyWriter(string path, TextWriter stdoutWriter) {
this.stdoutWriter = stdoutWriter;
this.fileWriter = new StreamWriter(path);
}
override public void Write(string s) {
stdoutWriter.Write(s);
fileWriter.Write(s);
fileWriter.Flush();
}
// Same as above for WriteLine() and WriteLine(string),
// plus whatever methods I need to override to inherit
// from TextWriter (Encoding.Get I guess).
}
public static void Main(string[] args) {
using (DirtyWriter dw = new DirtyWriter("path", Console.Out)) {
Console.SetOut(dw);
// Teh codez
}
}
}
</code></pre>
<p>See that it writes to and flushes the file all the time. I'd love to do it only at the end of the execution, but I couldn't find any way to access to the output buffer.</p>
<p>Also, excuse inaccuracies with the above code (had to write it <em>ad hoc</em>, sorry ;).</p>
|
<p>The perfect solution for this is to use <a href="http://logging.apache.org/log4net/" rel="noreferrer">log4net</a> with a console appender and a file appender. There are many other appenders available as well. It also allows you to turn the different appenders off and on at runtime. </p>
|
<p>Consider refactoring your application to separate the user-interaction portions from the business logic. In my experience, such a separation is quite beneficial to the structure of your program.</p>
<p>For the particular problem you're trying to solve here, it becomes straightforward for the user-interaction part to change its behavior from <code>Console.WriteLine</code> to file I/O.</p>
| 8,624
|
<p>Right now our test and production databases are on the same server, but with different names. Deploying has meant editing Web.config to change all the connection strings for the correct database. A step which I forget all too frequently... </p>
<p>We've finally created a new database server for testing, and I'm moving the databases over... but now the server will be different and we'll still need to deal with connection string issues. </p>
<p>I was thinking of managing it via a hosts file, but the thought of switching that on my desktop machine whenever I need to test against production data seems cumbersome at best.</p>
<p>So I'm just wondering if there's a better way out there. Something that would build with a "production" web config for deployment would be ideal...</p>
|
<p>I usually have three separate web configs: one for my development machine, one for QA, and one for production. The development one connects to my local SQL database (which is firewalled from outside) and it is the default web.config. The others are named web-prod.config and web-qa.config. After publishing I delete the two that I don't need and rename the correct one to web.config. If I forget, the app breaks the first time it attempts to access the database, since the default config references one it can't get to.</p>
<p>Since IIS refuses to serve up a file named .config, I make sure they all end in .config instead of say web.config-prod or web.config-qa.</p>
|
<p>I'll put my connection strings in the machine.config on our QA and Production boxes. I'll keep them in the web.config on my dev box for flexibility, though. Then, I'll use a web deployment project to overwrite my dev connection strings with nothing (no connection strings) when deploying to QA. Therefore the QA site relies on the connection strings in machine.config. I still deploy to Production manually to make sure everything succeeds. I do this by manually copying everything from QA (except for web.config) to production.</p>
| 21,775
|
<p>I have a image button. I wanted to add a text "Search" on it. I am not able to add it because the "imagebutton" property in VS 2008 does not have text control in it. Can anyone tell me how to add text to a image button?? </p>
<pre><code> <asp:ImageButton ID="Searchbutton" runat="server" AlternateText="Search"
CssClass="bluebutton"
ImageUrl="../Graphics/bluebutton.gif" Width="110px"
onclick="Searchbutton_Click"/>
</code></pre>
|
<pre><code><button runat="server"
style="background-image:url('/Content/Img/stackoverflow-logo-250.png')" >
your text here<br/>and some more<br/><br/> and some more ....
</button>
</code></pre>
|
<p>I don't think you can write text to an ImageButton control of ASP.NET. You can generate image on the fly if that's what you need, and write the text from your code behind, but it will be too complicated, use normal button with CSS instead, unless your image cannot be generated by CSS.</p>
| 32,796
|
<p>My only functional computer at the moment is a raspberry pi, and I was wondering if there was any software that supported it. My printer is a Newmatter mod-t, but I might be able to modify other software to support it</p>
|
<h2>Safety first</h2>
<p>I suggest the following handling of resins, some basic stuff first:</p>
<ul>
<li><strong>ALWAYS</strong> wear disposable, one-use gloves when handling resin.</li>
<li>Respirators are highly advised to be worn.</li>
<li>Work in a well-ventilated area.</li>
<li>Tools dedicated to resin handling are for resin only to prevent contamination of other tools.</li>
<li>Try to minimize the amount added to the vat, so you have as little rests as possible.</li>
</ul>
<h2>Re-cycling</h2>
<p>Now, what to do to get the used resin back to the cycle? Any resin that has been exosed to air and light, such as having been in the vat is best considered to be B-Quality. You can use it to cast greeblies or bits (aka disposal by curing), as one would do with leftover casting (2-component) resin, but that is a waste.</p>
<h3>Step 1: Re-botteling</h3>
<p>So, let's look at some better ways: first of all re-botteling the resin. We need to take in mind, that the quality of our resin will further degrade the longer it stays exposed to light (and to a lesser degree: air), so we need to handle the resin in a way that allows us to eliminate exposition to either. For this, it would be best to keep an empty resin bottle at hand and label it as the leftover bottle. To fill this bottle, you should use a <a href="https://www.thingiverse.com/search?q=resin%20vat&type=things&sort=relevant" rel="nofollow noreferrer">Jig</a> to keep the vat in a position that it pours into the bottle. You might want to use a funnel in some cases!</p>
<h2>Step 2: Re-conditioning</h2>
<p>Now, we know how to get the stuff back into the (B-quality) bottle. But how to make sure it has the best quality we can? As you notice, many of the jigs involve a funnel. This funnel is used in conjunction with a filter to remove larger particles. The finer the filter, the better. <a href="https://en.wikipedia.org/wiki/Coffee_filter#Paper_filter" rel="nofollow noreferrer">Coffee filters</a> manage to snatch particles down to about 10 to 15 micrometers. It is equivalent to about Grade 4 laboratory filter paper. However, laboratory filter paper of <a href="https://en.wikipedia.org/wiki/Filter_paper#Qualitative_filter_paper" rel="nofollow noreferrer">grades 1,2,3 or 602h</a> would allow to catch particles of even lower size, as the mesh gets even smaller, but might clog faster. Tea filters on the other hand have worse filtration ability and should be avoided.</p>
<p>To get the best out of it, use a filtration stack, that starts with a metal mesh filter before going through a rough and a fine filter to get out any chunks and large particles that would clog the fine filter.</p>
<p>It would be best to have this process run in the dark, so mounting the dripping and filtration stack in a box might first sound like overkill, but if you go through a large amount of resin (for example by running several printers) it might be an investment that can save a considerable amount of resin in the long run. However, if you run so many printers, you also might run them continually with the same resin colors and just refill them as needed and only filter if there had been a print failure.</p>
<h2>Step 3: Storage</h2>
<p>Store your bottles in a closed cupboard. It would be best if this cupboard is ventilated through a filtration unit and then outside. It should also keep a steady temperature above about 10 °C to prevent clumping. Just follow the storage manual for the normal resin actually.</p>
<h2>Step 4: Re-use</h2>
<p>Now comes the tricky part: re-using the resin. While technically the filtered and re-bottled resin should be almost as good as new, it would be best to make sure that we mix it with some virgin resin to make sure we have enough photoinitiator in the resin. For this, I would suggest mixing the recycled resin with between a sixth and half of the fresh stuff. Mix the two well to make sure you get the best possible. Make sure it's the same type and color of the used resin, best even from the same original batch.</p>
<p>Use up the re-cycled resin first, as you should consider it's best before date much shorter than on the virgin bottle.</p>
|
<p>Considerations for storing resin include using a light-tight bottle, preventing stray ultraviolet radiation from prematurely curing the resin.</p>
<p>You'll also note that users will filter the resin through a fine mesh filter. I've seen some videos in which the user pours through coffee filters to remove as many particulates as possible.</p>
<p>Left-over resin that has been carefully filtered is effectively the same as fresh-from-the-bottle material, from a purely technical view, but you can pick up contaminants that bypass the filter.</p>
| 1,753
|
<p>I have a product which has been traditionally shipped as an MSI file. It is deployed through some sort of SMS push to thousands of desktops by our various clients. The software we use to create these installers is getting long in the tooth and we are looking to replace it. We have already standardized on InstallAnywhere for most of our products as we support many operating systems. Unfortunately InstallAnywhere cannot produce MSI files. </p>
<p>I am wondering if it is required that SMS use MSI files or if it can handle other installer types (.exe). If not, are there any open source programmes for creating MSI files? </p>
|
<p>If your clients are using SMS then you're in the clear... SMS supports EXE. You enter a command line when creating 'Programs' and clients are probably already calling msiexec to launch the MSI. Also I'm pretty sure SMS predates the MSI file format :)</p>
<p>However if they're using <code>Active Directory / Group Policy Objects</code>.. then you're SOL as that does depend on MSI format for deployment.</p>
<p>If you do want to stick with InstallAnywhere, there are a number of "MSI repackaging" tools available. Assuming you're looking at a basic application (device drivers might be an issue) then repackaging should be a fairly painless process.</p>
|
<p>Actually, with group policies, there's the <code>ZAP</code> file alternative, but I would recommend regardless that you learn <code>MSI</code>. It's not that hard, and very flexible.</p>
| 4,175
|
<p>I want to make an etag that matches what Apache produces. How does apache create it's etags?</p>
|
<p>Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP:</p>
<pre><code>$fs = stat($file);
header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16)));
</code></pre>
|
<p>If you're dynamically generating your page though, this probably won't make sense. If you're in PHP, you can pick the inode and file size of the main script, but the modify time won't tell you if your data has changed. Unless you have a good caching process or just generate static pages, etags aren't helpful. If you do have a good caching process, the inode and file size are probably irrelevant.</p>
<p>Edit: For people who don't know what <a href="http://en.wikipedia.org/wiki/HTTP_ETag" rel="nofollow noreferrer">etag</a>s are - they're just supposed to be a value that changes when the content has changed, for caching purposes. The browser gets the etag from the web server, compares it to the etag for its cached copy and then fetches the whole page if the etag has changed.</p>
| 6,671
|
<p>We have a 42U rack which is getting a load of new 1U and 2U servers real soon. One of the guys here reckons that you need to leave a gap between the servers (of 1U) to aid cooling.</p>
<p>Question is, do you? When looking around the datacenter, no-one else seems to be, and it also diminishes how much we can fit in. We're using Dell 1850 and 2950 hardware.</p>
|
<p>Simply NO, the servers and switches, and KVMs, and PSUs are all designed to be on the rack stacked on top of eachother. I'm basing this on a few years building, COs and Data centers for AT&T.</p>
|
<p>The last two places I worked have large datacenters and they stack all their servers and appliances with no gaps. The servers have plenty of cooling with their internal fans. It is also recommended to run the rack on a raised floor with perforated tiles in the front of the rack and A/C air return above the rear of the racks for circulation.</p>
| 8,088
|
<p>We use COM objects to access excel spreadsheets in an NT service (via the Windows Scripting Host). Prior to Vista, this worked beautifully, but starting with Vista, we receive this error:</p>
<p>Microsoft Office Excel cannot access the file 'c:\myfiles\test.xls'. There are several possible reasons:</p>
<ul>
<li>The file name or path does not exist.</li>
<li>The file is being used by another program.</li>
<li>The workbook you are trying to save has the same name as a currently open workbook.</li>
</ul>
<p>I have tried changing the NT service logon settings to use my own account, an admin account and local system. I've looked through the Local Security Policy and have not found anything. I've spent days searching through the Microsoft KB to no avail.</p>
<p>If the script is executed from a console application, it works fine. The file opens and is processed with no problem. The error only occurs when executed from within the context of a service.</p>
<p>If the service is running on Windows XP or Server 2003 SP1, it also works fine. Only on Vista does it fail (and we've now gotten reports of it failing in Server 2003 SP2)!</p>
<p>The code, for what it is worth is exceptionally simple:</p>
<pre><code>dim xl_app
Set xl_app = CreateObject("Excel.Application")
xl_app.Workbooks.Open mypath,0,1
</code></pre>
<p>I suspect that this person might be experiencing the same issue:
<a href="http://bytes.com/forum/thread819740.html" rel="nofollow noreferrer"><a href="http://bytes.com/forum/thread819740.html" rel="nofollow noreferrer">http://bytes.com/forum/thread819740.html</a></a></p>
|
<p>just some further questions:</p>
<ul>
<li>Which version of Excel are you using? </li>
<li>Have you tried running the service with elevated privileges?</li>
</ul>
|
<p>I have "kind of" solved this problem. If you use "dcomcnfg" to change the account to launch the excel application to a user account or "interactive user" the excel launched from the service starts in that account and it now can access the file system.</p>
<p>The problem is this is a global setting. If you use:
* "this User": then excel ALWAYS opens with that user AND always opens up with no UI in session 0, even for interactive use of excel. IE its always invisible.
* "Interactive User": Now excel always launches in the interactive user accout which I don't think will work for a service which will launch on bootup with NO interactive user.</p>
<p>There must be some security setting on this. I hope others have other ideas. </p>
| 37,277
|
<p>Do any asynchronous connectors exist for Mysql that can be used within a C or C++ application? I'm looking for something that can be plugged into a <a href="http://en.wikipedia.org/wiki/Reactor_pattern" rel="noreferrer" title="reactor pattern">reactor pattern</a> written in <a href="http://www.boost.org/doc/libs/release/libs/asio/index.html" rel="noreferrer" title="Boost.Asio">Boost.Asio</a>.</p>
<p>[Edit:] Running a synchronous connector in threads is not an option.</p>
|
<p><a href="http://forums.mysql.com/read.php?45,183339,183339" rel="nofollow noreferrer">http://forums.mysql.com/read.php?45,183339,183339</a>
enjoy</p>
<p>Updated link to the original article showing how to do async mysql queries:</p>
<p><a href="http://jan.kneschke.de/projects/mysql/async-mysql-queries-with-c-api/" rel="nofollow noreferrer">http://jan.kneschke.de/projects/mysql/async-mysql-queries-with-c-api/</a></p>
|
<p>I think the only solution will be to create an asynchronous service that wraps a <a href="http://dev.mysql.com/downloads/connector/odbc/5.1.html" rel="nofollow noreferrer">standard connector</a>. You'll need to understand the ODBC APIs though.</p>
| 5,937
|
<p>I was always attracted to the world of kernel hacking and embedded systems.<br>
Has anyone got good tutorials (+easily available hardware) on starting to mess with such stuff?<br>
Something like kits for writing drivers etc, which come with good documentation and are affordable?</p>
<p>Thanks!</p>
|
<p>If you are completely new to kernel development, i would suggest not starting with hardware development and going to some "software-only" kernel modules like proc file / sysfs or for more complex examples filesystem / network development , developing on a uml/vmware/virtualbox/... machine so crashing your machine won't hurt so much :) For embedded development you could go for a small ARM Development Kit or a small Via C3/C4 machine, or any old PC which you can burn with your homebrew USB / PCI / whatever device.</p>
<p>A good place to start is probably <a href="http://kernelnewbies.org/" rel="noreferrer">Kernelnewbies.org</a> - which has lots of links and useful information for kernel developers, and also features a list of easy to implement tasks to tackle for beginners.</p>
<p>Some books to read:</p>
<p><a href="http://books.google.de/books?id=cbbMrRNiC4cC&dq=understanding+the+linux+kernel&pg=PP1&ots=TvUb8_r9Yd&sig=7Cn76JnJktn0B9cvLjh-pxFEdfo&hl=de&sa=X&oi=book_result&resnum=5&ct=result#PPP1,M1" rel="noreferrer">Understanding the Linux Kernel</a> - a very good reference detailing the design of the kernel subsystems</p>
<p><a href="http://lwn.net/Kernel/LDD3/" rel="noreferrer">Linux Device Drivers</a> - is written more like a tutorial with a lot of example code, focusing on getting you going and explaining key aspects of the linux kernel. It introduces the build process and the basics of kernel modules.</p>
<p><a href="http://www.tldp.org/LDP/lkmpg/2.6/html/" rel="noreferrer">Linux Kernel Module Programming Guide</a> - Some more introductory material</p>
<p>As suggested earlier, looking at the linux code is always a good idea, especially as Linux Kernel API's tend to change quite often ... LXR helps a lot with a very nice browsing interface - <a href="http://lxr.linux.no" rel="noreferrer">lxr.linux.no</a></p>
<p>To understand the Kernel Build process, this link might be helpful:</p>
<p><a href="http://www.ravnborg.org/kbuild/makefiles.html" rel="noreferrer">Linux Kernel Makefiles (kbuild)</a></p>
<p>Last but not least, browse the Documentation directory of the Kernel Source distribution!</p>
<p>Here are some interesting exercises insolently stolen from a kernel development class: </p>
<ul>
<li>Write a kernel module which creates the file /proc/jiffies reporting the current time in jiffies on every read access.</li>
<li>Write a kernel module providing the proc file /proc/sleep. When an application writes a number of seconds as ASCII text into this file ("echo 3 > /proc/sleep"), it should block for the specified amount of seconds. Write accesses should have no side effect on the contents of the file, i.e., on the read accesses, the file should appear to be empty (see LDD3, ch. 6/7)</li>
<li>Write a proc file where you can store some text temporarily (using echo "blah" > /proc/pipe) and get it out again (cat /proc/pipe), clearing the file. Watch out for synchronisation issues.</li>
<li>Modify the pipe example module to register as a character device /dev/pipe, add dynamic memory allocation for write requests.</li>
<li>Write a really simple file system.</li>
</ul>
|
<p>Some things to be prepared for:</p>
<ul>
<li>you'll be cross-compiling. The embedded device will use a MIPS, PowerPC, or ARM CPU but won't have enough CPU power, memory, or storage to compile its own kernel in a reasonable amount of time. </li>
<li>An embedded system often uses a serial port as the console, and to lower the cost there is usually no connector soldered onto production boards. Debugging kernel panics is very difficult unless you can solder on a serial port connector, you won't have much information about what went wrong. </li>
</ul>
<p>The <A HREF="http://www.nslu2-linux.org/" rel="nofollow noreferrer">Linksys NSLU2</A> is a low-cost way to get a real embedded system to work with, and has a USB port to add peripherals. Any of a number of wireless access points can also be used, see the <A HREF="http://wiki.openwrt.org/TableOfHardware" rel="nofollow noreferrer">OpenWrt compatibility page.</A> Be aware that current models of the Linksys WRT54G you'll find in stores can no longer be used with Linux: they have less RAM and Flash in order to reduce the cost. Cisco/Linksys now uses vxWorks on the WRT54G, with a smaller memory footprint.</p>
<p>If you really want to get into it, evaluation kits for embedded CPUs start at a couple hundred US dollars. I'd recommend not spending money on these unless you need it professionally for a job or consulting contract.</p>
| 8,575
|
<p>Does anyone know of a script that can select all text references to URLs and automatically replace them with anchor tags pointing to those locations?</p>
<pre><code>For example:
http://www.google.com
would automatically turn into
<a href="http://www.google.com">http://www.google.com</a>
</code></pre>
<p>Note: I am wanting this because I don't want to go through all my content and wrap them with anchor tags. </p>
|
<p><strong>NOTE:</strong> An updated and corrected version of this script is now available at <a href="https://github.com/maranomynet/linkify" rel="nofollow noreferrer">https://github.com/maranomynet/linkify</a> (GPL/MIT licence)</p>
<hr>
<p>Hmm... to me this seems like the perfect task for jQuery.</p>
<p>...something like this came off the top of my mind:</p>
<pre><code>// Define: Linkify plugin
(function($){
var url1 = /(^|&lt;|\s)(www\..+?\..+?)(\s|&gt;|$)/g,
url2 = /(^|&lt;|\s)(((https?|ftp):\/\/|mailto:).+?)(\s|&gt;|$)/g,
linkifyThis = function () {
var childNodes = this.childNodes,
i = childNodes.length;
while(i--)
{
var n = childNodes[i];
if (n.nodeType == 3) {
var html = $.trim(n.nodeValue);
if (html)
{
html = html.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(url1, '$1<a href="http://$2">$2</a>$3')
.replace(url2, '$1<a href="$2">$2</a>$5');
$(n).after(html).remove();
}
}
else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {
linkifyThis.call(n);
}
}
};
$.fn.linkify = function () {
return this.each(linkifyThis);
};
})(jQuery);
// Usage example:
jQuery('div.textbody').linkify();
</code></pre>
<p>It attempts to turn all occurrences of the following into links:</p>
<ul>
<li><code>www.example.com/path</code></li>
<li><code>http://www.example.com/path</code></li>
<li><code>mailto:me@example.com</code></li>
<li><code>ftp://www.server.com/path</code></li>
<li>...all of the above wrapped in angle brackets (i.e. <code><</code>...<code>></code>)</li>
</ul>
<p>Enjoy :-)</p>
|
<p>If you want a solution from another perspective... if you can run the pages through php and HTML Purifier, it can autoformat the output and linkify any urls.</p>
| 30,742
|
<p>Consider the case of a simple news article web application that has a DB table column of "Status" that is accessible by a radio button set of:</p>
<p>Status - [x] Publish [ ] Draft [ ] Archive</p>
<p>...where "Publish" shows an article publicly and "Draft" and "Archive" do not. Functionally "Draft" and "Archive" do the same thing but carry additional meta data meanings. The two functional states of "show" and "hide" along with the meta data of "publish", "draft" and "archive" are intermixed in the same column of "status".</p>
<p>Is this a good practice? While this is a very simple case, larger cases might reveal flaws with such a practice (or not...).</p>
|
<p>Functional states are about behavior - they do not need to be modeled in your database. If your business logic only cares about "showing" articles with a status of "Published" - there's no reason to double the complexity of your data with a Show column.</p>
<p>At the point that you decide your business logic needs <em>additional data</em> to make the decision whether to show or hide an article (perhaps an IsApproved flag), then you can store that data.</p>
<p>Looking at it from a different angle - if you were to add another column of "Show", then what would an article with a status of "Draft" and "Show" = 1 do? According to your business rules, that is an invalid state.</p>
|
<p>In this instance, I would say that this is the appropriate functionality.</p>
<p>We've all seen WTF's in the media where someone accidentally hit show[x]
and draft[x] at the same time.</p>
<p>The way it is now, it is impossible to accidentally show a draft. This is important in newspapers as reporters are notorious for stuff like:</p>
<p>John Doe, of StackOverflow said, "---I can't remember what that ugly f*cker said - Check the tape and fill in later"</p>
<p>Which probably shouldn't be printed.</p>
| 19,914
|
<p>It's possible to create digrams in SQL Server 2000 that can be useful to show the relationships between tables. The problem we run into is that when somebody refreshes our development database, the diagrams get lost. We can load tables, stored procedures, views, etc. with SQL scripts, but we have to create the diagrams by hand.</p>
<p>Is there a way to script out the diagrams? Or can they be saved outside of the database some other way?</p>
|
<p>It can be done for SQL Server 2005 - see <a href="http://www.codeproject.com/KB/database/ScriptDiagram2005.aspx" rel="nofollow noreferrer">here</a>.</p>
<p>And info. on SQL Server 2000 - <a href="http://bytes.com/forum/thread81534.html" rel="nofollow noreferrer">here</a>.</p>
|
<p>If you have Visio you can use the "Reverse Engineer" to diagram the DB.</p>
| 19,651
|
<p>We ship Java applications that are run on Linux, AIX and HP-Ux (PA-RISC). We seem to struggle to get acceptable levels of performance on HP-Ux from applications that work just fine in the other two environments. This is true of both execution time and memory consumption.</p>
<p>Although I'm yet to find a definitive article on "why", I believe that measuring memory consumption using "top" is a crude approach due to things like the shared code giving misleading results. However, it's about all we have to go on with a customer site where memory consumption on HP-Ux has become an issue. It only became an issue this time when we moved from Java 1.4 to Java 1.5 (on HP-Ux 11.23 PA-RISC). By "an issue", I mean that the machine ceased to create new processes because we had exhausted all 16GB of physical memory.</p>
<p>By measuring "before" and "after" total "free memory" we are trying to gauge how much has been consumed by a Java application. I wrote a quick app that stores 10,000 random 64 bit strings in an ArrayList and tried this approach to measuring consumption on Linux and HP-Ux under Java 1.4 and Java 1.5.</p>
<p>The results:</p>
<p>HP Java 1.4 ~60MB</p>
<p>HP Java 1.5 ~150MB</p>
<p>Linux Java 1.4 ~24MB</p>
<p>Linux Java 1.5 ~16MB</p>
<p>Can anyone explain why these results might arise? Is this some idiosyncrasy of the way "top" measures free memory? Does Java 1.5 on HP really consume 2.5 times more memory than Java 1.4?</p>
<p>Thanks.</p>
|
<p>I don't have a HP box right now to test my hypothesis. However, if I were you, I would use a profiler like JConsole(comes with JDK) OR yourkit to measure what is happening.</p>
<p>However, it appears that you started measuring after you saw something amiss; So, I'm NOT discounting that it's happening -- just pointing you at something I'd have done in the same situation.</p>
|
<p>First, it's not clear what did you measure by "10,000 random 64 bit strings" test. You supposed to start the application, measure it's bootstrap memory footprint, and then run your test. It could easily be that Java 1.5 acquires more heap right after start (due to heap manager settings, for instance).</p>
<p>Second, we do run Java apps under 1.4, 1.5 and 1.6 under HP-UX, and they don't demonstrate any special memory requirements. We have Itanium hardware, though.</p>
<p>Third, why do you use top? Why not just print Runtime.getRuntime().totalMemory()?</p>
<p>Fourth, by adding values to ArrayList you create memory fragmentation. ArrayList has to double it's internal storage now and then. Depending on GC settings and ArrayList.ensureCapacity() implementation the amount of non-collected memory may differ dramatically between 1.4 and 1.5.</p>
<p>Essentially, instead of figuring out the cause of problem you have run a random test that gives you no useful information. You should run a profiler on the application to figure out where the memory leaks.</p>
| 30,965
|
<p>I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and would like to port some Python code that I've written to Jython. In order to do this quickly, I need a NumPy clone for Jython (or Java). Is there anything like this out there?</p>
|
<p>I can't find anything that's a clone of numpy, but there's a long list of Java numerics packages <a href="http://math.nist.gov/javanumerics/" rel="noreferrer">here</a> - these should all be usable from Jython. Which one meets your requirements depends on what you're doing with numpy, I guess.</p>
|
<p>There is a build called JNumeric available on sourceforge:</p>
<p>The sourceforge version has not had a release in a long time, but it seems like an updated version for Jython 2.51 is also available (have not tried it myself):</p>
<p><a href="http://bitbucket.org/zornslemon/jnumeric-ra/downloads/" rel="nofollow noreferrer">http://bitbucket.org/zornslemon/jnumeric-ra/downloads/</a></p>
| 40,854
|
<p>I have the following style in an external CSS file called first.css</p>
<pre><code>table { width: 100%; }
</code></pre>
<p>This makes the tables fill their container. If there are only two small columns they appear too far from each other.</p>
<p>To force the columns to appear nearer I have added this style</p>
<pre><code>table { width: 50%; }
</code></pre>
<p>to a new file called second.css and linked it into the html file.</p>
<p>Is there any way to override the width property in first.css without the need to specify a width in second.css?</p>
<p>I would like the html behave as if there has never been a width property, but I do not want to modify first.css</p>
|
<p>You can use:</p>
<pre><code>table { width: auto; }
</code></pre>
<p>in second.css, to strictly make "the html behave as if there was never been a width property". But I'm not 100% sure this is exactly what you want - if not, please clarify!</p>
|
<p>You could also add a style="width: auto" attribute to the table - this way only the html of the page will be modified.</p>
| 20,820
|
<p>Hey I have a windows server running python CGI scripts and I'm having a little trouble with smtplib. The server is running python 2.1 (unfortunately and I can not upgrade it). Anyway I have the following code:</p>
<pre><code>session = smtplib.SMTP("smtp-auth.ourhosting.com", 587)
session.login(smtpuser, smtppass)
</code></pre>
<p>and it's giving me this error:</p>
<pre><code>exceptions.AttributeError : SMTP instance has no attribute 'login' : <traceback object at 006BB1D0>
</code></pre>
<p>I'm assuming this is because the <code>login()</code> method was added after python 2.1. so how do I fix this?</p>
<p>I have to either add the module by uploading the files to the same directory as the cgi script (though I believe smtplib is written in C and needs to be compiled which we can't do on this server)</p>
<p>OR</p>
<p>Do it whatever way is expected by the libsmtp in python 2.1.</p>
|
<p>login() was introduced in Python 2.2, unluckily for you! The only way to do it in Python 2.1's own smtplib would be to issue the AUTH commands manually, which wouldn't be much fun.</p>
<p>I haven't tested it fully but it seems Python 2.2's smtplib should more or less work on 2.1 if you copy it across as you describe (perhaps call it smtplib2.py). It's only a Python module, no C compilation should be necessary. However you will at least need to copy the hmac.py library it relies on from 2.2's lib as well. If you use a later Python version to steal from it starts requiring the email package too which might be more work.</p>
|
<blockquote>
<p>Do it whatever way is expected by the libsmtp in python 2.1</p>
</blockquote>
| 32,392
|
<p>Does anyone know how to solve this java error?</p>
<pre><code>java.io.IOException: Invalid keystore format
</code></pre>
<p>I get it when I try and access the certificate store from the Java option in control panels. It's stopping me from loading applets that require elevated privileges.</p>
<p><a href="http://img72.imageshack.us/my.php?image=javaerrorxq7.jpg" rel="nofollow noreferrer">Error Image</a></p>
|
<p>I was able to reproduce the error by mangling the trusted.certs file at directory</p>
<p><code>C:\Documents and Settings\CDay\Application Data\Sun\Java\Deployment\security</code>. </p>
<p>Deleting the file fixed the problem. </p>
|
<p>For you guys who can't find the 'Documents and Settings' (whatever reason there may be) here is another path where the trusted.certs can be found:</p>
<pre><code>C:\Users\<username>\AppData\LocalLow\Sun\Java\Deployment\security
</code></pre>
<p>Hope this helps!</p>
| 15,426
|
<p>My project has collected CSS entropy (unused classes) during its course of development.</p>
<p>Now in order to keep the CSS file small, I want to remove all unused CSS references. But doing that manually involves searching for each class in the entire project. That takes time.</p>
<p>Do you know of any way/tool which I can adopt to find out which CSS classes are no longer used in my project, and remove it?</p>
<p>I am programming on ASP.NET. Visual Studio.</p>
|
<p>You might find this Firefox extension useful: <a href="http://www.sitepoint.com/dustmeselectors/" rel="noreferrer">http://www.sitepoint.com/dustmeselectors/</a></p>
|
<p>I wrote a tool which allows you to find all class and CssClass attributes in your aspx source code.</p>
<p>See my <a href="http://devio.wordpress.com/2008/04/21/checking-aspnet-source-code-with-graspx-part-2/" rel="noreferrer">blog entry</a> for info and download.</p>
| 38,185
|
<p>Back in the scripted ASP and ColdFusion days, I used to work on projects that would build code generators for ASP or Coldfusion, typically in C++, in order to be more object oriented in application design and not have developers writing scripted code, which often was called "spaghetti code" for it's size and complexity.</p>
<p>Since I've been coding asp.net since 2000, I haven't really had to deal with the issue at all, since the platform is not scripted.</p>
<p>I may be working on PHP projects in the future, and I was wondering if any code generators for PHP exist, or if any good references for building these generators exist.
It would be for the Linux platform, not targeted to Win2008 Servers running PHP.</p>
|
<p>Why not just build a proper app in PHP instead of going through the hassle? Recent PHP is <a href="http://us2.php.net/manual/en/language.types.object.php" rel="nofollow noreferrer">fully object-oriented</a> and lets you do some pretty decent stuff. There are even <a href="https://stackoverflow.com/questions/20709/which-php-framework-will-get-me-to-a-usable-ui-the-fastest">frameworks</a> that help you do this kind of stuff.</p>
|
<p>It's better that you learned good development practices in PHP than use code-generators. PHP might be a scripting language but it is quite potent, has a nice <a href="http://www.php.net/zend-engine-2.php" rel="nofollow noreferrer">OO</a> model, <a href="http://www.cakephp.org/" rel="nofollow noreferrer">plenty</a> of <a href="http://framework.zend.com/" rel="nofollow noreferrer">good</a> <a href="http://solarphp.com/" rel="nofollow noreferrer">frameworks</a> and other open-source packages.</p>
<p>It's up to the developer to create well designed and factored code base, regardless of whether it's compiled at run-time or not.</p>
| 47,188
|
<p>Have a use case wherein need to maintain a connection open to a database open to execute queries periodically. </p>
<p>Is it advisable to close connection after executing the query and then reopen it after the period interval (10 minutes). I would guess no since opening a connection to database is expensive.</p>
<p>Is connection pooling the alternative and keep using the connections?</p>
|
<p>You should use connection pooling. Write your application code to request a connection from the pool, use the connection, then return the connection back to the pool. This keeps your code clean. Then you rely on the pool implementation to determine the most efficient way to manage the connections (for example, keeping them open vs closing them).</p>
<p>Generally it is "expensive" to open a connection, typically due to the overhead of setting up a TCP/IP connection, authentication, etc. However, it can also be expensive to keep a connection open "too long", because the database (probably) has reserved resources (like memory) for use by the connection. So keeping a connection open can tie-up those resources.</p>
<p>You don't want to pollute your application code managing these types of efficiency trade-offs, so use a connection pool.</p>
|
<p>Connection pooling would be an option for you. You can then leave your code as it is including opening and closing connections. The connection pool will care about the connections. If you close a connection of a pool it will not be closed but just be made available in the pool again. If you open a connection after you closed one if there is a open connection in the pool the pool will return this. So in an application server you can use the build-in connection pools. For simple java applications most of the JDBC drivers also include a pool driver. </p>
| 45,298
|
<p>I'm trying to use stl algorithm for_each without proliferating templates throughout my code. std::for_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate.</p>
<p>My Question: </p>
<p>Does the STL or Boost already have such an adapter class? I don't want to have to reinvent the wheel!</p>
<pre><code> struct MyFunctor {
virtual ~MyFunctor() {}
virtual void operator()(int a) = 0;
}
namespace {
template<typename FunctorType, typename OperandType> struct
FunctorAdapter
{
FunctorAdapter(FunctorType* functor) : mFunctor(functor) {}
void operator()(OperandType& subject)
{
(*mFunctor)(subject);
}
FunctorType* mFunctor;
}; }
void applyToAll(MyFunctor &f) {
FunctorHelper<MyFunctor, int> tmp(&f);
std::for_each(myvector.begin(), myvector.end(), tmp); }
</code></pre>
<p>Cheers,</p>
<p>Dave </p>
|
<p>You could use the function adapters (and their shims) from <code>functional</code>.</p>
<pre><code>#include <functional>
using namespace std;
for_each( vec.begin(), vec.end(), :mem_fun_ptr( &MyClass::f ) );
</code></pre>
<p>If your container contains pointers-to-objects, use <code>mem_fun_ptr</code>, else use <code>mem_fun</code>. Next to these, there are wrappers for member functions that take 1 argument: <code>mem_fun1_ptr</code> and <code>mem_fun1</code>.</p>
<p>@Evan: indeed, you could call the member function with the same argument for each object. The first argument of the <code>mem_fun1</code> wrappers is the <code>this</code> pointer, the second is the member function argument:</p>
<pre><code>for_each( vec.begin(), vec.end(), bind2nd( mem_fun_ptr( &MyClass::f ), 1 ) );
</code></pre>
<p>With more arguments, it becomes more readable to create a loop yourself, or create a custom functor that has const member variables representing the arguments.</p>
|
<p>What about forgetting all the wrapping of the functor pointer, and instead use
<code>bind(functor_pointer,mem_fun1(&MyFunctor::operator());
</code>
as the functor? that way, you don't have to worry about managing the copy in any way shape or form.</p>
| 26,969
|
<p>how do you handle them?</p>
|
<p>In domain names, you can do use IDN domains, if they are supported by the registrars you want to register them with.</p>
<p>Elsewhere in the URL, they are generally sent by the browser as utf8 urlencoded. Only recently I was looking at:</p>
<p><a href="http://en.wikipedia.org/wiki/Pfeffern%C3%BCsse" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Pfeffern%C3%BCsse</a></p>
<p>And found it curious that there was a ü in the URL. Firefox shows it as a proper character though.</p>
|
<p>The problem with those names is that they are easily confused with other characters. So I should need a very good reason to use them. For example if your company name is "Schröder", I would use both schröder.com, schroder.com and even schroeder.com, the extra cost is justified because it is just to easy to create a malicious name.</p>
| 42,651
|
<p>I'm working on a Rails app and am looking to include some functionality from "<a href="https://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails">Getting the Hostname or IP in Ruby on Rails</a>" that I asked.</p>
<p>I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents:</p>
<pre><code>require 'socket'
module GetIP
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
</code></pre>
<p>I had also tried defining GetIP as a class but when I do the usual <code>ruby script/console</code>, I'm not able to use the <code>local_ip</code> method at all. Any ideas?</p>
|
<p>You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know.</p>
<p>The methods on a module never come into use unless the module is included into a class. Instance methods on a class require there to be an instance of the class. You probably want a class method instead. And the file itself should be loaded, generally through the require statement.</p>
<p>If the following code is in the file getip.rb,</p>
<pre><code>require 'socket'
class GetIP
def self.local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
</code></pre>
<p>Then you should be able to run it by saying,</p>
<pre><code>require 'getip'
GetIP.local_ip
</code></pre>
|
<p><code>require</code> and <code>include</code> are two different things.</p>
<p><code>require</code> is to strictly load a file once from a load path. The loadpath is a string and this is the key used to determine if the file has already been loaded.</p>
<p><code>include</code> is used to "mix-in" modules into other classes. <code>include</code> is called on a module and the module methods are included as instance methods on the class.</p>
<pre><code> module MixInMethods
def mixed_in_method
"I'm a part of #{self.class}"
end
end
class SampleClass
include MixInMethods
end
mixin_class = SampleClass.new
puts my_class.mixed_in_method # >> I'm a part of SampleClass
</code></pre>
<p>But many times the module you want to mix in is not in the same file as the target class. So you do a <code>require 'module_file_name'</code> and then inside the class you do an <code>include module</code>. </p>
| 6,709
|
<p>I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?</p>
|
<p><a href="http://en.wikipedia.org/wiki/Topological_sorting" rel="noreferrer">Topological Sort</a> (From Wikipedia):</p>
<blockquote>
<p>In graph theory, a topological sort or
topological ordering of a directed
acyclic graph (DAG) is a linear
ordering of its nodes in which each
node comes before all nodes to which
it has outbound edges. Every DAG has
one or more topological sorts.</p>
</blockquote>
<p>Pseudo code:</p>
<pre><code>L ← Empty list where we put the sorted elements
Q ← Set of all nodes with no incoming edges
while Q is non-empty do
remove a node n from Q
insert n into L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into Q
if graph has edges then
output error message (graph has a cycle)
else
output message (proposed topologically sorted order: L)
</code></pre>
|
<p>I would expect tools that need this simply walk the tree in a depth-first manner and when they hit a leaf, just process it (e.g. compile) and remove it from the graph (or mark it as processed, and treat nodes with all leaves processed as leaves).</p>
<p>As long as it's a DAG, this simple stack-based walk should be trivial.</p>
| 2,617
|
<p>I'm currently working on someone else's database where the primary keys are generated via a lookup table which contains a list of table names and the last primary key used. A stored procedure increments this value and checks it is unique before returning it to the calling 'insert' SP.</p>
<p>What are the benefits for using a method like this (or just generating a GUID) instead of just using the Identity/Auto-number?</p>
<p>I'm not talking about primary keys that actually 'mean' something like ISBNs or product codes, just the unique identifiers.</p>
<p>Thanks.</p>
|
<p>An auto generated ID can cause problems in situations where you are using replication (as I'm sure the techniques you've found can!). In these cases, I generally opt for a GUID.</p>
<p>If you are not likely to use replication, then an auto-incrementing PK will most likely work just fine.</p>
|
<p>The only real reason to do this is to be database agnostic (if different db versions use different auto-numbering techniques).</p>
<p>The other issue mentioned here is the ability to create records in multiple places (like in the central office as well as on traveling users' laptops). In that case, though, you would probably need something like a "sitecode" that was unique to each install that was prefixed to each ID.</p>
| 32,867
|
<p>I have a key that appears to be an empty string, however using <code>unset($array[""]);</code> does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.</p>
<p>The line for the element on a print_r is <code>[] => 1</code>, which indicates to me that the key is the empty string.</p>
<p>Using var_export, the element is listed as <code>'' => 1</code>.</p>
<p>Using var_dump, the element is listed as <code>[""]=>int(1)</code>.</p>
<p>So far, I have tried all of the suggested methods of removal, but none have removed the element. I have tried <code>unset($array[""]);</code>, <code>unset($array['']);</code>, and <code>unset($array[null]);</code> with no luck.</p>
|
<p>Try <code>unset($array[null]);</code></p>
<p>If that doesn't work, print the array via <code>var_export</code> or <code>var_dump</code> instead of <code>print_r</code>, since this allows you to see the type of the key. Use <code>var_export</code> to see the data in PHP syntax.</p>
<p><code>var_export($array);</code></p>
<p>Note that var_export does not work with recursive structures.</p>
|
<p>Please post the code you use to remove the element as well your checker code before and after that line.</p>
<p>What I'm looking for is something like this:</p>
<pre><code>var_export($array);
echo "\n";
unset($array[""]);
var_export($array);
</code></pre>
<p>Please also post the complete output of both <code>var_export</code> lines.</p>
<p>I'm looking for something like this:</p>
<pre><code>array (
'' => 1,
)
array (
)
</code></pre>
| 30,116
|
<p>I planning on getting a resin 3d printer kit, and I don't want to take any risks building it myself. Where, or who, could I hire a professional capable of constructing a 3D printer kit? They don't necessarily have to specialize in constructing 3d printers, I just need someone qualified with the mechanical and technical skills for the job.</p>
|
<p>If you have a makerspace in your area, you'll likely find individuals with reasonable mechanical skills suitable for simple kit assembly. Most kits are engineered to be reasonable assembly, not rocket surgery. Makers are by nature capable of construction, often from raw materials, and kits are typically not particularly challenging comparatively speaking.</p>
<p>Resin 3D printers are also simple in construction, as the component count is less than that of an FDM printer, or quite close in count. SLA designs involve laser modules, mirrors and alignment, while DLP designs involve light projection and light masking. Both designs involve vats and movement mechanics.</p>
<p>Even if you do not have a makerspace local to you, consider to contact one that might be nearer than farther away, as those spaces may have leads for you to locate a suitable victim/candidate.</p>
<p>Our local library makerspace often farms out contacts to me or other makers with the necessary skills to meet a patron's requirements.</p>
|
<p>I agree that a local makerspace is a good option, but I will say this...</p>
<p>Buying a kit and building it yourself, even with some frustration and learning curves, will help immensely with your ability to calibrate and troubleshoot issues later. If someone else builds it for you, chances are if something goes wrong, you'll need to seek out that person for help fixing things.</p>
<p>I just recently bought my first 3D printer (FDM) as a kit. Building it was a slight learning curve - I'm a technophile and have built things with Arduino before, but never a printer and the specifics that come along with it. Getting it to actually print reliably took me about two weeks. However, I'm MUCH more confident now to take care of issues as they arise, and keep it running smoothly. The value of this experience can not be overstated.</p>
| 719
|
<p>I need to be able to validate a string against a list of the possible United States Postal Service state abbreviations, and Google is not offering me any direction. </p>
<p>I know of the obvious solution: and that is to code a horridly huge if (or switch) statement to check and compare against all 50 states, but I am asking StackOverflow, since there has to be an easier way of doing this. Is there any RegEx or an enumerator object out there that I could use to quickly do this the most efficient way possible?</p>
<p>[C# and .net 3.5 by the way]</p>
<p><a href="https://www.usps.com/send/official-abbreviations.htm" rel="noreferrer">List of USPS State Abbreviations</a></p>
|
<p>I like something like this:</p>
<pre><code>private static String states = "|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|";
public static bool isStateAbbreviation (String state)
{
return state.Length == 2 && states.IndexOf( state ) > 0;
}
</code></pre>
<p>This method has the advantage of using an optimized system routine that is probably using a single machine instruction to do the search. If I was dealing with non-fixed length words, then I'd check for "|" + state + "|" to ensure that I hadn't hit a substring instead of full match. That would take a wee bit longer, due to the string concatenation, but it would still match in a fixed amount of time. If you want to validate lowercase abbreviations as well as uppercase, then either check for state.UpperCase(), or double the 'states' string to include the lowercase variants.</p>
<p>I'll guarantee that this will beat the Regex or Hashtable lookups every time, no matter how many runs you make, and it will have the least memory usage.</p>
|
<p>I know this is really old, but I came to see if there was a better solution than I came up with back in the 80's. In C it'd be something like (untested code):</p>
<pre class="lang-c prettyprint-override"><code>/* assumes 2 letter code is in upper case, returns 1 if valid or 0 if not */
int validate_state( const char *state )
{
if (state[0] == ' ' || state[1] == ' ' || state[2] != '\0') return 0;
return strstr("WVALAKSCARIDE CTNVTX NHINMNCOKY MSD MIA MOR WIL GAZ FL ME MD MA MT NE NJ NY ND OH PA UT WA WY", state) ? 1 : 0;
}
</code></pre>
<p>That could be written like this in C#:</p>
<pre class="lang-cs prettyprint-override"><code>/* assumes 2 letter code is in upper case */
bool ValidateState(string state)
{
const string ValidStatesMerged = "WVALAKSCARIDE CTNVTX NHINMNCOKY MSD MIA MOR WIL GAZ FL ME MD MA MT NE NJ NY ND OH PA UT WA WY";
if (state == null)
throw new ArgumentNullException(nameof(state));
if (state.Length != 2 || state[0] == ' ' || state[1] == ' ')
return false;
return ValidStatesMerged.IndexOf(state) >= 0;
}
</code></pre>
<p>As long as the <code>state</code> string is in all caps, this uses no regex but only simple string functions. The trick is to make sure there are no invalid combos in there, but that's easy enough if you start with the list and re-arrange them so the end of one is the beginning of the next, like <code>"WV"</code> then <code>"VA"</code>, then remove the dupe letter so you end up with <code>"WVA"</code> ... continue until they're all in and hopefully the shortest string you can make.</p>
<p>It's not hard to adapt that to other languages; I need it in a bash script and will use a Perl command to do that with the above "search string".</p>
| 21,215
|
<p>I am using tinyMCE and, rather annoyingly, it replaces all of my apostrophes with their HTML numeric equivalent. Now most of the time this isn't a problem but for some reason I am having a problem storing the apostrophe replacement. So i have to search through the string and replace them all. Any help would be much appreciated</p>
|
<p>did you try:</p>
<pre><code>$string = str_replace("&#39;", "<replacement>", $string);
</code></pre>
|
<p>Why work around the problem when you can fix the cause? You can just turn of the TinyMCE entity encoding*. More info: <a href="http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/entity_encoding" rel="nofollow noreferrer">here</a></p>
<p>*Unless you want all the other characters encoded, that is.</p>
| 39,731
|
<p>I have recently been working with Python using Komodo Edit and other simpler editors but now I am doing a project which is to be done in C# using VS 08. I would appreciate any hints on how to get productive on that platform as quickly as possible.</p>
|
<p>As far as becoming proficient with C# I would highly recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0596527438" rel="nofollow noreferrer" rel="nofollow noreferrer">Programming C#</a> and <a href="https://rads.stackoverflow.com/amzn/click/com/1933988363" rel="nofollow noreferrer" rel="nofollow noreferrer">C# in Depth</a>.</p>
<p>For Visual Studio, start poking around in the IDE a lot, play around, get familiar with it. Start with simple projects and explore all the different aspects. Learn how to <a href="https://stackoverflow.com/questions/8440/visual-studio-optimizations">optimize Visual Studio</a> and get familiar with some of the great <a href="https://stackoverflow.com/questions/98606/favorite-visual-studio-keyboard-shortcuts">keyboard shortcuts / hidden features</a> of the IDE.</p>
<p>Definitely do each of the following at least once:</p>
<p><strong>Projects:</strong></p>
<ul>
<li>Create a simple console application (e.g. hello world)</li>
<li>Create a class library (managed .dll) and use it from another application you create</li>
<li>Create a simple windows application</li>
<li>Create a simple asp.net web app</li>
</ul>
<p><strong>Debugging:</strong></p>
<ul>
<li>Debug a command line app</li>
<li>Get familiar with: breakpoints, the locals and watch windows, step over, step into, step out of, continue, stop debugging</li>
<li>Create a command line app which uses a function in a class library. Store the dll and symbol file (.pdb) for the library but delete the source code, debug through app as it goes into the library</li>
<li>Debug into a webservice</li>
<li>Learn how to use ILDasm and ILAsm</li>
</ul>
<p><strong>Command Line:</strong></p>
<ul>
<li>Get familiar with the Visual Studio command line environment</li>
<li>Build using only the command line</li>
<li>Debug from the command line using devenv.exe /debugexe</li>
<li>Use ILDasm / ILAsm from the command line to disassemble a simple app into .IL, reassemble it into a differently named file, test to see that it still works</li>
</ul>
<p><strong>Testing:</strong></p>
<ul>
<li>Create unit tests (right click in a method, select the option to create a test)</li>
<li>Learn how to: run all unit tests, run all unit tests under the debugger, rerun failed unit tests, see details on test failures, run a subset of unit tests</li>
<li>Learn how to collect code coverage statistics for your tests</li>
</ul>
<p><strong>Source Control:</strong></p>
<ul>
<li>Learn how to interact with your source control system of choice while developing using VS</li>
</ul>
<p><strong>Refactoring et al:</strong></p>
<ul>
<li>Become familiar with all of the built-in refactorings (especially rename and extract method)</li>
<li>Use "Go To Definition"</li>
<li>Use "Find All References"</li>
<li>Use "Find In Files" (ctrl-shift-F)</li>
</ul>
<p><strong>IDE & Keyboard Shortcuts:</strong></p>
<ul>
<li>Learn how to use the designer well for web and winforms</li>
<li>Get very familiar with the Solution Explorer window</li>
<li>Experiment with different window layouts until you find one your comfortable with, keep experimenting later to see if that's still the best choice</li>
<li>Learn the ins and outs of intellisense, use it to your advantage as much as possible</li>
<li>Learn the keyboard shortcut for everything you do</li>
</ul>
|
<p>Do small mini projects. Some of the top of my head.</p>
<p>1) Hello world <br>2) Console <br>3) GUI
design <br>4) Toy project<br></p>
<p>They're going to bring you up faster to speed than reading a tutorial. Grab a beer and have fun.</p>
| 19,482
|
<p>We have a domain which we are already blogging on in:
blog.domain.com</p>
<p>There are obviously pointers to the actual website at www.domain.com. I already see it in the google index but I'm worried google will think poorly of it when we launch because it says "Under Construction" or "Coming soon".</p>
<p>Are there any HTTP headers or practices to help medicate this?</p>
|
<p>Use HTTP status <strong>503</strong> for '<em>Service Temporarily Unavailable</em>' - see Google's HTTP status list for more information:
<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40132" rel="nofollow">http://www.google.com/support/webmasters/bin/answer.py?answer=40132</a></p>
<p>More related information on recommended ways of dealing with planned downtime: <a href="http://googlewebmastercentral.blogspot.com/2011/01/how-to-deal-with-planned-site-downtime.html" rel="nofollow">http://googlewebmastercentral.blogspot.com/2011/01/how-to-deal-with-planned-site-downtime.html</a></p>
|
<p>I would go ahead an give a description of the site you expect to be there one day, so that Google can begin getting an idea of what your site is about. </p>
<p>I'm basing this mostly on the widely-held belief that Google makes new sites <a href="http://en.wikipedia.org/wiki/Sandbox_Effect" rel="nofollow noreferrer">wait a while before indexing them with competitive terms.</a></p>
| 49,733
|
<p>It seems that Silverlight/WPF are the long term future for user interface development with .NET. This is great because as I can see the advantage of reusing XAML skills on both the client and web development sides. But looking at WPF/XAML/Silverlight they seem very large technologies and so where is the best place to get start?</p>
<p>I would like to hear from anyone who has good knowledge of both and can recommend which is a better starting point and why.</p>
|
<p>Should you learn ASP.NET or Winforms first? ASP or MFC? HTML or VB? C# or VB? </p>
<p>Set aside the idea that there is a logical progression through what has become a highly complex interwoven set of technologies, and take a step back and ask yourself a series of questions:</p>
<ul>
<li>What are your goals; how do you want to balance profit against enjoyment</li>
<li>Are you short term oriented or in for the long haul</li>
<li>Are you the type of person who likes to get good at something and do it a lot or do you get bored once you fully understand it?</li>
</ul>
<p>The next and hardest step is to come to accept that any advice you are given is bound to be wrong; and the longer the time horizon the more likely it is to be incorrect. If the advice is for more than six to 12 months, the probability the advice is wildly incorrect approaches 1. </p>
<p>I can only tell you my story, quickly. In 2000 I was happy as a consultant working profitably in C++ on Windows applications, writing about ASP.NET and WinForms. then I saw C# and the world turned upside down. I never went back. </p>
<p>Two years ago I had the same kind of revelation, only an order of magnitude bigger, stronger and with more conviction about Silverlight. Yes, WPF is magnificent, and it may be that I'm all wet about this, but I believe in my gut that Silverlight changes everything. There was no doubt then and there is no doubt today that Silverlight is the most important development platform for Microsoft since .NET (certainly) and possibly since the switch to C++. </p>
<p>In a nutshell, here is why. I don't understand where its limitations are. With most platforms I do: you can do this, but you can't do that. WPF is a pretty good case in point, as was ASP.Net and WinForms and, well really everything until now.<br>
With Silverlight, I don't see the boundaries yet. Silverlight has already leaped off the desktop onto phones, and I don't see any reason for it to stop there. Yes, it is true, it is bound by the browser, but I see that less as a jail cell than as a tank in which Silverlight will be riding over lots of terrain (it must be very late, I should go to bed). </p>
<p>In any case, for now, learning Silverlight is a gas, there is a lot of material on the <a href="http://www.silverlight.net/" rel="noreferrer">Silverlight.net site</a>, and what is the very best thing about learning Silverlight is that if you don't see what you need you can holler at me and I'll make sure you get it pretty quickly.</p>
<p>Enjoy, good luck and the dirty little secret is you'll be fine whichever you choose. It's all just software.</p>
<p>-jesse</p>
<hr>
<p>Jesse Liberty
<a href="http://jesseliberty.com/" rel="noreferrer">"Silverlight Geek"</a></p>
|
<p>Some tips at <a href="https://stackoverflow.com/questions/60620/getting-started-with-silverlight-development">Getting started with Silverlight Development</a></p>
| 8,647
|
<p>I have a specific scenario in mind, but I will ask this generally:</p>
<p><strong>Is there a way to make my mobile phone trigger an action on my computer?</strong> I am thinking that with a smart phone it must be possible to link the phone and the personal computer with bluetooth, and have some sort of small program running on my computer that will listen for incoming phone calls on the phone. When someone calls me, I want my mobile to simply submit the callers phone number to the personal computer, and then the personal computer will do its stuff from there. Then, I want to handle the call on the mobile phone as usual.</p>
<p><strong>Edit</strong>:<br></p>
<p>Updated this question! I am currently using the HTC Hero, and hopefully the Android SDK will make this more easy to accomplish.</p>
<p><strong>My specific scenario was:</strong><br></p>
<p>When my phone (Nokia N82) calls, i want to submit the callers <code>phonenumber</code> to a search <em>applet/application</em>, that will query <em>Microsoft Dynamics CRM</em> and see if a contact person or a company has that <code>phonenumber</code>, and if so, show the corresponding person or companys info on my screen. My preferred development platform is .NET Framework.</p>
|
<p>The N82 runs Symbian, so you could develop an application that used the CTelephony (C++) class to detect the phone status and do whatever you want with it. You have an example here</p>
<p><a href="http://www.symbian.com/developer/techlib/v9.1docs/doc_source/guide/Telephony-subsystem-guide/N1013A/answer.html" rel="noreferrer">http://www.symbian.com/developer/techlib/v9.1docs/doc_source/guide/Telephony-subsystem-guide/N1013A/answer.html</a></p>
|
<p>I know you certainly can't do this on an iphone.</p>
<p>Regarding a nokia n82, I'm not sure if symbian (that's what they use isn't it?) provides developer hooks for things like phone calls, but I wouldn't be at all surprised if it didn't. Phone calls fall in the category of "we really <em>really</em> don't want third parties to screw this up, so it's off limits"</p>
| 37,617
|
<p>I have a button on a website that creates a directory and copys a file. I developed it using Visual Studio 2008, ASP.Net 3.5. I am running Vista as my OS. The website uses identiy impersonation.</p>
<p>The functionality doesn't work ("Access to Path XYZ is denied") when:</p>
<ul>
<li>I run the website via IE hitting the local webserver</li>
</ul>
<p>The functionality works fine when [note Visual Studio run with Admin rights]:</p>
<ul>
<li>I hit play in Visual Studio </li>
<li>I say view in Browser from Visual Studio</li>
<li>I run the website via IE hitting the local webserver, but start IE with Admin rights</li>
<li>I deploy the website onto another webserver (also vista/IIS7)</li>
<li>I modify FireFox to accept integrated authentication, then access via FireFox and localhost</li>
</ul>
<p>I've never seen this behavior before, previously File.Copy type commands only cared that the rights on the folder being copied to were valid etc... (I have Everyone having full control while trying to debug this situation). It seems likely that the issue is having Admin rights or not? Or being logged in to the machine that it is running on?</p>
<p>What is happening here? Why does it work in the development environment and deployed to another machine, but not work when deployed on my own machine? Seems very odd, any help would be appreciated.</p>
<p><strong>EDIT</strong>: I've added "Everyone" to all of the relvant directories and give that user Full Control, so there shouldn't be any permission issues?</p>
|
<p>OK I have tracked down the solution to this issue given these symptoms. I'm not 100% sure why this works (particularly since it works fine in FireFox and works fine in IE if you not connecting locally), but the following seems to be a work-around.</p>
<p>In IE select Tools -> Internet Options -> Security -> Trusted Sites -> Sites and add <a href="http://localhost" rel="nofollow noreferrer">http://localhost</a> as a trusted site. This then enables you to use the website locally. Why you need to do this in IE when connecting locally and not in FireFox or IE when connecting to another machine is something I don't know. But it does seem to be a viable workaround.</p>
|
<p>My guess is the identity ASP.Net is running under doesn't have permissions (NetworkService) or the user used for anonymous authentication does have permission (IUSR)</p>
| 48,398
|
<p>I set up a website to use SqlMembershipProvider as written on <a href="http://msdn.microsoft.com/en-us/library/ms998347.aspx" rel="nofollow noreferrer">this page</a>.</p>
<p>I followed every step. I have the database, I modified the Web.config to use this provider, with the correct connection string, and the authentication mode is set to Forms. Created some users to test with.</p>
<p>I created a Login.aspx and put the Login control on it. Everything works fine until the point that a user can log in. </p>
<p>I call Default.aspx, it gets redirected to Login.aspx, I enter the user and the correct password. No error message, nothing seems to be wrong, but I see again the Login form, to enter the user's login information. However if I check the cookies in the browser, I can see that the cookie with the specified name exists.</p>
<p>I already tried to handle the events by myself and check, what is happening in them, but no success.</p>
<p>I'm using VS2008, Website in filesystem, SQL Express 2005 to store aspnetdb, no role management, tested with K-Meleon, IE7.0 and Chrome.</p>
<p>Any ideas?</p>
<p><strong>Resolution:</strong> After some mailing with Rob we have the ideal solution, which is now the accepted answer.</p>
|
<p>I have checked the code over in the files you have sent me (thanks again for sending them through).</p>
<p><strong>Note: I have not tested this since I have not installed the database etc..</strong></p>
<p>However, I am pretty sure this is the issue.</p>
<p>You need to set the <em>MembershipProvider</em> Property for your ASP.NET controls. Making the definitions for them:</p>
<pre><code><asp:Login ID="Login1" runat="server"
MembershipProvider="MySqlMembershipProvider">
<LayoutTemplate>
<!-- template code snipped for brevity -->
</LayoutTemplate>
</asp:Login>
</code></pre>
<p>And..</p>
<pre><code><asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
MembershipProvider="MySqlMembershipProvider">
<WizardSteps>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
</code></pre>
<p>This then binds the controls to the Membership Provider with the given name (which you have specified in the Web.Config.</p>
<p>Give this a whirl in your solution and let me know how you get on.
I hope this works for you :)</p>
<h3>Edit</h3>
<p>I should also add, I know you shouldn't need to do this as the default provider is set, but I <em>have</em> had problems in the past with this.. I ended up setting them all to manual and all worked fine.</p>
|
<p>Have you checked that the redirect path is being sent to the login form? Off my head I think it is <strong>ReturnURL</strong>?</p>
| 8,735
|
<p>I have a question about loops in flash....</p>
<p>In a tile game I'm making a have a mini map of the whole level. The way it renders the map is a function with a for loop in another for loop. It cycles through each tile position and attaches a map piece (basically a 3x3 pixel square) which is colored according to what the tile is. Anyway, my problem is that when the level gets big like 50x50 tiles the map redering takes forever (up to 3 seconds). Is there anyway to fix this? Or is there another way of doing a mini-map?? If the level gets ever bigger it could take like 10 seconds!</p>
<p>Any help is appreciated!</p>
<p>Thanks,
Matt</p>
|
<p>Flash doesn't render tiles very fast. It's great at storing graphics that don't change in a buffer and quickly displaying this buffer quickly. Every graphics object (or sprite) that is added as a child to the stage has to be rendered independently.</p>
<p>Your problem is flash has to draw 50x50 = 2500 tiles every frame! Even if they 3x3 pixels, flash still treats them as separate objects.</p>
<p>It would be nice if you could store everything in a buffer or in one object and display it. So try drawing these 3x3 tiles in the same object instead of multiple objects. However this might hinder your functionality as the whole object will have to be re-rendered every frame.</p>
<p>Some other suggestions might be to render the objects in larger cells on a grid. Instead of having 50x50, start with 10x10 and then draw 5x5 cells in each cell. This would probably speed things up.</p>
<p>Hope this helps. If you find a good solution please post!</p>
|
<p>It shouldn't take long for the loops themselves to run, but what, exactly, are you doing inside each loop? What are the operations for attaching and coloring a map piece?</p>
<p>-Adam</p>
| 18,912
|
<p>I know how to draw basic objects using JOGL or LWJGL to connect to OpenGL. What I would like is something that can generate some kind of geometry for trees, similar to what SpeedTree is famous for. Obviously I don't expect the same quality as SpeedTree.</p>
<p>I want the trees to not look repetitive. Speed is not a concern, I do not expect to need more than 100 trees on screen at one time. </p>
<p>Are there free tree-drawing libraries available in Java? Or sample code or demos?
Is there anything in other languages which I could port or learn from?</p>
|
<p><a href="http://arbaro.sourceforge.net/" rel="nofollow noreferrer">http://arbaro.sourceforge.net/</a></p>
<p><a href="http://www.propro.ru/go/Wshop/povtree/povtree.html" rel="nofollow noreferrer">http://www.propro.ru/go/Wshop/povtree/povtree.html</a></p>
<p>Non java: <a href="http://www.aust-manufaktur.de/austt.html" rel="nofollow noreferrer">http://www.aust-manufaktur.de/austt.html</a></p>
|
<p>If you are using eclipse/SWT, try Draw 2D.</p>
| 20,939
|
<p>How many possible combinations of the variables a,b,c,d,e are possible if I know that:</p>
<pre><code>a+b+c+d+e = 500
</code></pre>
<p>and that they are all integers and >= 0, so I know they are finite.</p>
|
<p>@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose <code>a</code> as <code>1</code> and <code>b</code> as <code>2</code>, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing <code>a</code> as <code>2</code> and <code>b</code> as <code>1</code>. (The number of such coincidences explodes as the numbers grow.)</p>
<p>The traditional way to attack such a problem is <a href="http://en.wikipedia.org/wiki/Dynamic_programming" rel="nofollow noreferrer">dynamic programming</a>: build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of <em>n</em> variables add up to <em>k</em>?" is the sum of the solutions to "how many combinations of <em>n-1</em> variables add up to <em>j</em>?" with 0 <= <em>j</em> <= <em>k</em>). </p>
<pre><code>public static long getCombos( int n, int sum ) {
// tab[i][j] is how many combinations of (i+1) vars add up to j
long[][] tab = new long[n][sum+1];
// # of combos of 1 var for any sum is 1
for( int j=0; j < tab[0].length; ++j ) {
tab[0][j] = 1;
}
for( int i=1; i < tab.length; ++i ) {
for( int j=0; j < tab[i].length; ++j ) {
// # combos of (i+1) vars adding up to j is the sum of the #
// of combos of i vars adding up to k, for all 0 <= k <= j
// (choosing i vars forces the choice of the (i+1)st).
tab[i][j] = 0;
for( int k=0; k <= j; ++k ) {
tab[i][j] += tab[i-1][k];
}
}
}
return tab[n-1][sum];
}
</code></pre>
<pre>
$ time java Combos
2656615626
real 0m0.151s
user 0m0.120s
sys 0m0.012s
</pre>
|
<p>Including negatives? Infinite.</p>
<p>Including only positives? In this case they wouldn't be called "integers", but "naturals", instead. In this case... I can't really solve this, I wish I could, but my math is too rusty. There is probably some crazy integral way to solve this. I can give some pointers for the math skilled around.</p>
<p>being x the end result,
the range of a would be from 0 to x,
the range of b would be from 0 to (x - a),
the range of c would be from 0 to (x - a - b),
and so forth until the e.</p>
<p>The answer is the sum of all those possibilities.</p>
<p>I am trying to find some more direct formula on Google, but I am really low on my Google-Fu today...</p>
| 8,444
|
<p>We have some very large data files (5 gig to 1TB) where we need quick read/write access. Since we have a fixed record size it seems like some form of ISAM would be the way to go. But would be happy to hear other suggestions. </p>
<p>Ideally the solution would have an Apache or LGPL style license but we will pay if we have to. </p>
<p>Must haves:</p>
<p>Scalable - over at least 1 TB files<br>
Stable - either doesn't corrupt data or has fast recovery process<br>
Runs well on X64 Windows </p>
<p>Nice to have: </p>
<p>Can participate in 2 phase commits<br>
Intrinsic compression facilities<br>
Portable to *nix platforms<br>
C# API or Java API</p>
<p>Thanks,</p>
<p>Terence</p>
|
<p>Give <a href="http://www.oracle.com/technology/products/berkeley-db/index.html" rel="nofollow noreferrer">Berkeley DB</a> a try. Opinions vary, but it's scalable, stable (if you use all necessary layers) and AFAIK runs well on x64 windows. Also portable to *nix and has C and Java API. Don't know about C# API.</p>
|
<p>Give <a href="http://www.oracle.com/technology/products/berkeley-db/index.html" rel="nofollow noreferrer">Berkeley DB</a> a try. Opinions vary, but it's scalable, stable (if you use all necessary layers) and AFAIK runs well on x64 windows. Also portable to *nix and has C and Java API. Don't know about C# API.</p>
| 16,226
|
<p>I have a classic client/server (fat client and database) program written in Delphi 2006. When certain conditions are met in the client, I need to notify all the other clients very quickly. Up until now this has been done using UDP broadcasts, but this is no longer viable as clients now connect from outside the LAN and the UDP broadcast is limited to the local network. </p>
<p>I'm aware of the Indy libraries but am not really sure of which components to use and how to structure it. I'm guessing I'll need to have a server that the clients connect to which will receive and distribute the messages...? Any samples out there to get me started?</p>
<p>Are there any other component sets or technologies I should look at instead/as well?</p>
|
<p>The simple answer is that the standard protocols available in Delphi (and other tools) don't allow for notification in reverse. I looked into this for a project where I wanted to use SOAP. They all assume client asks server, server responds and that's it. </p>
<p>For me, the solution was the RemObjects SDK. This allows you to send notifications to clients, and the notification can have any data you like (just like the client to server). Myself I use the SuperTCP connection, but it works with others too. It can still offer a SOAP interface for clients that must use it, but for where you have control of both client and server it works extremely well. </p>
|
<p>You should be able to use Multicast UDP for the same purpose. The only difference will be to join the multicast group from every client.</p>
<p><a href="http://en.wikipedia.org/wiki/IP_Multicast" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/IP_Multicast</a></p>
<p><a href="http://en.wikipedia.org/wiki/Internet_Group_Management_Protocol" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Internet_Group_Management_Protocol</a></p>
<p><strong>Edit:</strong> Just to clarify, multicast let you join a given "group" associated to a multicast ip address. Any packet sent to that address will reach every client who has join the group</p>
| 8,300
|
<p>I want to develop a bot who can chat from gtalk and I have some experience with java.<br>
I don't want to use the bot for IA purpose.<br>
I want to use the bot to emulate a console like xterm.<br></p>
<p><strong>Edit:</strong><br>
Ok: the question is "Any leads on how to develop it?"<br>
thanks for the awnsers.</p>
|
<p>Google Talk uses XMPP. You could look into using <a href="http://www.igniterealtime.org/projects/smack/index.jsp" rel="nofollow noreferrer">Smack</a>.</p>
|
<p>I think the easiest way to host your bot as <a href="http://code.google.com/appengine" rel="nofollow">Google App Engine</a> application. It has built in support for receiving and sending XMPP messages.</p>
| 38,907
|
<p>This is my first crack at a method that is run periodically during the lifetime of my ASP.NET application to clean up expired sessions stored in my database. It seems to work pretty well, but the software engineer in me doesn't feel "right" about this code. I've been working with LINQ to SQL for a few months now, but I'm not very confident in the following code. I'm worried about a few things:</p>
<ol>
<li><p>Is the following code safe to run in a situation where the database is being accessed by different threads in my application? I have a decent understanding of the idea of transactions, but I want to make sure I'm using them properly.</p></li>
<li><p>Is my query going to cause performance issues? Or is it appropriate in this case to select all of the records in this particular table? This method only runs every 15 minutes, so it's not like that query will be made over and over again in a short period of time.</p></li>
<li><p>Is there a better way that I could do this? I have a nagging feeling that there is.</p></li>
</ol>
<p>Code:</p>
<pre><code>/// <summary>
/// Method, run periodically, to remove all sign in records that correspond to expired sessions.
/// </summary>
/// <param name="connectionString">Database connection string</param>
/// <returns>Number of expired sign in records removed</returns>
public static int Clean(String connectionString)
{
MyDatabaseDataContext db = new MyDatabaseDataContext(connectionString);
var signIns = db.SignIns.Select(x => x);
int removeCount = 0;
using (TransactionScope scope = new TransactionScope())
{
foreach (SignIn signIn in signIns)
{
DateTime currentTime = DateTime.Now;
TimeSpan span = currentTime.Subtract(signIn.LastActivityTime);
if (span.Minutes > 10)
{
db.SignIns.DeleteOnSubmit(signIn);
++removeCount;
}
}
db.SubmitChanges();
scope.Complete();
}
return removeCount;
}
</code></pre>
|
<p>This sounds like something you could easily do in a sproc. SQLServer gives you a GETDATE() method that returns the current time... I don't see why you can't just</p>
<pre><code> DELETE * FROM tblSignIns
WHERE LastActivityTime < DATEADD("minute", -10, GETDATE());
</code></pre>
<p>Wouldn't that do the same thing?</p>
|
<p>You can have a stored proc as a method on your database context. Why not write one that does what you want and then call it through your context? That way you can also make use of set logic rather than iterating over your collection. (Linq to SQL might compile this away - not sure how it deals with deletes.)</p>
| 38,757
|
<p>What methods are there for automatically getting a stack trace on Unix systems? I don't mean just getting a core file or attaching interactively with GDB, but having a SIGSEGV handler that dumps a backtrace to a text file. </p>
<p>Bonus points for the following optional features:</p>
<ul>
<li>Extra information gathering at crash time (eg. config files).</li>
<li>Email a crash info bundle to the developers.</li>
<li>Ability to add this in a <code>dlopen</code>ed shared library</li>
<li>Not requiring a GUI</li>
</ul>
|
<p>If you are on systems with the BSD <a href="http://linux.die.net/man/3/backtrace" rel="nofollow noreferrer"><code>backtrace</code></a> functionality available (Linux, OSX 1.5, BSD of course), you can do this programmatically in your signal handler.</p>
<p>For example (<a href="http://www-128.ibm.com/developerworks/linux/library/l-cppexcep.html?ca=dgr-lnxw07ExceptionTricks" rel="nofollow noreferrer"><code>backtrace</code> code derived from IBM example</a>): </p>
<pre class="lang-c prettyprint-override"><code>#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sig_handler(int sig)
{
void * array[25];
int nSize = backtrace(array, 25);
char ** symbols = backtrace_symbols(array, nSize);
for (int i = 0; i < nSize; i++)
{
puts(symbols[i]);;
}
free(symbols);
signal(sig, &sig_handler);
}
void h()
{
kill(0, SIGSEGV);
}
void g()
{
h();
}
void f()
{
g();
}
int main(int argc, char ** argv)
{
signal(SIGSEGV, &sig_handler);
f();
}
</code></pre>
<p>Output:</p>
<pre><code>0 a.out 0x00001f2d sig_handler + 35
1 libSystem.B.dylib 0x95f8f09b _sigtramp + 43
2 ??? 0xffffffff 0x0 + 4294967295
3 a.out 0x00001fb1 h + 26
4 a.out 0x00001fbe g + 11
5 a.out 0x00001fcb f + 11
6 a.out 0x00001ff5 main + 40
7 a.out 0x00001ede start + 54
</code></pre>
<p>This doesn't get bonus points for the optional features (except not requiring a GUI), however, it does have the advantage of being very simple, and not requiring any additional libraries or programs.</p>
|
<p>Dereks solution is probably the best, but here's an alternative anyway:</p>
<p>Recent Linux kernel version allow you to pipe core dumps to a script or program. You could write a script to catch the core dump, collect any extra information you need and mail everything back.
This is a global setting though, so it'd apply to any crashing program on the system. It will also require root rights to set up.
It can be configured through the /proc/sys/kernel/core_pattern file. Set that to something like ' | /home/myuser/bin/my-core-handler-script'.</p>
<p>The Ubuntu people use this feature as well.</p>
| 3,886
|
<p>I'm being asked to add queryability to a database (Oracle) filled with mostly binary data.
So I need to be able to query binary ranges within a blobs of a few kilobytes. I've never done this before, so I'm wondering what are some good practices and pitfalls to consider when starting a project like this.</p>
<p>Thanks</p>
|
<p>Add a column of MD5, which is the MD5 checksum of the BLOB data. Or, you can create a new table with the same primary key and the MD5 column.</p>
<p>Your cache module outside the database can make use of that column not to have to retrieve the BLOB column twice in a cache-hit.</p>
<p>OR, you could drop the BLOB data in the database and store it in a file system with the MD5 value as a filename with an http server as a network file server.</p>
|
<p>Storage parameters can make quite a significant difference when it comes to both storing and retrieving relatively small BLOBs (< DB_BLOCK_SIZE * 2 or so). In general, you want to minimize row migration and row chaining, as well as minimize wasted free space.</p>
<p>Perhaps the greatest effect on the performance is enabling or disabling 'IN ROW' storage - it's definitely worth experimenting with.</p>
| 25,895
|
<p>I want to get a <code>System.Type</code> given only the type name in a <code>string</code>.</p>
<p>For instance, if I have an object:</p>
<pre><code>MyClass abc = new MyClass();
</code></pre>
<p>I can then say:</p>
<pre><code>System.Type type = abc.GetType();
</code></pre>
<p>But what if all I have is:</p>
<pre><code>string className = "MyClass";
</code></pre>
|
<pre><code>Type type = Type.GetType("foo.bar.MyClass, foo.bar");
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx" rel="noreferrer">MSDN</a>. Make sure the name is <a href="http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx" rel="noreferrer">Assembly Qualified</a>.</p>
|
<p><code>Type.GetType(...)</code>might fail sometimes if the <code>typeof</code> operator can not be used.</p>
<p>Instead you can reflect on the assemblies from the current domain in order to do it.</p>
<p>check my response on <a href="https://stackoverflow.com/questions/2367652/how-type-gettype-works-when-given-partially-qualified-type-name/7286354#7286354">this thread</a></p>
| 21,597
|
<p>I was thinking it would be nice to create a base class for NUnit test fixtures that opens a TransactionScope during the SetUp phase, then rolls back the transaction during tear down.
Something like this:</p>
<pre><code> public abstract class TestFixtureBase
{
private TransactionScope _transaction;
[TestFixtureSetUp]
public void TestFixtureSetup()
{
_transaction = new TransactionScope();
}
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
if (_transaction != null)
{
_transaction.Dispose();
}
}
}
</code></pre>
<p>Do you think this is a good idea?</p>
<p>Obviously the database is just a test database, not a live database, but it would still be annoying if it filled up with junk data from the unit tests.</p>
<p>What do other people do when running unit tests that involve a lot of data access?</p>
|
<p>You want to be careful here. TransactionScope is going to promote the transaction to a distributed transaction if you open up more than one connection to the database. I find that it is easier just to write some simple SQL that clears out the tables of interest to my test class before I start running the test.</p>
<p><strong>EDIT:</strong> Normally I would call any test that touches the database an integration test since it involves another system. Typically, I will mock out the database when unit testing my code.</p>
<pre><code>[TestSetup]
public void Setup()
{
foreach (string table in new string[] { "table1", "table2" })
{
ClearTable( table );
}
}
private void ClearTable( string table )
{
...standard stuff to set up connection...
SqlCommand command = connection.CreateCommand() );
command.CommandText = "delete from " + table;
command.ExecuteNonQuery();
... stuff to clean up connection...
}
</code></pre>
|
<p>You want to be careful here. TransactionScope is going to promote the transaction to a distributed transaction if you open up more than one connection to the database. I find that it is easier just to write some simple SQL that clears out the tables of interest to my test class before I start running the test.</p>
<p><strong>EDIT:</strong> Normally I would call any test that touches the database an integration test since it involves another system. Typically, I will mock out the database when unit testing my code.</p>
<pre><code>[TestSetup]
public void Setup()
{
foreach (string table in new string[] { "table1", "table2" })
{
ClearTable( table );
}
}
private void ClearTable( string table )
{
...standard stuff to set up connection...
SqlCommand command = connection.CreateCommand() );
command.CommandText = "delete from " + table;
command.ExecuteNonQuery();
... stuff to clean up connection...
}
</code></pre>
| 43,165
|
<p>What's the ASP equivalent to PHP's <code>.=</code> when concatenating strings? I'm referring to asp NOT asp.net.</p>
<p>I meant to specify that I'm in a for-loop. So I want to know the equivalent for <code>.=</code> (in php) not standard concatenation.</p>
<p><em>Example:</em></p>
<pre><code>For Each Item In Request.Form
If (Item = "service") then
For x=1 To Request.Form(item).Count
service = "&service="&Request.Form(Item)(x)
Next
End If
Next
</code></pre>
|
<p>In VBScript:</p>
<pre><code>Variable = Variable & "something more"
</code></pre>
<p>In JScript I believe you can use:</p>
<pre><code>variable += "something more";
</code></pre>
<p>Specifically:</p>
<pre><code>service = service & "&service=" & Request.Form(Item)(x)
</code></pre>
<p>assuming you want your result to look something like...</p>
<pre><code>&service=blah1&service=blah2&service=blah3
</code></pre>
<p>Though you may need to URL encode your Request.Form(Item)(x) values because any "&" (and other characters) could really muck up what you are trying to do. Also be careful when using unsanitized input like this directly from an HTML form, its very dangerous.</p>
|
<p>I can't remember for certain, but &= should work in ASP. I know it works in VB.Net. Although I can't recall if that worked in asp. If that doesn't work, the only solution is a = a & b.</p>
| 24,889
|
<p>P1 and P2 are processes or nodes in a cluster. f1 and f2 are their flags. Supposing strong memory model, and that both processes may be restarted at any moment, and that restarting a process clears it's flag, here's an algorithm that I came up with and couldn't yet break, but that bothers me for it's not theoretically proven and looks too simple compared with Peterson's.</p>
<pre><code>P1 start:
set f1
if f2 set then clear f1, wait some, goto start
else enter critical section
do whatever
clear f1
P2 start:
set f2
if f1 set then clear f2, wait some, goto start
else enter critical section
do whatever
clear f2
</code></pre>
<p>Can anybody see a flow? Except may be that one of the processes may starve the other by quickly re-entering the section?</p>
|
<p>If the "if X set then clear Y" operation is not atomic, there's a potential race condition that could prevent either from getting inside the critical section. I've tried to outline the flow below:</p>
<pre><code>P1: set f1
P2: set f2
P1: is f2 set?
P2: is f1 set?
P1: yes, clear f1
P2: yes, clear f2
P1: start wait
P2: start wait
P1: end wait
P2: end wait
P1: goto start
P2: goto start
</code></pre>
<p>This could potentially go on forever, until there's a difference in the allocation done by the task scheduler, or the wait times for the two P are different from one another.</p>
|
<p>Well, apart from the starvation issue, I don't see any other problems.</p>
<p>Peterson's algorithm, however, guarantees fairness - each process is guaranteed to get the critical section as soon as it is next available - which your algorithm doesn't provide.</p>
<p>I'm curious as to why you think Peterson's algorithm is less simple, though; it's not that different to what you have.</p>
<pre><code>P1 start:
set f1
x = 2
while f2 and (x == 2) wait
enter critical section, etc.
clear f1
</code></pre>
| 38,250
|
<p>Once I've called <code>DragManager.acceptDrag</code> is there any way to "unaccept" the drag? Say that I have a view which can accept drag and drop, but only in certain areas. Once the user drags over one of these areas I call <code>DragManager.acceptDrag(this)</code> (from a <code>DragEvent.DRAG_OVER</code> handler), but if the user then moves out of this area I'd like to change the status of the drag to not accepted and show the <code>DragManager.NONE</code> feedback. However, neither calling <code>DragManager.acceptDrag(null)</code> nor <code>DragManager.showFeedback(DragManager.NONE)</code> seems to have any effect. Once I've accepted the drag an set the feedback type I can't seem to change it.</p>
<p>Just to make it clear: the areas where the user should be able to drop are not components or even display objects, in fact they are just ranges in the text of a text field (like the selection). Had they been components of their own I could have solved it by making each of them accept drag events individually. I guess I could create proxy components that float over the text to emulate it, but I'd rather not if it isn't necessary.</p>
<hr>
<p>I've managed to get it working in both AIR and the browser now, but only by putting proxy components on top of the ranges of text where you should be able to drop things. That way I get the right feedback and drops are automatically unaccepted on drag exit.</p>
<p>This is the oddest thing about D&D in AIR:</p>
<pre><code>DragManager.doDrag(initiator, source, event, dragImage, offsetX, offsetY);
</code></pre>
<p>In browser-based Flex, <code>offsetX</code> and <code>offsetY</code> should be negative (so says the documentation, and it works fine). However, when running <em>exactly the same code</em> in AIR you have to make the offsets positive. The same numbers, but positive. That is very, very weird.</p>
<hr>
<p>I've tested some more and what <a href="https://stackoverflow.com/questions/10870/how-can-i-unaccept-a-drag-in-flex#11209">@maclema</a> works, but not if you run in AIR. It seems like drag and drop in AIR is different. It's really, really weird because not only is the feedback not showing correctly, and it's not possible to unaccept, but the coordinates are also completely off. I just tried my application in a browser instead of AIR and dragging and dropping is completely broken.</p>
<p>Also, skipping the <code>dragEnter</code> handler works fine in AIR, but breaks everything when running in a browser.</p>
|
<p>Are you using only the dragEnter method? If you are trying to reject the drag while still dragging over the same component you need to use both the dragEnter and dragOver methods.</p>
<p>Check out this example:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.core.DragSource;
import mx.managers.DragManager;
import mx.events.DragEvent;
private function onDragEnter(e:DragEvent):void {
if ( e.target == lbl ) {
if ( e.localX < lbl.width/2 ) {
trace("accept");
DragManager.acceptDragDrop(this);
}
else {
DragManager.acceptDragDrop(null);
}
}
}
private function doStartDrag(e:MouseEvent):void {
if ( e.buttonDown ) {
var ds:DragSource = new DragSource();
ds.addData("test", "text");
DragManager.doDrag(btn, ds, e);
}
}
]]>
</mx:Script>
<mx:Label id="lbl" text="hello world!" left="10" top="10" dragEnter="onDragEnter(event)" dragOver="onDragEnter(event)" />
<mx:Button id="btn" x="47" y="255" label="Button" mouseMove="doStartDrag(event)"/>
</mx:Application>
</code></pre>
|
<p>ok, I see the problem now. Rather than null, try setting it to the dragInitiator.</p>
<p>Check this out.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.DragEvent;
import mx.managers.DragManager;
import mx.core.DragSource;
private function doStartDrag(e:MouseEvent):void {
if ( e.buttonDown && !DragManager.isDragging ) {
var ds:DragSource = new DragSource();
ds.addData("test", "test");
DragManager.doDrag(btn, ds, e);
}
}
private function handleDragOver(e:DragEvent):void {
if ( e.localX < cvs.width/2 ) {
//since null does nothing, lets just set to accept the drag
//operation, but accept it to the dragInitiator
DragManager.acceptDragDrop(e.dragInitiator);
}
else {
//accept drag
DragManager.acceptDragDrop(cvs);
DragManager.showFeedback( DragManager.COPY );
}
}
private function handleDragDrop(e:DragEvent):void {
if ( e.dragSource.hasFormat("test") ) {
Alert.show("Got a drag drop!");
}
}
]]>
</mx:Script>
<mx:Canvas x="265" y="66" width="321" height="245" backgroundColor="#FF0000" id="cvs" dragOver="handleDragOver(event)" dragDrop="handleDragDrop(event)">
</mx:Canvas>
<mx:Button id="btn" x="82" y="140" label="Drag Me" mouseDown="doStartDrag(event)"/>
</mx:WindowedApplication>
</code></pre>
| 3,204
|
<p>Is there a C library function that will return the index of a character in a string?</p>
<p>So far, all I've found are functions like strstr that will return the found char *, not it's location in the original string.</p>
|
<p><code>strstr</code> returns a pointer to the found character, so you could use pointer arithmetic: (Note: this code not tested for its ability to compile, it's one step away from pseudocode.)</p>
<pre><code>char * source = "test string"; /* assume source address is */
/* 0x10 for example */
char * found = strstr( source, "in" ); /* should return 0x18 */
if (found != NULL) /* strstr returns NULL if item not found */
{
int index = found - source; /* index is 8 */
/* source[8] gets you "i" */
}
</code></pre>
|
<p>If you are not totally tied to pure C and can use string.h there is strchr()
<a href="http://www.cplusplus.com/reference/clibrary/cstring/strchr.html" rel="nofollow noreferrer">See here</a></p>
| 2,680
|
<p>Do any one know which sorting algorithm is used by .net when we implement <code>IComparer</code> in our class?</p>
|
<p><a href="http://en.wikipedia.org/wiki/QuickSort" rel="noreferrer">QuickSort</a> seems to be it.</p>
<p>The documentation on <a href="http://msdn.microsoft.com/en-us/library/system.collections.icomparer.aspx" rel="noreferrer">IComparer</a> says </p>
<blockquote>
<p>This interface is used in conjunction with the <a href="http://msdn.microsoft.com/en-us/library/system.array.sort.aspx" rel="noreferrer">Array.Sort</a> and <a href="http://msdn.microsoft.com/en-us/library/system.array.binarysearch.aspx" rel="noreferrer">Array.BinarySearch</a> methods.</p>
</blockquote>
<p>The <a href="http://msdn.microsoft.com/en-us/library/aw9s5t8f.aspx" rel="noreferrer">Array.Sort</a> documentation says</p>
<blockquote>
<p>This method uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.</p>
</blockquote>
|
<p>According to the <a href="http://msdn.microsoft.com/en-us/library/aw9s5t8f%28VS.80%29.aspx" rel="nofollow noreferrer">MSDN</a>, .NET uses QuickSort. By the way, the method absolutely doesn't depend on the comparer (as long as it's comparison-based), why should .NET therefore use a different method depending on whether you provide a custom comparer or not?</p>
| 25,080
|
<p>I am trying to match the folder name in a relative path using C#. I am using the expression: <code>"/(.*)?/"</code> and reversing the matching from left to right to right to left.
When I pass <code>"images/gringo/"</code> into the regular expression, it correctly gives me <code>"gringo"</code> in the first group - I'm only interested in what is between the brackets.
When I pass in <code>"images/"</code>, it fails to pick up <code>"images"</code>.
I have tried using <code>[/^]</code> and <code>[/$]</code> but neither work.</p>
<p>Thanks,
David</p>
|
<p>You're probably better off using the <a href="http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx" rel="noreferrer">System.IO.DirectoryInfo</a> class to interpret your relative path. You can then pick off folder or file names using its members:</p>
<pre><code>DirectoryInfo di = new DirectoryInfo("images/gringo/");
Console.Out.WriteLine(di.Name);
</code></pre>
<p>This will be much safer than any regexps you could use.</p>
|
<p>Agreed with the "<em>don't do it this way</em>" answers, but, since it's tagged "<em>regex</em>"...</p>
<ul>
<li>You don't need the <code>?</code>. <code>*</code> already accepts 0 repetitions as a match, so <code>(.*)</code> is exactly equivalent to <code>(.*)?</code></li>
<li>You rarely actually want to use <code>.*</code> anyhow. If you're trying to capture what's between a pair of slashes, use <code>/([^/]*)/</code> or else testing against "<em>foo/bar/baz/</em>" will (on most regex implementations) return a single match for "<em>bar/baz</em>" instead of matching "<em>bar</em>" and "<em>baz</em>" separately.</li>
</ul>
| 30,620
|
<p>I Have "SQL Native Client", but not "SQL Server" ODBC driver. I have SQL 2005 installed on my machine.</p>
<p>Tried to fix by installing SQL Server client tools.</p>
<p>Any ideas would be appreciated.</p>
<p>I'm running Windows XP Pro.</p>
|
<p>Found this <a href="http://www.microsoft.com/Downloads/details.aspx?familyid=6C050FE3-C795-4B7D-B037-185D0506396C&displaylang=en" rel="nofollow noreferrer">Microsoft download</a>. It says it provides the SQL Server ODBC driver.</p>
<p>Edit:
Here's the SP1 download: <a href="http://www.microsoft.com/Downloads/details.aspx?familyid=78CAC895-EFC2-4F8E-A9E0-3A1AFBD5922E&displaylang=en" rel="nofollow noreferrer">Service Pack 1</a>.</p>
|
<p>You can also try the OpenLink ODBC Drivers for SQL Server. These support older and newer versions of SQL Server (from 4.2 up to very latest release).</p>
<p>See: <a href="http://uda.openlinksw.com/" rel="nofollow noreferrer">http://uda.openlinksw.com/</a></p>
| 19,895
|
<p>I am working on a web application in Java which gets data from servlets via AJAX calls.</p>
<p>This application features several page elements which get new data from the server at fairly rapid intervals.</p>
<p>With a lot of users, the demand on the server has a potential to get fairly high, so I am curious:</p>
<p><strong>Which approach offers the best performance:</strong></p>
<p>Many servlets (one for each type of data request)?</p>
<p><strong>Or:</strong></p>
<p>a single servlet that can handle all of the requests?</p>
|
<p>There is no performance reason to have more than one servlet. In a web application, only a single instance of a servlet class is instantitated, no matter how many requests. Requests are not serialized, they are handled concurrently, hence the need for your servlet to be thread safe.</p>
|
<p>Like Tony said, there really isn't a reason to use more than one servlet, unless you need to break up a complex Java Servlet class or perhaps implement an intercepting filter.</p>
| 24,907
|
<p>To be more precise, I need to know whether (and if possible, how) I can find whether a given string has double byte characters or not. Basically, I need to open a pop-up to display a given text which can contain double byte characters, like Chinese or Japanese. In this case, we need to adjust the window size than it would be for English or ASCII.
Anyone has a clue?</p>
|
<p>JavaScript holds text internally as UCS-2, which can encode a fairly extensive subset of Unicode.</p>
<p>But that's not really germane to your question. One solution might be to loop through the string and examine the character codes at each position:</p>
<pre><code>function isDoubleByte(str) {
for (var i = 0, n = str.length; i < n; i++) {
if (str.charCodeAt( i ) > 255) { return true; }
}
return false;
}
</code></pre>
<p>This might not be as fast as you would like.</p>
|
<p>Why not let the window resize itself based on the runtime height/width?</p>
<p>Run something like this in your pop-up:</p>
<pre><code>window.resizeTo(document.body.clientWidth, document.body.clientHeight);
</code></pre>
| 17,801
|
<p>I have noticed that regardless of a given script's execution time, every date() call will return the same timestamp regardless of where the function is called within the script. It looks like it just returns the time at which the script first started executing.</p>
<p>For logging purposes, it would be extremely useful to be able to get incremental timestamps from within a script. Is this possible? Is there a way to do this that is relatively lightweight?</p>
<p><strong>Edit:</strong> Would the example for the <a href="http://us.php.net/microtime" rel="nofollow noreferrer">microtime()</a> function suggests it might do this. Can anyone confirm?</p>
<p><strong>Update:</strong> microtime() does work, but I cannot format it with the date() function because date() only accepts timestamps as integers (so no microseconds). How can I get a properly formatted date from the value returned by microtime() ?</p>
|
<p><a href="http://us.php.net/microtime" rel="nofollow noreferrer">http://us.php.net/microtime</a> gives me different times within the same script.</p>
|
<p>You can use the <a href="http://pear.php.net/package/Benchmark" rel="nofollow noreferrer">Pear Benchmarking package</a> for getting timing and profiling information.</p>
| 28,569
|
<p>When I pass a list of objects out of my silverlight app using WCF everything works fine until the List grows too big. It seems that when I exceed 80 items I get the error:
The remote server returned an unexpected response: (404) Not Found</p>
<p>I'm presuming that it's because the List has grown too big as when the List had 70 items everyhing works fine. Strange error message though, right?</p>
<p>In the config file I change the maxBufferSize to the highest value that it will accept but still I can't have more then 80 items in my List.
</p>
<p>How can I pass out large objects without having to split the object up?</p>
<hr>
<p>Thanks Shawn, so where exactly do I do it?
This is my ServiceReferences.ClientConfig</p>
<pre><code><configuration>
<system.serviceModel>
<client>
<!--"http://sy01911.fw.gsjbw.com/WcfService1/Service1.svc"-->
<endpoint address="http://localhost/WcfService1/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService11"
contract="SilverlightApplication1.ServiceReference1.IService1"
name="BasicHttpBinding_IService1" />
</client>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" maxBufferSize="655360000"
maxReceivedMessageSize="655360000">
<security mode="None" />
</binding>
<binding name="BasicHttpBinding_IService11" maxBufferSize="655360000"
maxReceivedMessageSize="655360000">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</code></pre>
<p></p>
<hr>
<p>and this is the server config that you mentioned</p>
<hr>
<pre><code><services>
<service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior" >
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" contract="WcfService1.IService1" >
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfService1.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</code></pre>
<p></p>
|
<p>There are two config files. The silverlight clientconfig will let you send the larger message, but if you'r eusing WCF, there is a server web.config that limits the size of the received message (to prevent DDOS attacks).</p>
|
<p>There are two config files. The silverlight clientconfig will let you send the larger message, but if you'r eusing WCF, there is a server web.config that limits the size of the received message (to prevent DDOS attacks).</p>
| 42,756
|
<p>This question is slightly related to <a href="https://stackoverflow.com/questions/61354/how-to-get-entire-chain-of-exceptions-in-applicationthreadexception-event-handl">this question about exception handling</a>. The workaround I found there consists of rolling my own message loop.</p>
<p>So my Main method now looks basically like this:</p>
<pre><code>[STAThread]
static void Main() {
// this is needed so there'll actually an exception be thrown by
// Application.Run/Application.DoEvents, instead of the ThreadException
// event being raised.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form form = new MainForm();
form.Show();
// the loop is here to keep app running if non-fatal exception is caught.
do {
try {
Application.DoEvents();
Thread.Sleep(100);
}
catch (Exception ex) {
ExceptionHandler.ConsumeException(ex);
}
}
while (!form.IsDisposed);
}
</code></pre>
<p>What I'm wondering though, <strong>is this a safe/decent way to replace the more typical
'Application.Run(new MainForm());'</strong>, whether it's used for exception handling or for whatever else, or should I always stick to using Application.Run?</p>
<p>On another app that's in testing now a similar approach is used for both loading (splashscreen) and exception handling, and I don't think it has caused any troubles (yet :-))</p>
|
<p>Pitfall 1: </p>
<pre><code>Thread.Sleep(100);
</code></pre>
<p>Never. Use WaitMessage().</p>
<p>Otherwise, it is possible roll out your own message loop, but in your scenario it seems somewhat pointless.</p>
<p>You may also want to examine Application.Run() code (with .Net Reflector, for instance).</p>
|
<p>Yes... I think some components wont work with that code. Some of them require to live in a thread that has an Application.Run in it to effectively pick up their messages.</p>
| 8,655
|
<p>What's the best way to get a function like the following to work:</p>
<pre><code>def getNearest(zipCode, miles):
</code></pre>
<p>That is, given a zipcode (07024) and a radius, return all zipcodes which are within that radius?</p>
|
<p>There is a project on SourceForge that could assist with this:</p>
<p><a href="http://sourceforge.net/projects/zips/" rel="noreferrer">http://sourceforge.net/projects/zips/</a></p>
<p>It gives you a database with zip codes and their latitude / longitude, as well as coding examples of how to calculate the distance between two sets of coordinates. There is probably a better way to do it, but you could have your function retrieve the zipcode and its coordinates, and then step through each zipcode in the list and add the zipcode to a list if it falls within the number of miles specified.</p>
|
<p>Maybe this can help. The project is configured in kilometers though. You can modify these in CityDAO.java</p>
<pre><code>public List<City> findCityInRange(GeoPoint geoPoint, double distance) {
List<City> cities = new ArrayList<City>();
QueryBuilder queryBuilder = geoDistanceQuery("geoPoint")
.point(geoPoint.getLat(), geoPoint.getLon())
//.distance(distance, DistanceUnit.KILOMETERS) original
.distance(distance, DistanceUnit.MILES)
.optimizeBbox("memory")
.geoDistance(GeoDistance.ARC);
SearchRequestBuilder builder = esClient.getClient()
.prepareSearch(INDEX)
.setTypes("city")
.setSearchType(SearchType.QUERY_THEN_FETCH)
.setScroll(new TimeValue(60000))
.setSize(100).setExplain(true)
.setPostFilter(queryBuilder)
.addSort(SortBuilders.geoDistanceSort("geoPoint")
.order(SortOrder.ASC)
.point(geoPoint.getLat(), geoPoint.getLon())
//.unit(DistanceUnit.KILOMETERS)); Original
.unit(DistanceUnit.MILES));
SearchResponse response = builder
.execute()
.actionGet();
SearchHit[] hits = response.getHits().getHits();
scroll:
while (true) {
for (SearchHit hit : hits) {
Map<String, Object> result = hit.getSource();
cities.add(mapper.convertValue(result, City.class));
}
response = esClient.getClient().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
if (response.getHits().getHits().length == 0) {
break scroll;
}
}
return cities;
}
</code></pre>
<p>The "LocationFinder\src\main\resources\json\cities.json" file contains all cities from Belgium. You can delete or create entries if you want too. As long as you don't change the names and/or structure, no code changes are required.</p>
<p>Make sure to read the README <a href="https://github.com/GlennVanSchil/LocationFinder" rel="nofollow">https://github.com/GlennVanSchil/LocationFinder</a></p>
| 42,365
|
<p>Comparable to cacti or mrtg.</p>
|
<p><a href="http://www.zenoss.com/" rel="nofollow noreferrer">http://www.zenoss.com/</a></p>
<p>This is a lot more than just SNMP but it is based on Python.</p>
|
<p>or you can start building your own solution (like me), you will be surprised how much can you do with few lines of code using for instance cherryp for web server, pysnmp, and python rrd module.</p>
| 40,048
|
<p>I have a large .NET web application. The system has projects for different intentions (e.g. CMS, Forum, eCommerce), and I have noticed a (naive) pattern of calling on another project's class. For example, the ecommerce module needs functionality to generate a file on the fly for products, and I call and reference a method in the CMS to do this, because file handling is really a job for the CMS.</p>
<p>Obviously (and I know why), this is bad design and a case of high coupling.</p>
<p>I know a few ways to handle high coupling, like restructuring the project (although I don't really think this is a robust solution), but what else can I do to reduce high coupling? Any simple tips? Also, it would be good to know why/how they reduce coupling. I use .NET 3.5 and Sql Server 2005 so things like JMS (which I keep coming across in my search for tips on this design issue), are not applicable.</p>
<p>Thanks</p>
<hr>
<p>BTW,</p>
<p>One of the reasons I ask this is that I have read the previous questions similar to this but usually if a question that has been asked before is asked again, different tips can be learnt as different people reply to the post.</p>
<p>I know of dependency injection/IOC, but I am interested in the small things that can be done to reduce coupling.</p>
<p>How could I choose between using a static class, or an interface-derived class, or the IOC approach when deciding on <em>how</em> to reduce coupling? Also, I could develop a web service which could call a static class - mixing up the approaches in my solution.</p>
<p>The interesting thing is that in my application, I don't want it to be disjointed. So I just have a forum, ecommerce system, and any other module required, but everything has to gel into one site so each module (which is represented as a dedicated project in my Visual Studio solution) needs to know about every other module and work with it. So for example, I might have a module which handles user profiles (working with ASP.NET membership, roles, etc), but this will work with the forum module as a user on the forum will be a registered user on the site (one login throughout), and his or her profile will be coming from the user profile module. This is as opposed to seperate profiles as seen on other sites I've come across).</p>
|
<p>It sounds like you have a layering problem. Your assemblies should have a single dependency cycle - from least stable to most stable. That allows you to version sensibly. Generally, that cycle would be something like UI (least stable) -> Domain Core (stable) -> Data Access (most stable). You can throw in a Utilities or some infrastructre assemblies along the way, but again - they should be considered more stable than the assemblies dependent on them.</p>
<p>I'd guess your App.ECommerce and App.Cms assemblies are more siblings than layers - so you would not want those to depend on each other, but that doesn't mean you can't reuse functionality. For your particular scenario, you need to push the needed functionality down to a Core or Utilities assembly that both ECommerce and Cms can depend on. If it's a specific implementation that ECommerce provides, then you can push an interface or abstract base class to the Core - and have a higher layer (perhaps IoC container) wire up the concrete Cms.FileCreator class to the ECommerce.IFileCreator dependency.</p>
|
<p>Well, I don't know anything about .NET, but how about refactoring common code into a separate, underlaying project/layer? Loads of stuff in a web app can be done generically to suit both a CMS, a forum and eCommerce, writing to a file is a perfect example.</p>
<p>Another approach could be to see the forum and eCommerce as modules in a CMS, which would also make sense. Then they could safely use specified API:s of the CMS.</p>
| 40,172
|
<p>You find plenty of tutorials on menu bars in HTML, but for this specific (though IMHO generic) case, I haven't found any decent solution:</p>
<pre><code># THE MENU ITEMS SHOULD BE JUSTIFIED JUST AS PLAIN TEXT WOULD BE #
# ^ ^ #
</code></pre>
<ul>
<li>There's an varying number of text-only menu items and the page layout is fluid.</li>
<li>The first menu item should be left-aligned, the last menu item should be right-aligned.</li>
<li>The remaining items should be spread optimally on the menu bar.</li>
<li>The number is varying,so there's no chance to pre-calculate the optimal widths.</li>
</ul>
<p>Note that a TABLE won't work here as well:</p>
<ul>
<li>If you center all TDs, the first and the last item aren’t aligned correctly.</li>
<li>If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal.</li>
</ul>
<p>Isn’t it strange that there is no obvious way to implement this in a clean way by using HTML and CSS?</p>
|
<p>The simplest thing to do is to is to force the line to break by inserting an element at the end of the line that will occupy more than the left available space and then hiding it. I've accomplished this quite easily with a simple <code>span</code> element like so:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#menu {
text-align: justify;
}
#menu * {
display: inline;
}
#menu li {
display: inline-block;
}
#menu span {
display: inline-block;
position: relative;
width: 100%;
height: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="menu">
<ul>
<li><a href="#">Menu item 1</a></li>
<li><a href="#">Menu item 3</a></li>
<li><a href="#">Menu item 2</a></li>
</ul>
<span></span>
</div></code></pre>
</div>
</div>
</p>
<p>All the junk inside the <code>#menu span</code> selector is (as far as I've found) required to please most browsers. It should force the width of the <code>span</code> element to 100%, which should cause a line break since it is considered an inline element due to the <code>display: inline-block</code> rule. <code>inline-block</code> also makes the <code>span</code> possible to block-level style rules like <code>width</code> which causes the element to not fit in line with the menu and thus the menu to line-break.</p>
<p>You of course need to adjust the width of the <code>span</code> to your use case and design, but I hope you get the general idea and can adapt it.</p>
|
<p>I know the original question specified HTML + CSS, but it didn't specifically say <em>no javascript</em> ;)</p>
<p>Trying to keep the css and markup as clean as possible, and as semantically meaningful as possible to (using a UL for the menu) I came up with this suggestion. Probably not ideal, but it may be a good starting point:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Kind-of-justified horizontal menu</title>
<style type="text/css">
ul {
list-style: none;
margin: 0;
padding: 0;
width: 100%;
}
ul li {
display: block;
float: left;
text-align: center;
}
</style>
<script type="text/javascript">
setMenu = function() {
var items = document.getElementById("nav").getElementsByTagName("li");
var newwidth = 100 / items.length;
for(var i = 0; i < items.length; i++) {
items[i].style.width = newwidth + "%";
}
}
</script>
</head>
<body>
<ul id="nav">
<li><a href="#">first item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">item</a></li>
<li><a href="#">last item</a></li>
</ul>
<script type="text/javascript">
setMenu();
</script>
</body>
</html>
</code></pre>
| 7,214
|
<p>I would like to add AES encryption to a software product, but am concerned by increasing the size of the data. I am guessing that the data does increase in size, and then I'll have to add a compression algorithm to compensate.</p>
|
<p>AES does not expand data. Moreover, the output will not generally be compressible; if you intend to compress your data, do so before encrypting it.</p>
<p>However, note that AES encryption is usually combined with <a href="https://en.wikipedia.org/wiki/Padding_%28cryptography%29" rel="noreferrer">padding</a>, which <em>will</em> increase the size of the data (though only by a few bytes).</p>
|
<p>If compression is necessary do it before you encrypt.</p>
| 11,895
|
<p>Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx" rel="noreferrer">System.Media.SoundPlayer</a> can handle only WAV, but those are typically to big to embed in a downloadable apllication. MP3 is protected with patents, so even if there was a fully managed decoder/player it wouldn't be free to redistribute. The best format available would seem to be OGG Vorbis, but I had no luck getting any C# Vorbis libraries to work (I managed to extract a raw PCM with <a href="https://github.com/mono/csvorbis" rel="noreferrer">csvorbis</a> but I don't know how to play it afterwards).</p>
<p>I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL.</p>
<p>[this question is a follow up to a <a href="http://lists.ximian.com/pipermail/mono-devel-list/2007-June/023863.html" rel="noreferrer">mailing list discussion on mono-dev</a> mailing list a year ago]</p>
|
<p>I finally revisited this topic, and, using help from <a href="https://stackoverflow.com/a/7152153/3205">BrokenGlass on writing WAVE header</a>, updated csvorbis. I've added an <a href="https://github.com/mono/csvorbis/blob/master/OggDecoder/OggDecodeStream.cs" rel="nofollow noreferrer">OggDecodeStream</a> that can be passed to <code>System.Media.SoundPlayer</code> to simply play any (compatible) Ogg Vorbis stream. Example usage:</p>
<pre><code>using (var file = new FileStream(oggFilename, FileMode.Open, FileAccess.Read))
{
var player = new SoundPlayer(new OggDecodeStream(file));
player.PlaySync();
}
</code></pre>
<p>'Compatible' in this case means 'it worked when I tried it out'. The decoder is fully managed, works fine on Microsoft .Net - at the moment, there seems to be a regression in Mono's <code>SoundPlayer</code> that causes distortion.</p>
<p>Outdated:</p>
<p><s> <code>System.Diagnostics.Process.Start("fullPath.mp3");</code></p>
<p>I am surprised but the <a href="https://stackoverflow.com/questions/35896/how-can-i-play-compressed-sound-files-in-c-in-a-portable-way#35987">method Dinah mentioned</a> actually works. However, I was thinking about playing short "jingle" sounds on various events occurring in the program, I don't want to launch user's media player each time I need to do a 'ping!' sound.</p>
<p>As for the code project link - this is unfortunately only a P/Invoke wrapper.</s></p>
|
<p>There is no way for you to do this without using something else for your play handling.</p>
<p>Using the System.Diagnostic will launch an external software and I doubt you want that, right? You just want X sound file to play in the background when Y happens in your program, right?</p>
<p>Voted up because it looks like an interesting question. :D</p>
| 5,648
|
<p>Ok, so I want to get a webapp running in tomcat (5.5) to run behind apache 2 (2.2.3 to be precise) serving from the root of the site (i.e. without the context), with static content being served via apache.</p>
<p>So if the app is running under "<code>/myapp</code>" on tomcat I want to use apache (plus <code>mod_rewrite</code>) to make it behave as if it's running under "<code>/</code>" instead.</p>
<p><code>Mod_jk</code> is setup and working ok. I can access the app from "<code>/myapp</code>", but I can't quite get the last bit working. Below is the config I've got for <code>mod_rewrite</code> to try and get this working. It correctly gets rewrites <code>/static/</code> urls to get apache to serve them from the unpacked webapp and if I enable the rewrite log I see that it does attempt to pass through all other requests to <code>/myapp</code> via <code>mod_jk</code>. However it seems that mod_jk is not processing the request afterwards.</p>
<pre>
<code>
JkMount /myapp/* worker1
RewriteEngine On
# ensure static stuff gets served by apache
RewriteRule ^/static/(.*)$ /var/lib/tomcat5.5/webapps/myapp/static/$1 [L]
# everything else should go through tomcat
RewriteRule ^/(.*)$ /myapp/$1 [L,PT]
</code>
</pre>
<p>When I've done this with apache 1 in the past I've had to make sure <code>mod_jk</code> get's loaded before <code>mod_rewrite</code>, but I can't seem to achieve this under apache 2. Any thoughts? How do other people usually do this?</p>
|
<p>Managed to get this working in the end. It appears that I need to set a JkOption to:</p>
<pre>
<code>
JkOptions +ForwardURICompat
</code>
</pre>
<p>And then <code>mod_jk</code> looks at the rewritten URL. Must admit not 100% sure quite why this works, but I believe it's reverting to an older form of behaviour. If anyone can tell me a better/more correct way of doing this I'd love to know.</p>
|
<p>We use the 'R' flag instead of 'PT':</p>
<pre><code>RewriteRule ^/(.*)$ /myapp/$1 [L,R]
</code></pre>
<p><strong>Edit:</strong>
I missed the point to not alter the URL the user sees. An alternative way is to do:</p>
<pre><code>JkMount /* worker1
JkUnmount /static/* worker1
</code></pre>
<p>Then you won´t need the RewriteRule's.</p>
<p>And according to <a href="http://tomcat.apache.org/security-jk.html" rel="nofollow noreferrer">Apache Tomcat Site</a> the new default settings of the <code>mod_jk</code> are incompatible with <code>mod_rewrite</code> and you should use <code>+ForwardURICompatUnparsed</code>.</p>
| 25,545
|
<p>I use the dark-blue2 color theme but it seems ugly under console.
So I want to use no color theme under terminal, what can I do then?</p>
|
<p>To be slightly shorter than those guys, the variable <strong><code>window-system</code></strong> is <em><code>something</code></em> if you're in a window-system, and <code>nil</code> if you're in a terminal, So if i wanted to load color-theme-darkblue2 i would have:</p>
<pre><code>(if window-system
(progn
(load "color-theme")
(color-theme-darkblue2)))
</code></pre>
<p>and it will just use the default colors in the terminal. Of course, you could obviously load a term-friendly theme in the else-part if you wanted to:</p>
<pre><code>(load "color-theme")
(if window-system
(color-theme-darkblue2)
(some-term-theme)))
</code></pre>
|
<p>Another simple one I use:</p>
<pre><code>(when window-system
(load-theme '<myThemeName>))
</code></pre>
<p>So this will load the theme in all cases where window-system is not nil, which is basically any kind of gui. </p>
| 34,756
|
<p>If my code throws an exception, sometimes - not everytime - the jsf presents a blank page. I´m using facelets for layout.
A similar error were reported at this <a href="http://forums.sun.com/thread.jspa?messageID=10237827" rel="nofollow noreferrer">Sun forumn´s post</a>, but without answers.
Anyone else with the same problem, or have a solution?
;)</p>
<p>Due to some requests. Here follow more datails:</p>
<p>web.xml</p>
<pre><code> <error-page>
<exception-type>com.company.ApplicationResourceException</exception-type>
<location>/error.faces</location>
</error-page>
</code></pre>
<p>And the stack related to jsf is printed after the real exception:</p>
<pre><code>####<Sep 23, 2008 5:42:55 PM GMT-03:00> <Error> <HTTP> <comp141> <AdminServer> <[ACTIVE] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1222202575662> <BEA-101107> <[weblogic.servlet.internal.WebAppServletContext@6d46b9 - appName: 'ControlPanelEAR', name: 'ControlPanelWeb', context-path: '/Web'] Problem occurred while serving the error page.
javax.servlet.ServletException: viewId:/error.xhtml - View /error.xhtml could not be restored.
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:249)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:525)
at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:261)
at weblogic.servlet.internal.ForwardAction.run(ForwardAction.java:22)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.ErrorManager.handleException(ErrorManager.java:144)
at weblogic.servlet.internal.WebAppServletContext.handleThrowableFromInvocation(WebAppServletContext.java:2201)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2053)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
javax.faces.application.ViewExpiredException: viewId:/error.xhtml - View /error.xhtml could not be restored.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:180)
at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:248)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:244)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
</code></pre>
<p>I´m using the jsf version <code>Mojarra 1.2_09</code>, <code>richfaces 3.2.1.GA</code> and <code>facelets 1.1.13</code>.</p>
<p>Hope some help :(</p>
|
<p>I think this largely depends on your JSF implementation. I've heard that some will render blank screens.</p>
<p>The one we were using would throw error 500's with a stack trace. Other times out buttons wouldn't work without any error for the user. This was all during our development phase. </p>
<p>But the best advice I can give you is to catch the exceptions and log them in an error log so you have the stack trace for debugging later. For messages that we couldn't do anything about like a backend failing we would just add a fatal message to the FacesContext that gets displayed on the screen and log the stack trace.</p>
|
<p>For a blank page on JSF 2, place a breakpoint in <code>ExceptionHandlerWrapper.handle</code> or a class overriding this method. In my case it was due to custom code which was a too restrictive and the error was not logged.</p>
| 15,059
|
<p>I am trying to get data from my server, used RemoteObject to accomplish it.
When I run the application on my localhost it works great but when iam using it on my server i get a Channel.Security.Error(Security Error accessing URL).</p>
<p>On the server side logs there is a mention about cross domain .
77.127.194.4 - - [23/Oct/2008 21:15:11] "GET /crossdomain.xml HTTP/1.1" 501</p>
<p>Any one encountered the same problem ? any idea ?</p>
|
<p>See <a href="http://www.projecthoneypot.org/" rel="noreferrer">Project Honeypot</a> - they're setting up bot traps on large scale (and have DNSRBL with their IPs).</p>
<p>Use tricky URLs and HTML:</p>
<pre><code><a href="//example.com/"> = http://example.com/ on http pages.
<a href="page&amp;&#x23;hash"> = page& + #hash
</code></pre>
<p>In HTML you can use plenty of tricks with comments, CDATA elements, entities, etc:</p>
<pre><code><a href="foo<!--bar-->"> (comment should not be removed)
<script>var haha = '<a href="bot">'</script>
<script>// <!-- </script> <!--><a href="bot"> <!-->
</code></pre>
|
<p>short answer: if a mid level programmer knows what he's doing you won't be able to detect a crawler without affecting the real user. Having your information publicly you won't be able to defend it against a crawler... it's like the 1st amendment right :)</p>
| 28,864
|
<p>From <a href="http://pypi.python.org/pypi/PyPubSub/" rel="noreferrer">PyPubSub</a>:</p>
<blockquote>
<p>Pypubsub provides a simple way for
your Python application to decouple
its components: parts of your
application can publish messages (with
or without data) and other parts can
subscribe/receive them. This allows
message "senders" and message
"listeners" to be unaware of each
other:</p>
<ul>
<li>one doesn't need to import the other</li>
<li>a sender doesn't need to know
<ul>
<li>"who" gets the messages, </li>
<li>what the listeners will do with the data, </li>
<li>or even if any listener will get the message data.</li>
</ul></li>
<li>similarly, listeners don't need to worry about where messages come from.</li>
</ul>
<p>This is a great tool for implementing
a Model-View-Controller architecture
or any similar architecture that
promotes decoupling of its components.</p>
</blockquote>
<p>There seem to be quite a few Python modules for publishing/subscribing floating around the web, from PyPubSub, to <a href="http://pydispatcher.sourceforge.net/" rel="noreferrer">PyDispatcher</a> to simple "home-cooked" classes.</p>
<p>Are there specific advantages and disadvantages when comparing different different modules? Which sets of modules have been benchmarked and compared?</p>
<p>Thanks in advance</p>
|
<p><a href="http://pydispatcher.sourceforge.net/" rel="noreferrer">PyDispatcher</a> is used heavily in <a href="http://pydispatcher.sourceforge.net/" rel="noreferrer">Django</a> and it's working perfectly for me (and for whole Django community, I guess). </p>
<p>As I remember, there are some performance issues:</p>
<ul>
<li>Arguments checking made by PyDispatcher is slow.</li>
<li>Unused connections have unnecessary overhead.</li>
</ul>
<p>AFAIK it's very unlikely you will run into this issues in a small-to-medium sized application. So these issues may not concern you. If you think you need every pound of performance (premature optimization is the root of all evil!), you can look at modifications done to PyDispatcher in Django.</p>
<p>Hope this helps.</p>
|
<p>The fact alone that PyPubSub seems to be a somewhat chaotically managed project (the Wiki on SF is dead, the website (another Wiki) which is linked on SF is currently broken) would be enough reason for me not to use it.
PyDispatcher has an intact website, but the only documentation they seem to provide is the one for the API generated from the docstrings. No traffic on the mailing list either... a bad sign!</p>
<p>As Mike also mentioned, it's perfectly possible to choose a solution that is independent of Python. Now don't get me wrong, I <em>love</em> Python, but still, in this field it can make sense use a framework that is decoupled from the programming language.</p>
<p>I'm not experienced with messaging, but I'm planning to have a look into a few solutions. So far these two (free, open source) projects seem to be the most promising for me (coincidentally, both are Apache projects):</p>
<ul>
<li><a href="http://activemq.apache.org/" rel="nofollow noreferrer">ActiveMQ</a></li>
<li><a href="http://qpid.apache.org/" rel="nofollow noreferrer">Qpid</a></li>
</ul>
<p>Both seem to be reasonably matured projects, at least a far as documentation and community. I can't comment on the software's quality though, as I said, I didn't use any of the software.</p>
<p>Qpid ships with client libraries for Python, but you could also use <a href="http://barryp.org/software/py-amqplib/" rel="nofollow noreferrer">py-amqplib</a>. For ActiveMQ there's <a href="http://code.google.com/p/pyactivemq/" rel="nofollow noreferrer">pyactivemq</a>, which you can use to connect either via STOMP (Streaming Text Orientated Messaging Protocol) or via Openwire.</p>
| 14,121
|
<p>My understanding is that <a href="http://www.wxwidgets.org" rel="noreferrer">wxWidgets</a> is for a number of programming languages (C++, Python, Perl, and C#/.NET) but that does not include C. Is there a similar framework for the C programming language, or is this not something that C is used for?</p>
|
<p>You can try <a href="http://www.gtk.org/" rel="nofollow noreferrer">GTK+</a>. I believe wxWidgets implementation for linux is written in GTK+.</p>
|
<p>Obviously No, Because it has predefined classes but if you insist you can try GTK which is for C.</p>
| 4,968
|
<p>What is a fairly standard way for storing application settings, mainly for windows but also easy to move over to other platforms.</p>
<p>There's basically 4 groups of settings I want to have:</p>
<ul>
<li>Global settings, affects all users, and may be moved between machines</li>
<li>Global system settings, affects all users, but specific to that system (eg defaults for that system, eg graphics options)</li>
<li>User settings, user settings that are moved between systems (eg sound volume)</li>
<li>User system settings, user settings specific to that system (eg graphics options that are hardware dependent)</li>
</ul>
<p>Each level overrides the previous level, allowing for "global settings" to be largly the applications defaults, with user settings storing the options the user chose.
The first two will basically be defaults where there is no user setting (eg for a new user).</p>
<p>I considered implementing a set of functions, which I could then implement for the different systems (likely to be through ini files), but is this the best way?</p>
<p>(c++) </p>
<pre><code>namespace config
{
void Init(const std::string &AppName);
//updates config for keys/sections that don't exist (ie don't overwrite changes by advanced users by rewriting the entire file)
void Defaults (std::map<std::string,std::map<std::string,std::string> > &Map);
void SystemDefaults (std::map<std::string,std::map<std::string,std::string> > &Map);
void Set (const std::string &Section, const std::string &Key, const std::string &Value);
void SetSystem (const std::string &Section, const std::string &Key, const std::string &Value);
void SetUser (const std::string &Section, const std::string &Key, const std::string &Value);
void SetUserSystem (const std::string &Section, const std::string &Key, const std::string &Value);
std::string GetValue (const std::string &Section, const std::string &Key);
}
</code></pre>
<p>I know windows has a set of directories for such settings, but are these the correct dirs for my needs? </p>
<p>EDIT: I would rather go with files (ini or xml), rather than using say the windows registery. However wheres the best places to put these config files under each OS?</p>
<p>Under Vista I found these, which seem to fit my groups, however what of older windows versions (I need to support win2000, XP, etc), and does mac/linux have there own simelar folders? </p>
<ul>
<li>Global settings - <SYSDRIVE>\Users\Default\Appdata\Roaming</li>
<li>Global system settings - <SYSDRIVE>\Users\Default\Appdata\Local</li>
<li>User settings - <SYSDRIVE>\Users\<USER>\AppData\Roaming</li>
<li>User system settings - <SYSDRIVE>\Users\<USER>\AppData\Local</li>
</ul>
|
<p>If you are a boost user, you might take a look at the <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/program_options.html" rel="noreferrer">program options</a> library, it supports using config files as well as environment variables and (of course) command line options.</p>
<p>It is designed to be portable, so that should ease your cross-platform headaches. </p>
|
<p>There are (at least) three reasonable choices:</p>
<p>Registry: This is my least favorite because of portability and relative opacity.</p>
<p>Environment variables: I recommend using one (just one) that points to a place where your material is kept - an "installation directory" or some such.</p>
<p>Files: Both a/the user-home directory (or in a subdirectory thereof) and project/product directory are suitable for storing things.</p>
<p>You might want to use a simple keyword=value paradigm, and basic rules so your variables - settings - can be read by more than one type of code very easily. For example, I typically use the Java paradigm for Property files and use matching behavior C code so both my codelines can easily read the settings.</p>
| 25,578
|
<p>Are there any systems out there where one can check in changes for a website and have that automatically update the website. </p>
<p>The website effetively runs off the latest stable build the whole time without the need to ftp the files to the server.</p>
|
<p>I would look into using a <a href="http://svnbook.red-bean.com/en/1.4/svn.ref.reposhooks.post-commit.html" rel="nofollow noreferrer">post-commit hook</a> to update the site when changes are made. This could be something as simple as using "svn export" to export the current state of the repository to the live website location. Of course, this has performance considerations if your site has lots of content, so you may want to do something more sophisticated and only push updates for content that was changed in the commit.</p>
|
<p>SVN's post_commit hook is ideal for things like this.</p>
<p><a href="http://amiworks.co.in/talk/ads-automatic-deployment-script/" rel="nofollow noreferrer">ADS (automatic deployment script</a> looks like a solution to this, but I've never tried it - just found it with a few seconds of Googling.</p>
| 9,662
|
<p>So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.</p>
<p>Turns out the IList interface doesn't have a sort method built in. </p>
<p>I ended up using the <code>ArrayList.Adapter(list).Sort(new MyComparer())</code> method to solve the problem but it just seemed a bit "ghetto" to me.</p>
<p>I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.</p>
<p>So my question is, does anyone have an elegant solution to sorting an IList</p>
|
<p>How about using LINQ To Objects to sort for you?</p>
<p>Say you have a <code>IList<Car></code>, and the car had an <code>Engine</code> property, I believe you could sort as follows:</p>
<pre><code>from c in list
orderby c.Engine
select c;
</code></pre>
<p><em>Edit: You do need to be quick to get answers in here. As I presented a slightly different syntax to the other answers, I will leave my answer - however, the other answers presented are equally valid.</em></p>
|
<p>Convert your <code>IList</code> into <code>List<T></code> or some other generic collection and then you can easily query/sort it using <code>System.Linq</code> namespace (it will supply bunch of extension methods)</p>
| 3,630
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.