qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
138,948
<p>I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support <code>äöå</code> etc. for regular Finnish text and Cyrillic alphabets like <code>ЦжФ</code> for special cases.</p> <p>My setup is the following:</p> <ul> <li>Development environment: Windows XP</li> <li>Production environment: Debian</li> </ul> <p>Database used: MySQL 5.x</p> <p>Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site.</p> <p>How to achieve this?</p>
[ { "answer_id": 138950, "author": "kosoant", "author_id": 15114, "author_profile": "https://Stackoverflow.com/users/15114", "pm_score": 10, "selected": true, "text": "<p><em>Answering myself as the FAQ of this site encourages it. This works for me: </em></p>\n\n<p>Mostly characters äåö ar...
2008/09/26
[ "https://Stackoverflow.com/questions/138948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15114/" ]
I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support `äöå` etc. for regular Finnish text and Cyrillic alphabets like `ЦжФ` for special cases. My setup is the following: * Development environment: Windows XP * Production environment: Debian Database used: MySQL 5.x Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site. How to achieve this?
*Answering myself as the FAQ of this site encourages it. This works for me:* Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters. To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following: Configuring Tomcat's server.xml ------------------------------- It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters: ``` <Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" compression="on" compressionMinSize="128" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript" URIEncoding="UTF-8" /> ``` The key part being **URIEncoding="UTF-8"** in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded. As a result, when the user writes the following to the address bar of the browser: ``` https://localhost:8443/ID/Users?action=search&name=*ж* ``` the character ж is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as **%D0%B6**. *POST request are not affected by this.* CharsetFilter -------------- Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following: ``` package fi.foo.filters; import javax.servlet.*; import java.io.IOException; public class CharsetFilter implements Filter { private String encoding; public void init(FilterConfig config) throws ServletException { encoding = config.getInitParameter("requestEncoding"); if (encoding == null) encoding = "UTF-8"; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException { // Respect the client-specified character encoding // (see HTTP specification section 3.4.1) if (null == request.getCharacterEncoding()) { request.setCharacterEncoding(encoding); } // Set the default response content type and encoding response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); next.doFilter(request, response); } public void destroy() { } } ``` This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8. The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application. This filter has to be added to the **web.xml** or the deployment descriptor of the webapp: ``` <!--CharsetFilter start--> <filter> <filter-name>CharsetFilter</filter-name> <filter-class>fi.foo.filters.CharsetFilter</filter-class> <init-param> <param-name>requestEncoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharsetFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` The instructions for making this filter are found at the [tomcat wiki (<http://wiki.apache.org/tomcat/Tomcat/UTF-8>)](http://wiki.apache.org/tomcat/Tomcat/UTF-8) JSP page encoding ------------------ In your **web.xml**, add the following: ``` <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <page-encoding>UTF-8</page-encoding> </jsp-property-group> </jsp-config> ``` Alternatively, all JSP-pages of the webapp would need to have the following at the top of them: ``` <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> ``` If some kind of a layout with different JSP-fragments is used, then this is needed in **all** of them. HTML-meta tags --------------- JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding. Then it's time to tell the browser in which encoding the html page is: This is done with the following at the top of each xhtml page produced by the webapp: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi"> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> ... ``` JDBC-connection ---------------- When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in **context.xml** or wherever the JDBC connection is defiend as follows: ``` <Resource name="jdbc/AppDB" auth="Container" type="javax.sql.DataSource" maxActive="20" maxIdle="10" maxWait="10000" username="foo" password="bar" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ ID_development?useEncoding=true&amp;characterEncoding=UTF-8" /> ``` MySQL database and tables -------------------------- The used database must use UTF-8 encoding. This is achieved by creating the database with the following: ``` CREATE DATABASE `ID_development` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */; ``` Then, all of the tables need to be in UTF-8 also: ``` CREATE TABLE `Users` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(30) collate utf8_swedish_ci default NULL PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC; ``` The key part being **CHARSET=utf8**. MySQL server configuration --------------------------- MySQL serveri has to be configured also. Typically this is done in Windows by modifying **my.ini** -file and in Linux by configuring **my.cnf** -file. In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8. ``` [client] port=3306 default-character-set=utf8 [mysql] default-character-set=utf8 ``` Mysql procedures and functions ------------------------------- These also need to have the character set defined. For example: ``` DELIMITER $$ DROP FUNCTION IF EXISTS `pathToNode` $$ CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8 READS SQL DATA BEGIN DECLARE path VARCHAR(255) CHARACTER SET utf8; SET path = NULL; ... RETURN path; END $$ DELIMITER ; ``` GET requests: latin1 and UTF-8 ------------------------------- If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly: ``` https://localhost:8443/ID/Users?action=search&name=Petteri https://localhost:8443/ID/Users?action=search&name=ж ``` Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly. The Cyrillic character ж is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as **%D0%B6**. If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as **%D0%B6**. The end result is that all users with name "Petteri" are found and also all users with the name "ж" are found. ### But what about äåö? HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following ``` https://localhost:8443/ID/Users?action=search&name=*Päivi* ``` in to the encoded version ``` https://localhost:8443/ID/Users?action=search&name=*P%E4ivi* ``` In latin1 the character **ä** is encoded as **%E4**. *Even though the page/request/everything is defined to use UTF-8*. The UTF-8 encoded version of ä is **%C3%A4** The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8. **Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8** Stuff to read -------------- A very big thank you for the writers of the following for giving the answers for my problem: * http://tagunov.tripod.com/i18n/i18n.html * http://wiki.apache.org/tomcat/Tomcat/UTF-8 * http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/ * http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html * http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html * http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html * http://jeppesn.dk/utf-8.html * http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html * http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso\_table.html * http://www.utf8-chartable.de/ Important Note -------------- [mysql](/questions/tagged/mysql "show questions tagged 'mysql'") supports the [Basic Multilingual Plane](http://en.wikipedia.org/wiki/Plane_%28Unicode%29#Basic_Multilingual_Plane) using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of `VARBINARY` column type or use the [`utf8mb4` character set](http://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html) (which requires MySQL 5.5.3 or later). Just be aware that using the `utf8` character set in MySQL won't work 100% of the time. Tomcat with Apache ------------------ One more thing If you are using Apache + Tomcat + mod\_JK connector then you also need to do following changes: 1. Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod\_JK connector. `<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>` 2. Goto your apache folder i.e. `/etc/httpd/conf` and add `AddDefaultCharset utf-8` in `httpd.conf file`. **Note:** First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.
138,981
<p>Is there any way to find out if a file is a directory?</p> <p>I have the file name in a variable. In Perl I can do this:</p> <pre><code>if(-d $var) { print "it's a directory\n" } </code></pre>
[ { "answer_id": 138995, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 7, "selected": true, "text": "<p>You can do it like so:</p>\n\n<pre><code>IF EXIST %VAR%\\NUL ECHO It's a directory\n</code></pre>\n\n<p>However, this o...
2008/09/26
[ "https://Stackoverflow.com/questions/138981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
Is there any way to find out if a file is a directory? I have the file name in a variable. In Perl I can do this: ``` if(-d $var) { print "it's a directory\n" } ```
You can do it like so: ``` IF EXIST %VAR%\NUL ECHO It's a directory ``` However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows: ``` FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory ``` The `%%~si` converts `%%i` to an 8.3 filename. To see all the other tricks you can perform with `FOR` variables enter `HELP FOR` at a command prompt. (Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the `%%` with `%` in both places.)
138,994
<p>I have a procedure with a lot of </p> <pre><code>i := i +1; </code></pre> <p>in it and I think </p> <pre><code> inc(i); </code></pre> <p>looks a lot better. Is there a performance difference or does the function call just get inlined by the compiler? I know this probably doesn't matter at all to my app, I'm just curious.</p> <p>EDIT: I did some gauging of the performance and found the difference to be very small, in fact as small as 5.1222741794670901427682121946224e-8! So it really doesn't matter. And optimization options really didn't change the outcome much. Thanks for all tips and suggestions!</p>
[ { "answer_id": 139008, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 4, "selected": true, "text": "<p>Modern compilers optimize the code.<br>\ninc(i) and i:= i+1; are pretty much the same.</p>\n\n<p>Use whichever you pref...
2008/09/26
[ "https://Stackoverflow.com/questions/138994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9077/" ]
I have a procedure with a lot of ``` i := i +1; ``` in it and I think ``` inc(i); ``` looks a lot better. Is there a performance difference or does the function call just get inlined by the compiler? I know this probably doesn't matter at all to my app, I'm just curious. EDIT: I did some gauging of the performance and found the difference to be very small, in fact as small as 5.1222741794670901427682121946224e-8! So it really doesn't matter. And optimization options really didn't change the outcome much. Thanks for all tips and suggestions!
Modern compilers optimize the code. inc(i) and i:= i+1; are pretty much the same. Use whichever you prefer. Edit: As Jim McKeeth corrected: with Overflow Checking there is a difference. Inc does not do a range checking.
138,999
<p>I just started learning JSP technology, and came across a wall.</p> <p><em>How do you output HTML from a method in &lt;%! ... %> JSP declaration block?</em></p> <p>This doesn't work:</p> <pre><code>&lt;%! void someOutput() { out.println("Some Output"); } %&gt; ... &lt;% someOutput(); %&gt; </code></pre> <p>Server says there's no &ldquo;out&rdquo;.</p> <p><strong>U:</strong> I do know how to rewrite code with this method returning a string, but is there a way to do this inside &lt;%! void () { } %> ? Though it may be non-optimal, it's still interesting.</p>
[ { "answer_id": 139018, "author": "Ashley Mercer", "author_id": 13065, "author_profile": "https://Stackoverflow.com/users/13065", "pm_score": 5, "selected": false, "text": "<p>You can't use the 'out' variable (nor any of the other \"predeclared\" scriptlet variables) inside directives.</p...
2008/09/26
[ "https://Stackoverflow.com/questions/138999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1764/" ]
I just started learning JSP technology, and came across a wall. *How do you output HTML from a method in <%! ... %> JSP declaration block?* This doesn't work: ``` <%! void someOutput() { out.println("Some Output"); } %> ... <% someOutput(); %> ``` Server says there's no “out”. **U:** I do know how to rewrite code with this method returning a string, but is there a way to do this inside <%! void () { } %> ? Though it may be non-optimal, it's still interesting.
You can't use the 'out' variable (nor any of the other "predeclared" scriptlet variables) inside directives. The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start "<%"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called "out". This is why you can use the "out" parameter directly in scriptlets. Directives, on the other hand (which start with "<%!") get translated as separate Java methods. As an example, a very simple page (let's call it foo.jsp): ``` <html> <head/> <body> <%! String someOutput() { return "Some output"; } %> <% someOutput(); %> </body> </html> ``` would end up looking something like this (with a lot of the detail ignored for clarity): ``` public final class foo_jsp { // This is where the request comes in public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // JspWriter instance is gotten from a factory // This is why you can use 'out' directly in scriptlets JspWriter out = ...; // Snip out.write("<html>"); out.write("<head/>"); out.write("<body>"); out.write(someOutput()); // i.e. write the results of the method call out.write("</body>"); out.write("</html>"); } // Directive gets translated as separate method - note // there is no 'out' variable declared in scope private String someOutput() { return "Some output"; } } ```
139,000
<p>I hope someone might be able to help me here. I've tried to simplify my example as best I can.</p> <p>I have an absolutely positioned DIV, which for this example I've made fill the browser window. This div has the overflow:auto attribute to provide scroll bars when the content is too big for the DIV to display.</p> <p>Within the DIV I have a table to present some data, and it's width is 100%.</p> <p>When the content becomes too large vertically, I expect the vertical scroll bar to appear and the table to shrink horizontally slightly to accommodate the scroll bar. However in IE7 what happens is the horizontal scroll bar also appears, despite there still being enough space horizontally for all the content in the div.</p> <p>This is IE specific - firefox works perfectly.</p> <p>Full source below. Any help greatly appreciated.</p> <p>Tony</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;Table sizing bug?&lt;/title&gt; &lt;style&gt; #maxsize { position: absolute; left: 5px; right: 5px; top: 5px; bottom: 5px; border: 5px solid silver; overflow: auto; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div id="maxsize"&gt; &lt;p&gt;This will be fine until such time as the vertical size forces a vertical scroll bar. At this point I'd expect the table to re-size to now take into account of the new vertical scroll bar. Instead, IE7 keeps the table the full size and introduces a horizontal scroll bar. &lt;/p&gt; &lt;table width="100%" cellspacing="0" cellpadding="0" border="1"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;A&lt;/td&gt; &lt;td&gt;B&lt;/td&gt; &lt;td&gt;C&lt;/td&gt; &lt;td&gt;D&lt;/td&gt; &lt;td&gt;E&lt;/td&gt; &lt;td&gt;F&lt;/td&gt; &lt;td&gt;G&lt;/td&gt; &lt;td&gt;H&lt;/td&gt; &lt;td&gt;I&lt;/td&gt; &lt;td&gt;J&lt;/td&gt; &lt;td&gt;K&lt;/td&gt; &lt;td&gt;L&lt;/td&gt; &lt;td&gt;M&lt;/td&gt; &lt;td&gt;N&lt;/td&gt; &lt;td&gt;O&lt;/td&gt; &lt;td&gt;P&lt;/td&gt; &lt;td&gt;Q&lt;/td&gt; &lt;td&gt;R&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;Resize the browser window vertically so this content doesn't fit any more&lt;/p&gt; &lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt; &lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt;&lt;p&gt;Hello&lt;/p&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p><strong>added 03/16/10...</strong> thought it might be interesting to point out that GWT's source code points to this question in a comment... <a href="http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&amp;q=%22hack%20to%20account%20for%20the%22%20scrollpanel&amp;sa=N&amp;cd=1&amp;ct=rc&amp;l=48" rel="noreferrer">http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&amp;q=%22hack%20to%20account%20for%20the%22%20scrollpanel&amp;sa=N&amp;cd=1&amp;ct=rc&amp;l=48</a></p>
[ { "answer_id": 139024, "author": "Patcouch22", "author_id": 19226, "author_profile": "https://Stackoverflow.com/users/19226", "pm_score": 0, "selected": false, "text": "<p>This looks like it should fix your problem, as long as you are not apposed to condition statements. <a href=\"http:...
2008/09/26
[ "https://Stackoverflow.com/questions/139000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I hope someone might be able to help me here. I've tried to simplify my example as best I can. I have an absolutely positioned DIV, which for this example I've made fill the browser window. This div has the overflow:auto attribute to provide scroll bars when the content is too big for the DIV to display. Within the DIV I have a table to present some data, and it's width is 100%. When the content becomes too large vertically, I expect the vertical scroll bar to appear and the table to shrink horizontally slightly to accommodate the scroll bar. However in IE7 what happens is the horizontal scroll bar also appears, despite there still being enough space horizontally for all the content in the div. This is IE specific - firefox works perfectly. Full source below. Any help greatly appreciated. Tony ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Table sizing bug?</title> <style> #maxsize { position: absolute; left: 5px; right: 5px; top: 5px; bottom: 5px; border: 5px solid silver; overflow: auto; } </style> </head> <body> <form id="form1" runat="server"> <div id="maxsize"> <p>This will be fine until such time as the vertical size forces a vertical scroll bar. At this point I'd expect the table to re-size to now take into account of the new vertical scroll bar. Instead, IE7 keeps the table the full size and introduces a horizontal scroll bar. </p> <table width="100%" cellspacing="0" cellpadding="0" border="1"> <tbody> <tr> <td>A</td> <td>B</td> <td>C</td> <td>D</td> <td>E</td> <td>F</td> <td>G</td> <td>H</td> <td>I</td> <td>J</td> <td>K</td> <td>L</td> <td>M</td> <td>N</td> <td>O</td> <td>P</td> <td>Q</td> <td>R</td> </tr> </tbody> </table> <p>Resize the browser window vertically so this content doesn't fit any more</p> <p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p> <p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p> </div> </form> </body> </html> ``` --- **added 03/16/10...** thought it might be interesting to point out that GWT's source code points to this question in a comment... <http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&q=%22hack%20to%20account%20for%20the%22%20scrollpanel&sa=N&cd=1&ct=rc&l=48>
I had a problem with excessive horizonal bar in IE7. I've used D Carter's solution slighty changed ``` <div style="zoom: 1; overflow: auto;"> <div id="myDiv" style="zoom: 1;"> <table style="width: 100%"... ... </table> </div> </div> ``` To work in IE browser lesser than 7 you need add: ``` <!--[if lt IE 7]><style> #myDiv { overflow: auto; } </style><![endif]--> ```
139,010
<p>I need to find out the file/directory name that a .lnk is pointing to using c#.</p> <p>What is the simplest way to do this?</p> <p>Thanks.</p>
[ { "answer_id": 139032, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": false, "text": "<p>This may help:</p>\n\n<p><a href=\"http://www.neowin.net/forum/index.php?s=3ad7f1ffb995ba84999376f574e9250f&amp;showtopic=65892...
2008/09/26
[ "https://Stackoverflow.com/questions/139010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to find out the file/directory name that a .lnk is pointing to using c#. What is the simplest way to do this? Thanks.
I wrote this for video browser, it works really well ``` #region Signitures imported from http://pinvoke.net [DllImport("shfolder.dll", CharSet = CharSet.Auto)] internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath); [Flags()] enum SLGP_FLAGS { /// <summary>Retrieves the standard short (8.3 format) file name</summary> SLGP_SHORTPATH = 0x1, /// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary> SLGP_UNCPRIORITY = 0x2, /// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary> SLGP_RAWPATH = 0x4 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] struct WIN32_FIND_DATAW { public uint dwFileAttributes; public long ftCreationTime; public long ftLastAccessTime; public long ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName; } [Flags()] enum SLR_FLAGS { /// <summary> /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set, /// the high-order word of fFlags can be set to a time-out value that specifies the /// maximum amount of time to be spent resolving the link. The function returns if the /// link cannot be resolved within the time-out duration. If the high-order word is set /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out /// duration, in milliseconds. /// </summary> SLR_NO_UI = 0x1, /// <summary>Obsolete and no longer used</summary> SLR_ANY_MATCH = 0x2, /// <summary>If the link object has changed, update its path and list of identifiers. /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine /// whether or not the link object has changed.</summary> SLR_UPDATE = 0x4, /// <summary>Do not update the link information</summary> SLR_NOUPDATE = 0x8, /// <summary>Do not execute the search heuristics</summary> SLR_NOSEARCH = 0x10, /// <summary>Do not use distributed link tracking</summary> SLR_NOTRACK = 0x20, /// <summary>Disable distributed link tracking. By default, distributed link tracking tracks /// removable media across multiple devices based on the volume name. It also uses the /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary> SLR_NOLINKINFO = 0x40, /// <summary>Call the Microsoft Windows Installer</summary> SLR_INVOKE_MSI = 0x80 } /// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary> [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")] interface IShellLinkW { /// <summary>Retrieves the path and file name of a Shell link object</summary> void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags); /// <summary>Retrieves the list of item identifiers for a Shell link object</summary> void GetIDList(out IntPtr ppidl); /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary> void SetIDList(IntPtr pidl); /// <summary>Retrieves the description string for a Shell link object</summary> void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName); /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary> void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); /// <summary>Retrieves the name of the working directory for a Shell link object</summary> void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); /// <summary>Sets the name of the working directory for a Shell link object</summary> void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary> void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); /// <summary>Sets the command-line arguments for a Shell link object</summary> void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); /// <summary>Retrieves the hot key for a Shell link object</summary> void GetHotkey(out short pwHotkey); /// <summary>Sets a hot key for a Shell link object</summary> void SetHotkey(short wHotkey); /// <summary>Retrieves the show command for a Shell link object</summary> void GetShowCmd(out int piShowCmd); /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary> void SetShowCmd(int iShowCmd); /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary> void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon); /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary> void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); /// <summary>Sets the relative path to the Shell link object</summary> void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved); /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary> void Resolve(IntPtr hwnd, SLR_FLAGS fFlags); /// <summary>Sets the path and file name of a Shell link object</summary> void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); } [ComImport, Guid("0000010c-0000-0000-c000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPersist { [PreserveSig] void GetClassID(out Guid pClassID); } [ComImport, Guid("0000010b-0000-0000-C000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPersistFile : IPersist { new void GetClassID(out Guid pClassID); [PreserveSig] int IsDirty(); [PreserveSig] void Load([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, uint dwMode); [PreserveSig] void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [In, MarshalAs(UnmanagedType.Bool)] bool fRemember); [PreserveSig] void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName); [PreserveSig] void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName); } const uint STGM_READ = 0; const int MAX_PATH = 260; // CLSID_ShellLink from ShlGuid.h [ ComImport(), Guid("00021401-0000-0000-C000-000000000046") ] public class ShellLink { } #endregion public static string ResolveShortcut(string filename) { ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder sb = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); } ```
139,012
<p>Does anyone know how I can achieve the following effect in OpenGL:</p> <ul> <li>Change the brightness of the rendered scene</li> <li>Or implementing a Gamma setting in OpenGL</li> </ul> <p>I have tried by changing the ambient parameter of the light and the type of light (directional and omnidirectional) but the result was not uniform. TIA.</p> <p>Thanks for your help, some additional information: * I can't use any windows specifics API. * The gamma setting should not affect the whole window as I must have different gamma for different views.</p>
[ { "answer_id": 139038, "author": "Harald Scheirich", "author_id": 22080, "author_profile": "https://Stackoverflow.com/users/22080", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.gamedev.net/community/forums/topic.asp?topic_id=435400\" rel=\"nofollow noreferrer\">http...
2008/09/26
[ "https://Stackoverflow.com/questions/139012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18564/" ]
Does anyone know how I can achieve the following effect in OpenGL: * Change the brightness of the rendered scene * Or implementing a Gamma setting in OpenGL I have tried by changing the ambient parameter of the light and the type of light (directional and omnidirectional) but the result was not uniform. TIA. Thanks for your help, some additional information: \* I can't use any windows specifics API. \* The gamma setting should not affect the whole window as I must have different gamma for different views.
On win32 you can use SetDeviceGammaRamp to adjust the overall brightness / gamma. However, this affects the entire display so it's not a good idea unless your app is fullscreen. The portable alternative is to either draw the entire scene brighter or dimmer (which is a hassle), or to slap a fullscreen alpha-blended quad over the whole scene to brighten or darken it as desired. Neither of these approaches can affect the gamma-curve, only the overall brightness; to adjust the gamma you need grab the entire scene into a texture and then render it back to the screen via a pixel-shader that runs each texel through a gamma function. Ok, having read the updated question, what you need is a quad with blending set up to darken or brighten everything underneath it. Eg. ``` if( brightness > 1 ) { glBlendFunc( GL_DEST_COLOR, GL_ONE ); glColor3f( brightness-1, brightness-1, brightness-1 ); } else { glBlendFunc( GL_ZERO, GL_SRC_COLOR ); glColor3f( brightness, brightness, brightness ); } glEnable( GL_BLEND ); draw_quad(); ```
139,015
<p>I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string. To date I have been using this:</p> <pre><code>my @search_results = `grep -i -l \"$string\" *.pdf`; </code></pre> <p>where $string is the text to look for. However this fails for most pdf's because the file format is obviously not ASCII.</p> <p>What can I do that's easiest?</p> <p>Clarification: There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet.</p> <p>Final solution using Adam Bellaire's suggestion below:</p> <pre><code>@search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`; </code></pre>
[ { "answer_id": 139077, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 4, "selected": true, "text": "<p>The PerlMonks thread <a href=\"http://www.perlmonks.org/?node_id=582868\" rel=\"noreferrer\">here</a> talks about ...
2008/09/26
[ "https://Stackoverflow.com/questions/139015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22654/" ]
I have a bunch of PDF files and my Perl program needs to do a full-text search of them to return which ones contain a specific string. To date I have been using this: ``` my @search_results = `grep -i -l \"$string\" *.pdf`; ``` where $string is the text to look for. However this fails for most pdf's because the file format is obviously not ASCII. What can I do that's easiest? Clarification: There are about 300 pdf's whose name I do not know in advance. PDF::Core is probably overkill. I am trying to get pdftotext and grep to play nice with each other given I don't know the names of the pdf's, I can't find the right syntax yet. Final solution using Adam Bellaire's suggestion below: ``` @search_results = `for i in \$( ls ); do pdftotext \$i - | grep --label="\$i" -i -l "$search_string"; done`; ```
The PerlMonks thread [here](http://www.perlmonks.org/?node_id=582868) talks about this problem. It seems that for your situation, it might be simplest to get **pdftotext** (the command line tool), then you can do something like: ``` my @search_results = `pdftotext myfile.pdf - | grep -i -l \"$string\"`; ```
139,046
<p>I need to write code that picks up PGP-encrypted files from an FTP location and processes them. The files will be encrypted with my public key (not that I have one yet). Obviously, I need a PGP library that I can use from within Microsoft Access. Can you recommend one that is easy to use? </p> <p>I'm looking for something that doesn't require a huge amount of PKI knowledge. Ideally, something that will easily generate the one-off private/public key pair, and then have a simple routine for decryption.</p>
[ { "answer_id": 139104, "author": "Birger", "author_id": 11485, "author_profile": "https://Stackoverflow.com/users/11485", "pm_score": 1, "selected": false, "text": "<p>I would look for a command line encrypter / decrypter and just call the exe from within your Access application, with th...
2008/09/26
[ "https://Stackoverflow.com/questions/139046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21379/" ]
I need to write code that picks up PGP-encrypted files from an FTP location and processes them. The files will be encrypted with my public key (not that I have one yet). Obviously, I need a PGP library that I can use from within Microsoft Access. Can you recommend one that is easy to use? I'm looking for something that doesn't require a huge amount of PKI knowledge. Ideally, something that will easily generate the one-off private/public key pair, and then have a simple routine for decryption.
A command line solution is good. If your database is an internal application, not to be redistributed, I can recommend [Gnu Privacy Guard](http://www.gnupg.org). This command-line based tool will allow you to do anything that you need to with regard to the OpenPGP standard. Within Access, you can use the Shell() command in a Macro like this: ``` Public Sub DecryptFile(ByVal FileName As String) Dim strCommand As String strCommand = "C:\Program Files\GNU\GnuPG\gpg.exe " _ & "--batch --passphrase ""My PassPhrase that I used""" & FileName Shell strCommand, vbNormalFocus End Sub ``` This will run the command-line tool to decrypt the file. This syntax uses a plaintext version of your secret passphrase. This is not the most secure solution, but is acceptable if your database is internal and only used by trusted personnel. GnuPG supports other techniques to secure the passphrase.
139,055
<p>I'm using Subversive plugin in Ganymede, but after today's update it stopped working - it just doesn't see any valid svn connectors (I've already been using 1.2.0 dev version of SVNKit, instead of a stable one, because Subversive / Ganymede could not handle it; now it can't handle even the dev one). Any ideas how to make it work? Are subversive guys releasing a new version of their plugin / connectors soon?</p>
[ { "answer_id": 139160, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": "<p>I'm using <a href=\"http://subclipse.tigris.org/\" rel=\"nofollow noreferrer\">Subclipse</a> in Ganymede successfully,...
2008/09/26
[ "https://Stackoverflow.com/questions/139055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4688/" ]
I'm using Subversive plugin in Ganymede, but after today's update it stopped working - it just doesn't see any valid svn connectors (I've already been using 1.2.0 dev version of SVNKit, instead of a stable one, because Subversive / Ganymede could not handle it; now it can't handle even the dev one). Any ideas how to make it work? Are subversive guys releasing a new version of their plugin / connectors soon?
I had a similar problem right after the update. It turned out that I had been getting the connectors (the base connector and both the SVNKit and JavaHL connectors) from the Polarion site that had "ganymede" in the URL. Instead, I should have been using the general URL. Checking my current configuration, you should be using this update URL: ``` http://www.polarion.org/projects/subversive/download/eclipse/2.0/update-site/ ``` The one I had been using, that should be deprecated if you are using it, is: ``` http://www.polarion.org/projects/subversive/download/eclipse/2.0/ganymede-site/ ``` Note the difference. Once I changed that, I was able to download the 2.0.3 versions of the connectors, and Subversion again worked for me.
139,076
<p>I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?</p> <pre><code>String unformattedXml = "&lt;tag&gt;&lt;nested&gt;hello&lt;/nested&gt;&lt;/tag&gt;"; String formattedXml = new [UnknownClass]().format(unformattedXml); </code></pre> <p>Note: My input is a <strong>String</strong>. My output is a <strong>String</strong>. </p> <p>(Basic) mock result:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;root&gt; &lt;tag&gt; &lt;nested&gt;hello&lt;/nested&gt; &lt;/tag&gt; &lt;/root&gt; </code></pre>
[ { "answer_id": 139096, "author": "Lorenzo Boccaccia", "author_id": 2273540, "author_profile": "https://Stackoverflow.com/users/2273540", "pm_score": 8, "selected": false, "text": "<pre class=\"lang-java prettyprint-override\"><code>Transformer transformer = TransformerFactory.newInstance...
2008/09/26
[ "https://Stackoverflow.com/questions/139076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ]
I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this? ``` String unformattedXml = "<tag><nested>hello</nested></tag>"; String formattedXml = new [UnknownClass]().format(unformattedXml); ``` Note: My input is a **String**. My output is a **String**. (Basic) mock result: ``` <?xml version="1.0" encoding="UTF-8"?> <root> <tag> <nested>hello</nested> </tag> </root> ```
Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6. ``` import org.w3c.dom.Node; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilderFactory; import java.io.StringReader; /** * Pretty-prints xml, supplied as a string. * <p/> * eg. * <code> * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>"); * </code> */ public class XmlFormatter { public String format(String xml) { try { final InputSource src = new InputSource(new StringReader(xml)); final Node document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement(); final Boolean keepDeclaration = Boolean.valueOf(xml.startsWith("<?xml")); //May need this: System.setProperty(DOMImplementationRegistry.PROPERTY,"com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl"); final DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); final DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS"); final LSSerializer writer = impl.createLSSerializer(); writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); // Set this to true if the output needs to be beautified. writer.getDomConfig().setParameter("xml-declaration", keepDeclaration); // Set this to true if the declaration is needed to be outputted. return writer.writeToString(document); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) { String unformattedXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" + " xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" + " xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" + " <Query>\n" + " <query:CategorySchemeWhere>\n" + " \t\t\t\t\t <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" + " </query:CategorySchemeWhere>\n" + " </Query>\n\n\n\n\n" + "</QueryMessage>"; System.out.println(new XmlFormatter().format(unformattedXml)); } } ```
139,088
<p>when i use setDefaultLookAndFeelDecorated(true) method in Java why is the Frame appear FullScreen when i maximize the Frame ? and how can i disaple the FullScreen mode in this method ?</p>
[ { "answer_id": 139126, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 0, "selected": false, "text": "<p>If you don't want your JFrame to be maximize-able then then call .setResizable(false); on it. </p>\n" }, { "an...
2008/09/26
[ "https://Stackoverflow.com/questions/139088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ]
when i use setDefaultLookAndFeelDecorated(true) method in Java why is the Frame appear FullScreen when i maximize the Frame ? and how can i disaple the FullScreen mode in this method ?
Setting `setDefaultLookAndFeelDecorated` to true causes the decorations to be handled by the look and feel; this means that a System look-and-feel on both Windows and Mac (I have no Linux at hand now) retains the borders you would expect them of a native window, e.g. staying clear of the taskbar in Windows. When using the Cross Platform look-and-feel, a.k.a. Metal, which is the default on Windows, the Windows version will take over the entire screen, making it look like a full-screen window. On Mac, the OS refuses to give away its own titlebar, and draws a complete Metal frame (including the title bar) in a Mac-native window. So, in short, if you want to make sure the taskbar gets respected, use the Windows system look-and-feel on Windows. You can set it by using something like ``` UIManager.setLookAndFeel((LookAndFeel) Class.forName(UIManager.getCrossPlatformLookAndFeelClassName()).newInstance()); ```
139,090
<p>I have a DLL that's loaded into a 3rd party parent process as an extension. From this DLL I instantiate external processes (my own) by using CreateProcess API. This works great in 99.999% of the cases but sometimes this suddenly fails and stops working permanently (maybe a restart of the parent process would solve this but this is undesirable and I don't want to recommend that until I solve the problem.) The failure is symptomized by external process not being invoked any more even though CreteProcess() doesn't report an error and by GetExitCodeProcess() returning 128. Here's the simplified version of what I'm doing:</p> <pre><code>STARTUPINFO si; ZeroMemory(&amp;si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; PROCESS_INFORMATION pi; ZeroMemory(&amp;pi, sizeof(pi)); if(!CreateProcess( NULL, // No module name (use command line). "&lt;my command line&gt;", NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. CREATE_SUSPENDED, // Create suspended. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &amp;si, // Pointer to STARTUPINFO structure. &amp;pi)) // Pointer to PROCESS_INFORMATION structure. { // Handle error. } else { // Do something. // Resume the external process thread. DWORD resumeThreadResult = ResumeThread(pi.hThread); // ResumeThread() returns 1 which is OK // (it means that the thread was suspended but then restarted) // Wait for the external process to finish. DWORD waitForSingelObjectResult = WaitForSingleObject(pi.hProcess, INFINITE); // WaitForSingleObject() returns 0 which is OK. // Get the exit code of the external process. DWORD exitCode; if(!GetExitCodeProcess(pi.hProcess, &amp;exitCode)) { // Handle error. } else { // There is no error but exitCode is 128, a value that // doesn't exist in the external process (and even if it // existed it doesn't matter as it isn't being invoked any more) // Error code 128 is ERROR_WAIT_NO_CHILDREN which would make some // sense *if* GetExitCodeProcess() returned FALSE and then I were to // get ERROR_WAIT_NO_CHILDREN with GetLastError() } // PROCESS_INFORMATION handles for process and thread are closed. } </code></pre> <p>External process can be manually invoked from Windows Explorer or command line and it starts just fine on its own. Invoked like that it, before doing any real work, creates a log file and logs some information about it. But invoked like described above this logging information doesn't appear at all so I'm assuming that the main thread of the external process never enters main() (I'm testing that assumption now.)</p> <p>There is at least one thing I could do to try to circumvent the problem (not start the thread suspended) but I would first like to understand the root of the failure first. Does anyone has any idea what could cause this and how to fix it?</p>
[ { "answer_id": 139230, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "<p>Quoting from the MSDN article on <a href=\"http://msdn.microsoft.com/en-us/library/aa915088.aspx\" rel=\"nofollow noreferr...
2008/09/26
[ "https://Stackoverflow.com/questions/139090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a DLL that's loaded into a 3rd party parent process as an extension. From this DLL I instantiate external processes (my own) by using CreateProcess API. This works great in 99.999% of the cases but sometimes this suddenly fails and stops working permanently (maybe a restart of the parent process would solve this but this is undesirable and I don't want to recommend that until I solve the problem.) The failure is symptomized by external process not being invoked any more even though CreteProcess() doesn't report an error and by GetExitCodeProcess() returning 128. Here's the simplified version of what I'm doing: ``` STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if(!CreateProcess( NULL, // No module name (use command line). "<my command line>", NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. CREATE_SUSPENDED, // Create suspended. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &si, // Pointer to STARTUPINFO structure. &pi)) // Pointer to PROCESS_INFORMATION structure. { // Handle error. } else { // Do something. // Resume the external process thread. DWORD resumeThreadResult = ResumeThread(pi.hThread); // ResumeThread() returns 1 which is OK // (it means that the thread was suspended but then restarted) // Wait for the external process to finish. DWORD waitForSingelObjectResult = WaitForSingleObject(pi.hProcess, INFINITE); // WaitForSingleObject() returns 0 which is OK. // Get the exit code of the external process. DWORD exitCode; if(!GetExitCodeProcess(pi.hProcess, &exitCode)) { // Handle error. } else { // There is no error but exitCode is 128, a value that // doesn't exist in the external process (and even if it // existed it doesn't matter as it isn't being invoked any more) // Error code 128 is ERROR_WAIT_NO_CHILDREN which would make some // sense *if* GetExitCodeProcess() returned FALSE and then I were to // get ERROR_WAIT_NO_CHILDREN with GetLastError() } // PROCESS_INFORMATION handles for process and thread are closed. } ``` External process can be manually invoked from Windows Explorer or command line and it starts just fine on its own. Invoked like that it, before doing any real work, creates a log file and logs some information about it. But invoked like described above this logging information doesn't appear at all so I'm assuming that the main thread of the external process never enters main() (I'm testing that assumption now.) There is at least one thing I could do to try to circumvent the problem (not start the thread suspended) but I would first like to understand the root of the failure first. Does anyone has any idea what could cause this and how to fix it?
Quoting from the MSDN article on [GetExitCodeProcess](http://msdn.microsoft.com/en-us/library/aa915088.aspx): The following termination statuses can be returned if the process has terminated: * The exit value specified in the ExitProcess or TerminateProcess function * The return value from the main or WinMain function of the process * The exception value for an unhandled exception that caused the process to terminate Given the scenario you described, I think the most likely cause ist the third: An unhandled exception. Have a look at the source of the processes you create.
139,115
<p>Here is the scenario:</p> <p>I have a winforms application using NHibernate. When launched, I populate a DataGridView with the results of a NHibernate query. This part works fine. If I update a record in that list and flush the session, the update takes in the database. Upon closing the form after the update, I call a method to retrieve a list of objects to populate the DataGridView again to pick up the change and also get any other changes that may have occurred by somebody else. The problem is that the record that got updated, NHibernate doesn't reflect the change in the list it gives me. When I insert or delete a record, everything works fine. It is just when I update, that I get this behavior. I narrowed it down to NHibernate with their caching mechanism. I cannot figure out a way to make NHibernate retrieve from the database instead of using the cache after an update occurs. I posted on the NHibernate forums, but the suggestions they gave me didn't work. I stated this and nobody replied back. I am not going to state what I have tried in case I didn't do it right. If you answer with something that I tried exactly, I will state it in the comments of your answer.</p> <p>This is the code that I use to retrieve the list:</p> <pre><code>public IList&lt;WorkOrder&gt; FindBy(string fromDate, string toDate) { IQuery query = _currentSession.CreateQuery("from WorkOrder wo where wo.Date &gt;= ? and wo.Date &lt;= ?"); query.SetParameter(0, fromDate); query.SetParameter(1, toDate); return query.List&lt;WorkOrder&gt;(); } </code></pre> <p>The session is passed to the class when it is constructed. I can post my mapping file also, but I am not sure if there is anything wrong with it, since everything else works. Anybody seen this before? This is the first project that I have used NHibernate, thanks for the help.</p>
[ { "answer_id": 139133, "author": "Richard", "author_id": 20038, "author_profile": "https://Stackoverflow.com/users/20038", "pm_score": 0, "selected": false, "text": "<p>what about refresh? - see <a href=\"http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/manipulatingdata...
2008/09/26
[ "https://Stackoverflow.com/questions/139115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1117/" ]
Here is the scenario: I have a winforms application using NHibernate. When launched, I populate a DataGridView with the results of a NHibernate query. This part works fine. If I update a record in that list and flush the session, the update takes in the database. Upon closing the form after the update, I call a method to retrieve a list of objects to populate the DataGridView again to pick up the change and also get any other changes that may have occurred by somebody else. The problem is that the record that got updated, NHibernate doesn't reflect the change in the list it gives me. When I insert or delete a record, everything works fine. It is just when I update, that I get this behavior. I narrowed it down to NHibernate with their caching mechanism. I cannot figure out a way to make NHibernate retrieve from the database instead of using the cache after an update occurs. I posted on the NHibernate forums, but the suggestions they gave me didn't work. I stated this and nobody replied back. I am not going to state what I have tried in case I didn't do it right. If you answer with something that I tried exactly, I will state it in the comments of your answer. This is the code that I use to retrieve the list: ``` public IList<WorkOrder> FindBy(string fromDate, string toDate) { IQuery query = _currentSession.CreateQuery("from WorkOrder wo where wo.Date >= ? and wo.Date <= ?"); query.SetParameter(0, fromDate); query.SetParameter(1, toDate); return query.List<WorkOrder>(); } ``` The session is passed to the class when it is constructed. I can post my mapping file also, but I am not sure if there is anything wrong with it, since everything else works. Anybody seen this before? This is the first project that I have used NHibernate, thanks for the help.
After your update, Evict the object from the first level cache. ``` Session.Update(obj); Session.Evict(obj); ``` You may want to commit and/or flush first.
139,118
<p>Does anyone know how to get the HTML out of an IFRAME I have tried several different ways:</p> <pre><code>document.getElementById('iframe01').contentDocument.body.innerHTML document.frames['iframe01'].document.body.innerHTML document.getElementById('iframe01').contentWindow.document.body.innerHTML </code></pre> <p>etc</p>
[ { "answer_id": 139132, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": "<p>If you take a look at <a href=\"http://www.jquery.com\" rel=\"noreferrer\">JQuery</a>, you can do something like:</p>\n\n...
2008/09/26
[ "https://Stackoverflow.com/questions/139118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does anyone know how to get the HTML out of an IFRAME I have tried several different ways: ``` document.getElementById('iframe01').contentDocument.body.innerHTML document.frames['iframe01'].document.body.innerHTML document.getElementById('iframe01').contentWindow.document.body.innerHTML ``` etc
I think this is what you want: ``` window.frames['iframe01'].document.body.innerHTML ``` **EDIT:** I have it on good authority that this won't work in Chrome and Firefox although it works perfectly in IE, which is where I tested it. In retrospect, that was a big mistake This will work: ``` window.frames[0].document.body.innerHTML ``` I understand that this isn't exactly what was asked but don't want to delete the answer because I think it has a place. I like @ravz's jquery answer below.
139,131
<p>i have a number of jsp files under web-inf folder. Inside my web.xml i specify an errorppage for 404 amd 403 and java.lang.exception. Do i need to include a page directive for each of my jsp's or will they automatically get forwarded to the exception handling page because they are under web-inf?</p> <p>If this is true does this mean that jsps which are not placed under web-inf do need to have the page directive added in order to forward them to the exception handling page?</p> <p>thank you , im just trying to understand the consequences of web-inf</p>
[ { "answer_id": 139174, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 2, "selected": true, "text": "<p>You just need to have whatever errorpage you would like to use in your app available with all the other jsps. So in the...
2008/09/26
[ "https://Stackoverflow.com/questions/139131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
i have a number of jsp files under web-inf folder. Inside my web.xml i specify an errorppage for 404 amd 403 and java.lang.exception. Do i need to include a page directive for each of my jsp's or will they automatically get forwarded to the exception handling page because they are under web-inf? If this is true does this mean that jsps which are not placed under web-inf do need to have the page directive added in order to forward them to the exception handling page? thank you , im just trying to understand the consequences of web-inf
You just need to have whatever errorpage you would like to use in your app available with all the other jsps. So in the following example you would just need to have the error pages in the root of the context path(where all of the other jsps are). Anytime the webapp receives a 404 or 403 error it will try to display one of these pages. . ``` <error-page> <error-code>404</error-code> <location>/404Error.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/403Error.jsp</location> </error-page> ``` Just make sure 404Error.jsp and 403Error.jsp contain: ``` <%@ page isErrorPage="true" %> ``` If you are actually using jsps for error pages (instead of just static html)
139,157
<p>I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them. </p> <p>So when the user accidentally (or on purpose) double clicks on the menu, the menu shows its sub-elements but its text does not highlight.</p> <p>There are a number of scripts out there floating around on the web, but many seem outdated. What's the best way?</p>
[ { "answer_id": 139185, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>You could:</p>\n\n<ul>\n<li>Give it (\"it\" being your text) a onclick event</li>\n<li>First click sets a variable to the c...
2008/09/26
[ "https://Stackoverflow.com/questions/139157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315650/" ]
I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them. So when the user accidentally (or on purpose) double clicks on the menu, the menu shows its sub-elements but its text does not highlight. There are a number of scripts out there floating around on the web, but many seem outdated. What's the best way?
In (Mozilla, Firefox, Camino, Safari, Google Chrome) you can use this: ``` div.noSelect { -moz-user-select: none; /* mozilla browsers */ -khtml-user-select: none; /* webkit browsers */ } ``` For IE there is no CSS option, but you can capture the ondragstart event, and return false; **Update** Browser support for this property has expanded since 2008. ``` div.noSelect { -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */ } ``` [https://www.w3schools.com/csSref/css3\_pr\_user-select.php](https://css-tricks.com/almanac/properties/u/user-select/)
139,180
<p>I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it.</p> <p>I want to call the <code>help</code> function on each one. In Ruby I can do something like <code>ClassName.methods</code> to get a list of all the methods available on that class. Is there something similar in Python?</p> <p>e.g. something like:</p> <pre><code>from somemodule import foo print(foo.methods) # or whatever is the correct method to call </code></pre>
[ { "answer_id": 139193, "author": "camflan", "author_id": 22445, "author_profile": "https://Stackoverflow.com/users/22445", "pm_score": 9, "selected": false, "text": "<p>You can use <code>dir(module)</code> to see all available methods/attributes. Also check out PyDocs.</p>\n" }, { ...
2008/09/26
[ "https://Stackoverflow.com/questions/139180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6527/" ]
I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. I want to call the `help` function on each one. In Ruby I can do something like `ClassName.methods` to get a list of all the methods available on that class. Is there something similar in Python? e.g. something like: ``` from somemodule import foo print(foo.methods) # or whatever is the correct method to call ```
Use the [`inspect`](https://docs.python.org/3/library/inspect.html) module: ``` from inspect import getmembers, isfunction from somemodule import foo print(getmembers(foo, isfunction)) ``` Also see the [`pydoc`](https://docs.python.org/3/library/pydoc.html) module, the `help()` function in the interactive interpreter and the `pydoc` command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.
139,199
<p>I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code:</p> <pre><code>sSanitizedInput = "'" &amp; Replace(sInput, "'", "''") &amp; "'" </code></pre> <p>Any single-quote the user enters is replaced with double single-quotes, which eliminates the users ability to end the string, so anything else they may type, such as semicolons, percent signs, etc., will all be part of the string and not actually executed as part of the command. </p> <p>We are using Microsoft SQL Server 2000, for which I believe the single-quote is the only string delimiter and the only way to escape the string delimiter, so there is no way to execute anything the user types in.</p> <p>I don't see any way to launch an SQL injection attack against this, but I realize that if this were as bulletproof as it seems to me someone else would have thought of it already and it would be common practice. </p> <p>What's wrong with this code? Is there a way to get an SQL injection attack past this sanitization technique? Sample user input that exploits this technique would be very helpful.</p> <hr/> <p>UPDATE:</p> <p>I still don't know of any way to effectively launch a SQL injection attack against this code. A few people suggested that a backslash would escape one single-quote and leave the other to end the string so that the rest of the string would be executed as part of the SQL command, and I realize that this method would work to inject SQL into a MySQL database, but in SQL&nbsp;Server 2000 the only way (that I've been able to find) to escape a single-quote is with another single-quote; backslashes won't do it.</p> <p>And unless there is a way to stop the escaping of the single-quote, none of the rest of the user input will be executed because it will all be taken as one contiguous string.</p> <p>I understand that there are better ways to sanitize input, but I'm really more interested in learning why the method I provided above won't work. If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it.</p>
[ { "answer_id": 139215, "author": "Rob", "author_id": 18505, "author_profile": "https://Stackoverflow.com/users/18505", "pm_score": -1, "selected": false, "text": "<p>It might work, but it seems a little hokey to me. I'd recommend verifing that each string is valid by testing it against a...
2008/09/26
[ "https://Stackoverflow.com/questions/139199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22392/" ]
I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code: ``` sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'" ``` Any single-quote the user enters is replaced with double single-quotes, which eliminates the users ability to end the string, so anything else they may type, such as semicolons, percent signs, etc., will all be part of the string and not actually executed as part of the command. We are using Microsoft SQL Server 2000, for which I believe the single-quote is the only string delimiter and the only way to escape the string delimiter, so there is no way to execute anything the user types in. I don't see any way to launch an SQL injection attack against this, but I realize that if this were as bulletproof as it seems to me someone else would have thought of it already and it would be common practice. What's wrong with this code? Is there a way to get an SQL injection attack past this sanitization technique? Sample user input that exploits this technique would be very helpful. --- UPDATE: I still don't know of any way to effectively launch a SQL injection attack against this code. A few people suggested that a backslash would escape one single-quote and leave the other to end the string so that the rest of the string would be executed as part of the SQL command, and I realize that this method would work to inject SQL into a MySQL database, but in SQL Server 2000 the only way (that I've been able to find) to escape a single-quote is with another single-quote; backslashes won't do it. And unless there is a way to stop the escaping of the single-quote, none of the rest of the user input will be executed because it will all be taken as one contiguous string. I understand that there are better ways to sanitize input, but I'm really more interested in learning why the method I provided above won't work. If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it.
First of all, it's just bad practice. Input validation is always necessary, but it's also always iffy. Worse yet, blacklist validation is always problematic, it's much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible - but to some extent it must always be done. Some research papers on the subject: * <http://www.imperva.com/docs/WP_SQL_Injection_Protection_LK.pdf> * <http://www.it-docs.net/ddata/4954.pdf> (Disclosure, this last one was mine ;) ) * <https://www.owasp.org/images/d/d4/OWASP_IL_2007_SQL_Smuggling.pdf> (based on the previous paper, which is no longer available) Point is, any blacklist you do (and too-permissive whitelists) can be bypassed. The last link to my paper shows situations where even quote escaping can be bypassed. Even if these situations do not apply to you, it's still a bad idea. Moreover, unless your app is trivially small, you're going to have to deal with maintenance, and maybe a certain amount of governance: how do you ensure that its done right, everywhere all the time? The proper way to do it: * Whitelist validation: type, length, format or accepted values * If you want to blacklist, go right ahead. Quote escaping is good, but within context of the other mitigations. * Use Command and Parameter objects, to preparse and validate * Call parameterized queries only. * Better yet, use Stored Procedures exclusively. * Avoid using dynamic SQL, and dont use string concatenation to build queries. * If using SPs, you can also limit permissions in the database to executing the needed SPs only, and not access tables directly. * you can also easily verify that the entire codebase only accesses the DB through SPs...
139,212
<p>I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail.</p> <p>How can I add cookies from a Python CookieJar to ZSI requests?</p>
[ { "answer_id": 145610, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 2, "selected": true, "text": "<p>If you read the <a href=\"https://pywebsvcs.svn.sourceforge.net/svnroot/pywebsvcs/trunk/zsi/ZSI/client.py\" rel=\"...
2008/09/26
[ "https://Stackoverflow.com/questions/139212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17583/" ]
I've added cookie support to SOAPpy by overriding HTTPTransport. I need functionality beyond that of SOAPpy, so I was planning on moving to ZSI, but I can't figure out how to put the Cookies on the ZSI posts made to the service. Without these cookies, the server will think it is an unauthorized request and it will fail. How can I add cookies from a Python CookieJar to ZSI requests?
If you read the [\_Binding class in client.py of ZSI](https://pywebsvcs.svn.sourceforge.net/svnroot/pywebsvcs/trunk/zsi/ZSI/client.py) you can see that it has a variable cookies, which is an instance of [Cookie.SimpleCookie](http://docs.python.org/lib/module-Cookie.html). Following the [ZSI example](http://pywebsvcs.sourceforge.net/zsi.html#SECTION003210000000000000000) and the [Cookie example](http://docs.python.org/lib/cookie-example.html) that is how it should work: ``` b = Binding(url='/cgi-bin/simple-test', tracefile=fp) b.cookies['foo'] = 'bar' ```
139,214
<p>The most egregiously redundant code construct I often see involves using the code sequence</p> <pre><code>if (condition) return true; else return false; </code></pre> <p>instead of simply writing</p> <pre><code>return (condition); </code></pre> <p>I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?</p>
[ { "answer_id": 139231, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "<p>Returning uselessly at the end:</p>\n\n<pre><code> // stuff\n return;\n}\n</code></pre>\n" }, { "answer_id": 13...
2008/09/26
[ "https://Stackoverflow.com/questions/139214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20520/" ]
The most egregiously redundant code construct I often see involves using the code sequence ``` if (condition) return true; else return false; ``` instead of simply writing ``` return (condition); ``` I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?
``` if (foo == true) { do stuff } ``` I keep telling the developer that does that that it should be ``` if ((foo == true) == true) { do stuff } ``` but he hasn't gotten the hint yet.
139,245
<p>How to get the relative path in t sql? Take for example a <code>.sql</code> file is located in the folder <code>D:\temp</code>, I want to get path of the file hello.txt in the folder <code>D:\temp\App_Data</code>. How to use the relative path reference?</p> <p>Let's say I am executing the sql file inside the SQL server management studio.</p>
[ { "answer_id": 139431, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 3, "selected": false, "text": "<p>The .sql file is just.... a file. It doesn't have any sense of its own location. It's the thing that excutes it (w...
2008/09/26
[ "https://Stackoverflow.com/questions/139245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
How to get the relative path in t sql? Take for example a `.sql` file is located in the folder `D:\temp`, I want to get path of the file hello.txt in the folder `D:\temp\App_Data`. How to use the relative path reference? Let's say I am executing the sql file inside the SQL server management studio.
The server is executing the t-sql. It doesn't know where the client loaded the file from. You'll have to have the path embedded within the script. ``` DECLARE @RelDir varchar(1000) SET @RelDir = 'D:\temp\' ... ``` Perhaps you can programmatically place the path into the SET command within the .sql script file, or perhaps you can use sqlcmd and pass the relative directory in as a variable.
139,260
<p>I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). </p> <p>I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this:</p> <pre><code>MemoryStream stream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1")); xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.WriteStartDocument(); //Start doc </code></pre> <p>Then I add my Norwegian text like this:</p> <pre><code>xmlTextWriter.WriteCData(myNorwegianText); </code></pre> <p>Then I write the file to disk like this:</p> <pre><code>FileStream myFile = new FileStream(myPath, FileMode.Create); StreamWriter sw = new StreamWriter(myFile); stream.Position = 0; StreamReader sr = new StreamReader(stream); string content = sr.ReadToEnd(); sw.Write(content); sw.Flush(); myFile.Flush(); myFile.Close(); </code></pre> <p>Now the problem is that in the file on this, all the Norwegian characters look funny.</p> <p>I'm probably doing the above in some stupid way. Any suggestions on how to fix it?</p>
[ { "answer_id": 139307, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 2, "selected": false, "text": "<p>Which encoding do you use for displaying the result file? If it is not in ISO-8859-1, it will not display correctly.</p>\n...
2008/09/26
[ "https://Stackoverflow.com/questions/139260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5795/" ]
I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this: ``` MemoryStream stream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1")); xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.WriteStartDocument(); //Start doc ``` Then I add my Norwegian text like this: ``` xmlTextWriter.WriteCData(myNorwegianText); ``` Then I write the file to disk like this: ``` FileStream myFile = new FileStream(myPath, FileMode.Create); StreamWriter sw = new StreamWriter(myFile); stream.Position = 0; StreamReader sr = new StreamReader(stream); string content = sr.ReadToEnd(); sw.Write(content); sw.Flush(); myFile.Flush(); myFile.Close(); ``` Now the problem is that in the file on this, all the Norwegian characters look funny. I'm probably doing the above in some stupid way. Any suggestions on how to fix it?
Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work. If you still want to do the double write, for whatever reason, do one of two things. Either 1. Make sure that the StreamReader and StreamWriter objects you use *all* use the *same* encoding as the one you used with the XmlWriter (not just the StreamWriter, like someone else suggested), or 2. Don't use StreamReader/StreamWriter. Instead just copy the stream at the byte level using a simple byte[] and Stream.Read/Write. This is going to be, btw, a lot more efficient anyway.
139,261
<p>For testing purposes I have to generate a file of a certain size (to test an upload limit). </p> <p>What is a command to create a file of a certain size on Linux?</p>
[ { "answer_id": 139278, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 5, "selected": false, "text": "<p>Use this command:</p>\n\n<pre>\ndd if=$INPUT-FILE of=$OUTPUT-FILE bs=$BLOCK-SIZE count=$NUM-BLOCKS\n</pre>\n\n<p>To ...
2008/09/26
[ "https://Stackoverflow.com/questions/139261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ]
For testing purposes I have to generate a file of a certain size (to test an upload limit). What is a command to create a file of a certain size on Linux?
For small files: ``` dd if=/dev/zero of=upload_test bs=file_size count=1 ``` Where `file_size` is the size of your test file in bytes. For big files: ``` dd if=/dev/zero of=upload_test bs=1M count=size_in_megabytes ```
139,288
<p>what is an efficient way to get a certain time for the next day in Java? Let's say I want the long for tomorrow 03:30:00. Setting Calendar fields and Date formatting are obvious. Better or smarter ideas, thanks for sharing them!</p> <p>Okami</p>
[ { "answer_id": 139319, "author": "Brandon DuRette", "author_id": 17834, "author_profile": "https://Stackoverflow.com/users/17834", "pm_score": 2, "selected": false, "text": "<p>I'm curious to hear what other people have to say about this one. My own experience is that taking shortcuts (i...
2008/09/26
[ "https://Stackoverflow.com/questions/139288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11450/" ]
what is an efficient way to get a certain time for the next day in Java? Let's say I want the long for tomorrow 03:30:00. Setting Calendar fields and Date formatting are obvious. Better or smarter ideas, thanks for sharing them! Okami
I take the brute force approach ``` // make it now Calendar dateCal = Calendar.getInstance(); // make it tomorrow dateCal.add(Calendar.DAY_OF_YEAR, 1); // Now set it to the time you want dateCal.set(Calendar.HOUR_OF_DAY, hours); dateCal.set(Calendar.MINUTE, minutes); dateCal.set(Calendar.SECOND, seconds); dateCal.set(Calendar.MILLISECOND, 0); return dateCal.getTime(); ```
139,325
<p>How to set all the values in a <code>std::map</code> to the same value, without using a loop iterating over each value? </p>
[ { "answer_id": 139377, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": true, "text": "<p>Using a loop <em>is</em> by far the simplest method. In fact, it’s a one-liner:<sup>[C++17]</sup></p>\n<pre><code>f...
2008/09/26
[ "https://Stackoverflow.com/questions/139325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6841/" ]
How to set all the values in a `std::map` to the same value, without using a loop iterating over each value?
Using a loop *is* by far the simplest method. In fact, it’s a one-liner:[C++17] ``` for (auto& [_, v] : mymap) v = value; ``` Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use `std::fill`. To use them anyway (pre-C++20), we need to write adapters — in the case of `std::fill`, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do *not* advise using it as-is. Use a library (such as [Boost.Iterator](https://www.boost.org/doc/libs/1_74_0/libs/iterator/doc/function_output_iterator.html)) for a more general, production-strength implementation. ``` template <typename M> struct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> { using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>; using underlying = typename M::iterator; using typename base_type::value_type; using typename base_type::reference; value_iter(underlying i) : i(i) {} value_iter& operator++() { ++i; return *this; } value_iter operator++(int) { auto copy = *this; i++; return copy; } reference operator*() { return i->second; } bool operator ==(value_iter other) const { return i == other.i; } bool operator !=(value_iter other) const { return i != other.i; } private: underlying i; }; template <typename M> auto value_begin(M& map) { return value_iter<M>(map.begin()); } template <typename M> auto value_end(M& map) { return value_iter<M>(map.end()); } ``` With this, we can use `std::fill`: ``` std::fill(value_begin(mymap), value_end(mymap), value); ```
139,358
<p>In a user defined wizard page, is there a way to capture change or focus events of the controls? I want to provide an immediate feedback on user input in some dropdowns (e.g. a message box)</p>
[ { "answer_id": 139404, "author": "Otherside", "author_id": 18697, "author_profile": "https://Stackoverflow.com/users/18697", "pm_score": 2, "selected": false, "text": "<p>Since the scripting in innosetup is loosely based on Delphi, the controls should have some events like <code>OnEnter<...
2008/09/26
[ "https://Stackoverflow.com/questions/139358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22114/" ]
In a user defined wizard page, is there a way to capture change or focus events of the controls? I want to provide an immediate feedback on user input in some dropdowns (e.g. a message box)
Took me some time to work it out, but after being pointed in the right direction by Otherside, I finally got it (works for version 5.2): ``` [Code] var MyCustomPage : TWizardPage; procedure MyEditField_OnChange(Sender: TObject); begin MsgBox('TEST', mbError, MB_OK); end; function MyCustomPage_Create(PreviousPageId: Integer): Integer; var MyEditField: TEdit; begin MyCustomPage := CreateCustomPage(PreviousPageId, 'Caption', 'Description'); MyEditField := TEdit.Create(MyCustomPage); MyEditField.OnChange := @MyEditField_OnChange; end; ```
139,365
<p>I've begun to use TDD. As mentioned in <a href="https://stackoverflow.com/questions/64333/what-is-the-downside-to-test-driven-development#64402">an earlier question</a> the biggest difficulty is handling interface changes. How do you reduce the impact on your test cases as requirements change?</p>
[ { "answer_id": 139378, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 0, "selected": false, "text": "<p>You write the tests before you write the code for the new interface.</p>\n" }, { "answer_id": 139380, "au...
2008/09/26
[ "https://Stackoverflow.com/questions/139365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16496/" ]
I've begun to use TDD. As mentioned in [an earlier question](https://stackoverflow.com/questions/64333/what-is-the-downside-to-test-driven-development#64402) the biggest difficulty is handling interface changes. How do you reduce the impact on your test cases as requirements change?
Changing an interface requires updating code that uses that interface. Test code isn't any different from non-test code in this respect. It's unavoidable that tests for that interface will need to change. Often when an interface changes you find that "too many" tests break, i.e. tests for largely unrelated functionality turn out to depend on that interface. That can be a sign that your tests are overly broad and need refactoring. There are many possible ways this can happen, but here's an example that hopefully shows the general idea as well as a particular case. For instance if the way to construct an Account object has changed, and this requires updating all or most of your tests for your Order class, something is wrong. Most of your Order unit tests probably don't care about how an account is made, so refactor tests like this: ``` def test_add_item_to_order(self): acct = Account('Joe', 'Bloggs') shipping_addr = Address('123 Elm St', 'etc' 'etc') order = Order(acct, shipping_addr) item = OrderItem('Purple Widget') order.addItem(item) self.assertEquals([item], order.items) ``` to this: ``` def make_order(self): acct = Account('Joe', 'Bloggs') shipping_addr = Address('123 Elm St', 'etc' 'etc') return Order(acct, shipping_addr) def make_order_item(self): return OrderItem('Purple Widget') def test_add_item_to_order(self): order = self.make_order() item = self.make_order_item() order.addItem(item) self.assertEquals([item], order.items) ``` This particular pattern is a [Creation Method](http://xunitpatterns.com/Creation%20Method.html). An advantage here is that your test methods for Order are insulated from how Accounts and Addresses are created; if those interfaces change you only have one place to change, rather than every single test that happens to use Accounts and Addresses. In short: tests are code too, and like all code, sometimes they need refactoring.
139,474
<p>I'd like to capture the output of <a href="http://us3.php.net/manual/en/function.var-dump.php" rel="noreferrer"><code>var_dump</code></a> to a string.</p> <p>The PHP documentation says;</p> <blockquote> <p>As with anything that outputs its result directly to the browser, the <a href="http://us3.php.net/manual/en/ref.outcontrol.php" rel="noreferrer">output-control functions</a> can be used to capture the output of this function, and save it in a string (for example).</p> </blockquote> <p>What would be an example of how that might work?</p> <p><code>print_r()</code> isn't a valid possibility, because it's not going to give me the information that I need.</p>
[ { "answer_id": 139491, "author": "Eran Galperin", "author_id": 10585, "author_profile": "https://Stackoverflow.com/users/10585", "pm_score": 10, "selected": true, "text": "<p>Use output buffering:</p>\n\n<pre><code>&lt;?php\nob_start();\nvar_dump($someVar);\n$result = ob_get_clean();\n?&...
2008/09/26
[ "https://Stackoverflow.com/questions/139474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I'd like to capture the output of [`var_dump`](http://us3.php.net/manual/en/function.var-dump.php) to a string. The PHP documentation says; > > As with anything that outputs its result directly to the browser, the [output-control functions](http://us3.php.net/manual/en/ref.outcontrol.php) can be used to capture the output of this function, and save it in a string (for example). > > > What would be an example of how that might work? `print_r()` isn't a valid possibility, because it's not going to give me the information that I need.
Use output buffering: ``` <?php ob_start(); var_dump($someVar); $result = ob_get_clean(); ?> ```
139,484
<p>I have two (UNIX) programs A and B that read and write from stdin/stdout.</p> <p>My first problem is how to connect the stdout of A to stdin of B <em>and</em> the stdout of B to the stdin of A. I.e., something like A | B but a bidirectional pipe. I suspect I could solve this by <a href="http://tldp.org/LDP/abs/html/x16834.html" rel="noreferrer">using exec to redirect</a> but I could not get it to work. The programs are interactive so a temporary file would not work.</p> <p>The second problem is that I would like to duplicate each direction and pipe a duplicate via a logging program to stdout so that I can see the (text-line based) traffic that pass between the programs. Here I may get away with tee >(...) if I can solve the first problem.</p> <p>Both these problems seems like they should have well known solutions but I have not be able to find anything.</p> <p>I would prefer a POSIX shell solution, or at least something that works in bash on cygwin.</p> <p>Thanks to your answers I came up with the following solution. The A/B commands uses nc to listen to two ports. The logging program uses sed (with -u for unbuffered processing).</p> <pre><code>bash-3.2$ fifodir=$(mktemp -d) bash-3.2$ mkfifo "$fifodir/echoAtoB" bash-3.2$ mkfifo "$fifodir/echoBtoA" bash-3.2$ sed -u 's/^/A-&gt;B: /' "$fifodir/echoAtoB" &amp; bash-3.2$ sed -u 's/^/B-&gt;A: /' "$fifodir/echoBtoA" &amp; bash-3.2$ mkfifo "$fifodir/loopback" bash-3.2$ nc -l -p 47002 &lt; "$fifodir/loopback" \ | tee "$fifodir/echoAtoB" \ | nc -l -p 47001 \ | tee "$fifodir/echoBtoA" &gt; "$fifodir/loopback" </code></pre> <p>This listens for connection to port 47001 and 47002 and echos all traffic to standard output.</p> <p>In shell 2 do:</p> <pre><code>bash-3.2$ nc localhost 47001 </code></pre> <p>In shell 3 do:</p> <pre><code>bash-3.2$ nc localhost 47002 </code></pre> <p>Now lines entered in shell 2 will be written to shell 3 and vice versa and the traffic logged to shell 1, something like:</p> <pre><code>B-&gt;A: input to port 47001 A-&gt;B: input to port 47002 </code></pre> <p>The above has been tested on Cygwin</p> <p>Update: The script above stopped working after a few days(!). Apparently it can deadlock. Some of the suggestions in the answers may be more reliable.</p>
[ { "answer_id": 139495, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://bisqwit.iki.fi/source/twinpipe.html\" rel=\"noreferrer\">http://bisqwit.iki.fi/source/twinpipe.html</a><...
2008/09/26
[ "https://Stackoverflow.com/questions/139484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22676/" ]
I have two (UNIX) programs A and B that read and write from stdin/stdout. My first problem is how to connect the stdout of A to stdin of B *and* the stdout of B to the stdin of A. I.e., something like A | B but a bidirectional pipe. I suspect I could solve this by [using exec to redirect](http://tldp.org/LDP/abs/html/x16834.html) but I could not get it to work. The programs are interactive so a temporary file would not work. The second problem is that I would like to duplicate each direction and pipe a duplicate via a logging program to stdout so that I can see the (text-line based) traffic that pass between the programs. Here I may get away with tee >(...) if I can solve the first problem. Both these problems seems like they should have well known solutions but I have not be able to find anything. I would prefer a POSIX shell solution, or at least something that works in bash on cygwin. Thanks to your answers I came up with the following solution. The A/B commands uses nc to listen to two ports. The logging program uses sed (with -u for unbuffered processing). ``` bash-3.2$ fifodir=$(mktemp -d) bash-3.2$ mkfifo "$fifodir/echoAtoB" bash-3.2$ mkfifo "$fifodir/echoBtoA" bash-3.2$ sed -u 's/^/A->B: /' "$fifodir/echoAtoB" & bash-3.2$ sed -u 's/^/B->A: /' "$fifodir/echoBtoA" & bash-3.2$ mkfifo "$fifodir/loopback" bash-3.2$ nc -l -p 47002 < "$fifodir/loopback" \ | tee "$fifodir/echoAtoB" \ | nc -l -p 47001 \ | tee "$fifodir/echoBtoA" > "$fifodir/loopback" ``` This listens for connection to port 47001 and 47002 and echos all traffic to standard output. In shell 2 do: ``` bash-3.2$ nc localhost 47001 ``` In shell 3 do: ``` bash-3.2$ nc localhost 47002 ``` Now lines entered in shell 2 will be written to shell 3 and vice versa and the traffic logged to shell 1, something like: ``` B->A: input to port 47001 A->B: input to port 47002 ``` The above has been tested on Cygwin Update: The script above stopped working after a few days(!). Apparently it can deadlock. Some of the suggestions in the answers may be more reliable.
<http://bisqwit.iki.fi/source/twinpipe.html>
139,513
<p>I made a class from Linq to SQL Clasees with VS 2008 SP1 Framework 3.5 SP1, in this case I extended the partial</p> <pre><code>partial void UpdateMyTable(MyTable instance){ // Business logic // Validation rules, etc. } </code></pre> <p>My problem is when I execute db.SubmitChanges(), it executes UpdateMyTable and makes the validations but it doesn't update, I get this error:</p> <pre><code>[Exception: Deliver] System.Data.Linq.ChangeProcessor.SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction) +197 System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) +255 System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +76 System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331 System.Data.Linq.DataContext.SubmitChanges() +19 </code></pre>
[ { "answer_id": 139625, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "<ul>\n<li>if you provide this method, you must perform the update in the method.</li>\n</ul>\n\n<hr>\n\n<p><a href=\"http://msd...
2008/09/26
[ "https://Stackoverflow.com/questions/139513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19710/" ]
I made a class from Linq to SQL Clasees with VS 2008 SP1 Framework 3.5 SP1, in this case I extended the partial ``` partial void UpdateMyTable(MyTable instance){ // Business logic // Validation rules, etc. } ``` My problem is when I execute db.SubmitChanges(), it executes UpdateMyTable and makes the validations but it doesn't update, I get this error: ``` [Exception: Deliver] System.Data.Linq.ChangeProcessor.SendOnValidate(MetaType type, TrackedObject item, ChangeAction changeAction) +197 System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) +255 System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +76 System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +331 System.Data.Linq.DataContext.SubmitChanges() +19 ```
* if you provide this method, you must perform the update in the method. --- <http://msdn.microsoft.com/en-us/library/bb882671.aspx> * If you implement the Insert, Update and Delete methods in your partial class, the LINQ to SQL runtime will call them **instead** of its own default methods when SubmitChanges is called. Try **MiTabla.OnValidate**
139,525
<p>I have an Xtext/Xpand (oAW 4.3, Eclipse 3.4) generator plug-in, which I run together with the editor plug-in in a second workbench. There, I'd like to run Xpand workflows programmatically on the model file I create. If I set the model file using the absolute path of the IFile I have, e.g. with:</p> <pre><code>String dslFile = file.getLocation().makeAbsolute().toOSString(); </code></pre> <p>Or if I use a file URI retrieved with:</p> <pre><code>String dslFile = file.getLocationURI().toString(); </code></pre> <p>The file is not found:</p> <pre><code>org.eclipse.emf.ecore.resource.Resource$IOWrappedException: Resource '/absolute/path/to/my/existing/dsl.file' does not exist. at org.openarchitectureware.xtext.parser.impl.AbstractParserComponent.invokeInternal(AbstractParserComponent.java:55) </code></pre> <p>To what value should I set the model file attribute (dslFile) in the map I hand to the WorkflowRunner:</p> <pre><code>Map properties = new HashMap(); properties.put("modelFile", dslFile); </code></pre> <p>I also tried leaving the properties empty and referencing the model file relative to the workflow file (inside the workflow file), but that yields a FileNotFoundException. Running all of this in a normal app (not in a second workbench) works fine.</p>
[ { "answer_id": 192038, "author": "Fabian Steeg", "author_id": 18154, "author_profile": "https://Stackoverflow.com/users/18154", "pm_score": 1, "selected": true, "text": "<p>I found help at the <a href=\"http://openarchitectureware.org/forum/viewtopic.php?showtopic=10197\" rel=\"nofollow ...
2008/09/26
[ "https://Stackoverflow.com/questions/139525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18154/" ]
I have an Xtext/Xpand (oAW 4.3, Eclipse 3.4) generator plug-in, which I run together with the editor plug-in in a second workbench. There, I'd like to run Xpand workflows programmatically on the model file I create. If I set the model file using the absolute path of the IFile I have, e.g. with: ``` String dslFile = file.getLocation().makeAbsolute().toOSString(); ``` Or if I use a file URI retrieved with: ``` String dslFile = file.getLocationURI().toString(); ``` The file is not found: ``` org.eclipse.emf.ecore.resource.Resource$IOWrappedException: Resource '/absolute/path/to/my/existing/dsl.file' does not exist. at org.openarchitectureware.xtext.parser.impl.AbstractParserComponent.invokeInternal(AbstractParserComponent.java:55) ``` To what value should I set the model file attribute (dslFile) in the map I hand to the WorkflowRunner: ``` Map properties = new HashMap(); properties.put("modelFile", dslFile); ``` I also tried leaving the properties empty and referencing the model file relative to the workflow file (inside the workflow file), but that yields a FileNotFoundException. Running all of this in a normal app (not in a second workbench) works fine.
I found help at the [openArchitectureWare forum](http://openarchitectureware.org/forum/viewtopic.php?showtopic=10197). Basically using ``` properties.put("modelFile", file.getLocation().makeAbsolute().toOSString()); ``` works, but you need to specify looking it up via URI in the workflow you are calling: ``` <component class="org.eclipse.mwe.emf.Reader"> <uri value='${modelFile}'/> <modelSlot value='theModel'/> </component> ```
139,580
<p>I'm working on some code for a loosely coupled cluster. To achieve optimal performance during jobs, I have the cluster remap its data each time a child enters or exits. This will eventually be made optional, but for now it performs its data balancing by default. My balancing is basically just making sure that each child never has more than the average number of files per machine, plus one. The plus one is for the remainder if the division isn't clean. And since the remainder will <em>always</em> be less than the number of children [except 0 case, but we can exclude that], children after a balancing will have at most avg + 1.</p> <p>Everything seems fine, until I realized my algorithm is O(n!). Go down the list of children, find out the avg, remainder, who has too many and who has too few. For each child in the too many list, go through list, send to each child who has too few.</p> <p>Is there a better solution to this? I feel there must be.</p> <p>Edit: Here is some psuedocode to show how i derived O(n!):</p> <pre><code>foreach ( child in children ) { if ( child.dataLoad &gt; avg + 1 ) { foreach ( child2 in children ) { if ( child != child2 &amp;&amp; child2.dataLoad &lt; avg ) { sendLoad(child, child2) } } } } </code></pre> <p>Edit: O(n^2). Foreach n, n => n*n => n^2. I guess I didn't have enough coffee this morning! ;)</p> <p>In the future I'd like to move to a more flexible and resilient distribution method[weights and hueristics], but for now, a uniform distribution of data works.</p>
[ { "answer_id": 139656, "author": "zvrba", "author_id": 2583, "author_profile": "https://Stackoverflow.com/users/2583", "pm_score": 2, "selected": false, "text": "<p>I think that your analysis is incorrect:</p>\n\n<ul>\n<li>walking through the list to find out the average is O(n)</li>\n<l...
2008/09/26
[ "https://Stackoverflow.com/questions/139580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ]
I'm working on some code for a loosely coupled cluster. To achieve optimal performance during jobs, I have the cluster remap its data each time a child enters or exits. This will eventually be made optional, but for now it performs its data balancing by default. My balancing is basically just making sure that each child never has more than the average number of files per machine, plus one. The plus one is for the remainder if the division isn't clean. And since the remainder will *always* be less than the number of children [except 0 case, but we can exclude that], children after a balancing will have at most avg + 1. Everything seems fine, until I realized my algorithm is O(n!). Go down the list of children, find out the avg, remainder, who has too many and who has too few. For each child in the too many list, go through list, send to each child who has too few. Is there a better solution to this? I feel there must be. Edit: Here is some psuedocode to show how i derived O(n!): ``` foreach ( child in children ) { if ( child.dataLoad > avg + 1 ) { foreach ( child2 in children ) { if ( child != child2 && child2.dataLoad < avg ) { sendLoad(child, child2) } } } } ``` Edit: O(n^2). Foreach n, n => n\*n => n^2. I guess I didn't have enough coffee this morning! ;) In the future I'd like to move to a more flexible and resilient distribution method[weights and hueristics], but for now, a uniform distribution of data works.
@zvrba: You do not even have to sort the list. When traversing the list the second time just move all items with less the average workload to the end of the list (you can keep a pointer to the last item at your first traversal). The order does not have to be perfect, it just changes when the iterators have to be augmented or decreased in your last step. [See previous answer](https://stackoverflow.com/questions/139580/balanced-distribution-algorithm#139656) The last step would look something like: In the second step keep a pointer to the first item with less than average workload in child2 (to prevent the necessity to have a double link list). ``` for each child in list { if child2 == nil then assert("Error in logic"); while child.workload > avg + 1 { sendwork(child, child2, min(avg + 1 - child2.workload, child.workload - (avg + 1))) if child2.workload == avg + 1 then child2 = child2.next; } } ```
139,592
<p>I've got a generic dictionary <code>Dictionary&lt;string, T&gt;</code> that I would like to essentially make a Clone() of ..any suggestions. </p>
[ { "answer_id": 139626, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": false, "text": "<p>(Note: although the cloning version is potentially useful, for a simple shallow copy the constructor I mention in the...
2008/09/26
[ "https://Stackoverflow.com/questions/139592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4398/" ]
I've got a generic dictionary `Dictionary<string, T>` that I would like to essentially make a Clone() of ..any suggestions.
Okay, the .NET 2.0 answers: If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.) If you *do* need to clone the values, you can use something like this: ``` public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue> (Dictionary<TKey, TValue> original) where TValue : ICloneable { Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count, original.Comparer); foreach (KeyValuePair<TKey, TValue> entry in original) { ret.Add(entry.Key, (TValue) entry.Value.Clone()); } return ret; } ``` That relies on `TValue.Clone()` being a suitably deep clone as well, of course.
139,593
<p>I have the following code:</p> <pre><code>info = new System.Diagnostics.ProcessStartInfo(&quot;TheProgram.exe&quot;, String.Join(&quot; &quot;, args)); info.CreateNoWindow = true; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; info.RedirectStandardOutput = true; info.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(info); p.WaitForExit(); Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents </code></pre> <p>I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at <code>WaitForExit</code>. Note also this code does NOT hang for smaller outputs (like 3KB).</p> <p>Is it possible that the internal <code>StandardOutput</code> in <code>ProcessStartInfo</code> can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?</p>
[ { "answer_id": 139604, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 7, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx\" rel=\"noreferrer\">doc...
2008/09/26
[ "https://Stackoverflow.com/questions/139593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have the following code: ``` info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args)); info.CreateNoWindow = true; info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; info.RedirectStandardOutput = true; info.UseShellExecute = false; System.Diagnostics.Process p = System.Diagnostics.Process.Start(info); p.WaitForExit(); Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents ``` I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at `WaitForExit`. Note also this code does NOT hang for smaller outputs (like 3KB). Is it possible that the internal `StandardOutput` in `ProcessStartInfo` can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?
The problem is that if you redirect `StandardOutput` and/or `StandardError` the internal buffer can become full. Whatever order you use, there can be a problem: * If you wait for the process to exit before reading `StandardOutput` the process can block trying to write to it, so the process never ends. * If you read from `StandardOutput` using ReadToEnd then *your* process can block if the process never closes `StandardOutput` (for example if it never terminates, or if it is blocked writing to `StandardError`). The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both `StandardOutput` and `StandardError` you can do this: EDIT: See answers below for how avoid an **ObjectDisposedException** if the timeout occurs. ``` using (Process process = new Process()) { process.StartInfo.FileName = filename; process.StartInfo.Arguments = arguments; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputWaitHandle.Set(); } else { output.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { errorWaitHandle.Set(); } else { error.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // Process completed. Check process.ExitCode here. } else { // Timed out. } } } ```
139,623
<p>How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript.</p> <p>So far I have the following but it has no time delay</p> <pre><code>&lt;body onload="document.location='newPage.html'"&gt; </code></pre>
[ { "answer_id": 139660, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 5, "selected": true, "text": "<p>A meta refresh is ugly but will work. The following will go to the new url after 5 seconds: </p>\n\n<pre><code>&lt;me...
2008/09/26
[ "https://Stackoverflow.com/questions/139623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript. So far I have the following but it has no time delay ``` <body onload="document.location='newPage.html'"> ```
A meta refresh is ugly but will work. The following will go to the new url after 5 seconds: ``` <meta http-equiv="refresh" content="5;url=http://example.com/"/> ``` <http://en.wikipedia.org/wiki/Meta_refresh>
139,630
<p>What's the difference between <code>TRUNCATE</code> and <code>DELETE</code> in SQL?</p> <p>If your answer is platform specific, please indicate that.</p>
[ { "answer_id": 139633, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 9, "selected": true, "text": "<p>Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in oth...
2008/09/26
[ "https://Stackoverflow.com/questions/139630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6742/" ]
What's the difference between `TRUNCATE` and `DELETE` in SQL? If your answer is platform specific, please indicate that.
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below. --- General Overview ================ If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE. Various system-specific issues have to be considered, as detailed below. --- Statement type ============== Delete is DML, Truncate is DDL ([What is DDL and DML?](https://stackoverflow.com/q/2578194/276052)) --- Commit and Rollback =================== Variable by vendor **SQL\*Server** Truncate can be rolled back. **PostgreSQL** Truncate can be rolled back. **Oracle** Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway. However, see Flashback below. --- Space reclamation ================= Delete does not recover space, Truncate recovers space **Oracle** If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset. --- Row scope ========= Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows. **Oracle** When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible. --- Object types ============ Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific) --- Data Object Identity ==================== **Oracle** Delete does not affect the data object id, but truncate assigns a new data object id *unless* there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation. --- Flashback (Oracle) ================== Flashback works across deletes, but a truncate prevents flashback to states prior to the operation. However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition [Use of FLASHBACK in Oracle](https://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle) <http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638> --- Privileges ========== Variable **Oracle** Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant. --- Redo/Undo ========= Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each. --- Indexes ======= **Oracle** A truncate operation renders unusable indexes usable again. Delete does not. --- Foreign Keys ============ A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys. --- Table Locking ============= **Oracle** Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table. --- Triggers ======== DML triggers do not fire on a truncate. **Oracle** DDL triggers are available. --- Remote Execution ================ **Oracle** Truncate cannot be issued over a database link. --- Identity Columns ================ **SQL\*Server** Truncate resets the sequence for IDENTITY column types, delete does not. --- Result set ========== In most implementations, a `DELETE` statement can return to the client the rows that were deleted. e.g. in an Oracle PL/SQL subprogram you could: ``` DELETE FROM employees_temp WHERE employee_id = 299 RETURNING first_name, last_name INTO emp_first_name, emp_last_name; ```
139,639
<p>I am working with Reporting Services and Sharepoint, I have an application that leverages reporting services however a client would like our application integrated into sharepoint. Currently we are tightly coupled to the ReportService.asmx webservice which exposes various methods for performing operations. Reporting Services has something called "Sharepoint Integration mode" when enabled the report server works differently and Sharepoint is used to manage the reports. Sharepoint adds a new web service called ReportService2006.asmx which is almost exactly the same. </p> <p>Now our application uses a web reference to the ReportService and uses various objects exposed by the service. ReportService2006 has exactly the same objects but they are obviously in a different namespace e.g I have 2 web references - 1 to each service so there is an object MyApplication.ReportService.CatalogItem and another MyApplication.ReportService2006.CatalogItem.</p> <p>I've tried to use dependency injection to absract the Service out of our application coupled with a factory pattern to determine which implementation of my interface to instantiate. Heres my interface. I've simplified it to include only the calls I need for this application.</p> <pre><code>using System; using NetworkUserEncrypt.ReportService; namespace MyApplication.Service { public interface IReportingService { CatalogItem CreateDataSource(string DataSource, string Parent, bool Overwrite, DataSourceDefinition Definition, Property[] Properties); void DeleteItem(string Item); DataSourceDefinition GetDataSourceContents(string DataSource); byte[] GetReportDefinition(string Report); CatalogItem[] ListChildren(string Item); } } </code></pre> <p>So I have 2 implementations of this each instantiating a different web service e.g:</p> <pre><code>namespace MyApp.Service.Implementation { class ReportingServiceImpl : IReportingService { ReportingService _service = null; public ReportingServiceImpl() { ReportingService _service = new ReportingService(); } /* SNIP */ } } </code></pre> <p>and</p> <pre><code>namespace MyApp.Service.Implementation { class ReportingService2006Impl : IReportingService { ReportingService2006 _service = null; public ReportingService2006Impl() { ReportingService2006 _service = new ReportingService2006(); } /* SNIP */ } } </code></pre> <p>So the plan is I can inject these into my ServiceWrapper at run time. However - if you'll notice the interface is tied to the ReportService and some of the methods return objects that are from the web reference e.g. CatalogItem. Thus my project won't build because my implementation for ReportService2006 is referencing the CatalogItem from a different namespace.</p> <p>Any ideas? Am I going totally the wrong direction with this?</p>
[ { "answer_id": 139633, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 9, "selected": true, "text": "<p>Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in oth...
2008/09/26
[ "https://Stackoverflow.com/questions/139639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950/" ]
I am working with Reporting Services and Sharepoint, I have an application that leverages reporting services however a client would like our application integrated into sharepoint. Currently we are tightly coupled to the ReportService.asmx webservice which exposes various methods for performing operations. Reporting Services has something called "Sharepoint Integration mode" when enabled the report server works differently and Sharepoint is used to manage the reports. Sharepoint adds a new web service called ReportService2006.asmx which is almost exactly the same. Now our application uses a web reference to the ReportService and uses various objects exposed by the service. ReportService2006 has exactly the same objects but they are obviously in a different namespace e.g I have 2 web references - 1 to each service so there is an object MyApplication.ReportService.CatalogItem and another MyApplication.ReportService2006.CatalogItem. I've tried to use dependency injection to absract the Service out of our application coupled with a factory pattern to determine which implementation of my interface to instantiate. Heres my interface. I've simplified it to include only the calls I need for this application. ``` using System; using NetworkUserEncrypt.ReportService; namespace MyApplication.Service { public interface IReportingService { CatalogItem CreateDataSource(string DataSource, string Parent, bool Overwrite, DataSourceDefinition Definition, Property[] Properties); void DeleteItem(string Item); DataSourceDefinition GetDataSourceContents(string DataSource); byte[] GetReportDefinition(string Report); CatalogItem[] ListChildren(string Item); } } ``` So I have 2 implementations of this each instantiating a different web service e.g: ``` namespace MyApp.Service.Implementation { class ReportingServiceImpl : IReportingService { ReportingService _service = null; public ReportingServiceImpl() { ReportingService _service = new ReportingService(); } /* SNIP */ } } ``` and ``` namespace MyApp.Service.Implementation { class ReportingService2006Impl : IReportingService { ReportingService2006 _service = null; public ReportingService2006Impl() { ReportingService2006 _service = new ReportingService2006(); } /* SNIP */ } } ``` So the plan is I can inject these into my ServiceWrapper at run time. However - if you'll notice the interface is tied to the ReportService and some of the methods return objects that are from the web reference e.g. CatalogItem. Thus my project won't build because my implementation for ReportService2006 is referencing the CatalogItem from a different namespace. Any ideas? Am I going totally the wrong direction with this?
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below. --- General Overview ================ If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE. Various system-specific issues have to be considered, as detailed below. --- Statement type ============== Delete is DML, Truncate is DDL ([What is DDL and DML?](https://stackoverflow.com/q/2578194/276052)) --- Commit and Rollback =================== Variable by vendor **SQL\*Server** Truncate can be rolled back. **PostgreSQL** Truncate can be rolled back. **Oracle** Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway. However, see Flashback below. --- Space reclamation ================= Delete does not recover space, Truncate recovers space **Oracle** If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset. --- Row scope ========= Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows. **Oracle** When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible. --- Object types ============ Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific) --- Data Object Identity ==================== **Oracle** Delete does not affect the data object id, but truncate assigns a new data object id *unless* there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation. --- Flashback (Oracle) ================== Flashback works across deletes, but a truncate prevents flashback to states prior to the operation. However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition [Use of FLASHBACK in Oracle](https://stackoverflow.com/questions/25950145/use-of-flashback-in-oracle) <http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638> --- Privileges ========== Variable **Oracle** Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant. --- Redo/Undo ========= Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each. --- Indexes ======= **Oracle** A truncate operation renders unusable indexes usable again. Delete does not. --- Foreign Keys ============ A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys. --- Table Locking ============= **Oracle** Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table. --- Triggers ======== DML triggers do not fire on a truncate. **Oracle** DDL triggers are available. --- Remote Execution ================ **Oracle** Truncate cannot be issued over a database link. --- Identity Columns ================ **SQL\*Server** Truncate resets the sequence for IDENTITY column types, delete does not. --- Result set ========== In most implementations, a `DELETE` statement can return to the client the rows that were deleted. e.g. in an Oracle PL/SQL subprogram you could: ``` DELETE FROM employees_temp WHERE employee_id = 299 RETURNING first_name, last_name INTO emp_first_name, emp_last_name; ```
139,650
<p>I have normally hand written xml like this:</p> <pre><code>&lt;tag&gt;&lt;?= $value ?&gt;&lt;/tag&gt; </code></pre> <p>Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that?</p>
[ { "answer_id": 139671, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 4, "selected": true, "text": "<p>Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using.</p>\n\n<p>Good XM...
2008/09/26
[ "https://Stackoverflow.com/questions/139650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
I have normally hand written xml like this: ``` <tag><?= $value ?></tag> ``` Having found tools such as simpleXML, should I be using those instead? What's the advantage of doing it using a tool like that?
Good XML tools will ensure that the resulting XML file properly validates against the DTD you are using. Good XML tools also save a bunch of repetitive typing of tags.
139,670
<p>In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return.</p> <p>Eg:</p> <pre><code>insert into table values ('test1 test2 test3 test4'); </code></pre> <p>When I retrieve it, I get the message in a line </p> <p>test1 test2 test3 test4</p> <p>The carriage return is treated as a single character.</p> <p>Is there way to get the carriage returns or its just the way its going to be stored?</p> <p>Thanks for the help guys!!!</p> <p>Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert.</p> <p>I return the data to the app development (C++) and may be some data or report viewer.</p> <p>I don't want to manipulate on the data.</p>
[ { "answer_id": 139687, "author": "Dejan", "author_id": 11471, "author_profile": "https://Stackoverflow.com/users/11471", "pm_score": 2, "selected": false, "text": "<p>Can you please clarify how you retrieve the data back from the database? What tool do you use? The data probably contains...
2008/09/26
[ "https://Stackoverflow.com/questions/139670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21968/" ]
In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return. Eg: ``` insert into table values ('test1 test2 test3 test4'); ``` When I retrieve it, I get the message in a line test1 test2 test3 test4 The carriage return is treated as a single character. Is there way to get the carriage returns or its just the way its going to be stored? Thanks for the help guys!!! Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert. I return the data to the app development (C++) and may be some data or report viewer. I don't want to manipulate on the data.
You can store Carriage return in the database. The problem here is that you are using SQL Server Management Studio to display the results of your query. You probably have it configured to show the results in a grid. Change the configuration of SSMS to show results to text and you will see the carriage returns. Right click in the query window -> Results To -> Results To Text Run your query again.
139,686
<p>The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still see them and occasionally hear performance implications given as their justification.</p> <p>It's easy to demonstrate in c that redundant initialisation is optimised out:</p> <pre><code>$ less test.c #include &lt;stdio.h&gt; main() { #ifdef INIT_LOC int a = 33; int b; memset(&amp;b,66,sizeof(b)); #else int a; int b; #endif a = 0; b = 0; printf ("a = %i, b = %i\n", a, b); } $ gcc --version gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) </code></pre> <p>[Not Optimised:]</p> <pre><code>$ gcc test.c -S -o no_init.s; gcc test.c -S -D INIT_LOC=1 -o init.s; diff no_in it.s init.s 22a23,28 &gt; movl $33, -4(%ebp) &gt; movl $4, 8(%esp) &gt; movl $66, 4(%esp) &gt; leal -8(%ebp), %eax &gt; movl %eax, (%esp) &gt; call _memset 33a40 &gt; .def _memset; .scl 3; .type 32; .endef </code></pre> <p>[Optimised:]</p> <pre><code>$ gcc test.c -O -S -o no_init.s; gcc test.c -O -S -D INIT_LOC=1 -o init.s; diff no_init.s init.s $ </code></pre> <p>So WRT performance under what circumstances is mandatory variable initialisation NOT a good idea?</p> <p>IF applicable, no need to restrict answers to c/c++ but please be clear about the language/environment (and reproducible evidence much preferred over speculation!)</p>
[ { "answer_id": 139731, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "<p>Sometimes you need a variable as a placeholder (e.g. using the <code>ftime</code> functions), so it doesn't make sense to i...
2008/09/26
[ "https://Stackoverflow.com/questions/139686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22640/" ]
The maintenance problems that uninitialised locals cause (particularly pointers) will be obvious to anyone who has done a bit of c/c++ maintenance or enhancement, but I still see them and occasionally hear performance implications given as their justification. It's easy to demonstrate in c that redundant initialisation is optimised out: ``` $ less test.c #include <stdio.h> main() { #ifdef INIT_LOC int a = 33; int b; memset(&b,66,sizeof(b)); #else int a; int b; #endif a = 0; b = 0; printf ("a = %i, b = %i\n", a, b); } $ gcc --version gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125) ``` [Not Optimised:] ``` $ gcc test.c -S -o no_init.s; gcc test.c -S -D INIT_LOC=1 -o init.s; diff no_in it.s init.s 22a23,28 > movl $33, -4(%ebp) > movl $4, 8(%esp) > movl $66, 4(%esp) > leal -8(%ebp), %eax > movl %eax, (%esp) > call _memset 33a40 > .def _memset; .scl 3; .type 32; .endef ``` [Optimised:] ``` $ gcc test.c -O -S -o no_init.s; gcc test.c -O -S -D INIT_LOC=1 -o init.s; diff no_init.s init.s $ ``` So WRT performance under what circumstances is mandatory variable initialisation NOT a good idea? IF applicable, no need to restrict answers to c/c++ but please be clear about the language/environment (and reproducible evidence much preferred over speculation!)
Short answer: declare the variable as close to first use as possible and initialize to "zero" if you still need to. Long answer: If you declare a variable at the start of a function, and don't use it until later, you should reconsider your placement of the variable to as local a scope as possible. You can then usually assign to it the needed value right away. If you must declare it uninitialized because it gets assigned in a conditional, or passed by reference and assigned to, initializing it to a null-equivalent value is a good idea. The compiler can sometimes save you if you compile under -Wall, as it will warn if you read from a variable before initializing it. However, it fails to warn you if you pass it to a function. If you play it safe and set it to a null-equivalent, you have done no harm if the function you pass it to overwrites it. If, however, the function you pass it to uses the value, you can pretty much be guaranteed failing an assert (if you have one), or at least segfaulting the second you use a null object. Random initialization can do all sorts of bad things, including "work".
139,739
<p>I've been doing a massive code review and one pattern I notice all over the place is this:</p> <pre><code>public bool MethodName() { bool returnValue = false; if (expression) { // do something returnValue = MethodCall(); } else { // do something else returnValue = Expression; } return returnValue; } </code></pre> <p>This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?</p> <p>I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.</p>
[ { "answer_id": 139754, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "<p>I would have used ternary, to reduce control structures...</p>\n\n<pre>\n<code>\nreturn expression ? MethodCall() : Expre...
2008/09/26
[ "https://Stackoverflow.com/questions/139739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
I've been doing a massive code review and one pattern I notice all over the place is this: ``` public bool MethodName() { bool returnValue = false; if (expression) { // do something returnValue = MethodCall(); } else { // do something else returnValue = Expression; } return returnValue; } ``` This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct? I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.
I would have used ternary, to reduce control structures... ``` return expression ? MethodCall() : Expression; ```
139,759
<p>Is there any way to list all the files that have changed between two tags in CVS?</p> <p>Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases.</p> <p>It would also work if I could find all files that had changed between two dates.</p>
[ { "answer_id": 139871, "author": "Decio Lira", "author_id": 12423, "author_profile": "https://Stackoverflow.com/users/12423", "pm_score": 6, "selected": true, "text": "<p>I suppose this command would help:</p>\n\n<pre><code>cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 &gt; diffs\n</code>...
2008/09/26
[ "https://Stackoverflow.com/questions/139759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ]
Is there any way to list all the files that have changed between two tags in CVS? Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases. It would also work if I could find all files that had changed between two dates.
I suppose this command would help: ``` cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs ``` where `RELEASE_1_0` and `RELEASE_1_1` are the names of your tags. You can find a little more information on cvs diff command [here](http://www.network-theory.co.uk/docs/cvsmanual/diffexamples.html) plus it should be fairly simple to create a script to make report more suitbable for your needs, ex: number of files changed, created deleted etc. As far as I know the most common cvs GUI tools (wincvs and tortoise) do not provide something like this out of the box. Hope it helps `;)`
139,794
<p>Let's say we have <code>index.php</code> and it is stored in <code>/home/user/public/www</code> and <code>index.php</code> calls the class <code>Foo-&gt;bar()</code> from the file <code>inc/app/Foo.class.php</code>. </p> <p>I'd like the bar function in the <code>Foo</code> class to get a hold of the path <code>/home/user/public/www</code> in this instance — I don't want to use a global variable, pass a variable, etc.</p>
[ { "answer_id": 139825, "author": "RobbieGee", "author_id": 6752, "author_profile": "https://Stackoverflow.com/users/6752", "pm_score": 1, "selected": false, "text": "<p>Found it. getcwd().</p>\n" }, { "answer_id": 139830, "author": "Devon", "author_id": 13850, "author...
2008/09/26
[ "https://Stackoverflow.com/questions/139794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752/" ]
Let's say we have `index.php` and it is stored in `/home/user/public/www` and `index.php` calls the class `Foo->bar()` from the file `inc/app/Foo.class.php`. I'd like the bar function in the `Foo` class to get a hold of the path `/home/user/public/www` in this instance — I don't want to use a global variable, pass a variable, etc.
Wouldn't this get you the directory of the running script more easily? ``` $dir=dirname($_SERVER["SCRIPT_FILENAME"]) ```
139,809
<p>I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?</p>
[ { "answer_id": 139886, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 5, "selected": true, "text": "<p>You don't need to inherit from <code>ServiceHost</code>. There are other approaches to your problem.</p>\n\n<p>You ...
2008/09/26
[ "https://Stackoverflow.com/questions/139809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8033/" ]
I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?
You don't need to inherit from `ServiceHost`. There are other approaches to your problem. You can pass an instance of the service class, instead of a type to `ServiceHost`. Thus, you can create the instance before you start the `ServiceHost`, and add your own event handlers to any events it exposes. Here's some sample code: ``` MyService svc = new MyService(); svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent); ServiceHost host = new ServiceHost(svc); host.Open(); ``` There are some caveats when using this approach, as described in <http://msdn.microsoft.com/en-us/library/ms585487.aspx> Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen.
139,819
<p>The following test fails:</p> <pre><code>#!/usr/bin/env python def f(*args): """ &gt;&gt;&gt; t = 1, -1 &gt;&gt;&gt; f(*map(lambda i: lambda: i, t)) [1, -1] &gt;&gt;&gt; f(*(lambda: i for i in t)) # -&gt; [-1, -1] [1, -1] &gt;&gt;&gt; f(*[lambda: i for i in t]) # -&gt; [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) if __name__ == '__main__': import doctest; doctest.testmod() </code></pre> <p>In other words:</p> <pre><code>&gt;&gt;&gt; t = 1, -1 &gt;&gt;&gt; args = [] &gt;&gt;&gt; for i in t: ... args.append(lambda: i) ... &gt;&gt;&gt; map(lambda a: a(), args) [-1, -1] &gt;&gt;&gt; args = [] &gt;&gt;&gt; for i in t: ... args.append((lambda i: lambda: i)(i)) ... &gt;&gt;&gt; map(lambda a: a(), args) [1, -1] &gt;&gt;&gt; args = [] &gt;&gt;&gt; for i in t: ... args.append(lambda i=i: i) ... &gt;&gt;&gt; map(lambda a: a(), args) [1, -1] </code></pre>
[ { "answer_id": 139880, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "<p>The lambda captures variables, not values, hence the code</p>\n\n<pre><code>lambda : i\n</code></pre>\n\n<p>will always ret...
2008/09/26
[ "https://Stackoverflow.com/questions/139819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ]
The following test fails: ``` #!/usr/bin/env python def f(*args): """ >>> t = 1, -1 >>> f(*map(lambda i: lambda: i, t)) [1, -1] >>> f(*(lambda: i for i in t)) # -> [-1, -1] [1, -1] >>> f(*[lambda: i for i in t]) # -> [-1, -1] [1, -1] """ alist = [a() for a in args] print(alist) if __name__ == '__main__': import doctest; doctest.testmod() ``` In other words: ``` >>> t = 1, -1 >>> args = [] >>> for i in t: ... args.append(lambda: i) ... >>> map(lambda a: a(), args) [-1, -1] >>> args = [] >>> for i in t: ... args.append((lambda i: lambda: i)(i)) ... >>> map(lambda a: a(), args) [1, -1] >>> args = [] >>> for i in t: ... args.append(lambda i=i: i) ... >>> map(lambda a: a(), args) [1, -1] ```
They are different, because the value of `i` in both the generator expression and the list comp are evaluated lazily, i.e. when the anonymous functions are invoked in `f`. By that time, `i` is bound to the last value if `t`, which is -1. So basically, this is what the list comprehension does (likewise for the genexp): ``` x = [] i = 1 # 1. from t x.append(lambda: i) i = -1 # 2. from t x.append(lambda: i) ``` Now the lambdas carry around a closure that references `i`, but `i` is bound to -1 in both cases, because that is the last value it was assigned to. If you want to make sure that the lambda receives the current value of `i`, do ``` f(*[lambda u=i: u for i in t]) ``` This way, you force the evaluation of `i` at the time the closure is created. **Edit**: There is one difference between generator expressions and list comprehensions: the latter leak the loop variable into the surrounding scope.
139,821
<p>What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message.</p>
[ { "answer_id": 139965, "author": "willem", "author_id": 22702, "author_profile": "https://Stackoverflow.com/users/22702", "pm_score": 2, "selected": false, "text": "<p>Ensure that you use a webHttpBinding on your endpoint (and not an httpBinding or wsHttpBinding). Here's my endpoint conf...
2008/09/26
[ "https://Stackoverflow.com/questions/139821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
What is the bare minimum I need to put in web.config to get WCF working with REST? I have annotated my methods with [WebGet], but they are not getting the message.
I discovered that you can add the following to the ServiceHost directive in the \*.svc file, and it will automatically setup WebHttpBinding and WebHttpBehavior for you: ``` Factory="System.ServiceModel.Activation.WebServiceHostFactory" ``` Note that the namespace is a little different from what is mentioned elsewhere on the web (such as in [this MSDN article](http://msdn.microsoft.com/en-us/magazine/cc135976.aspx)). After doing this, I was able to delete the entire section from web.config and everything still worked!
139,833
<p>I am using StringReplace to replace &amp;gt and &amp;lt by the char itself in a generated XML like this:</p> <pre><code>StringReplace(xml.Text,'&amp;gt;','&gt;',[rfReplaceAll]) ; StringReplace(xml.Text,'&amp;lt;','&lt;',[rfReplaceAll]) ; </code></pre> <p>The thing is it takes way tooo long to replace every occurence of &amp;gt.</p> <p>Do you purpose any better idea to make it faster?</p>
[ { "answer_id": 139876, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<p>The problem is that you are iterating the entire string size twice (one for replacing &amp;gt; by > and another on...
2008/09/26
[ "https://Stackoverflow.com/questions/139833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19224/" ]
I am using StringReplace to replace &gt and &lt by the char itself in a generated XML like this: ``` StringReplace(xml.Text,'&gt;','>',[rfReplaceAll]) ; StringReplace(xml.Text,'&lt;','<',[rfReplaceAll]) ; ``` The thing is it takes way tooo long to replace every occurence of &gt. Do you purpose any better idea to make it faster?
Try [FastStrings.pas](http://www.koders.com/delphi/fidFB386C5C240FD5E72013C882ADD7600FDF60E6C7.aspx?s=socket) from Peter Morris.
139,835
<p>I have a C# WinForms borderless window, for which I override WndProc and handle the WM_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar.</p> <p>This form uses these styles:</p> <pre><code>this.SetStyle( ControlStyles.AllPaintingInWmPaint, true ); this.SetStyle( ControlStyles.UserPaint, true ); this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true ); this.SetStyle( ControlStyles.ResizeRedraw, true ); </code></pre> <p>And has these non-default property values:</p> <pre><code>this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; </code></pre> <p>I've tried handling WM_NCRBUTTONDOWN and WM_NCRBUTTONUP, and send the WM_GETSYSMENU message, but it didn't work.</p>
[ { "answer_id": 139970, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 0, "selected": false, "text": "<p>I have the same properties in my application and Right click doesn't work either, so this is not <em>your probl...
2008/09/26
[ "https://Stackoverflow.com/questions/139835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4898/" ]
I have a C# WinForms borderless window, for which I override WndProc and handle the WM\_NCHITTEST message. For an area of that form, my hit test function returns HTSYSMENU. Double-clicking that area successfully closes the form, but right-clicking it does not show the window's system menu, nor does it show up when right-clicking the window's name in the taskbar. This form uses these styles: ``` this.SetStyle( ControlStyles.AllPaintingInWmPaint, true ); this.SetStyle( ControlStyles.UserPaint, true ); this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true ); this.SetStyle( ControlStyles.ResizeRedraw, true ); ``` And has these non-default property values: ``` this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; ``` I've tried handling WM\_NCRBUTTONDOWN and WM\_NCRBUTTONUP, and send the WM\_GETSYSMENU message, but it didn't work.
A borderless window, if I am not mistaken, is flagged such that it offers no system menu, and that it does not appear in the taskbar. The fact that any given window does not have a border and does not appear in the taskbar is the result of the style flags set on the window. These particular Style flags can be set using the `GetWindowLong` and `SetWindowLong` API calls. However you have to be careful as certain styles just don't work together. I have written a number of custom controls over the years and I am constantly coaxing windows to become something they weren't originally intended to be. For example I have written my own dropdown control where I needed a window to behave as a popup and not to activate. The following code will do that. Note that the code appears in the `OnHandleCreated` event handler. This is because the flags need to be changed just after the handle is setup which indicates that Windows has already set what it thinks the flags should be. ``` using System.Runtime.InteropServices; protected override void OnHandleCreated(EventArgs e) { uint dwWindowProperty; User32.SetParent(this.Handle, IntPtr.Zero); dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.EXSTYLE ); dwWindowProperty = dwWindowProperty | (uint)User32.WSEX.TOOLWINDOW | (uint)User32.WSEX.NOACTIVATE; User32.SetWindowLong( this.Handle, User32.GWL.EXSTYLE, dwWindowProperty ); dwWindowProperty = User32.GetWindowLong( this.Handle, User32.GWL.STYLE ); dwWindowProperty = ( dwWindowProperty & ~(uint)User32.WS.CHILD ) | (uint)User32.WS.POPUP; User32.SetWindowLong( this.Handle, User32.GWL.STYLE, dwWindowProperty ); base.OnHandleCreated (e); } //this is a fragment of my User32 library wrapper needed for the previous code segment. class User32 { [DllImport("user32.dll", SetLastError = true)] static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); [DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )] public static extern int SetWindowLong( IntPtr hWnd, User32.GWL gwlIndex, uint dwNewLong); [DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall )] public static extern uint GetWindowLong( IntPtr hWnd, User32.GWL gwlIndex ); [FlagsAttribute] public enum WS: uint { POPUP = 0x80000000, CHILD = 0x40000000, } public enum GWL { STYLE = -16, EXSTYLE = -20 } [FlagsAttribute] public enum WSEX: uint { TOP = 0x0, TOPMOST = 0x8, TOOLWINDOW = 0x80, NOACTIVATE = 0x08000000, } } ``` Unfortunately the `SysMenu` style cannot be set without using the `Caption` style, so I can't say if this is a problem in your implementation. You can check out the original style list and the extend style list at these two links: [Window Styles](https://learn.microsoft.com/en-us/windows/desktop/winmsg/window-styles) [CreateWindowEx](https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-createwindowexw)
139,859
<p>On <strong>Linux/NPTL</strong>, threads are created as some kind of process.</p> <p>I can see some of my process have a weird cmdline:</p> <pre><code>cat /proc/5590/cmdline hald-addon-storage: polling /dev/scd0 (every 2 sec) </code></pre> <p>Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging.</p> <p><em>/me now investigating in HAL source</em></p>
[ { "answer_id": 139935, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p><code>argv</code> points to writable strings. Just write stuff to them:</p>\n\n<pre><code>#include &lt;string.h&gt;\n#inc...
2008/09/26
[ "https://Stackoverflow.com/questions/139859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1277510/" ]
On **Linux/NPTL**, threads are created as some kind of process. I can see some of my process have a weird cmdline: ``` cat /proc/5590/cmdline hald-addon-storage: polling /dev/scd0 (every 2 sec) ``` Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging. */me now investigating in HAL source*
If you want to do this in a portable way, something that will work across multiple Unix variations, there are very few options available. What you have to do is that your caller process must call exec with the `argv [0]` argument pointing to the name that you would like to see in the process output, and the filename pointing to the actual executable. You can try this behavior from the shell by using: ``` exec -a "This is my cute name" bash ``` That will replace the current bash process with one named `"This is my cute name"`. For doing this in C, you can look at the source code of `sendmail` or any other piece of software that has been ported extensively and find all the variations that are needed across operating systems to support this. Some operating systems have a `setproctitle(3)` API, some others allow you to override the contents of `argv [0]` and show that result.
139,867
<p>Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.</p>
[ { "answer_id": 140235, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 6, "selected": false, "text": "<p>This code gets 242 countries in Sun Java 6:</p>\n\n<pre><code>String[] countryCodes = Locale.getISOCountries();\n</code></...
2008/09/26
[ "https://Stackoverflow.com/questions/139867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12531/" ]
Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.
Now an implementation of country code ([ISO 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1) [alpha-2](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2)/[alpha-3](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-3)/[numeric](http://en.wikipedia.org/wiki/ISO_3166-1_numeric)) list as Java enum is available at GitHub under Apache License version 2.0. **Example:** ```java CountryCode cc = CountryCode.getByCode("JP"); System.out.println("Country name = " + cc.getName()); // "Japan" System.out.println("ISO 3166-1 alpha-2 code = " + cc.getAlpha2()); // "JP" System.out.println("ISO 3166-1 alpha-3 code = " + cc.getAlpha3()); // "JPN" System.out.println("ISO 3166-1 numeric code = " + cc.getNumeric()); // 392 ``` --- **Last Edit** 2016-Jun-09 CountryCode enum was packaged into com.neovisionaries.i18n with other Java enums, LanguageCode ([ISO 639-1](http://en.wikipedia.org/wiki/ISO_639-1)), LanguageAlpha3Code ([ISO 639-2](http://en.wikipedia.org/wiki/ISO_639-2)), LocaleCode, ScriptCode ([ISO 15924](http://en.wikipedia.org/wiki/ISO_15924)) and CurrencyCode ([ISO 4217](http://en.wikipedia.org/wiki/ISO_4217)) and registered into the Maven Central Repository. **Maven** ```xml <dependency> <groupId>com.neovisionaries</groupId> <artifactId>nv-i18n</artifactId> <version>1.29</version> </dependency> ``` **Gradle** ``` dependencies { compile 'com.neovisionaries:nv-i18n:1.29' } ``` **GitHub** <https://github.com/TakahikoKawasaki/nv-i18n> **Javadoc** <https://takahikokawasaki.github.io/nv-i18n/> **OSGi** ``` Bundle-SymbolicName: com.neovisionaries.i18n Export-Package: com.neovisionaries.i18n;version="1.28.0" ```
139,889
<p>I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with <a href="http://httpd.apache.org/docs/2.0/mod/core.html#serveralias" rel="noreferrer">ServerAlias</a>) or do I <a href="http://httpd.apache.org/docs/2.0/mod/mod_alias.html#redirect" rel="noreferrer">Redirect</a> the request? </p> <p>Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used?</p> <p>Common vhost examples will have:</p> <pre><code>ServerName example.net ServerAlias www.example.net </code></pre> <p>Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site?</p> <p>UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load.</p> <p>UPDATE and ANSWER: Thanks Paul for finding the <a href="http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html" rel="noreferrer">Google link</a> which instructs us to "help your fellow webmasters by <strong>not</strong> perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&amp;brand=riedell or www.example.com/skates.asp?brand=riedell&amp;color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."</p>
[ { "answer_id": 139911, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 6, "selected": true, "text": "<p>Redirecting is better, then there is always one, canonical domain for your content. <strike>I hear Google penalises mul...
2008/09/26
[ "https://Stackoverflow.com/questions/139889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15948/" ]
I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with [ServerAlias](http://httpd.apache.org/docs/2.0/mod/core.html#serveralias)) or do I [Redirect](http://httpd.apache.org/docs/2.0/mod/mod_alias.html#redirect) the request? Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used? Common vhost examples will have: ``` ServerName example.net ServerAlias www.example.net ``` Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site? UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load. UPDATE and ANSWER: Thanks Paul for finding the [Google link](http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html) which instructs us to "help your fellow webmasters by **not** perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&brand=riedell or www.example.com/skates.asp?brand=riedell&color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."
Redirecting is better, then there is always one, canonical domain for your content. I hear Google penalises multiple domains hosting the same content, but I can't find a source for that at the moment (edit, [here's one article](http://www.searchenginejournal.com/duplicate-content-penalty-how-to-lose-google-ranking-fast/1886/), but from 2005, which is ancient history in Internet years!) *(not correct, see edit below)* Here's some mod-rewrite rules to redirect to a canonical domain: ``` RewriteCond %{HTTP_HOST} !^www\.foobar\.com [NC] RewriteCond %{HTTP_HOST} !^$ RewriteRule ^/(.*) http://www.foobar.com/$1 [L,R=permanent] ``` That checks that the host isn't the canonical domain (www.foobar.com) and checks that a domain has actually been specified, before deciding to redirect the request to the canonical domain. **Further Edit**: [Here's an article straight from the horses mouth](http://googlewebmastercentral.blogspot.com/2008/09/demystifying-duplicate-content-penalty.html) - seems it's not as big an issue as you might think. Please read this article CAREFULLY as it distinguishes between duplicate content on the same site (as in "www.example.com/skates.asp?color=black&brand=riedell and www.example.com/skates.asp?brand=riedell&color=black") and specifically says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."
139,909
<p>I have a problem with setting the TTL on my Datagram packets. I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0</p>
[ { "answer_id": 139917, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 4, "selected": true, "text": "<p>Basically you have to set an special system property telling the JVM to use an IPv4 stack:</p>\n\n<pre><code>-Djava.net....
2008/09/26
[ "https://Stackoverflow.com/questions/139909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a problem with setting the TTL on my Datagram packets. I am calling the setTTL(...) method on the packet before sending the packet to the multicastSocket but if I capture the packet with ethereal the TTL field is always set to 0
Basically you have to set an special system property telling the JVM to use an IPv4 stack: ``` -Djava.net.preferIPv4Stack=true ```
139,948
<p>I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed.</p> <p>How can this be accomplished? Ive included a sample of my current code below.</p> <p>sample.aspx</p> <pre><code>&lt;asp:textbox id=foo runat=server /&gt; &lt;asp:requiredfieldvalidator id=val runat=server controltovalidate=foo /&gt; &lt;asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') /&gt; </code></pre> <p>sample.aspx.vb</p> <pre><code>Sub Page_Load() If Page.IsPostback() Then Page.Validate() If Page.IsValid Then 'process page here' End If End If End Sub </code></pre> <p>Thanks for any help.</p>
[ { "answer_id": 139977, "author": "Dean", "author_id": 11802, "author_profile": "https://Stackoverflow.com/users/11802", "pm_score": 1, "selected": false, "text": "<p>can you not use the EnableClientScript property for the validator control allowing you to carry out the validation on the...
2008/09/26
[ "https://Stackoverflow.com/questions/139948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a page using .NETs server-side input validation controls. This page also has a javascript confirm box that fires when the form is submitted. Currently when the Submit button is selected, the javascript confirm box appears, and once confirmed the ASP.NET server-side validation controls are fired. I would like to fire the server-side validation controls BEFORE the javascript confirm box is displayed. How can this be accomplished? Ive included a sample of my current code below. sample.aspx ``` <asp:textbox id=foo runat=server /> <asp:requiredfieldvalidator id=val runat=server controltovalidate=foo /> <asp:button id=submit runat=server onClientClick=return confirm('Confirm this submission?') /> ``` sample.aspx.vb ``` Sub Page_Load() If Page.IsPostback() Then Page.Validate() If Page.IsValid Then 'process page here' End If End If End Sub ``` Thanks for any help.
This seems to be a very common problem. The workaround: Validate the page first, then call `confirm`, as shown [here](http://www.codedigest.com/CodeDigest/73-Fire-Validator-Controls-Before-JavaScript-Confirm-Box-Fires-in-ASP-Net-Page.aspx) and [here](http://www.stevekinsey.com/2007/06/04/onclientclick-and-form-validation-controls/). This does have the drawback of calling the validation twice - once in your code, and once in the generated code in the submit `onclick`. How to make this work properly, i.e. Validate the page first (and only once), then show the `confirm` box, I do not yet know. Edit: [Here](http://www.dotnetjohn.com/articles.aspx?articleid=39)'s a useful suggestion: > > What ASP.NET does behind the scenes > when validation controls exist, is add > an autogenerated onClick event for > each button. This OnClick event would > supercede the custom OnClick event. So to > overcome this I did the following: > > > 1. add CausesValidation = False > 2. added Validate() and IsValid code to the onClick event > behind the page to simulate the now > missing autogenerated validation code > behind the button. > > > Edit 2: A complete example ``` <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="if (Page_ClientValidate()){ return confirm('Do you want to submit this page?')}" CausesValidation="false" /> ```
139,954
<p>I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help.</p> <p>Basically, i have an URL like /products.aspx?categoryid=foo&amp;productid=bar</p> <p>Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc.</p> <p>But i need to map it to /products/foo/bar. (without "category")</p> <p>Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :)</p> <p>P.S. Sorry for my bad English.</p>
[ { "answer_id": 139986, "author": "Ben Scheirman", "author_id": 3381, "author_profile": "https://Stackoverflow.com/users/3381", "pm_score": 4, "selected": true, "text": "<p><em>(your English is just fine, no need to apologize!)</em></p>\n\n<p>You can define a route like this:</p>\n\n<pre>...
2008/09/26
[ "https://Stackoverflow.com/questions/139954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19610/" ]
I've started with ASP.NET MVC recently, reading blogs, tutorials, trying some routes, etc. Now, i've stumbled on a issue where i need some help. Basically, i have an URL like /products.aspx?categoryid=foo&productid=bar Most tutorials/examples propose to map this to something like: /products/category/foo/bar where "products" is the controller, "category" is the action, etc. But i need to map it to /products/foo/bar. (without "category") Is it possible? Am i missing something? Help will be highly appreciated. Thank you advance :) P.S. Sorry for my bad English.
*(your English is just fine, no need to apologize!)* You can define a route like this: ``` routes.MapRoute("productsByCategory", "products/{category}/{productid}", new { controller="products", action="findByCategory" }) ``` This will match `products/foo/bar` and call an action looking like this: ``` public class ProductsController : Controller { ... public ActionResult FindByCategory(string category, string productid) { .... } } ``` does this help?
139,979
<p>I have a C# interface with certain method parameters declared as <code>object</code> types. However, the actual type passed around can differ depending on the class implementing the interface:</p> <pre><code>public interface IMyInterface { void MyMethod(object arg); } public class MyClass1 : IMyInterface { public void MyMethod(object arg) { MyObject obj = (MyObject) arg; // do something with obj... } } public class MyClass2 : IMyInterface { public void MyMethod(object arg) { byte[] obj = (byte[]) arg; // do something with obj... } } </code></pre> <p>The problem with MyClass2 is that the conversion of <code>byte[]</code> to and from <code>object</code> is <a href="http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx" rel="noreferrer">boxing and unboxing</a>, which are computationally expensive operations affecting performance.</p> <p>Would solving this problem with a <a href="http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx" rel="noreferrer">generic interface</a> avoid boxing/unboxing?</p> <pre><code>public interface IMyInterface&lt;T&gt; { void MyMethod(T arg); } public class MyClass1 : IMyInterface&lt;MyObject&gt; { public void MyMethod(MyObject arg) { // typecast no longer necessary //MyObject obj = (MyObject) arg; // do something with arg... } } public class MyClass2 : IMyInterface&lt;byte[]&gt; { public void MyMethod(byte[] arg) { // typecast no longer necessary //byte[] obj = (byte[]) arg; // do something with arg... } } </code></pre> <p>How is this implemented in .NET vs Mono? Will there be any performance implications on either platform?</p> <p>Thank you!</p>
[ { "answer_id": 139994, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>The problem with MyClass2 is that the\n conversion of byte[] to and from\n object is boxing and unboxi...
2008/09/26
[ "https://Stackoverflow.com/questions/139979", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2576/" ]
I have a C# interface with certain method parameters declared as `object` types. However, the actual type passed around can differ depending on the class implementing the interface: ``` public interface IMyInterface { void MyMethod(object arg); } public class MyClass1 : IMyInterface { public void MyMethod(object arg) { MyObject obj = (MyObject) arg; // do something with obj... } } public class MyClass2 : IMyInterface { public void MyMethod(object arg) { byte[] obj = (byte[]) arg; // do something with obj... } } ``` The problem with MyClass2 is that the conversion of `byte[]` to and from `object` is [boxing and unboxing](http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx), which are computationally expensive operations affecting performance. Would solving this problem with a [generic interface](http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx) avoid boxing/unboxing? ``` public interface IMyInterface<T> { void MyMethod(T arg); } public class MyClass1 : IMyInterface<MyObject> { public void MyMethod(MyObject arg) { // typecast no longer necessary //MyObject obj = (MyObject) arg; // do something with arg... } } public class MyClass2 : IMyInterface<byte[]> { public void MyMethod(byte[] arg) { // typecast no longer necessary //byte[] obj = (byte[]) arg; // do something with arg... } } ``` How is this implemented in .NET vs Mono? Will there be any performance implications on either platform? Thank you!
I'm not sure how it is implemented in mono, but generic interfaces will help because the compiler creates a new function of the specific type for each different type used (internally, there are a few cases where it can utilize the same generated function). If a function of the specific type is generated, there is no need to box/unbox the type. This is why the Collections.Generic library was a big hit at .NET 2.0 because collections no longer required boxing and became significantly more efficient.
139,991
<p>I have two functions, <code>f</code> and <code>g</code>, which call each other recursively. Unfortunately, when <code>f</code> calls <code>g</code>, it has not yet been declared, so I get an "unbound variable" error. How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ?</p>
[ { "answer_id": 140386, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "<p>Mutual Recursion. Use <strong><code>and</code></strong> instead of <strong><code>fun</code></strong> between the two func...
2008/09/26
[ "https://Stackoverflow.com/questions/139991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10307/" ]
I have two functions, `f` and `g`, which call each other recursively. Unfortunately, when `f` calls `g`, it has not yet been declared, so I get an "unbound variable" error. How can I prototype (or whatever the equivalent vocabulary is) this function in SML/NJ?
Use `and`: ``` fun f x = ... and g x = ... ``` More info [here](http://www.dcs.napier.ac.uk/~cs66/course-notes/sml/lesson8.htm).
140,000
<p>I don't want to change how the Status field works I just want to change the labels to the states that the old system uses. (the old systems consists of spreadsheets and paper :P <br> We are using 3.0</p> <pre> * UNCONFIRMED --> PRELIMARY * NEW --> DESIGN REVIEW * ASSIGNED --> STR1 * RESOLVED --> STR2 * REOPEN * VERIIFED --> BMR * CLOSED --> TCG </pre>
[ { "answer_id": 140168, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 2, "selected": false, "text": "<p>If you log into the bugzilla system as an administrator you'll see on the bottom a link that says \"Field Values\", cl...
2008/09/26
[ "https://Stackoverflow.com/questions/140000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6539/" ]
I don't want to change how the Status field works I just want to change the labels to the states that the old system uses. (the old systems consists of spreadsheets and paper :P We are using 3.0 ``` * UNCONFIRMED --> PRELIMARY * NEW --> DESIGN REVIEW * ASSIGNED --> STR1 * RESOLVED --> STR2 * REOPEN * VERIIFED --> BMR * CLOSED --> TCG ```
I think this can be done by modifying the templates look here: <http://www.bugzilla.org/docs/2.22/html/cust-templates.html> specifically: **global/variables.none.tmpl**
140,002
<p>I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary.</p> <p>Here is the relevant part of my function:</p> <pre><code>Function GetSomeStuff() ' ' Get a recordset... ' Dim stuff Set stuff = CreateObject("Scripting.Dictionary") rs.MoveFirst Do Until rs.EOF stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value rs.MoveNext Loop GetSomeStuff = stuff End Function </code></pre> <p>How do I call this function and use the returned dictionary?</p> <p>EDIT: I've tried this:</p> <pre><code>Dim someStuff someStuff = GetSomeStuff </code></pre> <p>and</p> <pre><code>Dim someStuff Set someStuff = GetSomeStuff </code></pre> <p>When I try to access someStuff, I get an error:</p> <pre><code>Microsoft VBScript runtime error: Object required: 'GetSomeStuff' </code></pre> <p>EDIT 2: Trying this in the function:</p> <pre><code>Set GetSomeStuff = stuff </code></pre> <p>Results in this error:</p> <pre><code>Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment. </code></pre>
[ { "answer_id": 140064, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 0, "selected": false, "text": "<p>Have you tried:</p>\n\n<pre><code>Dim returnedStuff\nSet returnedStuff = GetSomeStuff()\n</code></pre>\n\n<p>Then \"For Each\...
2008/09/26
[ "https://Stackoverflow.com/questions/140002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2441/" ]
I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary. Here is the relevant part of my function: ``` Function GetSomeStuff() ' ' Get a recordset... ' Dim stuff Set stuff = CreateObject("Scripting.Dictionary") rs.MoveFirst Do Until rs.EOF stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value rs.MoveNext Loop GetSomeStuff = stuff End Function ``` How do I call this function and use the returned dictionary? EDIT: I've tried this: ``` Dim someStuff someStuff = GetSomeStuff ``` and ``` Dim someStuff Set someStuff = GetSomeStuff ``` When I try to access someStuff, I get an error: ``` Microsoft VBScript runtime error: Object required: 'GetSomeStuff' ``` EDIT 2: Trying this in the function: ``` Set GetSomeStuff = stuff ``` Results in this error: ``` Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment. ```
I wasn't too sure of what was your problem, so I experimented a bit. It appears that you just missed that to assign a reference to an object, you have to use `set`, even for a return value: ``` Function GetSomeStuff Dim stuff Set stuff = CreateObject("Scripting.Dictionary") stuff.Add "A", "Anaconda" stuff.Add "B", "Boa" stuff.Add "C", "Cobra" Set GetSomeStuff = stuff End Function Set d = GetSomeStuff Wscript.Echo d.Item("A") Wscript.Echo d.Exists("B") items = d.Items For i = 0 To UBound(items) Wscript.Echo items(i) Next ```
140,033
<p>Assume I have a class foo, and wish to use a std::map to store some boost::shared_ptrs, e.g.:</p> <pre><code>class foo; typedef boost::shared_ptr&lt;foo&gt; foo_sp; typeded std::map&lt;int, foo_sp&gt; foo_sp_map; foo_sp_map m; </code></pre> <p>If I add a new foo_sp to the map but the key used already exists, will the existing entry be deleted? For example:</p> <pre><code>foo_sp_map m; void func1() { foo_sp p(new foo); m[0] = p; } void func2() { foo_sp p2(new foo); m[0] = p2; } </code></pre> <p>Will the original pointer (p) be freed when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing.</p>
[ { "answer_id": 140048, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 4, "selected": true, "text": "<p>First off, your question title says boost::auto_ptr, but you actually mean boost::shared_ptr</p>\n\n<p>And yes, the ori...
2008/09/26
[ "https://Stackoverflow.com/questions/140033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Assume I have a class foo, and wish to use a std::map to store some boost::shared\_ptrs, e.g.: ``` class foo; typedef boost::shared_ptr<foo> foo_sp; typeded std::map<int, foo_sp> foo_sp_map; foo_sp_map m; ``` If I add a new foo\_sp to the map but the key used already exists, will the existing entry be deleted? For example: ``` foo_sp_map m; void func1() { foo_sp p(new foo); m[0] = p; } void func2() { foo_sp p2(new foo); m[0] = p2; } ``` Will the original pointer (p) be freed when it is replaced by p2? I'm pretty sure it will be, but I thought it was worth asking/sharing.
First off, your question title says boost::auto\_ptr, but you actually mean boost::shared\_ptr And yes, the original pointer will be freed (if there are no further shared references to it).
140,043
<p>How do I loop into all the resources in the resourcemanager?</p> <p>Ie: foreach (string resource in ResourceManager) //Do something with the recource.</p> <p>Thanks</p>
[ { "answer_id": 140060, "author": "VVS", "author_id": 21038, "author_profile": "https://Stackoverflow.com/users/21038", "pm_score": 6, "selected": true, "text": "<p>Use ResourceManager.<a href=\"http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.getresourceset.aspx\"...
2008/09/26
[ "https://Stackoverflow.com/questions/140043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ]
How do I loop into all the resources in the resourcemanager? Ie: foreach (string resource in ResourceManager) //Do something with the recource. Thanks
Use ResourceManager.[GetResourceSet](http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.getresourceset.aspx)() for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach). --- To answer Nico's question: you can count the elements of an `IEnumerable` by casting it to the generic `IEnumerable<object>` and use the [`Enumerable.Count<T>()`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.count.aspx) extension method, which is new in C# 3.5: ``` using System.Linq; ... var resourceSet = resourceManager.GetResourceSet(..); var count = resSet.Cast<object>().Count(); ```
140,044
<p>I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page.</p> <p>Any sample code would be greatly appreciated!</p> <p>Link to API: <a href="http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf" rel="nofollow noreferrer">http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf</a></p>
[ { "answer_id": 148494, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 1, "selected": false, "text": "<p>I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simples...
2008/09/26
[ "https://Stackoverflow.com/questions/140044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483/" ]
I need to create a user control in either vb.net or c# to search a RightNow CRM database. I have the documentation on their XML API, but I'm not sure how to post to their parser and then catch the return data and display it on the page. Any sample code would be greatly appreciated! Link to API: <http://community.rightnow.com/customer/documentation/integration/82_crm_integration.pdf>
I don't know RightNow CRM, but according to the documentation you can send the XML requests using HTTP post. The simplest way to do this in .NET is using the WebClient class. Alternatively you might want to take a look at the HttpWebRequest/HttpWebResponse classes. Here is some sample code using WebClient: ``` using System.Net; using System.Text; using System; namespace RightNowSample { class Program { static void Main(string[] args) { string serviceUrl = "http://<your_domain>/cgi-bin/<your_interface>.cfg/php/xml_api/parse.php"; WebClient webClient = new WebClient(); string requestXml = @"<connector> <function name=""ans_get""> <parameter name=""args"" type=""pair""> <pair name=""id"" type=""integer"">33</pair> <pair name=""sub_tbl"" type='pair'> <pair name=""tbl_id"" type=""integer"">164</pair> </pair> </parameter> </function> </connector>"; string secString = ""; string postData = string.Format("xml_doc={0}, sec_string={1}", requestXml, secString); byte[] postDataBytes = Encoding.UTF8.GetBytes(postData); byte[] responseDataBytes = webClient.UploadData(serviceUrl, "POST", postDataBytes); string responseData = Encoding.UTF8.GetString(responseDataBytes); Console.WriteLine(responseData); } } } ``` I have no access to RightNow CRM, so I could not test this, but it can serve as s tarting point for you.
140,054
<p>I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently.</p> <p>Is there are way to do something like this:</p> <pre><code>installutil.exe myservice.exe /customarg1=username /customarg2=password </code></pre>
[ { "answer_id": 140086, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 0, "selected": false, "text": "<p>No, installutil doesn't support that.</p>\n\n<p>Of course if you wrote an installer; with a <a href=\"http://arcanecode....
2008/09/26
[ "https://Stackoverflow.com/questions/140054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3106/" ]
I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently. Is there are way to do something like this: ``` installutil.exe myservice.exe /customarg1=username /customarg2=password ```
Bravo to my co-worker (Bruce Eddy). He found a way we can make this command-line call: ``` installutil.exe /user=uname /password=pw myservice.exe ``` It is done by overriding OnBeforeInstall in the installer class: ``` namespace Test { [RunInstaller(true)] public class TestInstaller : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller serviceProcessInstaller; public OregonDatabaseWinServiceInstaller() { serviceInstaller = new ServiceInstaller(); serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; serviceInstaller.ServiceName = "Test"; serviceInstaller.DisplayName = "Test Service"; serviceInstaller.Description = "Test"; serviceInstaller.StartType = ServiceStartMode.Automatic; Installers.Add(serviceInstaller); serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = ServiceAccount.User; Installers.Add(serviceProcessInstaller); } public string GetContextParameter(string key) { string sValue = ""; try { sValue = this.Context.Parameters[key].ToString(); } catch { sValue = ""; } return sValue; } // Override the 'OnBeforeInstall' method. protected override void OnBeforeInstall(IDictionary savedState) { base.OnBeforeInstall(savedState); string username = GetContextParameter("user").Trim(); string password = GetContextParameter("password").Trim(); if (username != "") serviceProcessInstaller.Username = username; if (password != "") serviceProcessInstaller.Password = password; } } } ```
140,104
<p>If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?</p>
[ { "answer_id": 140154, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 8, "selected": true, "text": "<p>There is a <a href=\"http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.aspx\" re...
2008/09/26
[ "https://Stackoverflow.com/questions/140104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ]
If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?
There is a [`WebOperationContext`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.aspx) that you can access and it has a [`OutgoingResponse`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.weboperationcontext.outgoingresponse.aspx) property of type [`OutgoingWebResponseContext`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.outgoingwebresponsecontext.aspx) which has a [`StatusCode`](http://msdn.microsoft.com/en-us/library/system.servicemodel.web.outgoingwebresponsecontext.statuscode.aspx) property that can be set. ``` WebOperationContext ctx = WebOperationContext.Current; ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; ```
140,131
<p>I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array.</p> <p>I couldn't have phrased it better than the person that posted <a href="http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html" rel="noreferrer">the same question here</a>.</p> <p>But to keep it original, I'll phrase it my own way: suppose I have a string <code>"00A0BF"</code> that I would like interpreted as the</p> <pre><code>byte[] {0x00,0xA0,0xBf} </code></pre> <p>what should I do?</p> <p>I am a Java novice and ended up using <code>BigInteger</code> and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple. </p>
[ { "answer_id": 140147, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 7, "selected": false, "text": "<p>The Hex class in commons-codec should do that for you.</p>\n\n<p><a href=\"http://commons.apache.org/codec/\" rel=\"no...
2008/09/26
[ "https://Stackoverflow.com/questions/140131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11798/" ]
I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array. I couldn't have phrased it better than the person that posted [the same question here](http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21062554.html). But to keep it original, I'll phrase it my own way: suppose I have a string `"00A0BF"` that I would like interpreted as the ``` byte[] {0x00,0xA0,0xBf} ``` what should I do? I am a Java novice and ended up using `BigInteger` and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.
Update (2021) - **Java 17** now includes [`java.util.HexFormat`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HexFormat.html) (only took 25 years): `HexFormat.of().parseHex(s)` --- For older versions of Java: Here's a solution that I think is better than any posted so far: ``` /* s must be an even-length string. */ public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } ``` Reasons why it is an improvement: * Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte) * Doesn't convert the String into a `char[]`, or create StringBuilder and String objects for every single byte. * No library dependencies that may not be available Feel free to add argument checking via `assert` or exceptions if the argument is not known to be safe.
140,133
<p>I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed.</p> <pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); </code></pre> <p>Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers.</p> <p><strong>UPDATE:</strong><br> I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally. </p> <pre><code>var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); $(popupWindow.window).unload(function() { alert('hello'); }); </code></pre> <p>Does anybody have any idea as to why the unload event could be raised when the window is loading?</p> <p>One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do:</p> <pre><code>popupWindow.onunload = function(){alert('hello')}; </code></pre> <p>It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the <code>popupWindow.closed</code> property inside of the event to ensure the window was really closed.</p>
[ { "answer_id": 140183, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 0, "selected": false, "text": "<p>Use <a href=\"http://developer.mozilla.org/en/DOM/window.onunload\" rel=\"nofollow noreferrer\">window.onUnload</a></p>\n" ...
2008/09/26
[ "https://Stackoverflow.com/questions/140133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I want to raise an event when a popup window is closed, or preferably, just before closing. I'm storing the popup window object as an object, but I don't know of any way to bind to the close event, or an event just before the window is closed. ``` var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); ``` Is there any way to subscribe to the close event using jQuery, or just raw javascript? I'm using jQuery and can't add another library, so if it can't be done in jQuery I'll have to roll my own event system somehow so that it will work across all browsers. **UPDATE:** I've tried using the unload event in jQuery and for some reason the event is raised as soon as my popup opens instead of when it is closed. If I use Firebug to set a breakpoint to delay the unload event from being subscribed to, the unload event works the way it is supposed to, but for whatever reason, it doesn't work correctly when the javascript is allowed to execute naturally. ``` var popupWindow = window.open("/popup.aspx", "popupWindow", "height=550,width=780"); $(popupWindow.window).unload(function() { alert('hello'); }); ``` Does anybody have any idea as to why the unload event could be raised when the window is loading? One other catch is that I've noticed that jQuery's "unload" event does not stay subscribed to the window like it normally does if I just do: ``` popupWindow.onunload = function(){alert('hello')}; ``` It seems to unsubscribe from the event every time it is raised. Is this supposed to happen? If it weren't for this bug (or feature?) in jQuery, it would by fine to have the event get raised on load since I can check the `popupWindow.closed` property inside of the event to ensure the window was really closed.
I created a watcher that checks if the window has been closed: ``` var w = window.open("http://www.google.com", "_blank", 'top=442,width=480,height=460,resizable=yes', true); var watchClose = setInterval(function() { if (w.closed) { clearTimeout(watchClose); //Do something here... } }, 200); ```
140,137
<p>I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that. </p> <p>Does anyone know how to create a custom 404 error page in Umbraco? Is there a way to create a custom error page for runtime errors?</p>
[ { "answer_id": 140169, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 4, "selected": false, "text": "<p>In <code>/config/umbracoSettings.config</code> modify <code>&lt;error404&gt;1&lt;/error404&gt;</code> \"<em>1</em>\" with...
2008/09/26
[ "https://Stackoverflow.com/questions/140137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20483/" ]
I'm working on a client site who is using Umbraco as a CMS. I need to create a custom 404 error page. I've tried doing it in the IIS config but umbraco overrides that. Does anyone know how to create a custom 404 error page in Umbraco? Is there a way to create a custom error page for runtime errors?
In `/config/umbracoSettings.config` modify `<error404>1</error404>` "*1*" with the id of the page you want to show. ``` <errors> <error404>1</error404> </errors> ``` Other ways to do it can be found at [Not found handlers](http://our.umbraco.org/wiki/how-tos/how-to-implement-your-own-404-handler "Umbraco not found handlers")
140,149
<p>I have a custom performance counter category. Visual Studio Server Explorer refuses to delete it, claiming it is 'not registered or a system category'. Short of doing it programmatically, how can I delete the category? Is there a registry key I can delete?</p>
[ { "answer_id": 140185, "author": "Jaykul", "author_id": 8718, "author_profile": "https://Stackoverflow.com/users/8718", "pm_score": 6, "selected": true, "text": "<p>As far as I know, there <strong>is no way</strong> to safely delete them except programatically (they're intended for apps ...
2008/09/26
[ "https://Stackoverflow.com/questions/140149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ]
I have a custom performance counter category. Visual Studio Server Explorer refuses to delete it, claiming it is 'not registered or a system category'. Short of doing it programmatically, how can I delete the category? Is there a registry key I can delete?
As far as I know, there **is no way** to safely delete them except programatically (they're intended for apps to create and remove during install) but it is trivial to do from a [PowerShell](http://Microsoft.com/PowerShell) command-line console. Just run this command: ``` [Diagnostics.PerformanceCounterCategory]::Delete( "Your Category Name" ) ``` **HOWEVER: (EDIT)** You *can* delete the registry key that's created, and that will make the category vanish. For a category called "Inventory" you can delete the whole key at `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Inventory` ... and although *I wouldn't be willing to bet that cleans up everything*, it **will** make the category disappear. (If you run [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) while running the Delete() method, you can see can a lot of other activity happening, and there doesn't seem to be any other *changes* made). It's important to note that **as I said originally**: when you get that error from Visual Studio, it might be that it's already deleted and you need to refresh the view in VS. In my testing, I had to restart applications in order to get them to actually get a clean list of the available categories. You can check the full list of categories from PowerShell to see if it's listed: ``` [Diagnostics.PerformanceCounterCategory]::GetCategories() | Format-Table -auto ``` But if you check them, then delete the registry key ... they'll still show up, until you restart PowerShell (if you start another instance, you can run the same query over there, and it will NOT show the deleted item, but re-running GetCategories in the first one will continue showing it. By the way, you can filter that list if you want to using -like for patterns, or -match for full regular expressions: ``` [Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -like "*network*" } | Format-Table -auto [Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -match "^SQL.*Stat.*" } | Format-Table -auto ```
140,162
<p>In a servlet I do the following:</p> <pre><code> Context context = new InitialContext(); value = (String) context.lookup("java:comp/env/propertyName"); </code></pre> <p>On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key <em>propertyName</em>?</p> <p>In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web.</p>
[ { "answer_id": 143749, "author": "Mike Spross", "author_id": 17862, "author_profile": "https://Stackoverflow.com/users/17862", "pm_score": 1, "selected": false, "text": "<p>One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more <code>&...
2008/09/26
[ "https://Stackoverflow.com/questions/140162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2985/" ]
In a servlet I do the following: ``` Context context = new InitialContext(); value = (String) context.lookup("java:comp/env/propertyName"); ``` On an Apache Geronimo instance (WAS CE 2.1) how do i associate a value with the key *propertyName*? In Websphere AS 6 i can configure these properties for JNDI lookup under the "Name Space Bindings" page in the management console, but for the life of me I can find no way to do this in community edition on the web.
One possibility is to add the properties to your web.xml file (in the WEB-INF directory), using one or more `<env-entry>` tags. For example, something like the following: ``` <env-entry> <description>My string property</descriptor> <env-entry-name>propertyName</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>Your string goes here</env-entry-value> </env-entry> ``` Each env-entry tag declares a new environment variable that you can then access from the `java:comp/env` context. Once you add the necessary `env-entry`'s you can use code similar to what you already posted to access these values. Mind you, I don't have Geronimo installed, so I don't know if there is any additional configuration that needs to be done in order to make this work.
140,182
<p>When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... </p> <p>Right now I'm doing this...</p> <pre><code>def getExpandedText(pattern, text, replaceValue): """ One liner... really ugly but it's only used in here. """ return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \ text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):] </code></pre> <p>so if I do sth like</p> <pre><code>&gt;&gt;&gt; getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo") 'hola aaaooobbb como estas?' </code></pre> <p>It changes the (...) with 'ooo'.</p> <p>Do you guys know whether with python regular expressions we can do this?</p> <p>thanks a lot guys!!</p>
[ { "answer_id": 140208, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 1, "selected": false, "text": "<p>Of course. See the 'sub' and 'subn' methods of compiled regular expressions, or the 're.sub' and 're.subn' funct...
2008/09/26
[ "https://Stackoverflow.com/questions/140182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/293/" ]
When using regular expressions we generally, if not always use them to extract some kind of information. What I need is to replace the match value with some other value... Right now I'm doing this... ``` def getExpandedText(pattern, text, replaceValue): """ One liner... really ugly but it's only used in here. """ return text.replace(text[text.find(re.findall(pattern, text)[0]):], replaceValue) + \ text[text.find(re.findall(pattern, text)[0]) + len(replaceValue):] ``` so if I do sth like ``` >>> getExpandedText("aaa(...)bbb", "hola aaaiiibbb como estas?", "ooo") 'hola aaaooobbb como estas?' ``` It changes the (...) with 'ooo'. Do you guys know whether with python regular expressions we can do this? thanks a lot guys!!
``` sub (replacement, string[, count = 0]) ``` [sub](https://docs.python.org/howto/regex.html#search-and-replace) returns the string obtained by replacing the leftmost non-overlapping occurrences of the RE in string by the replacement replacement. If the pattern isn't found, string is returned unchanged. ``` p = re.compile( '(blue|white|red)') >>> p.sub( 'colour', 'blue socks and red shoes') 'colour socks and colour shoes' >>> p.sub( 'colour', 'blue socks and red shoes', count=1) 'colour socks and red shoes' ```
140,204
<p>Given a typical class:</p> <pre> struct Whatever { void Doit(); }; Whatever w; </pre> <p>what is the best way to get the member function to be called by a C void* based callback such as pthread_create() or a signal handler ?</p> <pre> pthread_t pid; pthread_create(&pid, 0, ... &w.Doit() ... ); </pre>
[ { "answer_id": 140230, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>The member function MUST be static. Non-static have an implied \"this\" argument. Pass the pointer to your Whatev...
2008/09/26
[ "https://Stackoverflow.com/questions/140204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22725/" ]
Given a typical class: ``` struct Whatever { void Doit(); }; Whatever w; ``` what is the best way to get the member function to be called by a C void\* based callback such as pthread\_create() or a signal handler ? ``` pthread_t pid; pthread_create(&pid, 0, ... &w.Doit() ... ); ```
Most C callbacks allow to specify an argument e.g. ``` int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); ``` So you could have ``` void myclass_doit(void* x) { MyClass* c = reinterpret_cast<MyClass*>(x); c->doit(); } pthread_create(..., &myclass_doit, (void*)(&obj)); ```
140,205
<p>I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like</p> <pre><code>StudentID StartDate EndDate Field1 Field2 1 9/3/2007 10/20/2007 3 True 1 10/21/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True </code></pre> <p>The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like</p> <pre><code>StudentID StartDate EndDate Field1 Field2 1 9/3/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True </code></pre> <p>What would be the SELECT statement for this query?</p>
[ { "answer_id": 140222, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 0, "selected": false, "text": "<p>In my experience, I have to combine the ranges in post-processing (not in SQL but in my script). I'm not sure th...
2008/09/26
[ "https://Stackoverflow.com/questions/140205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18891/" ]
I'm working on a query that needs to have some data rows combined based on date ranges. These rows are duplicated in all the data values, except the date ranges are split. For example the table data may look like ``` StudentID StartDate EndDate Field1 Field2 1 9/3/2007 10/20/2007 3 True 1 10/21/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True ``` The result of the query should have the split date ranges combined. The query should combine date ranges with a gap of only one day. If there is more than a one day gap, then the rows shouldn't be combined. The rows that don't have a split date range should come through unchanged. The result would look like ``` StudentID StartDate EndDate Field1 Field2 1 9/3/2007 6/12/2008 3 True 2 10/10/2007 3/20/2008 4 False 3 9/3/2007 11/3/2007 8 True 3 12/15/2007 6/12/2008 8 True ``` What would be the SELECT statement for this query?
The following code should work. I've made a few assumptions as follows: there are no overlaps of date ranges, there are no NULL values in any of the fields, and the start date for a given row is always less than the end date. If your data doesn't fit these criteria, you'll need to adjust this method, but it should point you in the right direction. You can use subqueries instead of the views, but that can be cumbersome so I used the views to make the code clearer. ``` CREATE VIEW dbo.StudentStartDates AS SELECT S.StudentID, S.StartDate, S.Field1, S.Field2 FROM dbo.Students S LEFT OUTER JOIN dbo.Students PREV ON PREV.StudentID = S.StudentID AND PREV.Field1 = S.Field1 AND PREV.Field2 = S.Field2 AND PREV.EndDate = DATEADD(dy, -1, S.StartDate) WHERE PREV.StudentID IS NULL GO CREATE VIEW dbo.StudentEndDates AS SELECT S.StudentID, S.EndDate, S.Field1, S.Field2 FROM dbo.Students S LEFT OUTER JOIN dbo.Students NEXT ON NEXT.StudentID = S.StudentID AND NEXT.Field1 = S.Field1 AND NEXT.Field2 = S.Field2 AND NEXT.StartDate = DATEADD(dy, 1, S.EndDate) WHERE NEXT.StudentID IS NULL GO SELECT SD.StudentID, SD.StartDate, ED.EndDate, SD.Field1, SD.Field2 FROM dbo.StudentStartDates SD INNER JOIN dbo.StudentEndDates ED ON ED.StudentID = SD.StudentID AND ED.Field1 = SD.Field1 AND ED.Field2 = SD.Field2 AND ED.EndDate > SD.StartDate AND NOT EXISTS (SELECT * FROM dbo.StudentEndDates ED2 WHERE ED2.StudentID = SD.StudentID AND ED2.Field1 = SD.Field1 AND ED2.Field2 = SD.Field2 AND ED2.EndDate < ED.EndDate AND ED2.EndDate > SD.StartDate) GO ```
140,217
<p>As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier?</p>
[ { "answer_id": 140316, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 2, "selected": false, "text": "<p>In general you find something that isn't how it should be, and work backwards until you understand why.</p>\n\n<p>...
2008/09/26
[ "https://Stackoverflow.com/questions/140217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16044/" ]
As a developer, how do you use gdb to track down bugs within your code? What techniques tricks do you use to make your life easier?
In general you find something that isn't how it should be, and work backwards until you understand why. The most obvious is the most useful: Setting a breakpoint on a function or line number and walking through the code line by line. Another handy tip is to have show functions for all your structures/objects even if they are never used in your program, because you can run these functions from within gdb: ``` gdb> p show_my_struct(struct) My custom display of Foo: ... ``` Watchpoints can be really handy too, but may slow down your program a lot. These break the flow when the value of a variable or address changes.: ``` gdb> watch foo Watchpoint4: foo gdb> ```
140,303
<p>What is the cause of this exception in ASP.NET? Obviously it is a viewstate exception, but I can't reproduce the error on the page that is throwing the exception (a simple two TextBox form with a button and navigation links).</p> <p>FWIW, I'm not running a web farm.</p> <h2>Exception</h2> <blockquote> <p>Error Message: Unable to validate data.</p> <p>Error Source: System.Web</p> <p>Error Target Site: Byte[] GetDecodedData(Byte[], Byte[], Int32, Int32, Int32 ByRef)</p> </blockquote> <h2>Post Data</h2> <blockquote> <p><em>VIEWSTATE:</em></p> <p>/wEPDwULLTE4NTUyODcyMTFkZF96FHxDUAHIY3NOAMRJYZ+CKsnB</p> <p><em>EVENTVALIDATION:</em></p> <p>/wEWBAK+8ZzHAgKOhZRcApDF79ECAoLch4YMeQ2ayv/Gi76znHooiRyBFrWtwyg=</p> </blockquote> <h2>Exception Stack Trace</h2> <pre><code> at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.default_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) </code></pre> <p>~ William Riley-Land</p>
[ { "answer_id": 140517, "author": "Chris Van Opstal", "author_id": 7264, "author_profile": "https://Stackoverflow.com/users/7264", "pm_score": 5, "selected": true, "text": "<p>The most likely cause of this error is when a postback is stopped before all the viewstate loads (the user hits t...
2008/09/26
[ "https://Stackoverflow.com/questions/140303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17847/" ]
What is the cause of this exception in ASP.NET? Obviously it is a viewstate exception, but I can't reproduce the error on the page that is throwing the exception (a simple two TextBox form with a button and navigation links). FWIW, I'm not running a web farm. Exception --------- > > Error Message: Unable to validate > data. > > > Error Source: System.Web > > > Error Target Site: Byte[] > GetDecodedData(Byte[], Byte[], Int32, > Int32, Int32 ByRef) > > > Post Data --------- > > *VIEWSTATE:* > > > /wEPDwULLTE4NTUyODcyMTFkZF96FHxDUAHIY3NOAMRJYZ+CKsnB > > > *EVENTVALIDATION:* > > > /wEWBAK+8ZzHAgKOhZRcApDF79ECAoLch4YMeQ2ayv/Gi76znHooiRyBFrWtwyg= > > > Exception Stack Trace --------------------- ``` at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.default_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) ``` ~ William Riley-Land
The most likely cause of this error is when a postback is stopped before all the viewstate loads (the user hits the stop or back buttons), the viewstate will fail to validate and throw the error. Other potential causes: * An application pool recycling between the time the viewstate was generated and the time that the user posts it back to the server (unlikely). * A web farm where the machineKeys are not synchronized (not your issue). Update: [Microsoft article on the issue](http://support.microsoft.com/default.aspx?scid=kb;en-us;555353). In addition to the above they suggest two other potential causes: * Modification of viewstate by firewalls/anti-virus software * Posting from one aspx page to another.
140,329
<p>I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I think might help.</p> <p>Thanks!</p>
[ { "answer_id": 140398, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 3, "selected": false, "text": "<p>I usually add an HtmlMeta control to the Page.Header.Controls collection on the master page when the user has \"...
2008/09/26
[ "https://Stackoverflow.com/questions/140329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14710/" ]
I am currently working on an web application that uses ASP.NET 2.0 framework. I need to redirect to a certain page, say SessionExpired.aspx, when the user session expires. There are lot of pages in the project, so adding code to every page of the site is not really a good solution. I have MasterPages though, which I think might help. Thanks!
You can handle this in global.asax in the Session\_Start event. You can check for a session cookie in the request there. If the session cookie exists, the session has expired: ``` public void Session_OnStart() { if (HttpContext.Current.Request.Cookies.Contains("ASP.NET_SessionId") != null) { HttpContext.Current.Response.Redirect("SessionTimeout.aspx") } } ``` Alas I have not found any elegant way of finding out the name of the session cookie.
140,331
<p>I have a following SQL Server 2005 database schema:</p> <pre><code>CREATE TABLE Messages ( MessageID int, Subject varchar(500), Text varchar(max) NULL, UserID NULL ) </code></pre> <p>The column "UserID" - which can be null - is a foreign key and links to the table</p> <pre><code>CREATE TABLE Users ( UserID int, ... ) </code></pre> <p>Now I have several POCO classes with names Message, User etc. that I use in the following query:</p> <pre><code>public IList&lt;Message&gt; GetMessages(...) { var q = (from m in dataContext.Messages.Include("User") where ... select m); // could call ToList(), but... return (from m in q select new Message { ID = m.MessageID, User = new User { ID = m.User.UserID, FirstName = m.User.FirstName, ... } }).ToList(); } </code></pre> <p>Now note that I advise the entity framework - using Include("Users") - to load a user associated with a message, if any. Also note that I don't call ToList() after the first LINQ statement. By doing so only specified columns in the projection list - in this case MessageID, UserID, FirstName - will be returned from the database. </p> <p>Here lies the problem - as soon as Entity Framework encounters a message with UserID == NULL, it throws an exception, saying that it could not convert to Int32 because the DB value is NULL.</p> <p>If I change the last couple of lines to</p> <pre><code>return (from m in q select new Message { ID = m.MessageID, User = m.User == null ? null : new User { ID = m.User.UserID, ... } }).ToList() </code></pre> <p>then a run-time NotSupportedException is thrown telling that it can't create a constant User type and only primitives like int, string, guid are supported.</p> <p>Anybody has any idea how to handle it besides materializing the results just right after the first statement and using in-memory projection afterwards? Thanks.</p>
[ { "answer_id": 140385, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": -1, "selected": false, "text": "<p>I suspect your relationship is not 1 to 1.</p>\n" }, { "answer_id": 140424, "author": "Orion Adrian", "...
2008/09/26
[ "https://Stackoverflow.com/questions/140331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a following SQL Server 2005 database schema: ``` CREATE TABLE Messages ( MessageID int, Subject varchar(500), Text varchar(max) NULL, UserID NULL ) ``` The column "UserID" - which can be null - is a foreign key and links to the table ``` CREATE TABLE Users ( UserID int, ... ) ``` Now I have several POCO classes with names Message, User etc. that I use in the following query: ``` public IList<Message> GetMessages(...) { var q = (from m in dataContext.Messages.Include("User") where ... select m); // could call ToList(), but... return (from m in q select new Message { ID = m.MessageID, User = new User { ID = m.User.UserID, FirstName = m.User.FirstName, ... } }).ToList(); } ``` Now note that I advise the entity framework - using Include("Users") - to load a user associated with a message, if any. Also note that I don't call ToList() after the first LINQ statement. By doing so only specified columns in the projection list - in this case MessageID, UserID, FirstName - will be returned from the database. Here lies the problem - as soon as Entity Framework encounters a message with UserID == NULL, it throws an exception, saying that it could not convert to Int32 because the DB value is NULL. If I change the last couple of lines to ``` return (from m in q select new Message { ID = m.MessageID, User = m.User == null ? null : new User { ID = m.User.UserID, ... } }).ToList() ``` then a run-time NotSupportedException is thrown telling that it can't create a constant User type and only primitives like int, string, guid are supported. Anybody has any idea how to handle it besides materializing the results just right after the first statement and using in-memory projection afterwards? Thanks.
You forgot to include the declaration of your "Message" class but I suspect that the UserID property in that class is not declared as a nullable type. If that is the case, change it from "int" to "int?" (nullable int).
140,347
<p>I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it!</p> <p>Does anyone know what it is?</p> <p>It will do something similar to:</p> <pre><code>const CRect client(0, 0, 200, 200); const CRect window = ClientRectToWindowRect(client); SetWindowPos(...) </code></pre>
[ { "answer_id": 140373, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 4, "selected": true, "text": "<p>You're probably thinking of <a href=\"http://msdn.microsoft.com/en-us/library/ms632667(VS.85).aspx\" rel=\"noreferrer\"><code>...
2008/09/26
[ "https://Stackoverflow.com/questions/140347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
I know there is a function somewhere that will accept a client rect and it will convert it into a window rect for you. I just can't find / remember it! Does anyone know what it is? It will do something similar to: ``` const CRect client(0, 0, 200, 200); const CRect window = ClientRectToWindowRect(client); SetWindowPos(...) ```
You're probably thinking of [`AdjustWindowRectEx()`](http://msdn.microsoft.com/en-us/library/ms632667(VS.85).aspx). Keep in mind, this is intended for use when *creating* a window - there's no guarantee that it will produce an accurate set of window dimensions for an existing window; for that, use [`GetWindowRect()`](http://msdn.microsoft.com/en-us/library/ms633519(VS.85).aspx).
140,439
<p>How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears.</p> <p>I can't even bind to perform a simple query:</p> <pre><code>import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.SCOPE_SUBTREE Filter = "(&amp;(objectClass=user)(sAMAccountName="+un+"))" Attrs = ["displayName"] l = ldap.initialize(Server) l.protocol_version = 3 print l.simple_bind_s(DN, Secret) r = l.search(Base, Scope, Filter, Attrs) Type,user = l.result(r,60) Name,Attrs = user[0] if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'): displayName = Attrs['displayName'][0] print displayName sys.exit() </code></pre> <p>Running this with <code>myusername@mydomain.co.uk password username</code> gives me one of two errors:</p> <p><code>Invalid Credentials</code> - When I mistype or intentionally use wrong credentials it fails to authenticate.</p> <blockquote> <p>ldap.INVALID_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'}</p> </blockquote> <p>Or </p> <blockquote> <p>ldap.OPERATIONS_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'}</p> </blockquote> <p>What am I missing out to bind properly?</p> <p>I am getting the same errors on fedora and windows.</p>
[ { "answer_id": 140495, "author": "1729", "author_id": 4319, "author_profile": "https://Stackoverflow.com/users/4319", "pm_score": 7, "selected": true, "text": "<p>I was missing </p>\n\n<pre><code>l.set_option(ldap.OPT_REFERRALS, 0)\n</code></pre>\n\n<p>From the init.</p>\n" }, { ...
2008/09/26
[ "https://Stackoverflow.com/questions/140439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4319/" ]
How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears. I can't even bind to perform a simple query: ``` import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.SCOPE_SUBTREE Filter = "(&(objectClass=user)(sAMAccountName="+un+"))" Attrs = ["displayName"] l = ldap.initialize(Server) l.protocol_version = 3 print l.simple_bind_s(DN, Secret) r = l.search(Base, Scope, Filter, Attrs) Type,user = l.result(r,60) Name,Attrs = user[0] if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'): displayName = Attrs['displayName'][0] print displayName sys.exit() ``` Running this with `myusername@mydomain.co.uk password username` gives me one of two errors: `Invalid Credentials` - When I mistype or intentionally use wrong credentials it fails to authenticate. > > ldap.INVALID\_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'} > > > Or > > ldap.OPERATIONS\_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'} > > > What am I missing out to bind properly? I am getting the same errors on fedora and windows.
I was missing ``` l.set_option(ldap.OPT_REFERRALS, 0) ``` From the init.
140,460
<p>We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data).</p> <p>I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out?</p>
[ { "answer_id": 140508, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 4, "selected": false, "text": "<p>One piece of the puzzle:</p>\n\n<pre><code>/**\n * Determines if a form is dirty by comparing the current value of...
2008/09/26
[ "https://Stackoverflow.com/questions/140460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22732/" ]
We have a typical web application that is essentially a data entry application with lots of screens some of which have some degree of complexity. We need to provide that standard capability on making sure if the user forgets to click the "Save" button before navigating away or closing their browser they get a warning and can cancel (but only when there is unsaved or dirty data). I know the basics of what I've got to do-- in fact I'm sure I've done it all before over the years (tie in to onbeforeunload, track the "dirty" state of the page, etc...) but before I embark on coding this YET AGAIN, does anyone have some suggestions for libraries already out there (free or otherwise) that will help out?
One piece of the puzzle: ``` /** * Determines if a form is dirty by comparing the current value of each element * with its default value. * * @param {Form} form the form to be checked. * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code> * otherwise. */ function formIsDirty(form) { for (var i = 0; i < form.elements.length; i++) { var element = form.elements[i]; var type = element.type; if (type == "checkbox" || type == "radio") { if (element.checked != element.defaultChecked) { return true; } } else if (type == "hidden" || type == "password" || type == "text" || type == "textarea") { if (element.value != element.defaultValue) { return true; } } else if (type == "select-one" || type == "select-multiple") { for (var j = 0; j < element.options.length; j++) { if (element.options[j].selected != element.options[j].defaultSelected) { return true; } } } } return false; } ``` [And another](http://developer.mozilla.org/en/DOM/window.onbeforeunload): ``` window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms["someFormOfInterest"])) { // For IE and Firefox if (e) { e.returnValue = "You have unsaved changes."; } // For Safari return "You have unsaved changes."; } }; ``` Wrap it all up, and what do you get? ``` var confirmExitIfModified = (function() { function formIsDirty(form) { // ...as above } return function(form, message) { window.onbeforeunload = function(e) { e = e || window.event; if (formIsDirty(document.forms[form])) { // For IE and Firefox if (e) { e.returnValue = message; } // For Safari return message; } }; }; })(); confirmExitIfModified("someForm", "You have unsaved changes."); ``` You'll probably also want to change the registration of the `beforeunload` event handler to use `LIBRARY_OF_CHOICE`'s event registration.
140,490
<p>Which gets called first - the base constructor or "other stuff here"?</p> <pre><code>public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } } </code></pre>
[ { "answer_id": 140497, "author": "Mastermind", "author_id": 22213, "author_profile": "https://Stackoverflow.com/users/22213", "pm_score": 3, "selected": false, "text": "<p>I'd say base</p>\n\n<p>EDIT see:</p>\n\n<p><a href=\"http://www.c-sharpcorner.com/UploadFile/rajeshvs/ConsNDestructo...
2008/09/26
[ "https://Stackoverflow.com/questions/140490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16872/" ]
Which gets called first - the base constructor or "other stuff here"? ``` public class MyExceptionClass : Exception { public MyExceptionClass(string message, string extrainfo) : base(message) { //other stuff here } } ```
The base constructor will be called first. try it: ``` public class MyBase { public MyBase() { Console.WriteLine("MyBase"); } } public class MyDerived : MyBase { public MyDerived():base() { Console.WriteLine("MyDerived"); } } ```
140,602
<p>I am trying to call a WCF webservice (which I developed) from a Silverlight application. For some reason the Silverlight app does not make the http soap call to the service. I know this because I am sniffing all http traffic with Fiddler (and it is not a localhost call).</p> <p>This my configuration in the server relevant to WCF:</p> <pre><code>&lt;system.serviceModel&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="ServiceBehavior"&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;serviceDebug includeExceptionDetailInFaults="false"/&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true"/&gt; &lt;services&gt; &lt;service behaviorConfiguration="ServiceBehavior" name="Service"&gt; &lt;endpoint address="" binding="basicHttpBinding" contract="Service"/&gt; &lt;endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/&gt; &lt;/service&gt; &lt;/services&gt; &lt;/system.serviceModel&gt; </code></pre> <p>And the ServiceReferences.ClientConfig file in the silverlight app (i am using the beta 2):</p> <pre><code>&lt;system.serviceModel&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="BasicHttpBinding_Service" maxBufferSize="65536" maxReceivedMessageSize="65536"&gt; &lt;security mode="None" /&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;client&gt; &lt;endpoint address="http://itlabws2003/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Service" contract="Silverlight_organigram.DataService.Service" name="BasicHttpBinding_Service" /&gt; &lt;/client&gt; &lt;/system.serviceModel&gt; </code></pre> <p>This is the silverlight method that calls the service, I paste the whole method for copleteness, the lambda is to make the call synchronous, I have debugged it and after the line client.GetPersonsAsync(), Fiddler does not show any message travelling to the server.</p> <pre><code> public static List&lt;Person&gt; GetPersonsFromDatabase() { List&lt;Person&gt; persons = new List&lt;Person&gt;(); ServiceClient client = new ServiceClient(); ManualResetEvent eventGetPersons = new ManualResetEvent(false); client.GetPersonsCompleted += new EventHandler&lt;GetPersonsCompletedEventArgs&gt;(delegate(object sender, GetPersonsCompletedEventArgs e) { foreach (DTOperson dtoPerson in e.Result) { persons.Add(loadFromDto(dtoPerson)); } eventGetPersons.Set(); }); client.GetPersonsAsync(); eventGetPersons.WaitOne(); return persons; } </code></pre> <p>Does anyone have any suggestions how I might fix this?</p>
[ { "answer_id": 140646, "author": "Bill Reiss", "author_id": 18967, "author_profile": "https://Stackoverflow.com/users/18967", "pm_score": 0, "selected": false, "text": "<p>You wouldn't happen to be running from the filesystem would you? If you are serving up the silverlight application y...
2008/09/26
[ "https://Stackoverflow.com/questions/140602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19010/" ]
I am trying to call a WCF webservice (which I developed) from a Silverlight application. For some reason the Silverlight app does not make the http soap call to the service. I know this because I am sniffing all http traffic with Fiddler (and it is not a localhost call). This my configuration in the server relevant to WCF: ``` <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <services> <service behaviorConfiguration="ServiceBehavior" name="Service"> <endpoint address="" binding="basicHttpBinding" contract="Service"/> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> </system.serviceModel> ``` And the ServiceReferences.ClientConfig file in the silverlight app (i am using the beta 2): ``` <system.serviceModel> <bindings> <basicHttpBinding> <binding name="BasicHttpBinding_Service" maxBufferSize="65536" maxReceivedMessageSize="65536"> <security mode="None" /> </binding> </basicHttpBinding> </bindings> <client> <endpoint address="http://itlabws2003/Service.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_Service" contract="Silverlight_organigram.DataService.Service" name="BasicHttpBinding_Service" /> </client> </system.serviceModel> ``` This is the silverlight method that calls the service, I paste the whole method for copleteness, the lambda is to make the call synchronous, I have debugged it and after the line client.GetPersonsAsync(), Fiddler does not show any message travelling to the server. ``` public static List<Person> GetPersonsFromDatabase() { List<Person> persons = new List<Person>(); ServiceClient client = new ServiceClient(); ManualResetEvent eventGetPersons = new ManualResetEvent(false); client.GetPersonsCompleted += new EventHandler<GetPersonsCompletedEventArgs>(delegate(object sender, GetPersonsCompletedEventArgs e) { foreach (DTOperson dtoPerson in e.Result) { persons.Add(loadFromDto(dtoPerson)); } eventGetPersons.Set(); }); client.GetPersonsAsync(); eventGetPersons.WaitOne(); return persons; } ``` Does anyone have any suggestions how I might fix this?
If the Silverlight application is not hosted in the same domain that exposes the Web service you want to call, then cross-domain restrictions applies. If you want the Silverlight application to be hosted in another domain than the web service, you may want to have a look on [this post](http://timheuer.com/blog/archive/2008/06/10/silverlight-services-cross-domain-404-not-found.aspx) to help you to have a cross domain definition file, or to write a middle "proxy" instead.
140,616
<p>Is there a NAnt task that will echo out all property names and values that are currently set during a build? Something equivalent to the Ant <a href="http://ant.apache.org/manual/Tasks/echoproperties.html" rel="noreferrer">echoproperties</a> task maybe?</p>
[ { "answer_id": 140739, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 1, "selected": false, "text": "<p>You can't prove a negative, but I can't find one and haven't seen one. I've traditionally rolled my own property echo...
2008/09/26
[ "https://Stackoverflow.com/questions/140616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ]
Is there a NAnt task that will echo out all property names and values that are currently set during a build? Something equivalent to the Ant [echoproperties](http://ant.apache.org/manual/Tasks/echoproperties.html) task maybe?
Try this snippet: ``` <project> <property name="foo" value="bar"/> <property name="fiz" value="buz"/> <script language="C#" prefix="util" > <code> <![CDATA[ public static void ScriptMain(Project project) { foreach (DictionaryEntry entry in project.Properties) { Console.WriteLine("{0}={1}", entry.Key, entry.Value); } } ]]> </code> </script> </project> ``` You can just save and run with nant. And no, there isn't a task or function to do this for you already.
140,627
<p>I just wrote my first web service so lets make the assumption that my web service knowlege is non existant. I want to try to call a dbClass function from the web service. However I need some params that are in the session. Is there any way I can get these call these session variables from the webservice??</p>
[ { "answer_id": 140644, "author": "Yitzchok", "author_id": 5723, "author_profile": "https://Stackoverflow.com/users/5723", "pm_score": 0, "selected": false, "text": "<p>Maybe this will work HttpContext.Current.Session[\"Name]\nOr else you might have to take in some parameters or store the...
2008/09/26
[ "https://Stackoverflow.com/questions/140627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16820/" ]
I just wrote my first web service so lets make the assumption that my web service knowlege is non existant. I want to try to call a dbClass function from the web service. However I need some params that are in the session. Is there any way I can get these call these session variables from the webservice??
If you are using ASP.NET web services and you want to have a session environment maintained for you, you need to embellish your web service method with an attribute that indicates you require a session. ``` [WebMethod(EnableSession = true)] public void MyWebService() { Foo foo; Session["MyObjectName"] = new Foo(); foo = Session["MyObjectName"] as Foo; } ``` Once you have done this, you may access session objects similar to aspx. Metro.
140,643
<p>When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown. These tables have execute permission for the schema where the view was created. If I execute the view's SQL Statement it works. What am I missing?</p>
[ { "answer_id": 140665, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 5, "selected": true, "text": "<p>As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement...
2008/09/26
[ "https://Stackoverflow.com/questions/140643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22769/" ]
When I try to execute a view that includes tables from different schemas an ORA-001031 Insufficient privileges is thrown. These tables have execute permission for the schema where the view was created. If I execute the view's SQL Statement it works. What am I missing?
As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as. ``` grant SELECT on TABLE_NAME to READ_USERNAME; ```
140,728
<p>It often happens that characters such as <em>é</em> gets transformed to <em>é</em>, even though the collation for the MySQL DB, table and field is set to utf8_general_ci. The encoding in the <em>Content-Type</em> for the page is also set to UTF8.</p> <p>I know about utf8_encode/decode, but I'm not quite sure about where and how to use it.</p> <p>I have read the &quot;<a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a>&quot; article, but I need some MySQL / PHP specific pointers.</p> <p>How do I ensure that user entered data containing international characters doesn't get corrupted?</p>
[ { "answer_id": 141011, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 5, "selected": true, "text": "<p>On the first look at <a href=\"http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet\" rel=\"noreferrer\">htt...
2008/09/26
[ "https://Stackoverflow.com/questions/140728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
It often happens that characters such as *é* gets transformed to *é*, even though the collation for the MySQL DB, table and field is set to utf8\_general\_ci. The encoding in the *Content-Type* for the page is also set to UTF8. I know about utf8\_encode/decode, but I'm not quite sure about where and how to use it. I have read the "[The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)" article, but I need some MySQL / PHP specific pointers. How do I ensure that user entered data containing international characters doesn't get corrupted?
On the first look at <http://www.nicknettleton.com/zine/php/php-utf-8-cheatsheet> I think that one important thing is missing (perhaps I overlooked this one). Depending on your MySQL installation and/or configuration you have to set the connection encoding so that MySQL knows what encoding you're expecting on the client side (meaning the client side of the MySQL connection, which should be you PHP script). You can do this by manually issuing a ``` SET NAMES utf8 ``` query prior to any other query you send to the MySQL server. If your're using PDO on the PHP side you can set-up the connection to automatically issue this query on every (re)connect by using ``` $db=new PDO($dsn, $user, $pass); $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8"); ``` when initializing your db connection.
140,734
<p>What would be the best practice way to handle the caching of images using PHP.</p> <p>The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag.</p> <p>When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size. </p> <p>The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner,</p> <p>Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.)</p>
[ { "answer_id": 140767, "author": "sgibbons", "author_id": 2327, "author_profile": "https://Stackoverflow.com/users/2327", "pm_score": 0, "selected": false, "text": "<p>Your approach seems quite reasonable - I would add that some mechanism should be put into place to check that the date t...
2008/09/26
[ "https://Stackoverflow.com/questions/140734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22776/" ]
What would be the best practice way to handle the caching of images using PHP. The filename is currently stored in a MySQL database which is renamed to a GUID on upload, along with the original filename and alt tag. When the image is put into the HTML pages it is done so using a url such as '/images/get/200x200/{guid}.jpg which is rewritten to a php script. This allows my designers to specify (roughly - the source image maybe smaller) the file size. The php script then creates a hash of the size (200x200 in the url) and the GUID filename and if the file has been generated before (file with the name of the hash exists in TMP directory) sends the file from the application TMP directory. If the hashed filename does not exist, then it is created, written to disk and served up in the same manner, Is this efficient as it could be? (It also supports watermarking the images and the watermarking settings are stored in the hash as well, but thats out of scope for this.)
There is two typos in Dan Udey's rewrite example (and I can't comment on it), it should rather be : ``` RewriteCond %{REQUEST_URI} ^/images/cached/ RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f RewriteRule (.*) /images/generate.php?$1 [L] ``` Regards.
140,758
<p>In Java you can do <code>File.listFiles()</code> and receive all of the files in a directory. You can then easily recurse through directory trees.</p> <p>Is there an analogous way to do this in Python?</p>
[ { "answer_id": 140778, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 2, "selected": false, "text": "<p>Straight from Python's Refererence Library</p>\n\n<pre><code>&gt;&gt;&gt; import glob\n&gt;&gt;&gt; glob.glob('./[0-9].*...
2008/09/26
[ "https://Stackoverflow.com/questions/140758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
In Java you can do `File.listFiles()` and receive all of the files in a directory. You can then easily recurse through directory trees. Is there an analogous way to do this in Python?
Yes, there is. The Python way is even better. There are three possibilities: **1) Like File.listFiles():** Python has the function os.listdir(path). It works like the Java method. **2) pathname pattern expansion with glob:** The module glob contains functions to list files on the file system using Unix shell like pattern, e.g. ```` files = glob.glob('/usr/joe/*.gif') ```` **3) File Traversal with walk:** Really nice is the os.walk function of Python. The walk method returns a generation function that recursively list all directories and files below a given starting path. An Example: ```` import os from os.path import join for root, dirs, files in os.walk('/usr'): print "Current directory", root print "Sub directories", dirs print "Files", files ```` You can even on the fly remove directories from "dirs" to avoid walking to that dir: if "joe" in dirs: dirs.remove("joe") to avoid walking into directories called "joe". listdir and walk are documented [here](http://docs.python.org/lib/os-file-dir.html). glob is documented [here](http://docs.python.org/lib/module-glob.html).
140,786
<p>The code is</p> <pre><code>return min + static_cast&lt;int&gt;(static_cast&lt;double&gt;(max - min + 1.0) * (number / (UINT_MAX + 1.0))); </code></pre> <p>number is a random number obtained by rand_s. min and max are ints and represent minimum and maximum values (inclusive).</p> <p>If you provide a solution not using unsigned int as a number, please also explain how to make it be random.</p> <p>Please do not submit solutions using rand().</p>
[ { "answer_id": 140812, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "<p>How about <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/random/index.html\" rel=\"nofollow noreferrer\">Boost...
2008/09/26
[ "https://Stackoverflow.com/questions/140786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
The code is ``` return min + static_cast<int>(static_cast<double>(max - min + 1.0) * (number / (UINT_MAX + 1.0))); ``` number is a random number obtained by rand\_s. min and max are ints and represent minimum and maximum values (inclusive). If you provide a solution not using unsigned int as a number, please also explain how to make it be random. Please do not submit solutions using rand().
The `static_cast<double>` is redundant because the "+1.0"s will cause promotion to double anyway.
140,820
<p>Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just testing if msiexec is running?</p> <p>[Update 2]</p> <p>Improved the previous code I had been using to just access the mutex directly, this is a lot more reliable:</p> <pre><code>using System.Threading; [...] /// &lt;summary&gt; /// Wait (up to a timeout) for the MSI installer service to become free. /// &lt;/summary&gt; /// &lt;returns&gt; /// Returns true for a successful wait, when the installer service has become free. /// Returns false when waiting for the installer service has exceeded the timeout. /// &lt;/returns&gt; public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime) { // The _MSIExecute mutex is used by the MSI installer service to serialize installations // and prevent multiple MSI based installations happening at the same time. // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx const string installerServiceMutexName = "Global\\_MSIExecute"; try { Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName, System.Security.AccessControl.MutexRights.Synchronize | System.Security.AccessControl.MutexRights.Modify); bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false); MSIExecuteMutex.ReleaseMutex(); return waitSuccess; } catch (WaitHandleCannotBeOpenedException) { // Mutex doesn't exist, do nothing } catch (ObjectDisposedException) { // Mutex was disposed between opening it and attempting to wait on it, do nothing } return true; } </code></pre>
[ { "answer_id": 140875, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 4, "selected": true, "text": "<p>See the description of the <a href=\"http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx\" rel=\"noreferrer\...
2008/09/26
[ "https://Stackoverflow.com/questions/140820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332/" ]
Assuming I'm trying to automate the installation of something on windows and I want to try to test whether another installation is in progress before attempting install. I don't have control over the installer and have to do this in the automation framework. Is there a better way to do this, some win32 api?, than just testing if msiexec is running? [Update 2] Improved the previous code I had been using to just access the mutex directly, this is a lot more reliable: ``` using System.Threading; [...] /// <summary> /// Wait (up to a timeout) for the MSI installer service to become free. /// </summary> /// <returns> /// Returns true for a successful wait, when the installer service has become free. /// Returns false when waiting for the installer service has exceeded the timeout. /// </returns> public static bool WaitForInstallerServiceToBeFree(TimeSpan maxWaitTime) { // The _MSIExecute mutex is used by the MSI installer service to serialize installations // and prevent multiple MSI based installations happening at the same time. // For more info: http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx const string installerServiceMutexName = "Global\\_MSIExecute"; try { Mutex MSIExecuteMutex = Mutex.OpenExisting(installerServiceMutexName, System.Security.AccessControl.MutexRights.Synchronize | System.Security.AccessControl.MutexRights.Modify); bool waitSuccess = MSIExecuteMutex.WaitOne(maxWaitTime, false); MSIExecuteMutex.ReleaseMutex(); return waitSuccess; } catch (WaitHandleCannotBeOpenedException) { // Mutex doesn't exist, do nothing } catch (ObjectDisposedException) { // Mutex was disposed between opening it and attempting to wait on it, do nothing } return true; } ```
See the description of the [\_MSIExecute Mutex](http://msdn.microsoft.com/en-us/library/aa372909(VS.85).aspx) on MSDN.
140,825
<p>Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error?</p> <pre><code>struct myobj { int value; } /* This macro does not satisfy the read-only requirement */ #define VALUE(o) (o)-&gt;value /* This macro uses a function, unfortunately */ int getvalue(struct myobj *o) { return o-&gt;value; } #define VALUE(o) getvalue(o) void dostuff(struct myobj *foo) { printf("The value of foo is %d.\n", VALUE(foo)); /* OK */ VALUE(foo) = 1; /* We want a compile error here */ foo-&gt;value = 1; /* This is ok. */ } </code></pre>
[ { "answer_id": 140853, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": true, "text": "<p>If the variable is always numeric, this works:</p>\n\n<pre><code>#define VALUE(x) (x+0)\n</code></pre>\n\n<p>or in the...
2008/09/26
[ "https://Stackoverflow.com/questions/140825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14732/" ]
Can you define a macro that accesses a normal variable, but in a read-only fashion (other than defining it as a call to a function)? For example, can the VALUE macro in the following code be defined in such a way that the dostuff() function causes a compile error? ``` struct myobj { int value; } /* This macro does not satisfy the read-only requirement */ #define VALUE(o) (o)->value /* This macro uses a function, unfortunately */ int getvalue(struct myobj *o) { return o->value; } #define VALUE(o) getvalue(o) void dostuff(struct myobj *foo) { printf("The value of foo is %d.\n", VALUE(foo)); /* OK */ VALUE(foo) = 1; /* We want a compile error here */ foo->value = 1; /* This is ok. */ } ```
If the variable is always numeric, this works: ``` #define VALUE(x) (x+0) ``` or in the context of your example, ``` #define VALUE(x) (x->value+0) ```
140,926
<p>I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent?</p> <p>So something that would yield this kind of translation table:</p> <pre><code>\r --&gt; \r\n \n --&gt; \r\n \n\n --&gt; \r\n\r\n \n\r --&gt; \r\n \r\n --&gt; \r\n \r\n\n --&gt; \r\n\r\n </code></pre>
[ { "answer_id": 140952, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<p>A Regex would help.. could do something roughly like this..</p>\n\n<p>(\\r\\n|\\n\\n|\\n\\r|\\r|\\n) replace w...
2008/09/26
[ "https://Stackoverflow.com/questions/140926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13154/" ]
I have a data stream that may contain \r, \n, \r\n, \n\r or any combination of them. Is there a simple way to normalize the data to make all of them simply become \r\n pairs to make display more consistent? So something that would yield this kind of translation table: ``` \r --> \r\n \n --> \r\n \n\n --> \r\n\r\n \n\r --> \r\n \r\n --> \r\n \r\n\n --> \r\n\r\n ```
I believe this will do what you need: ``` using System.Text.RegularExpressions; // ... string normalized = Regex.Replace(originalString, @"\r\n|\n\r|\n|\r", "\r\n"); ``` I'm not 100% sure on the exact syntax, and I don't have a .Net compiler handy to check. I wrote it in perl, and converted it into (hopefully correct) C#. The only real trick is to match "\r\n" and "\n\r" first. To apply it to an entire stream, just run in on chunks of input. (You could do this with a stream wrapper if you want.) --- The original perl: ``` $str =~ s/\r\n|\n\r|\n|\r/\r\n/g; ``` The test results: ``` [bash$] ./test.pl \r -> \r\n \n -> \r\n \n\n -> \r\n\r\n \n\r -> \r\n \r\n -> \r\n \r\n\n -> \r\n\r\n ``` --- Update: Now converts \n\r to \r\n, though I wouldn't call that normalization.
140,935
<p>Anyone knows if is possible to have partial class definition on C++ ?</p> <p>Something like:</p> <p>file1.h:</p> <pre> class Test { public: int test1(); }; </pre> <p>file2.h: </p> <pre> class Test { public: int test2(); }; </pre> <p>For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes.</p> <p>I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs. </p> <p>Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class:</p> <pre> class genericTest { public: int genericMethod(); }; </pre> <p>Then let's say for win32:</p> <pre> class win32Test: public genericTest { public: int win32Method(); }; </pre> <p>And maybe:</p> <pre> class macTest: public genericTest { public: int macMethod(); }; </pre> <p>Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this:</p> <pre> #ifdef _WIN32 genericTest *test = new win32Test(); #elif MAC genericTest *test = new macTest(); #endif test->genericMethod(); </pre> <p>Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code.</p> <p>That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that.</p>
[ { "answer_id": 140942, "author": "Jamie", "author_id": 22748, "author_profile": "https://Stackoverflow.com/users/22748", "pm_score": 4, "selected": false, "text": "<p>Try inheritance</p>\n\n<p>Specifically</p>\n\n<pre><code>class AllPlatforms {\npublic:\n int common();\n};\n</code></p...
2008/09/26
[ "https://Stackoverflow.com/questions/140935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18623/" ]
Anyone knows if is possible to have partial class definition on C++ ? Something like: file1.h: ``` class Test { public: int test1(); }; ``` file2.h: ``` class Test { public: int test2(); }; ``` For me it seems quite useful for definining multi-platform classes that have common functions between them that are platform-independent because inheritance is a cost to pay that is non-useful for multi-platform classes. I mean you will never have two multi-platform specialization instances at runtime, only at compile time. Inheritance could be useful to fulfill your public interface needs but after that it won't add anything useful at runtime, just costs. Also you will have to use an ugly #ifdef to use the class because you can't make an instance from an abstract class: ``` class genericTest { public: int genericMethod(); }; ``` Then let's say for win32: ``` class win32Test: public genericTest { public: int win32Method(); }; ``` And maybe: ``` class macTest: public genericTest { public: int macMethod(); }; ``` Let's think that both win32Method() and macMethod() calls genericMethod(), and you will have to use the class like this: ``` #ifdef _WIN32 genericTest *test = new win32Test(); #elif MAC genericTest *test = new macTest(); #endif test->genericMethod(); ``` Now thinking a while the inheritance was only useful for giving them both a genericMethod() that is dependent on the platform-specific one, but you have the cost of calling two constructors because of that. Also you have ugly #ifdef scattered around the code. That's why I was looking for partial classes. I could at compile-time define the specific platform dependent partial end, of course that on this silly example I still need an ugly #ifdef inside genericMethod() but there is another ways to avoid that.
This is not possible in C++, it will give you an error about redefining already-defined classes. If you'd like to share behavior, consider inheritance.
140,996
<p>In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this:</p> <pre><code>&lt;TextBlock&gt;&lt;Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}"&gt;Object Name&lt;/Hyperlink&gt;&lt;/TextBlock&gt; </code></pre> <p>But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this:</p> <pre><code>&lt;TextBlock&gt;&lt;Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/&gt;&lt;/TextBlock&gt; </code></pre> <p>However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property).</p> <p>Any ideas?</p>
[ { "answer_id": 141008, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 9, "selected": true, "text": "<p>It looks strange, but it works. We do it in about 20 different places in our app. <code>Hyperlink</code> implicitly const...
2008/09/26
[ "https://Stackoverflow.com/questions/140996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22789/" ]
In WPF, I want to create a hyperlink that navigates to the details of an object, and I want the text of the hyperlink to be the name of the object. Right now, I have this: ``` <TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}">Object Name</Hyperlink></TextBlock> ``` But I want "Object Name" to be bound to the actual name of the object. I would like to do something like this: ``` <TextBlock><Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}" Text="{Binding Path=Name}"/></TextBlock> ``` However, the Hyperlink class does not have a text or content property that is suitable for data binding (that is, a dependency property). Any ideas?
It looks strange, but it works. We do it in about 20 different places in our app. `Hyperlink` implicitly constructs a `<Run/>` if you put text in its "content", but in .NET 3.5 `<Run/>` won't let you bind to it, so you've got to explicitly use a `TextBlock`. ``` <TextBlock> <Hyperlink Command="local:MyCommands.ViewDetails" CommandParameter="{Binding}"> <TextBlock Text="{Binding Path=Name}"/> </Hyperlink> </TextBlock> ``` --- **Update**: Note that as of .NET 4.0 the [Run.Text property](http://msdn.microsoft.com/en-us/library/system.windows.documents.run.text.aspx?PHPSESSID=o1fb21liejulfgrptbmi9dec92) can now be bound: ``` <Run Text="{Binding Path=Name}" /> ```
141,007
<p>Is there a way to add a resource to a ResourceDictionary from code without giving it a resource key?</p> <p>For instance, I have this resource in XAML:</p> <pre><code>&lt;TreeView.Resources&gt; &lt;HierarchicalDataTemplate DataType="{x:Type xbap:FieldPropertyInfo}" ItemsSource="{Binding Path=Value.Values}"&gt; &lt;TextBlock Text="{Binding Path=Name}" /&gt; &lt;HierarchicalDataTemplate&gt; &lt;/TreeView.Resources&gt; </code></pre> <p>I need to create this resource dynamically from code and add it to the TreeView ResourceDictionary. However, in XAML having no Key means that it's used, by default, for all FieldPropertyInfo types. Is there a way to add it to the resource in code without having a key or is there a way I can use a key and still have it used on all FieldPropertyInfo types?</p> <p>Here's what I've done in C# so far:</p> <pre><code>HierarchicalDataTemplate fieldPropertyTemplate = new HierarchicalDataTemplate("FieldProperyInfo"); fieldPropertyTemplate.ItemsSource = new Binding("Value.Values"); this.Resources.Add(null, fieldPropertyTemplate); </code></pre> <p>Obviously, adding a resource to the ResourceDictionary the key null doesn't work.</p>
[ { "answer_id": 141018, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "<p>Use the type that you want the template to apply to as the key:</p>\n\n<pre><code>this.Resources.Add(FieldPropertyIn...
2008/09/26
[ "https://Stackoverflow.com/questions/141007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
Is there a way to add a resource to a ResourceDictionary from code without giving it a resource key? For instance, I have this resource in XAML: ``` <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type xbap:FieldPropertyInfo}" ItemsSource="{Binding Path=Value.Values}"> <TextBlock Text="{Binding Path=Name}" /> <HierarchicalDataTemplate> </TreeView.Resources> ``` I need to create this resource dynamically from code and add it to the TreeView ResourceDictionary. However, in XAML having no Key means that it's used, by default, for all FieldPropertyInfo types. Is there a way to add it to the resource in code without having a key or is there a way I can use a key and still have it used on all FieldPropertyInfo types? Here's what I've done in C# so far: ``` HierarchicalDataTemplate fieldPropertyTemplate = new HierarchicalDataTemplate("FieldProperyInfo"); fieldPropertyTemplate.ItemsSource = new Binding("Value.Values"); this.Resources.Add(null, fieldPropertyTemplate); ``` Obviously, adding a resource to the ResourceDictionary the key null doesn't work.
Use the type that you want the template to apply to as the key: ``` HierarchicalDataTemplate fieldPropertyTemplate = new HierarchicalDataTemplate("FieldProperyInfo"); fieldPropertyTemplate.SetBinding( HierarchialDataTemplate.ItemSourceProperty, new Binding("Value.Values"); this.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate); ``` The reason your code wasn't working was your *weren't actually setting the binding*. You need to call SetBinding, with the property you want the binding bound to.
141,045
<p>I want to replace the first occurrence in a given string. </p> <p>How can I accomplish this in .NET?</p>
[ { "answer_id": 141062, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 4, "selected": false, "text": "<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx\" rel=...
2008/09/26
[ "https://Stackoverflow.com/questions/141045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to replace the first occurrence in a given string. How can I accomplish this in .NET?
``` string ReplaceFirst(string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } ``` Example: ``` string str = "The brown brown fox jumps over the lazy dog"; str = ReplaceFirst(str, "brown", "quick"); ``` **EDIT**: As @itsmatt [mentioned](https://stackoverflow.com/questions/141045/how-do-i-replace-a-string-in-net#141062), there's also Regex.Replace(String, String, Int32), which can do the same, but is probably more expensive at runtime, since it's utilizing a full featured parser where my method does one find and three string concatenations. **EDIT2**: If this is a common task, you might want to make the method an extension method: ``` public static class StringExtension { public static string ReplaceFirst(this string text, string search, string replace) { // ...same as above... } } ``` Using the above example it's now possible to write: ``` str = str.ReplaceFirst("brown", "quick"); ```
141,068
<p>I have an Image column (Allow Null = true) in SQL Server 2005. I am using Crystal Reports designer (ver 10.5) that comes with Visual Studio 2008. Crystal sees the column as blob field and puts an image object for the column. When I am trying to limit the record selection by using </p> <pre><code> NOT ISNULL({Employee.Picture}) </code></pre> <p>as Selection Formula, I get the following error:</p> <blockquote> <p>Error in formula .<br> 'NOT (ISNULL({Employee.Picture}))'<br> This function cannot be used because it must be evaluated later.</p> </blockquote> <p>Is there a way to filter out rows with out pictures?</p> <p>Thanks,<br> Kishore A</p>
[ { "answer_id": 141178, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 0, "selected": false, "text": "<p>since no one is jumping in on this I'll try (note: i can't test these possibilities at the moment).</p>\n\n<ul>\n<li><p>if you...
2008/09/26
[ "https://Stackoverflow.com/questions/141068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18169/" ]
I have an Image column (Allow Null = true) in SQL Server 2005. I am using Crystal Reports designer (ver 10.5) that comes with Visual Studio 2008. Crystal sees the column as blob field and puts an image object for the column. When I am trying to limit the record selection by using ``` NOT ISNULL({Employee.Picture}) ``` as Selection Formula, I get the following error: > > Error in formula . > > 'NOT (ISNULL({Employee.Picture}))' > > This function cannot be used because it must be evaluated later. > > > Is there a way to filter out rows with out pictures? Thanks, Kishore A
The `ISNULL` function is more like the `SWITCH` function in in VB. What you are looking for is probably something more along the lines of: ``` WHERE NOT Employee.Picture IS NULL ``` Two separate words for `IS NULL`.
141,088
<p>I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?</p>
[ { "answer_id": 141098, "author": "Pablo Fernandez", "author_id": 7595, "author_profile": "https://Stackoverflow.com/users/7595", "pm_score": 13, "selected": true, "text": "<pre class=\"lang-cs prettyprint-override\"><code>foreach(KeyValuePair&lt;string, string&gt; entry in myDictionary)\...
2008/09/26
[ "https://Stackoverflow.com/questions/141088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9311/" ]
I've seen a few different ways to iterate over a dictionary in C#. Is there a standard way?
```cs foreach(KeyValuePair<string, string> entry in myDictionary) { // do something with entry.Value or entry.Key } ```
141,108
<p>Is it possible to find the <code>foreach</code> index?</p> <p>in a <code>for</code> loop as follows:</p> <pre><code>for ($i = 0; $i &lt; 10; ++$i) { echo $i . ' '; } </code></pre> <p><code>$i</code> will give you the index.</p> <p>Do I have to use the <code>for</code> loop or is there some way to get the index in the <code>foreach</code> loop?</p>
[ { "answer_id": 141114, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 11, "selected": true, "text": "<pre><code>foreach($array as $key=&gt;$value) {\n // do stuff\n}\n</code></pre>\n\n<p><code>$key</code> is the index of each...
2008/09/26
[ "https://Stackoverflow.com/questions/141108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18334/" ]
Is it possible to find the `foreach` index? in a `for` loop as follows: ``` for ($i = 0; $i < 10; ++$i) { echo $i . ' '; } ``` `$i` will give you the index. Do I have to use the `for` loop or is there some way to get the index in the `foreach` loop?
``` foreach($array as $key=>$value) { // do stuff } ``` `$key` is the index of each `$array` element
141,136
<p>I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows: </p> <p>txtStart.Text = 09/19/2008 07:00:00</p> <p>txtEnd.Text = 09/19/2008 05:00:00</p> <p>I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page. </p>
[ { "answer_id": 141159, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": true, "text": "<p>Once your textbox date formats are known in advance, you can use <a href=\"http://www.mattkruse.com/javascript/date/\" rel...
2008/09/26
[ "https://Stackoverflow.com/questions/141136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096/" ]
I have a .net 2.0 ascx control with a start time and end time textboxes. The data is as follows: txtStart.Text = 09/19/2008 07:00:00 txtEnd.Text = 09/19/2008 05:00:00 I would like to calculate the total time (hours and minutes) in JavaScript then display it in a textbox on the page.
Once your textbox date formats are known in advance, you can use [Matt Kruse's Date functions](http://www.mattkruse.com/javascript/date/) in Javascript to convert the two to a timestamp, subtract and then write to the resulting text box. Equally the [JQuery Date Input](http://jonathanleighton.com/projects/date-input#date-formatting) code for `stringToDate` could be adapted for your purposes - the below takes a string in the format "YYYY-MM-DD" and converts it to a date object. The timestamp (`getTime()`) of these objects could be used for your calculations. ``` stringToDate: function(string) { var matches; if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) { return new Date(matches[1], matches[2] - 1, matches[3]); } else { return null; }; } ```
141,140
<p>The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment:</p> <pre><code>void methodName() { int i = 7; for (int j = 0; j &lt; 10; j++) { int i = j * 2; } } </code></pre> <p>Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this!</p> <p>What's the rationale for this design decision for Java?</p> <p>Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)</p>
[ { "answer_id": 141150, "author": "OregonGhost", "author_id": 20363, "author_profile": "https://Stackoverflow.com/users/20363", "pm_score": 3, "selected": false, "text": "<p>It leads to bugs that are hard to spot, I guess. It's similar in C#.</p>\n\n<p>Pascal does not support this, since ...
2008/09/26
[ "https://Stackoverflow.com/questions/141140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18103/" ]
The following method does not work because the inner block declares a variable of the same name as one in the outer block. Apparently variables belong to the method or class in which they are declared, not to the block in which they are declared, so I therefore can't write a short little temporary block for debugging that happens to push a variable in the outer scope off into shadow just for a moment: ``` void methodName() { int i = 7; for (int j = 0; j < 10; j++) { int i = j * 2; } } ``` Almost every block-scoped language I've ever used supported this, including trivial little languages that I wrote interpreters and compilers for in school. Perl can do this, as can Scheme, and even C. Even PL/SQL supports this! What's the rationale for this design decision for Java? Edit: as somebody pointed out, Java does have block-scoping. What's the name for the concept I'm asking about? I wish I could remember more from those language-design classes. :)
I believe the rationale is that most of the time, that isn't intentional, it is a programming or logic flaw. in an example as trivial as yours, its obvious, but in a large block of code, accidentally redeclaring a variable may not be obvious. ETA: it might also be related to exception handling in java. i thought part of this question was discussed in a question related to why variables declared in a try section were not available in the catch/finally scopes.