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
262,966
<p>I have a problem with Gridview sorting that is similar to others but I'm binding to a collection object as opposed to a data table.</p> <p>The existing business rules and data access layers of an application follow the pattern of having an object and, if you need a collection of objects of that type, to have another class inheriting CollectionBase and implementing IBindingList.</p> <p>For desktop applications, it was easy to databind a gridview to one of these objects and there weren't any problems with turning on column sorting. Everything was 'in state' in the desktop app's presentation layer.</p> <p>Now that code is being moved to a new web application (ASP.NET 2.0, VB codebehind pages).</p> <p>I've played around with what I had to do to only have certain columns of the collection show up in the gridview and the gridview looked pretty good. When I turned on 'allow sorting', that's when the problems showed up.</p> <p>I'm getting the error about not having a .Sorting method, etc. In researching this, I found all sorts of solutions that were easily implemented with dataviews <em>if</em> my source was a data table. But it's not - it's a collection. I tried to "cheap shot" a datasource by converting the collection to an XML memory stream and them trying to .ReadXML back into a dataset but that didn't work [Root element is missing error was as far as I got in the dataset.ReadXml(ioTemp) where ioTemp was the System.IO.MemoryStream used in the xml serializer].</p> <p>Because of the old desktop apps, I've never had to worry about sorting a collection since the gridview handled it once it was loaded. In fact, it's a 'standard' that the collection's .SortProperty, .SortDirection and .ApplySort all through NotSupportedExceptions (I inherited this code from programmers long gone).</p> <p>Is there an easy way to convert the collection to a data table or a way to sort the collection without having to go back to the database each time? Object Data Sources won't work becuase of the intricate rules in how the objects are built - the wizards in VS2005 just can't handle what we need to do (grabbing data from several tables conditionally to make an object).</p> <p>Thanks in advance.</p>
[ { "answer_id": 263060, "author": "SecretDeveloper", "author_id": 2720, "author_profile": "https://Stackoverflow.com/users/2720", "pm_score": 0, "selected": false, "text": "<p>I had a similar issue and i needed to implement IComparable on the objects. Basically to sort a collection of objects you need a way to distinguish their order. The IComparable interface has one method called Compare which allows the .Net framework to work out the order of the objects when you sort them. You need to implement this method yourself to get the sort method to work.</p>\n\n<p><a href=\"http://www.google.ie/search?hl=en&amp;q=vb.net+implement+icomparable&amp;btnG=Google+Search&amp;meta=\" rel=\"nofollow noreferrer\" title=\"Google results\">Google results</a></p>\n\n<p>You don't mention the error message so i cant be sure if this is the case, can you post the error?</p>\n\n<p>EDIT :</p>\n\n<p>In regards to your comment; you can implement multi column sorting, it just requires more work. You can specify the fields to sort the collection by and then use this information within the CompareTo Method.</p>\n\n<p><a href=\"http://codebetter.com/blogs/david.hayden/archive/2005/02/27/56099.aspx\" rel=\"nofollow noreferrer\">Have a look at this</a></p>\n" }, { "answer_id": 263858, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 0, "selected": false, "text": "<p>Given that you apparently are populating the grid with a collection of your own objects, this sounds like a perfect job for Linq for Objects. With just a little elbow grease you can achieve what is effectively an SQL Select statement against your collection. Very cool stuff.</p>\n\n<p><a href=\"http://www.hookedonlinq.com/LINQtoObjects5MinuteOverview.ashx\" rel=\"nofollow noreferrer\">http://www.hookedonlinq.com/LINQtoObjects5MinuteOverview.ashx</a></p>\n\n<p>Also, do you really just want to sort the data in the grid? If so, then'd definitely pursue using Linq against your objects. However, rarely does sorting the contents of the grid really answer the problem (\"sorting the grid\" usually translates into changing the access path of the data used to fill the grid.) Browser apps aren't like Windows apps and don't have a full-time connection to the underlying data source to make things happen quite as magically as the DataGridView in Windows makes things seem.</p>\n" }, { "answer_id": 517640, "author": "Sean Taylor", "author_id": 47212, "author_profile": "https://Stackoverflow.com/users/47212", "pm_score": 2, "selected": false, "text": "<p>Have you considered client side sorting instead? </p>\n\n<p>I have used the jquery tablesorter plugin in the past with ASP Gridviews.</p>\n\n<p><a href=\"http://tablesorter.com/\" rel=\"nofollow noreferrer\">http://tablesorter.com/</a></p>\n" }, { "answer_id": 1992326, "author": "SBurris", "author_id": 31474, "author_profile": "https://Stackoverflow.com/users/31474", "pm_score": 0, "selected": false, "text": "<p>You can put link buttons with an On_Click event as the header's of each column. </p>\n\n<p>When the event is triggered, figure out which header was clicked on (one method per header or a commandArgument value). Once that is know, do a .orderBy or .OrderByDescending by on the collection of objects, and put the result back in as datasource of the gridview and databind on that.</p>\n" }, { "answer_id": 1999261, "author": "David", "author_id": 15891, "author_profile": "https://Stackoverflow.com/users/15891", "pm_score": 1, "selected": true, "text": "<p>In the year since I originally asked this question, I managed to get a new 'standard' implemented so that collections of business objects were now generic lists.</p>\n\n<p>So now a \"Collection class\" that is little more than a \"Inherits List(Of MyBusinessObject)\" with a Sort Method that looks like this (performance wasn't an issue):</p>\n\n<pre><code>Public Overloads Sub Sort(ByVal strPropertyName As String, ByVal strDirection As String)\n Dim arSortedList As New ArrayList\n For Each item As MyBusinessObject In Me\n arSortedList.Add(item)\n Next\n arSortedList.Sort(New CaseInsensitiveComparer(Of MyBusinessObject)(strPropertyName, strDirection))\n For intI As Integer = 0 To arSortedList.Count - 1\n Item(intI) = arSortedList(intI)\n Next\nEnd Sub\n</code></pre>\n\n<p>This seemed to work perfectly with the methodology used by the GridView for firing events.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/262966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15891/" ]
I have a problem with Gridview sorting that is similar to others but I'm binding to a collection object as opposed to a data table. The existing business rules and data access layers of an application follow the pattern of having an object and, if you need a collection of objects of that type, to have another class inheriting CollectionBase and implementing IBindingList. For desktop applications, it was easy to databind a gridview to one of these objects and there weren't any problems with turning on column sorting. Everything was 'in state' in the desktop app's presentation layer. Now that code is being moved to a new web application (ASP.NET 2.0, VB codebehind pages). I've played around with what I had to do to only have certain columns of the collection show up in the gridview and the gridview looked pretty good. When I turned on 'allow sorting', that's when the problems showed up. I'm getting the error about not having a .Sorting method, etc. In researching this, I found all sorts of solutions that were easily implemented with dataviews *if* my source was a data table. But it's not - it's a collection. I tried to "cheap shot" a datasource by converting the collection to an XML memory stream and them trying to .ReadXML back into a dataset but that didn't work [Root element is missing error was as far as I got in the dataset.ReadXml(ioTemp) where ioTemp was the System.IO.MemoryStream used in the xml serializer]. Because of the old desktop apps, I've never had to worry about sorting a collection since the gridview handled it once it was loaded. In fact, it's a 'standard' that the collection's .SortProperty, .SortDirection and .ApplySort all through NotSupportedExceptions (I inherited this code from programmers long gone). Is there an easy way to convert the collection to a data table or a way to sort the collection without having to go back to the database each time? Object Data Sources won't work becuase of the intricate rules in how the objects are built - the wizards in VS2005 just can't handle what we need to do (grabbing data from several tables conditionally to make an object). Thanks in advance.
In the year since I originally asked this question, I managed to get a new 'standard' implemented so that collections of business objects were now generic lists. So now a "Collection class" that is little more than a "Inherits List(Of MyBusinessObject)" with a Sort Method that looks like this (performance wasn't an issue): ``` Public Overloads Sub Sort(ByVal strPropertyName As String, ByVal strDirection As String) Dim arSortedList As New ArrayList For Each item As MyBusinessObject In Me arSortedList.Add(item) Next arSortedList.Sort(New CaseInsensitiveComparer(Of MyBusinessObject)(strPropertyName, strDirection)) For intI As Integer = 0 To arSortedList.Count - 1 Item(intI) = arSortedList(intI) Next End Sub ``` This seemed to work perfectly with the methodology used by the GridView for firing events.
263,005
<p>In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following:</p> <pre><code>import os os.environ["FOO"] = "A_Value" </code></pre> <p>When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process?</p> <p>I know you typically solve this problem using something like</p> <pre><code>source script_name.sh </code></pre> <p>But this conflicts with other requirements I have.</p>
[ { "answer_id": 263022, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": false, "text": "<p>It's not possible, for any child process, to change the environment of the parent process. The best you can do is to output shell statements to stdout that you then source, or write it to a file that you source in the parent.</p>\n" }, { "answer_id": 263068, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": true, "text": "<p>No process can change its parent process (or any other existing process' environment).</p>\n\n<p>You can, however, create a new environment by creating a new interactive shell with the modified environment.</p>\n\n<p>You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance.</p>\n\n<p>You need to do something like use subprocess.Popen to run <code>/bin/bash -i</code>.</p>\n\n<p>So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.</p>\n" }, { "answer_id": 263162, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 4, "selected": false, "text": "<p>I would use the bash eval statement, and have the python script output the shell code</p>\n\n<p>child.py:</p>\n\n<pre><code>#!/usr/bin/env python\nprint 'FOO=\"A_Value\"'\n</code></pre>\n\n<p>parent.sh</p>\n\n<pre><code>#!/bin/bash\neval `./child.py`\n</code></pre>\n" }, { "answer_id": 73166920, "author": "André C. Andersen", "author_id": 604048, "author_profile": "https://Stackoverflow.com/users/604048", "pm_score": 0, "selected": false, "text": "<p>I needed something similar, I ended up creating a script <code>envtest.py</code> with:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys, os\nsys.stdout = open(os.devnull, 'w')\n\n# Python code with any number of prints (to stdout).\nprint(&quot;This is some other logic, which shouldn't pollute stdout.&quot;)\n\nsys.stdout = sys.__stdout__\nprint(&quot;SomeValue&quot;)\n</code></pre>\n<p>Then in bash:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>export MYVAR=$(python3 envtest.py)\necho &quot;MYVAR is $MYVAR&quot;\n</code></pre>\n<p>Which echos the expected: <code>MYVAR is SomeValue</code></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34329/" ]
In Linux When I invoke python from the shell it replicates its environment, and starts the python process. Therefore if I do something like the following: ``` import os os.environ["FOO"] = "A_Value" ``` When the python process returns, FOO, assuming it was undefined originally, will still be undefined. Is there a way for the python process (or any child process) to modify the environment of its parent process? I know you typically solve this problem using something like ``` source script_name.sh ``` But this conflicts with other requirements I have.
No process can change its parent process (or any other existing process' environment). You can, however, create a new environment by creating a new interactive shell with the modified environment. You have to spawn a new copy of the shell that uses the upgraded environment and has access to the existing stdin, stdout and stderr, and does its reinitialization dance. You need to do something like use subprocess.Popen to run `/bin/bash -i`. So the original shell runs Python, which runs a new shell. Yes, you have a lot of processes running. No it's not too bad because the original shell and Python aren't really doing anything except waiting for the subshell to finish so they can exit cleanly, also.
263,013
<p>I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a <code>JProgressBar</code> widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file. </p>
[ { "answer_id": 263037, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 6, "selected": true, "text": "<p>Any HTTP response is <em>supposed</em> to contain a Content-Length header, so you could query the URLConnection object for this value.</p>\n\n<pre><code>//once the connection has been opened\nList values = urlConnection.getHeaderFields().get(\"content-Length\")\nif (values != null &amp;&amp; !values.isEmpty()) {\n\n // getHeaderFields() returns a Map with key=(String) header \n // name, value = List of String values for that header field. \n // just use the first value here.\n String sLength = (String) values.get(0);\n\n if (sLength != null) {\n //parse the length into an integer...\n ...\n }\n</code></pre>\n\n<p>It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get <em>some</em> usable value most of the time.</p>\n\n<p><strong>update:</strong> Or, now that I look at the URLConnection javadoc more completely, you could just use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getContentLength%28%29\" rel=\"noreferrer\">getContentLength()</a> method.</p>\n" }, { "answer_id": 263065, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 2, "selected": false, "text": "<p>You'll want to use the content length (URLConnection.getContentLength()). Unfortunately, this won't always be accurate, or may not always be provided, so it's not always safe to rely on it.</p>\n" }, { "answer_id": 263127, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": false, "text": "<p>As mentioned, URLConnection's <a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getContentLengthLong--\" rel=\"nofollow noreferrer\"><code>getContentLengthLong()</code></a> is your best bet, but it won't always give a definite length. That's because the HTTP protocol (and others that could be represented by a <code>URLConnection</code>) doesn't always convey the length.</p>\n\n<p>In the case of HTTP, the length of dynamic content typically isn't known in advance&mdash;when the <code>content-length</code> header would normally be sent. Instead, another header, <code>transfer-encoding</code>, specifies that a \"chunked\" encoding is used. With chunked encoding, the length of the entire response is unspecified, and the response is sent back in pieces, where the size of each piece is specified. In practice, the server buffers output from the servlet. Whenever the buffer fills up, another chunk is sent. Using this mechanism, HTTP could actually start streaming a response of infinite length.</p>\n\n<p>If a file is larger than 2 Gb, its size can't be represented as an <code>int</code>, so the older method, <a href=\"https://docs.oracle.com/javase/8/docs/api/java/net/URLConnection.html#getContentLength--\" rel=\"nofollow noreferrer\"><code>getContentLength()</code></a> will return -1 in that case.</p>\n" }, { "answer_id": 4872268, "author": "Petromir Dzhunev", "author_id": 599677, "author_profile": "https://Stackoverflow.com/users/599677", "pm_score": 0, "selected": false, "text": "<p>As @erickson said, sometimes there is header \"Transfer-Encoding: chunked\", instead of \"Content-Length: \" and of course you have null value for length.</p>\n\n<p>About the available() method - nobody can guarantee to you that it will return proper value, so I recommend you to not use it.</p>\n" }, { "answer_id": 7673089, "author": "betty", "author_id": 982009, "author_profile": "https://Stackoverflow.com/users/982009", "pm_score": 5, "selected": false, "text": "<p>Using a HEAD request, i got my webserver to reply with the correct content-length field which otherwise was empty. I don't know if this works in general but in my case it does:</p>\n\n<pre><code> private int tryGetFileSize(URL url) {\n HttpURLConnection conn = null;\n try {\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestMethod(\"HEAD\");\n conn.getInputStream();\n return conn.getContentLength();\n } catch (IOException e) {\n return -1;\n } finally {\n conn.disconnect();\n }\n }\n</code></pre>\n" }, { "answer_id": 37980912, "author": "Abdul Sheikh", "author_id": 6047193, "author_profile": "https://Stackoverflow.com/users/6047193", "pm_score": 1, "selected": false, "text": "<pre><code> //URLConnection connection\n\nprivate int FileSize(String url) {\n\n // this is the method and it get the url as a parameter.\n\n // this java class will allow us to get the size of the file.\n\n URLConnection con; \n\n // its in a try and catch incase the url given is wrong or invalid\n\n try{ \n\n // we open the stream\n\n con = new URL(url).openConnection()\n\n return con.getContentLength(); \n }catch (Exception e){\n\n e.printStackTrace();\n\n // this is returned if the connection went invalid or failed.\n\n return 0; \n }\n }\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
I'm working on a project for school, and I'm implementing a tool which can be used to download files from the web ( with a throttling option ). The thing is, I'm gonna have a GUI for it, and I will be using a `JProgressBar` widget, which I would like to show the current progress of the download. For that I would need to know the size of the file. How do you get the size of the file prior to downloading the file.
Any HTTP response is *supposed* to contain a Content-Length header, so you could query the URLConnection object for this value. ``` //once the connection has been opened List values = urlConnection.getHeaderFields().get("content-Length") if (values != null && !values.isEmpty()) { // getHeaderFields() returns a Map with key=(String) header // name, value = List of String values for that header field. // just use the first value here. String sLength = (String) values.get(0); if (sLength != null) { //parse the length into an integer... ... } ``` It might not always be possible for a server to return an accurate Content-Length, so the value could be inaccurate, but at least you would get *some* usable value most of the time. **update:** Or, now that I look at the URLConnection javadoc more completely, you could just use the [getContentLength()](http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getContentLength%28%29) method.
263,023
<p>I was doing some testing and straight LINQ-to-SQL queries run at least 80% faster than if calling stored procedures via the LINQ query</p> <p>In SQL Server profiler a generic LINQ query </p> <pre><code> var results = from m in _dataContext.Members select m; </code></pre> <p>took only 19 milliseconds as opposed to a stored procedure</p> <pre><code> var results = from m in _dataContext.GetMember(userName) select m; </code></pre> <p>(<code>GetMember</code> being the stored procedure) doing the same query which took 100 milliseconds</p> <p>Why is this?</p> <p><strong>Edit:</strong></p> <p>The straight LINQ looks like this in Profiler</p> <pre><code>SELECT [t1].[MemberID], [t1].[Aspnetusername], [t1].[Aspnetpassword], [t1].[EmailAddr], [t1].[DateCreated], [t1].[Location], [t1].[DaimokuGoal], [t1].[PreviewImageID], [t1].[value] AS [LastDaimoku], [t1].[value2] AS [LastNotefied], [t1].[value3] AS [LastActivityDate], [t1].[IsActivated] FROM (SELECT [t0].[MemberID], [t0].[Aspnetusername], [t0].[Aspnetpassword], [t0].[EmailAddr], [t0].[DateCreated], [t0].[Location], [t0].[DaimokuGoal], [t0].[PreviewImageID], [t0].[LastDaimoku] AS [value], [t0].[LastNotefied] AS [value2], [t0].[LastActivityDate] AS [value3], [t0].[IsActivated] FROM [dbo].[Members] AS [t0]) AS [t1] WHERE [t1].[EmailAddr] = @p0 </code></pre> <p>The stored procedure is this</p> <pre><code>SELECT Members.* FROM Members WHERE dbo.Members.EmailAddr = @Username </code></pre> <p>So you see the stored procedure query is much simpler.. but yet its slower.... makes no sense to me.</p>
[ { "answer_id": 263066, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>A noted in the comments some of this is that you are not comparing apples to apples. You are trying to compare two different queries, thus getting different results.</p>\n\n<p>If you want to try and determine performance you would want to compare the SAME queries, with the same values etc.</p>\n\n<p>Also, you might try using LinqPad to be able to see the generated SQL to potentially identify areas that are causing slowness in response.</p>\n" }, { "answer_id": 263080, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>1) Compare like with like. Perform exactly the same operation in both cases, rather than fetching all values in one case and doing a query in another.</p>\n\n<p>2) Don't just execute the code once - do it lots of times, so the optimiser has a chance to work and to avoid one-time performance hits.</p>\n\n<p>3) Use a profiler (well, one on the .NET side and one on the SQL side) to find out where the performance is <em>actually</em> differing.</p>\n" }, { "answer_id": 273733, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>One thing that might make it slower is the select *. Usually a query is faster if columns are specified, And in particular if the LINQ query is not using all the possible columns inthe query, it will be faster than select *.</p>\n" }, { "answer_id": 273739, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 1, "selected": false, "text": "<p>I forgot, the proc could also have parameter sniffing issues.</p>\n" }, { "answer_id": 4687725, "author": "Zunandi", "author_id": 576521, "author_profile": "https://Stackoverflow.com/users/576521", "pm_score": 0, "selected": false, "text": "<p>The * will extend the time it takes to run the query by quite a bit. Also, the straight SQL from LINQ you see in profiler is bracketing ([]) all of the object names - this will trim more time off the query execution time for the LINQ query.</p>\n" }, { "answer_id": 16823723, "author": "Stoleg", "author_id": 2409965, "author_profile": "https://Stackoverflow.com/users/2409965", "pm_score": 0, "selected": false, "text": "<p>May I add to John Skeet's answer, that when running code several time please remember clean up any query cache.</p>\n\n<p>I can suggest using 'EXPLAIN' with both queries: it seems that MySQL creates query execution plan for a query and SP differently. For SP it complies before substituting parameters with their values, and therefore it does not use indexes, that used in case of hard-coded or substituted parameter. Here is <a href=\"https://stackoverflow.com/questions/16752922/mysql-stored-procedure-is-slower-20-times-than-standart-query\">another question about different run times for SP and straight query</a> from SO with query plan data given for both cases.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22093/" ]
I was doing some testing and straight LINQ-to-SQL queries run at least 80% faster than if calling stored procedures via the LINQ query In SQL Server profiler a generic LINQ query ``` var results = from m in _dataContext.Members select m; ``` took only 19 milliseconds as opposed to a stored procedure ``` var results = from m in _dataContext.GetMember(userName) select m; ``` (`GetMember` being the stored procedure) doing the same query which took 100 milliseconds Why is this? **Edit:** The straight LINQ looks like this in Profiler ``` SELECT [t1].[MemberID], [t1].[Aspnetusername], [t1].[Aspnetpassword], [t1].[EmailAddr], [t1].[DateCreated], [t1].[Location], [t1].[DaimokuGoal], [t1].[PreviewImageID], [t1].[value] AS [LastDaimoku], [t1].[value2] AS [LastNotefied], [t1].[value3] AS [LastActivityDate], [t1].[IsActivated] FROM (SELECT [t0].[MemberID], [t0].[Aspnetusername], [t0].[Aspnetpassword], [t0].[EmailAddr], [t0].[DateCreated], [t0].[Location], [t0].[DaimokuGoal], [t0].[PreviewImageID], [t0].[LastDaimoku] AS [value], [t0].[LastNotefied] AS [value2], [t0].[LastActivityDate] AS [value3], [t0].[IsActivated] FROM [dbo].[Members] AS [t0]) AS [t1] WHERE [t1].[EmailAddr] = @p0 ``` The stored procedure is this ``` SELECT Members.* FROM Members WHERE dbo.Members.EmailAddr = @Username ``` So you see the stored procedure query is much simpler.. but yet its slower.... makes no sense to me.
1) Compare like with like. Perform exactly the same operation in both cases, rather than fetching all values in one case and doing a query in another. 2) Don't just execute the code once - do it lots of times, so the optimiser has a chance to work and to avoid one-time performance hits. 3) Use a profiler (well, one on the .NET side and one on the SQL side) to find out where the performance is *actually* differing.
263,053
<p>So I have a column with different numbers and wish to categorize them by range within 30 minute intervals. So 5 would be 0-30, 697 would be 690-720, and 169 would be 150-180. I was first thinking of doing a case statement, but it doesn't look like Access 2003 supports it. Is there perhaps some sort of algorithm that could determine the range? Preferably, this would be done within the query.</p> <p>Thank you.</p>
[ { "answer_id": 263079, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use / (integer division) and * (multiplication).\n5/30*30 = 0\n697/30*30 = 690\n169/30*30 = 150\n...</p>\n" }, { "answer_id": 263097, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 3, "selected": true, "text": "<p>Take the integer portion of (number / 30) using the Int function and multiply it by 30 to get your lower bound, then add 30 to that number to get your upper bound.</p>\n\n<p>Examples<br></p>\n\n<pre><code>Int(5 / 30) = 0 * 30 = 0\nInt(697 / 30) = 23 * 30 = 690\n</code></pre>\n" }, { "answer_id": 263100, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 0, "selected": false, "text": "<p>Let x be your column with the values you want to catalogue, the in pseudo-SQL you have:</p>\n\n<pre><code>select ((x/30)*30) as minrange,\n(((x/30)+1)*30) as maxrange\nfrom yourtable\n</code></pre>\n\n<p>(you should take the integer part of the division).<br/>\nHope this helps.</p>\n" }, { "answer_id": 263126, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 0, "selected": false, "text": "<p>This is fairly straight forward. You can just use the following.</p>\n\n<pre><code>(number \\ 30) * 30\n</code></pre>\n\n<p>This will give you the lower index of your range. It does have one problem, which is that 30, 720, 180 etc, will be returned as themselves. This means your ranges either need to be 0-29, 690-719, etc, or have your caller take this into account.</p>\n\n<p>This assumes you are using VBA where the '\\' operator returns only the quotient. See more on VB operators <A href=\"http://msdn.microsoft.com/en-us/library/b6ex274z(VS.80).aspx\" rel=\"nofollow noreferrer\">here</A></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25371/" ]
So I have a column with different numbers and wish to categorize them by range within 30 minute intervals. So 5 would be 0-30, 697 would be 690-720, and 169 would be 150-180. I was first thinking of doing a case statement, but it doesn't look like Access 2003 supports it. Is there perhaps some sort of algorithm that could determine the range? Preferably, this would be done within the query. Thank you.
Take the integer portion of (number / 30) using the Int function and multiply it by 30 to get your lower bound, then add 30 to that number to get your upper bound. Examples ``` Int(5 / 30) = 0 * 30 = 0 Int(697 / 30) = 23 * 30 = 690 ```
263,069
<p>How can I play two or more video files/streams in different windows with frame-level synchronism?</p> <p>What tools, libraries or APIs could I use to do that?</p> <p>By frame-level synchronism I mean that my solution must guarantee that each frame of each video file must be shown at the same time its corresponding frames (from the other files) are shown.</p> <p>Eg:</p> <pre><code> in sync out of sync Time -+-+-+-+-+-+ ... +-+-+-+-+-+-+ video 1 fr1 fr2 fr3 fr1 fr2 fr3 video 2 fr1 fr2 fr3 ... fr2 fr3 fr4 video N fr1 fr2 fr3 fr1 fr2 fr3 </code></pre>
[ { "answer_id": 263098, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 0, "selected": false, "text": "<p>On OS X, the <a href=\"http://developer.apple.com/documentation/GraphicsImaging/Conceptual/CoreVideo/CVProg_Intro/chapter_1_section_1.html\" rel=\"nofollow noreferrer\">Core Video</a> framework will do the job. Core Video's express purpose is to provide a link between QuickTime media (such as audio and video) and the Quartz compositing system with frame-level synchronization.</p>\n" }, { "answer_id": 263108, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Could you expand a little on what you mean by \"frame-level synchronism\"? </p>\n\n<p>compiz does this when multiple videos are playing and you spin the desktop</p>\n\n<p>opengl can render multiple videos simultaneously on the sides of a cube, etc</p>\n" }, { "answer_id": 966332, "author": "Øystein E. Krog", "author_id": 67895, "author_profile": "https://Stackoverflow.com/users/67895", "pm_score": 1, "selected": false, "text": "<p>On windows it should be possible to create custom directshow filters/components to do this.\nWe use c# and directshow.net to achieve something similar, however we do not yet have \"true\" frame synchronization and I am in fact searching for a solution as well. \nThe caveat here is that you can not just use the default/provided directshow filters, I fear one would have to write some new filters or perhaps modify the base classes a bit.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16120/" ]
How can I play two or more video files/streams in different windows with frame-level synchronism? What tools, libraries or APIs could I use to do that? By frame-level synchronism I mean that my solution must guarantee that each frame of each video file must be shown at the same time its corresponding frames (from the other files) are shown. Eg: ``` in sync out of sync Time -+-+-+-+-+-+ ... +-+-+-+-+-+-+ video 1 fr1 fr2 fr3 fr1 fr2 fr3 video 2 fr1 fr2 fr3 ... fr2 fr3 fr4 video N fr1 fr2 fr3 fr1 fr2 fr3 ```
On windows it should be possible to create custom directshow filters/components to do this. We use c# and directshow.net to achieve something similar, however we do not yet have "true" frame synchronization and I am in fact searching for a solution as well. The caveat here is that you can not just use the default/provided directshow filters, I fear one would have to write some new filters or perhaps modify the base classes a bit.
263,081
<p>I'm using Lucene.net, but I am tagging this question for both .NET and Java versions because the API is the same and I'm hoping there are solutions on both platforms.</p> <p>I'm sure other people have addressed this issue, but I haven't been able to find any good discussions or examples. </p> <p>By default, Lucene is very picky about query syntax. For example, I just got the following error:</p> <pre><code>[ParseException: Cannot parse 'hi there!': Encountered "&lt;EOF&gt;" at line 1, column 9. Was expecting one of: "(" ... "*" ... &lt;QUOTED&gt; ... &lt;TERM&gt; ... &lt;PREFIXTERM&gt; ... &lt;WILDTERM&gt; ... "[" ... "{" ... &lt;NUMBER&gt; ... ] Lucene.Net.QueryParsers.QueryParser.Parse(String query) +239 </code></pre> <p>What is the best way to prevent ParseExceptions when processing queries from users? It seems to me that the most <em>usable</em> search interface is one that always executes a query, even if it might be the wrong query. </p> <p>It seems that there are a few possible, and complementary, strategies:</p> <ul> <li>"Clean" the query prior to sending it to the QueryProcessor</li> <li>Handle exceptions gracefully <ul> <li>Show an intelligent error message to the user</li> <li>Perhaps execute a simpler query, leaving off the erroneous bit</li> </ul></li> </ul> <p>I don't really have any great ideas about how to do any of those strategies. Has anyone else addressed this issue? Are there any "simple" or "graceful" parsers that I don't know about?</p>
[ { "answer_id": 263241, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 1, "selected": false, "text": "<p>I'm in the same situation as you.</p>\n\n<p>Here's what I do. I do catch the exception, but only so that I can make the error look prettier. I don't change the text.</p>\n\n<p>I also provide a link to an explanation of the Lucene syntax which I have simplified a little bit:<br>\n<a href=\"http://ifdefined.com/btnet/lucene_syntax.html\" rel=\"nofollow noreferrer\">http://ifdefined.com/btnet/lucene_syntax.html</a></p>\n" }, { "answer_id": 263527, "author": "Jay Kominek", "author_id": 32878, "author_profile": "https://Stackoverflow.com/users/32878", "pm_score": 3, "selected": false, "text": "<p>Well, the easiest thing to do would be to give the raw form of the query a shot, and if that fails, fall back to cleaning it up.</p>\n\n<pre><code>Query safe_query_parser(QueryParser qp, String raw_query)\n throws ParseException\n{\n Query q;\n try {\n q = qp.parse(raw_query);\n } catch(ParseException e) {\n q = null;\n }\n if(q==null)\n {\n String cooked;\n // consider changing this \"\" to \" \"\n cooked = raw_query.replaceAll(\"[^\\w\\s]\",\"\");\n q = qp.parse(cooked);\n }\n return q;\n}\n</code></pre>\n\n<p>This gives the raw form of the user's query a chance to run, but if parsing fails, we strip everything except letters, numbers, spaces and underscores; then we try again. We still risk throwing ParseException, but we've drastically reduced the odds.</p>\n\n<p>You could also consider tokenizing the user's query yourself, turning each token into a term query, and glomming them together with a BooleanQuery. If you're not really expecting your users to take advantage of the features of the QueryParser, that would be the best bet. You'd be completely(?) robust, and users could search for whatever funny characters will make it through your analyzer</p>\n" }, { "answer_id": 265022, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 1, "selected": false, "text": "<p>I do not know much about Lucene.net. For general Lucene, I highly recommend the book <a href=\"http://www.manning.com/hatcher2/\" rel=\"nofollow noreferrer\">Lucene in Action</a>. For the question at hand, it depends on your users. There are strong reasons, such as ease of use, security and performance, to limit your users' queries. The book shows ways to parse the queries using a custom parser instead of QueryParser. I second Jay's idea about the BooleanQuery, although you can build stronger queries using a custom parser. </p>\n" }, { "answer_id": 265065, "author": "ljorquera", "author_id": 9132, "author_profile": "https://Stackoverflow.com/users/9132", "pm_score": 5, "selected": false, "text": "<p>Yo can make Lucene ignore the special characters by sanitizing the query with something like</p>\n\n<pre><code>query = QueryParser.Escape(query)\n</code></pre>\n\n<p>If you do not want your users to ever use advanced syntax in their queries, you can do this always. </p>\n\n<p>If you want your users to use advanced syntax but you also want to be more forgiving with the mistakes you should only sanitize after a ParseException has occured.</p>\n" }, { "answer_id": 265071, "author": "Stefan Schultze", "author_id": 6358, "author_profile": "https://Stackoverflow.com/users/6358", "pm_score": 1, "selected": false, "text": "<p>If you don't need all Lucene features, you might go better by writing your own query parser. It's not as complicated as it might seem in the first place.</p>\n" }, { "answer_id": 855189, "author": "josefresno", "author_id": 88774, "author_profile": "https://Stackoverflow.com/users/88774", "pm_score": 2, "selected": false, "text": "<p>FYI... Here is the code I am using for .NET</p>\n\n<pre><code>private Query GetSafeQuery(QueryParser qp, String query)\n{\n Query q;\n try \n {\n q = qp.Parse(query);\n } \n\n catch(Lucene.Net.QueryParsers.ParseException e) \n {\n q = null;\n }\n\n if(q==null)\n {\n string cooked;\n\n cooked = Regex.Replace(query, @\"[^\\w\\.@-]\", \" \");\n q = qp.Parse(cooked);\n }\n\n return q;\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31015/" ]
I'm using Lucene.net, but I am tagging this question for both .NET and Java versions because the API is the same and I'm hoping there are solutions on both platforms. I'm sure other people have addressed this issue, but I haven't been able to find any good discussions or examples. By default, Lucene is very picky about query syntax. For example, I just got the following error: ``` [ParseException: Cannot parse 'hi there!': Encountered "<EOF>" at line 1, column 9. Was expecting one of: "(" ... "*" ... <QUOTED> ... <TERM> ... <PREFIXTERM> ... <WILDTERM> ... "[" ... "{" ... <NUMBER> ... ] Lucene.Net.QueryParsers.QueryParser.Parse(String query) +239 ``` What is the best way to prevent ParseExceptions when processing queries from users? It seems to me that the most *usable* search interface is one that always executes a query, even if it might be the wrong query. It seems that there are a few possible, and complementary, strategies: * "Clean" the query prior to sending it to the QueryProcessor * Handle exceptions gracefully + Show an intelligent error message to the user + Perhaps execute a simpler query, leaving off the erroneous bit I don't really have any great ideas about how to do any of those strategies. Has anyone else addressed this issue? Are there any "simple" or "graceful" parsers that I don't know about?
Yo can make Lucene ignore the special characters by sanitizing the query with something like ``` query = QueryParser.Escape(query) ``` If you do not want your users to ever use advanced syntax in their queries, you can do this always. If you want your users to use advanced syntax but you also want to be more forgiving with the mistakes you should only sanitize after a ParseException has occured.
263,086
<p>I've created a dtsx package with Sql Server Business Intelligence Development studio, and I am executing it using the dtexec utility. Using dtexec I am setting certain properties at runtime using the /set switch. So my command looks something like:</p> <pre><code>dtexec /f "mypackage.dtsx" /set \Package.Connections[Destination].Properties[UserName];myUserName </code></pre> <p>This works perfectly when I run it on my local system (the one it was developed on). Unfortunately, when I copy this package to a different system and attempt to run this exact same command, I receive the following error:</p> <pre><code>Warning: The package path referenced an object that could not be found: \Package.Connections[Destination].Properties[UserName]. This occurs when an attempt is made to resolve a package path to an object that cannot not be found. </code></pre> <p>The new system that the package was moved to has SSIS installed and is running the same version of Sql Server as my local system (SP2). Maybe I'm misunderstanding something about the intended use of dtsx packages, but I really don't see how/why this is happening.</p>
[ { "answer_id": 265086, "author": "baldy", "author_id": 2012, "author_profile": "https://Stackoverflow.com/users/2012", "pm_score": 1, "selected": false, "text": "<p>You'll need to create a deployment utility if you;re moving the package between machines. Your connection information gets encrypted using a key specific to your machine.</p>\n\n<p>If you go to the project properties in VS, Select the deployment utility section and set the CreateDeploymentUtility option to true. This will create the deployment utility in the bin folder, you can then copy all that to the new machine, run the installer, and all should work fine.</p>\n" }, { "answer_id": 323129, "author": "Dale Wright", "author_id": 11523, "author_profile": "https://Stackoverflow.com/users/11523", "pm_score": 1, "selected": false, "text": "<p>The quickest way to move packages between machines and avoid all the signing of the packages is the following.</p>\n\n<p>In Visual Studio with the package open select \"Save copy of PackageName\" As </p>\n\n<p>You then get a wizard up. Easiest one is probably to just select file store. Then at the base of the wizard you will see protection level. Select Encrypt Sensitive data with a password. Enter a password.</p>\n\n<p>On the server you wish to move it to select Import Package and it will prompt you for the password. Enter it and your connection information will be correctly move to the new server.</p>\n\n<p>Definitely not best practice but it is a good method for quickly moving things around test servers.</p>\n" }, { "answer_id": 418379, "author": "Jobo", "author_id": 51915, "author_profile": "https://Stackoverflow.com/users/51915", "pm_score": 1, "selected": false, "text": "<p>On your control flow properties, there is a property called \"ProtectionLevel\". If you set this to 'DontSaveSensitive' then that might cause you less headaches while doing dev and testing. For production scenarios where security is a requirement then you might need to find another solution.</p>\n" }, { "answer_id": 446067, "author": "Irawan Soetomo", "author_id": 54908, "author_profile": "https://Stackoverflow.com/users/54908", "pm_score": 3, "selected": false, "text": "<p>This steps is for creating an XML configuration file (.dtsConfig) which can keep your sensitive data, like the password of your connection string, without having a Protection Level that can make you difficult to move the package from one machine to another.</p>\n\n<p>In this example, assumed you have an OLE DB Connection to an SQL database called MyDb.</p>\n\n<ol>\n<li><p>Control Flow, Property: set \"ProtectionLevel\" to \"DontSaveSensitive\"</p></li>\n<li><p>Control Flow, right-click empty space to get menu: click \"Package Configuration\"</p></li>\n<li><p>Package Configuration Organizer: tick \"Enable package configuration\"; click \"Add\"</p></li>\n<li><p>Package Configuration Wizard, Select Configuration Type: set \"Configuration type\" to \"XML configuration file\"; choose \"Specify configuration directly\" radio button; click \"Browse...\"</p></li>\n<li><p>Select Configuration File Location, fill \"Filename\": [PackageName].dtsConfig (easy if same folder and same filename as the package itself, just different extension); click \"Save\"</p></li>\n<li><p>Package Configuration Wizard, Select Configuration Type: click \"Next >\"</p></li>\n<li><p>Package Configuration Wizard, Select Properties to Export: traverse the following tree nodes and tick its checkbox; click \"Next >\"</p>\n\n<p>\\[PackageName]\\Connection Managers\\MyDb\\Properties\\Connection String</p>\n\n<p>\\[PackageName]\\Connection Managers\\MyDb\\Properties\\Password</p></li>\n<li><p>Package Configuration Wizard, Completing Wizard, click \"Finish\"</p></li>\n<li><p>Package Configuration Organizer: click \"Close\"</p></li>\n<li><p>Solution Explorer: right click the root tree for menu, click \"Add\", \"Existing Item...\", click [PackageName].dtsConfig, click \"Add\"</p></li>\n<li><p>Solution Explorer: double click \\Miscellaneous\\[PackageName].dtsConfig to load into editor;</p></li>\n<li><p>Main menu: click \"Edit\", click \"Advanced\", click \"Format Document\"</p></li>\n<li><p>Traverse the XML tree node: \\DTSConfiguration\\Configuration[Path=\"\\Package.Connections[MyDb].Properties[Password]\"]\\ConfiguredValue; key in the database password; save the file</p></li>\n<li><p>Windows Explorer: navigate and double click [PackageName].dtsx</p></li>\n<li><p>Execute Package Utility, Configuration, click \"Add\", double click [PackageName].dtsConfig, click \"Execute\"</p></li>\n</ol>\n\n<p>When required to move the .dtsx to another machine, simply accompany it with its .dtsConfig. Hope this helps.</p>\n\n<p>Cheers, Ari.</p>\n" }, { "answer_id": 7850977, "author": "Huske", "author_id": 814050, "author_profile": "https://Stackoverflow.com/users/814050", "pm_score": 0, "selected": false, "text": "<p>Here are the guidelines from MSDN about package security. <a href=\"http://msdn.microsoft.com/en-us/library/ms141747.aspx\" rel=\"nofollow\">Setting the Protection Level of Packages</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2327/" ]
I've created a dtsx package with Sql Server Business Intelligence Development studio, and I am executing it using the dtexec utility. Using dtexec I am setting certain properties at runtime using the /set switch. So my command looks something like: ``` dtexec /f "mypackage.dtsx" /set \Package.Connections[Destination].Properties[UserName];myUserName ``` This works perfectly when I run it on my local system (the one it was developed on). Unfortunately, when I copy this package to a different system and attempt to run this exact same command, I receive the following error: ``` Warning: The package path referenced an object that could not be found: \Package.Connections[Destination].Properties[UserName]. This occurs when an attempt is made to resolve a package path to an object that cannot not be found. ``` The new system that the package was moved to has SSIS installed and is running the same version of Sql Server as my local system (SP2). Maybe I'm misunderstanding something about the intended use of dtsx packages, but I really don't see how/why this is happening.
This steps is for creating an XML configuration file (.dtsConfig) which can keep your sensitive data, like the password of your connection string, without having a Protection Level that can make you difficult to move the package from one machine to another. In this example, assumed you have an OLE DB Connection to an SQL database called MyDb. 1. Control Flow, Property: set "ProtectionLevel" to "DontSaveSensitive" 2. Control Flow, right-click empty space to get menu: click "Package Configuration" 3. Package Configuration Organizer: tick "Enable package configuration"; click "Add" 4. Package Configuration Wizard, Select Configuration Type: set "Configuration type" to "XML configuration file"; choose "Specify configuration directly" radio button; click "Browse..." 5. Select Configuration File Location, fill "Filename": [PackageName].dtsConfig (easy if same folder and same filename as the package itself, just different extension); click "Save" 6. Package Configuration Wizard, Select Configuration Type: click "Next >" 7. Package Configuration Wizard, Select Properties to Export: traverse the following tree nodes and tick its checkbox; click "Next >" \[PackageName]\Connection Managers\MyDb\Properties\Connection String \[PackageName]\Connection Managers\MyDb\Properties\Password 8. Package Configuration Wizard, Completing Wizard, click "Finish" 9. Package Configuration Organizer: click "Close" 10. Solution Explorer: right click the root tree for menu, click "Add", "Existing Item...", click [PackageName].dtsConfig, click "Add" 11. Solution Explorer: double click \Miscellaneous\[PackageName].dtsConfig to load into editor; 12. Main menu: click "Edit", click "Advanced", click "Format Document" 13. Traverse the XML tree node: \DTSConfiguration\Configuration[Path="\Package.Connections[MyDb].Properties[Password]"]\ConfiguredValue; key in the database password; save the file 14. Windows Explorer: navigate and double click [PackageName].dtsx 15. Execute Package Utility, Configuration, click "Add", double click [PackageName].dtsConfig, click "Execute" When required to move the .dtsx to another machine, simply accompany it with its .dtsConfig. Hope this helps. Cheers, Ari.
263,101
<p>I'm using an Informix (Version 7.32) DB. On one operation I create a temp table with the ID of a regular table and a serial column (so I would have all the IDs from the regular table numbered continuously). But I want to insert the info from the regular table ordered by ID something like: </p> <pre><code>CREATE TEMP TABLE tempTable (id serial, folio int ); INSERT INTO tempTable(id,folio) SELECT 0,folio FROM regularTable ORDER BY folio; </code></pre> <p>But this creates a syntax error (because of the ORDER BY)</p> <p>Is there any way I can order the info then insert it to the tempTable?</p> <p>UPDATE: The reason I want to do this is because the regular table has about 10,000 items and in a jsp file, it has to show every record, but it would take to long, so the real reason I want to do this is to <em>paginate</em> the output. This version of Informix doesn't have <code>Limit</code> nor <code>Skip</code>. I can't renumber the serial because is in a relationship, and this is the only solution we could get a fixed number of results on one page (for example 500 results per page). In the Regular table has skipped id's (called folio) because they have been deleted. if i were to put </p> <pre><code>SELECT * FROM regularTable WHERE folio BETWEEN X AND Y </code></pre> <p>I would get maybe 300 in one page, then 500 in the next page </p>
[ { "answer_id": 263176, "author": "Dema", "author_id": 407003, "author_profile": "https://Stackoverflow.com/users/407003", "pm_score": 1, "selected": true, "text": "<p>You might try it iterating a cursor over the SELECT ... ORDER BY and doing the INSERTs within the loop.</p>\n" }, { "answer_id": 263187, "author": "kurosch", "author_id": 30153, "author_profile": "https://Stackoverflow.com/users/30153", "pm_score": 1, "selected": false, "text": "<p>It's been years since I worked on Informix, but perhaps something like this will work:</p>\n\n<pre><code>INSERT INTO tempTable(id,folio)\nSELECT 0, folio \nFROM (\n SELECT folio FROM regularTable ORDER BY folio\n);\n</code></pre>\n" }, { "answer_id": 263299, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "<p>In Informix when using a SELECT as a sub-clause in an INSERT statement, you are <strong>limited \nto a subset of the SELECT syntax</strong>. </p>\n\n<p>The following SELECT clauses are not supported in this case:</p>\n\n<ul>\n<li>INTO TEMP</li>\n<li>ORDER BY</li>\n<li>UNION. </li>\n</ul>\n\n<p>Additionally, the FROM clause of the SELECT can not reference the same table as referenced by the INSERT (not that this matters in your case). </p>\n" }, { "answer_id": 263498, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>It makes no sense to order the rows as you insert into a table. Relational databases do not allow you to specify the order of rows in a table. </p>\n\n<p>Even if you could, SQL does not guarantee a query will return rows in any order, such as the order you inserted them. You must specify an <code>ORDER BY</code> clause to guarantee an order for a query result. </p>\n\n<p>So it would do you no good to change the order in which you insert the rows.</p>\n" }, { "answer_id": 264225, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 0, "selected": false, "text": "<p>As stated by Bill, there's not a lot of point ordering the input, you really need to order the output. In the simplistic example you've provided, it just makes no sense, so I can only assume that the real problem you're trying to solve is more complex - deduplication perhaps?</p>\n\n<p>The functionality you're after is <code>CREATE SEQUENCE</code>, but I'm pretty sure it's not available in such an old version of Informix.</p>\n\n<p>If you really need to do what you're asking, you could look into <code>UNLOAD</code>ing the data in the required order, and then <code>LOAD</code>ing it again. That would ensure the SERIAL values get allocated sequentially.</p>\n" }, { "answer_id": 266638, "author": "kurosch", "author_id": 30153, "author_profile": "https://Stackoverflow.com/users/30153", "pm_score": 0, "selected": false, "text": "<p>Would something like this work?</p>\n\n<pre><code>SELECT\n folio\nFROM\n (\n SELECT\n ROWNUM n,\n folio\n FROM\n regularTable\n ORDER BY \n folio\n )\nWHERE\n n BETWEEN 501 AND 1000\n</code></pre>\n\n<p>It may not be terribly efficient if the table grows larger or you're fetching later \"pages\", but 10K rows is pretty small.</p>\n\n<p>I don't recall if Informix has a ROWNUM concept, I use Oracle.</p>\n" }, { "answer_id": 5861208, "author": "YWard", "author_id": 734960, "author_profile": "https://Stackoverflow.com/users/734960", "pm_score": 2, "selected": false, "text": "<p>You can do this by breaking up the SQL into two temp tables:</p>\n\n<pre><code>CREATE TEMP TABLE tempTable1 (\nid serial,\nfolio int);\n\nSELECT folio FROM regularTable ORDER BY folio\nINTO TEMP tempTable2;\n\nINSERT INTO tempTable1(id,folio) SELECT 0,folio FROM tempTable2;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23146/" ]
I'm using an Informix (Version 7.32) DB. On one operation I create a temp table with the ID of a regular table and a serial column (so I would have all the IDs from the regular table numbered continuously). But I want to insert the info from the regular table ordered by ID something like: ``` CREATE TEMP TABLE tempTable (id serial, folio int ); INSERT INTO tempTable(id,folio) SELECT 0,folio FROM regularTable ORDER BY folio; ``` But this creates a syntax error (because of the ORDER BY) Is there any way I can order the info then insert it to the tempTable? UPDATE: The reason I want to do this is because the regular table has about 10,000 items and in a jsp file, it has to show every record, but it would take to long, so the real reason I want to do this is to *paginate* the output. This version of Informix doesn't have `Limit` nor `Skip`. I can't renumber the serial because is in a relationship, and this is the only solution we could get a fixed number of results on one page (for example 500 results per page). In the Regular table has skipped id's (called folio) because they have been deleted. if i were to put ``` SELECT * FROM regularTable WHERE folio BETWEEN X AND Y ``` I would get maybe 300 in one page, then 500 in the next page
You might try it iterating a cursor over the SELECT ... ORDER BY and doing the INSERTs within the loop.
263,116
<p>I'm running into a common pattern in the code that I'm writing, where I need to wait for all threads in a group to complete, with a timeout. The timeout is supposed to be the time required for <em>all</em> threads to complete, so simply doing <code>Thread.Join(timeout)</code> for each thread won't work, since the possible timeout is then <code>timeout * numThreads</code>.</p> <p>Right now I do something like the following:</p> <pre><code>var threadFinishEvents = new List&lt;EventWaitHandle&gt;(); foreach (DataObject data in dataList) { // Create local variables for the thread delegate var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset); threadFinishEvents.Add(threadFinish); var localData = (DataObject) data.Clone(); var thread = new Thread( delegate() { DoThreadStuff(localData); threadFinish.Set(); } ); thread.Start(); } Mutex.WaitAll(threadFinishEvents.ToArray(), timeout); </code></pre> <p>However, it seems like there should be a simpler idiom for this sort of thing.</p>
[ { "answer_id": 263170, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 3, "selected": false, "text": "<p>Off the top of my head, why don't you just Thread.Join(timeout) and remove the time it took to join from the total timeout?</p>\n\n<pre><code>// pseudo-c#:\n\nTimeSpan timeout = timeoutPerThread * threads.Count();\n\nforeach (Thread thread in threads)\n{\n DateTime start = DateTime.Now;\n\n if (!thread.Join(timeout))\n throw new TimeoutException();\n\n timeout -= (DateTime.Now - start);\n}\n</code></pre>\n\n<p><strong>Edit:</strong> code is now less pseudo. don't understand why you would mod an answer -2 when the answer you modded +4 is exactly the same, only less detailed.</p>\n" }, { "answer_id": 263186, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 6, "selected": true, "text": "<p>I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do </p>\n\n<pre><code>if(!thread.Join(End-now))\n throw new NotFinishedInTime();\n</code></pre>\n" }, { "answer_id": 263223, "author": "Jon Norton", "author_id": 4797, "author_profile": "https://Stackoverflow.com/users/4797", "pm_score": 3, "selected": false, "text": "<p>This may not be an option for you, but if you can use the Parallel Extension for .NET then you could use <code>Task</code>s instead of raw threads and then use <code>Task.WaitAll()</code> to wait for them to complete.</p>\n" }, { "answer_id": 3840304, "author": "Dylan", "author_id": 463988, "author_profile": "https://Stackoverflow.com/users/463988", "pm_score": 0, "selected": false, "text": "<p>I was tying to figure out how to do this but i could not get any answers from google.\nI know this is an old thread but here was my solution:</p>\n\n<p>Use the following class:</p>\n\n<pre><code>class ThreadWaiter\n {\n private int _numThreads = 0;\n private int _spinTime;\n\n public ThreadWaiter(int SpinTime)\n {\n this._spinTime = SpinTime;\n }\n\n public void AddThreads(int numThreads)\n {\n _numThreads += numThreads;\n }\n\n public void RemoveThread()\n {\n if (_numThreads &gt; 0)\n {\n _numThreads--;\n }\n }\n\n public void Wait()\n {\n while (_numThreads != 0)\n {\n System.Threading.Thread.Sleep(_spinTime);\n }\n }\n }\n</code></pre>\n\n<ol>\n<li>Call Addthreads(int numThreads) before executing a thread(s).</li>\n<li>Call RemoveThread() after each one has completed.</li>\n<li>Use Wait() at the point that you want to wait for all the threads to complete\nbefore continuing</li>\n</ol>\n" }, { "answer_id": 3902923, "author": "Brian Gideon", "author_id": 158779, "author_profile": "https://Stackoverflow.com/users/158779", "pm_score": 3, "selected": false, "text": "<p>Since the question got bumped I will go ahead and post my solution.</p>\n\n<pre><code>using (var finished = new CountdownEvent(1)) \n{ \n for (DataObject data in dataList) \n { \n finished.AddCount();\n var localData = (DataObject)data.Clone(); \n var thread = new Thread( \n delegate() \n {\n try\n {\n DoThreadStuff(localData); \n threadFinish.Set();\n }\n finally\n {\n finished.Signal();\n }\n } \n ); \n thread.Start(); \n } \n finished.Signal(); \n finished.Wait(YOUR_TIMEOUT); \n} \n</code></pre>\n" }, { "answer_id": 6380075, "author": "T. Webster", "author_id": 266457, "author_profile": "https://Stackoverflow.com/users/266457", "pm_score": 4, "selected": false, "text": "<p>With .NET 4.0 I find <a href=\"http://msdn.microsoft.com/en-us/library/dd235608.aspx\" rel=\"noreferrer\">System.Threading.Tasks</a> a lot easier to work with. Here's spin-wait loop which works reliably for me. It blocks the main thread until all the tasks complete. There's also <a href=\"http://msdn.microsoft.com/en-us/library/dd270695.aspx\" rel=\"noreferrer\">Task.WaitAll</a>, but that hasn't always worked for me.</p>\n\n<pre><code> for (int i = 0; i &lt; N; i++)\n {\n tasks[i] = Task.Factory.StartNew(() =&gt;\n { \n DoThreadStuff(localData);\n });\n }\n while (tasks.Any(t =&gt; !t.IsCompleted)) { } //spin wait\n</code></pre>\n" }, { "answer_id": 12903899, "author": "Alex Aza", "author_id": 732945, "author_profile": "https://Stackoverflow.com/users/732945", "pm_score": 0, "selected": false, "text": "<p>Possible solution:</p>\n\n<pre><code>var tasks = dataList\n .Select(data =&gt; Task.Factory.StartNew(arg =&gt; DoThreadStuff(data), TaskContinuationOptions.LongRunning | TaskContinuationOptions.PreferFairness))\n .ToArray();\n\nvar timeout = TimeSpan.FromMinutes(1);\nTask.WaitAll(tasks, timeout);\n</code></pre>\n\n<p>Assuming dataList is the list of items and each item needs to be processed in a separate thread.</p>\n" }, { "answer_id": 18745935, "author": "Bùi Công Giao", "author_id": 2769419, "author_profile": "https://Stackoverflow.com/users/2769419", "pm_score": 1, "selected": false, "text": "<p>I read the book C# 4.0: The Complete Reference of Herbert Schildt. The author use join to give a solution : </p>\n\n<pre><code>class MyThread\n {\n public int Count;\n public Thread Thrd;\n public MyThread(string name)\n {\n Count = 0;\n Thrd = new Thread(this.Run);\n Thrd.Name = name;\n Thrd.Start();\n }\n // Entry point of thread.\n void Run()\n {\n Console.WriteLine(Thrd.Name + \" starting.\");\n do\n {\n Thread.Sleep(500);\n Console.WriteLine(\"In \" + Thrd.Name +\n \", Count is \" + Count);\n Count++;\n } while (Count &lt; 10);\n Console.WriteLine(Thrd.Name + \" terminating.\");\n }\n }\n // Use Join() to wait for threads to end.\n class JoinThreads\n {\n static void Main()\n {\n Console.WriteLine(\"Main thread starting.\");\n // Construct three threads.\n MyThread mt1 = new MyThread(\"Child #1\");\n MyThread mt2 = new MyThread(\"Child #2\");\n MyThread mt3 = new MyThread(\"Child #3\");\n mt1.Thrd.Join();\n Console.WriteLine(\"Child #1 joined.\");\n mt2.Thrd.Join();\n Console.WriteLine(\"Child #2 joined.\");\n mt3.Thrd.Join();\n Console.WriteLine(\"Child #3 joined.\");\n Console.WriteLine(\"Main thread ending.\");\n Console.ReadKey();\n }\n }\n</code></pre>\n" }, { "answer_id": 20897995, "author": "Vincent", "author_id": 2352618, "author_profile": "https://Stackoverflow.com/users/2352618", "pm_score": 4, "selected": false, "text": "<p>This doesn't answer the question (no timeout), but I've made a very simple extension method to wait all threads of a collection:</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Threading;\nnamespace Extensions\n{\n public static class ThreadExtension\n {\n public static void WaitAll(this IEnumerable&lt;Thread&gt; threads)\n {\n if(threads!=null)\n {\n foreach(Thread thread in threads)\n { thread.Join(); }\n }\n }\n }\n}\n</code></pre>\n\n<p>Then you simply call:</p>\n\n<pre><code>List&lt;Thread&gt; threads=new List&lt;Thread&gt;();\n//Add your threads to this collection\nthreads.WaitAll();\n</code></pre>\n" }, { "answer_id": 74035618, "author": "Theodor Zoulias", "author_id": 11178549, "author_profile": "https://Stackoverflow.com/users/11178549", "pm_score": 0, "selected": false, "text": "<p>Here is an implementation inspired by <a href=\"https://stackoverflow.com/a/263186/11178549\">Martin v. Löwis</a>'s answer:</p>\n<pre><code>/// &lt;summary&gt;\n/// Blocks the calling thread until all threads terminate, or the specified\n/// time elapses. Returns true if all threads terminated in time, or false if\n/// at least one thread has not terminated after the specified amount of time\n/// elapsed.\n/// &lt;/summary&gt;\npublic static bool JoinAll(IEnumerable&lt;Thread&gt; threads, TimeSpan timeout)\n{\n ArgumentNullException.ThrowIfNull(threads);\n if (timeout &lt; TimeSpan.Zero)\n throw new ArgumentOutOfRangeException(nameof(timeout));\n\n Stopwatch stopwatch = Stopwatch.StartNew();\n foreach (Thread thread in threads)\n {\n if (!thread.IsAlive) continue;\n TimeSpan remaining = timeout - stopwatch.Elapsed;\n if (remaining &lt; TimeSpan.Zero) return false;\n if (!thread.Join(remaining)) return false;\n }\n return true;\n}\n</code></pre>\n<p>For measuring the remaining time, instead of the <code>DateTime.Now</code> it uses a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch\" rel=\"nofollow noreferrer\"><code>Stopwatch</code></a>. The <code>Stopwatch</code> component is not sensitive to system-wide clock adjustments.</p>\n<p>Usage example:</p>\n<pre><code>bool allTerminated = JoinAll(new[] { thread1, thread2 }, TimeSpan.FromSeconds(10));\n</code></pre>\n<p>The <code>timeout</code> must be a positive or zero <code>TimeSpan</code>. The <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.timeout.infinitetimespan\" rel=\"nofollow noreferrer\"><code>Timeout.InfiniteTimeSpan</code></a> constant is not supported.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8078/" ]
I'm running into a common pattern in the code that I'm writing, where I need to wait for all threads in a group to complete, with a timeout. The timeout is supposed to be the time required for *all* threads to complete, so simply doing `Thread.Join(timeout)` for each thread won't work, since the possible timeout is then `timeout * numThreads`. Right now I do something like the following: ``` var threadFinishEvents = new List<EventWaitHandle>(); foreach (DataObject data in dataList) { // Create local variables for the thread delegate var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset); threadFinishEvents.Add(threadFinish); var localData = (DataObject) data.Clone(); var thread = new Thread( delegate() { DoThreadStuff(localData); threadFinish.Set(); } ); thread.Start(); } Mutex.WaitAll(threadFinishEvents.ToArray(), timeout); ``` However, it seems like there should be a simpler idiom for this sort of thing.
I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do ``` if(!thread.Join(End-now)) throw new NotFinishedInTime(); ```
263,121
<p>Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes</p>
[ { "answer_id": 263174, "author": "David Koelle", "author_id": 2197, "author_profile": "https://Stackoverflow.com/users/2197", "pm_score": 2, "selected": false, "text": "<p>Java's answer to multiple inheritance is the ability to implement multiple interfaces. Of course, this means you'll get the method declarations, but not the logic.</p>\n\n<p>You could try emulating mixins by composition: your Java class could define member variables that represent other classes that perform some common business logic.</p>\n\n<p>In designing Java classes, I have not found the lack of C++ style multiple inheritance to inhibit the design of my architecture. You will find a way to achieve what you want to do.</p>\n" }, { "answer_id": 263178, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 4, "selected": false, "text": "<p>Not the way you want to do it. <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321356683\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java</a> recommends that you \"Favor composition over inheritance\". Meaning you move the common logic to other classes and delegate. This is how you get around the lack of multiple inheritance in java. </p>\n" }, { "answer_id": 263184, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 5, "selected": true, "text": "<p>I would encapsulate all of the business logic into a new class <code>BusinessLogic</code> and have each class that needs <code>BusinessLogic</code> make calls to the class. If you need a single rooted heirarchy for your classes that make calls to <code>BusinessLogic</code>, you'll have to create an interface as well (<code>BusinessLogicInterface</code>?)</p>\n\n<p>In pseudo-code:</p>\n\n<pre><code>interface BusinessLogicInterace\n{\n void method1();\n void method2();\n}\n\nclass BusinessLogic implements BusinessLogicInterface\n{\n void method1() { ... }\n void method2() { ... }\n}\n\nclass User \n extends OtherClass \n implements BusinessLogicInterface\n{\n BusinessLogic logic = new BusinessLogic();\n\n @Override\n void method1() { logic.method1(); }\n\n @Override\n void method2() { logic.method2(); }\n}\n</code></pre>\n\n<p>This isn't the prettiest implementation to work around a lack of multiple inheritance and it becomes quite cumbersome when the interface has a lot of methods. Most likely, you'll want to try and redesign your code to avoid needing mixins.</p>\n" }, { "answer_id": 263311, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 3, "selected": false, "text": "<p>Is the object-purist stirring in you today?</p>\n<p>Think you could do with a little <em>composite oriented programming?</em></p>\n<p>Then you, sir, are looking for <a href=\"http://polygene.apache.org/\" rel=\"nofollow noreferrer\">Apache Polygene</a> (formerly named Qi4J, then it renamed to Zest and/or Apache-Zest) ;)</p>\n<p><strong>Update 2022;</strong> It's discontinued currently, but useful anyway.</p>\n" }, { "answer_id": 3936001, "author": "Pablo La Greca", "author_id": 476103, "author_profile": "https://Stackoverflow.com/users/476103", "pm_score": 2, "selected": false, "text": "<p>QI4J allows you to use mixins</p>\n" }, { "answer_id": 7848653, "author": "x_rex", "author_id": 1006977, "author_profile": "https://Stackoverflow.com/users/1006977", "pm_score": 0, "selected": false, "text": "<p>Implementing simple mixin/traits support in java using CGLib/javassit is quite easy.\nYou can take a look for instance <a href=\"http://justonjava.blogspot.com/2011/10/mixins-aka-traits-implementation-in.html\" rel=\"nofollow\">here</a> for small example.\nMore complete, ready to use solution might be found: <a href=\"http://insightfullogic.com/blog/2011/sep/16/multiple-inheritance/\" rel=\"nofollow\">here</a></p>\n" }, { "answer_id": 16337353, "author": "Henno Vermeulen", "author_id": 593533, "author_profile": "https://Stackoverflow.com/users/593533", "pm_score": 2, "selected": false, "text": "<p>You can exploit the fact that interfaces allow nested classes (automatically public static) to keep the default implementation of the interface methods encapsulated within the interface itself. I.e. move the BusinessLogic class of Alex B's example inside the interface.</p>\n\n<p>This is similar to the way Scala generates the JVM code for traits as explained here <a href=\"https://stackoverflow.com/questions/2557303/how-are-scala-traits-compiled-into-java-bytecode\">How are Scala traits compiled into Java bytecode?</a></p>\n\n<p>When doing this the example becomes:</p>\n\n<pre><code>interface BusinessLogicInterface {\n void method0();\n\n class DefaultImpl {\n private DefaultImpl() {\n }\n\n public static void method1(BusinessLogicInterface self) { ... }\n public static void method2(BusinessLogicInterface self) { ... }\n }\n\n void method1();\n void method2();\n}\n\nclass User extends OtherClass implements BusinessLogicInterface {\n @Override\n void method0() { ... }\n\n @Override\n void method1() { BusinessLogic.defaultImpl.method1(this); }\n\n @Override\n void method2() { BusinessLogic.defaultImpl.method2(this); }\n}\n</code></pre>\n\n<p>Note that we pass an object of the interface type as the \"self\" parameter. This means the business logic can use other abstract methods (method0). This can be very useful for creating a trait with abstract methods that are all orthogonal to each other and utility \"extension\" methods that may be implemented in terms of these orthogonal methods.</p>\n\n<p>The drawback is that each interface must copy/paste the boilerplate delegation code. Another often used pattern in Java without this drawback (but with less cohesion and less OO way to call the methods) is to create a class with the plural name as the interface containing the static methods, this is used in the Collections utility class.</p>\n" }, { "answer_id": 30299686, "author": "user3478180", "author_id": 3478180, "author_profile": "https://Stackoverflow.com/users/3478180", "pm_score": 2, "selected": false, "text": "<p>As of Java-8, default interface methods were added. This, together with multiple inheritance of interfaces in Java should allow some sort of mixin. Clearly the interfaces have to operate independently. So, there will be significant limitations. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20641/" ]
Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes
I would encapsulate all of the business logic into a new class `BusinessLogic` and have each class that needs `BusinessLogic` make calls to the class. If you need a single rooted heirarchy for your classes that make calls to `BusinessLogic`, you'll have to create an interface as well (`BusinessLogicInterface`?) In pseudo-code: ``` interface BusinessLogicInterace { void method1(); void method2(); } class BusinessLogic implements BusinessLogicInterface { void method1() { ... } void method2() { ... } } class User extends OtherClass implements BusinessLogicInterface { BusinessLogic logic = new BusinessLogic(); @Override void method1() { logic.method1(); } @Override void method2() { logic.method2(); } } ``` This isn't the prettiest implementation to work around a lack of multiple inheritance and it becomes quite cumbersome when the interface has a lot of methods. Most likely, you'll want to try and redesign your code to avoid needing mixins.
263,122
<p>I'm writing an image bank with Django, and I want to add a button to get a hi-res version of an image (the low-res is shown in the details page). If I put just an <code>&lt;a&gt;</code> link, the browser will open the image instead of downloading it. Adding an HTTP header like:</p> <pre><code>Content-Disposition: attachment; filename="beach008.jpg" </code></pre> <p>works, but since it's an static file, I don't want to handle the request with Django. Currently, I'm using NGINX to serve static files, and dynamic pages are redirected via FastCGI to the Django process. I'm thinking about using NGINX <code>add-header</code> command, but could it set the <code>filename="xx"</code> part?. Or maybe there's some way to handle the request in Django, but make NGINX serve the content?</p>
[ { "answer_id": 263554, "author": "Andrew Kurinnyi", "author_id": 33887, "author_profile": "https://Stackoverflow.com/users/33887", "pm_score": 2, "selected": false, "text": "<p>I wrote a simple decorator, for django.views.static.serve view</p>\n\n<p>Which works for me perfectly. </p>\n\n<pre><code>def serve_download(view_func):\n def _wrapped_view_func(request, *args, **kwargs):\n response = view_func(request, *args, **kwargs)\n response['Content-Type'] = 'application/octet-stream';\n import os.path\n response['Content-Disposition'] = 'attachment; filename=\"%s\"' % os.path.basename(kwargs['path'])\n return response\n return _wrapped_view_func\n</code></pre>\n\n<p>Also you can play with nginx mime-types </p>\n\n<p><a href=\"http://wiki.codemongers.com/NginxHttpCoreModule#types\" rel=\"nofollow noreferrer\">http://wiki.codemongers.com/NginxHttpCoreModule#types</a></p>\n\n<p>This solution didn't work for me, because I wanted to have both direct link for the file (so user can view images, for example), and download link.</p>\n" }, { "answer_id": 263671, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 0, "selected": false, "text": "<p>What i'm doing now is to use a different URL for download than for 'views', and add the filename as an URL arg:</p>\n\n<p>usual media link: <code>http://xx.com/media/images/lores/f_123123.jpg</code>\ndownload link: <code>http://xx.com/downs/hires/f_12323?beach008.jpg</code></p>\n\n<p>and nginx has a config like this:</p>\n\n<pre><code> location /downs/ {\n root /var/www/nginx-attachment;\n add_header Content-Disposition 'attachment; filename=\"$args\"';\n }\n</code></pre>\n\n<p>but i really don't like the smell of it.</p>\n" }, { "answer_id": 386460, "author": "Vasil", "author_id": 7883, "author_profile": "https://Stackoverflow.com/users/7883", "pm_score": 4, "selected": true, "text": "<p>If your django app is proxied by nginx you can use <a href=\"http://blog.kovyrin.net/2006/11/01/nginx-x-accel-redirect-php-rails/\" rel=\"nofollow noreferrer\">x-accell-redirect</a>. You need to pass a special header in your response, nginx will intercepet this and start serving the file, you can also pass Content-Disposition in the same response to force a download.</p>\n\n<p>That solution is good if you want to control which users acess these files. </p>\n\n<p>You can also use a configuration like this:</p>\n\n<pre><code> #files which need to be forced downloads\n location /static/high_res/ {\n root /project_root;\n\n #don't ever send $request_filename in your response, it will expose your dir struct, use a quick regex hack to find just the filename\n if ($request_filename ~* ^.*?/([^/]*?)$) {\n set $filename $1;\n }\n\n #match images\n if ($filename ~* ^.*?\\.((jpg)|(png)|(gif))$) {\n add_header Content-Disposition \"attachment; filename=$filename\";\n }\n }\n\n location /static {\n root /project_root;\n }\n</code></pre>\n\n<p>This will force download on all images in some high_res folder (MEDIAROOT/high_rest). And for the other static files it will behave like normal. Please note that this is a modified quick hack that works for me. It may have security implications, so use it with precaution.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11649/" ]
I'm writing an image bank with Django, and I want to add a button to get a hi-res version of an image (the low-res is shown in the details page). If I put just an `<a>` link, the browser will open the image instead of downloading it. Adding an HTTP header like: ``` Content-Disposition: attachment; filename="beach008.jpg" ``` works, but since it's an static file, I don't want to handle the request with Django. Currently, I'm using NGINX to serve static files, and dynamic pages are redirected via FastCGI to the Django process. I'm thinking about using NGINX `add-header` command, but could it set the `filename="xx"` part?. Or maybe there's some way to handle the request in Django, but make NGINX serve the content?
If your django app is proxied by nginx you can use [x-accell-redirect](http://blog.kovyrin.net/2006/11/01/nginx-x-accel-redirect-php-rails/). You need to pass a special header in your response, nginx will intercepet this and start serving the file, you can also pass Content-Disposition in the same response to force a download. That solution is good if you want to control which users acess these files. You can also use a configuration like this: ``` #files which need to be forced downloads location /static/high_res/ { root /project_root; #don't ever send $request_filename in your response, it will expose your dir struct, use a quick regex hack to find just the filename if ($request_filename ~* ^.*?/([^/]*?)$) { set $filename $1; } #match images if ($filename ~* ^.*?\.((jpg)|(png)|(gif))$) { add_header Content-Disposition "attachment; filename=$filename"; } } location /static { root /project_root; } ``` This will force download on all images in some high\_res folder (MEDIAROOT/high\_rest). And for the other static files it will behave like normal. Please note that this is a modified quick hack that works for me. It may have security implications, so use it with precaution.
263,129
<p>I have a php script and i'm using ajax with it. I have a textarea form connect with the ajax class</p> <p>The problem when I pass a text like (<code>&amp;some text</code>) the function return an empty text, I guess that I have a problem with (<code>&amp;</code>).</p> <p>The javascript function:</p> <pre><code>function sendFormData(idForm, dataSource, divID, ifLoading) { var postData=''; var strReplaceTemp; if(XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader("Method", "POST " + dataSource + " HTTP/1.1"); XMLHttpRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 &amp;&amp; XMLHttpRequestObject.status == 200) { try { var objDiv = document.getElementById(divID); objDiv.innerHTML = XMLHttpRequestObject.responseText; } catch(e){document.write("sendFormData: getElementById(divID) Error");} } else { if(ifLoading) { try { var objDiv = document.getElementById(divID); objDiv.innerHTML = "&lt;img src=loading.gif&gt;"; } catch(e){document.write("sendFormData-&gt;ifLoading: getElementById(divID) Error");} } } } for(i=0; i&lt;document.getElementById(idForm).elements.length - 1; i++) { strReplaceTemp = document.getElementById(idForm).elements[i].name; postData += "&amp;aryFormData["+strReplaceTemp+"][]="+document.getElementById(idForm).elements[i].value; } postData += "&amp;parm="+new Date().getTime(); try { XMLHttpRequestObject.send(postData); } catch(e){document.write("sendFormData: XMLHttpRequestObject.send Error");} } } </code></pre>
[ { "answer_id": 263161, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 0, "selected": false, "text": "<p>when i see HTML and &amp; and problem, i look to make sure that my character encoding is all properly specified. </p>\n\n<p>also, the code in your PHP script may be choking on an un/escaped '&amp;' character.</p>\n" }, { "answer_id": 263179, "author": "Blank", "author_id": 19521, "author_profile": "https://Stackoverflow.com/users/19521", "pm_score": 1, "selected": false, "text": "<p>Make sure your &amp; is encoded with &amp;amp; if you're passing it using Javascript. All &amp; need to be encoded, or some browsers can freak out a bit, and any validater will complain at you.</p>\n" }, { "answer_id": 263224, "author": "Eric Caron", "author_id": 34340, "author_profile": "https://Stackoverflow.com/users/34340", "pm_score": 0, "selected": false, "text": "<p>In your function, if you wrap document.getElementById(idForm).elements[i].value and even strReplaceTemp (in your postData +=) line with \"encodeURI()\", you won't have any issues with the data being properly received.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ]
I have a php script and i'm using ajax with it. I have a textarea form connect with the ajax class The problem when I pass a text like (`&some text`) the function return an empty text, I guess that I have a problem with (`&`). The javascript function: ``` function sendFormData(idForm, dataSource, divID, ifLoading) { var postData=''; var strReplaceTemp; if(XMLHttpRequestObject) { XMLHttpRequestObject.open("POST", dataSource); XMLHttpRequestObject.setRequestHeader("Method", "POST " + dataSource + " HTTP/1.1"); XMLHttpRequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); XMLHttpRequestObject.onreadystatechange = function() { if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) { try { var objDiv = document.getElementById(divID); objDiv.innerHTML = XMLHttpRequestObject.responseText; } catch(e){document.write("sendFormData: getElementById(divID) Error");} } else { if(ifLoading) { try { var objDiv = document.getElementById(divID); objDiv.innerHTML = "<img src=loading.gif>"; } catch(e){document.write("sendFormData->ifLoading: getElementById(divID) Error");} } } } for(i=0; i<document.getElementById(idForm).elements.length - 1; i++) { strReplaceTemp = document.getElementById(idForm).elements[i].name; postData += "&aryFormData["+strReplaceTemp+"][]="+document.getElementById(idForm).elements[i].value; } postData += "&parm="+new Date().getTime(); try { XMLHttpRequestObject.send(postData); } catch(e){document.write("sendFormData: XMLHttpRequestObject.send Error");} } } ```
Make sure your & is encoded with &amp; if you're passing it using Javascript. All & need to be encoded, or some browsers can freak out a bit, and any validater will complain at you.
263,151
<p>Generally, when using the conditional operator, here's the syntax:</p> <pre><code>int x = 6; int y = x == 6 ? 5 : 9; </code></pre> <p>Nothing fancy, pretty straight forward.</p> <p>Now, let's try to use this when assigning a Lambda to a Func type. Let me explain:</p> <pre><code>Func&lt;Order, bool&gt; predicate = id == null ? p =&gt; p.EmployeeID == null : p =&gt; p.EmployeeID == id; </code></pre> <p>That's the same syntax, and <em>should</em> work? Right? For some reason that doesn't. The compiler gives this nice cryptic message:</p> <blockquote> <p>Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression'</p> </blockquote> <p>I then went ahead and changed the syntax and this way it <em>did</em> work:</p> <pre><code>Func&lt;Order, bool&gt; predicate = id == null ? predicate = p =&gt; p.EmployeeID == null : predicate = p =&gt; p.EmployeeID == id; </code></pre> <p>I'm just curious as to why it doesn't work the first way?</p> <p>(Side note: I ended up not needing this code, as I found out that when comparing an int value against null, you just use object.Equals)</p>
[ { "answer_id": 263177, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "<p>You can convert a lambda expression to a particular target delegate type, but in order to determine the type of the conditional expression, the compiler needs to know the type of each of the second and third operands. While they're both just \"lambda expression\" there's no conversion from one to the other, so the compiler can't do anything useful.</p>\n\n<p>I wouldn't suggest using an assignment, however - a cast is more obvious:</p>\n\n<pre><code>Func&lt;Order, bool&gt; predicate = id == null \n ? (Func&lt;Order, bool&gt;) (p =&gt; p.EmployeeID == null)\n : p =&gt; p.EmployeeID == id;\n</code></pre>\n\n<p>Note that you only need to provide it for one operand, so the compiler can perform the conversion from the other lambda expression.</p>\n" }, { "answer_id": 263183, "author": "Jake", "author_id": 24730, "author_profile": "https://Stackoverflow.com/users/24730", "pm_score": 3, "selected": false, "text": "<p>The C# compiler cannot infer the type of the created lambda expression because it processes the ternary first and then the assignment. you could also do:</p>\n\n<pre><code>Func&lt;Order, bool&gt; predicate = \n id == null ? \n new Func&lt;Order,bool&gt;(p =&gt; p.EmployeeID == null) :\n new Func&lt;Order,bool&gt;(p =&gt; p.EmployeeID == id);\n</code></pre>\n\n<p>but that just sucks,\nyou could also try</p>\n\n<pre><code>Func&lt;Order, bool&gt; predicate = \n id == null ? \n (Order p) =&gt; p.EmployeeID == null :\n (Order p) =&gt; p.EmployeeID == id;\n</code></pre>\n" }, { "answer_id": 48275048, "author": "Elnaz", "author_id": 5620296, "author_profile": "https://Stackoverflow.com/users/5620296", "pm_score": 1, "selected": false, "text": "<p>Let me have my own example since I had the same problem, too (with the hope that the example be helpful for others):</p>\n\n<p>My <code>Find</code> method is generic method that gets <code>Expression&lt;Func&lt;T, bool&gt;&gt;</code> as predicate and gives <code>List&lt;T&gt;</code> as output.<br>\nI wanted to find countries, but I need all of them if language list was empty, and filtered list, if language list was filled.\nFirst I used the Code as below: </p>\n\n<pre><code>var countries= \nFind(languages.Any() \n ? (country =&gt; languages.Contains(country.Language))\n : (country =&gt; true));\n</code></pre>\n\n<p>But exactly I get the error :<code>there is no implicit conversion between lambda expression and lambda expression.</code></p>\n\n<p>The problem was that, we have just two lambda expressions here, and nothing else, for example, what is <code>country =&gt; true</code> exactly?? We have to determine the type of <strong>at least one of lambda expressions</strong>. If just of one of the expressions be determined, then the error will be omitted. But for make the code more readable, I extracted both lambda expressions, and used the variable instead, as below: </p>\n\n<pre><code> Expression&lt;Func&lt;Country, bool&gt;&gt; getAllPredicate = country =&gt; true;\n Expression&lt;Func&lt;Country, bool&gt;&gt; getCountriesByLanguagePredicate = country =&gt; languages.Contains(country.Language);\n\n var countries= Find(languages.Any()\n ? getCountriesByLanguagePredicate\n : getAllPredicate);\n</code></pre>\n\n<p>I emphasize that, if I just determined one of the expression's type, the error will be fixed.</p>\n" }, { "answer_id": 70199481, "author": "StuartLC", "author_id": 314291, "author_profile": "https://Stackoverflow.com/users/314291", "pm_score": 1, "selected": false, "text": "<p>Just an update - in C# 10, it IS now possible for the compiler to infer the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions#natural-type-of-a-lambda-expression\" rel=\"nofollow noreferrer\">'natural type' of a lambda</a>, provided that the input type(s) are provided, e.g.</p>\n<pre><code>var evenFilter = (int i) =&gt; i % 2 == 0; // evenFilter inferred as `Func&lt;int, bool&gt;`\n</code></pre>\n<p>This also means that 0 input Funcs and Actions can be inferred:</p>\n<pre><code>var zeroInputFunc = () =&gt; 44 % 2 == 0;\nvar myAction = () =&gt; {Console.WriteLine(&quot;Foo&quot;);};\n</code></pre>\n<p>However, this won't work:</p>\n<pre><code>var filter = i =&gt; i % 2 == 0; &lt;&lt; Error: The delegate type could not be inferred\n</code></pre>\n<p>As a result, it is now possible to do what the OP originally wanted to do, provided that at least the input types are provided, e.g.</p>\n<pre><code>Func&lt;int, bool&gt; myPredicate = selectorFlag\n ? i =&gt; i % 2 == 0\n : i =&gt; i % 2 == 1;\n</code></pre>\n<p>However, this still isn't permitted:</p>\n<pre><code>var myPredicate = selectorFlag\n ? (int i) =&gt; i % 2 == 0\n : (int i) =&gt; i % 2 == 1;\n</code></pre>\n<blockquote>\n<p>Error : no implicit conversion between 'lambda expression' and 'lambda expression'</p>\n</blockquote>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15861/" ]
Generally, when using the conditional operator, here's the syntax: ``` int x = 6; int y = x == 6 ? 5 : 9; ``` Nothing fancy, pretty straight forward. Now, let's try to use this when assigning a Lambda to a Func type. Let me explain: ``` Func<Order, bool> predicate = id == null ? p => p.EmployeeID == null : p => p.EmployeeID == id; ``` That's the same syntax, and *should* work? Right? For some reason that doesn't. The compiler gives this nice cryptic message: > > Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression' > > > I then went ahead and changed the syntax and this way it *did* work: ``` Func<Order, bool> predicate = id == null ? predicate = p => p.EmployeeID == null : predicate = p => p.EmployeeID == id; ``` I'm just curious as to why it doesn't work the first way? (Side note: I ended up not needing this code, as I found out that when comparing an int value against null, you just use object.Equals)
You can convert a lambda expression to a particular target delegate type, but in order to determine the type of the conditional expression, the compiler needs to know the type of each of the second and third operands. While they're both just "lambda expression" there's no conversion from one to the other, so the compiler can't do anything useful. I wouldn't suggest using an assignment, however - a cast is more obvious: ``` Func<Order, bool> predicate = id == null ? (Func<Order, bool>) (p => p.EmployeeID == null) : p => p.EmployeeID == id; ``` Note that you only need to provide it for one operand, so the compiler can perform the conversion from the other lambda expression.
263,191
<p>In C#, I want to initialize a string value with an empty string.</p> <p>How should I do this? What is the right way, and why?</p> <pre><code>string willi = string.Empty; </code></pre> <p>or</p> <pre><code>string willi = String.Empty; </code></pre> <p>or</p> <pre><code>string willi = ""; </code></pre> <p>or what?</p>
[ { "answer_id": 263195, "author": "MidnightGun", "author_id": 13220, "author_profile": "https://Stackoverflow.com/users/13220", "pm_score": 4, "selected": false, "text": "<p>I personally prefer \"\" unless there is a good reason to something more complex.</p>\n" }, { "answer_id": 263196, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 3, "selected": false, "text": "<p>Any of the above.</p>\n\n<p>There are many, many better things to pontificate. Such as what colour bark suits a tree best, I think vague brown with tinges of dulcet moss.</p>\n" }, { "answer_id": 263199, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>I use the third, but of the other two the first seems less odd.\nstring is an alias for String, but seeing them across an assignment feels off.</p>\n" }, { "answer_id": 263203, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>The compiler should make them all the same in the long run. Pick a standard so that your code will be easy to read, and stick with it.</p>\n" }, { "answer_id": 263204, "author": "Magus", "author_id": 2188, "author_profile": "https://Stackoverflow.com/users/2188", "pm_score": 1, "selected": false, "text": "<p>I think the second is \"proper,\" but to be honest I don't think it will matter. The compiler should be smart enough to compile any of those to the exact same bytecode. I use \"\" myself.</p>\n" }, { "answer_id": 263205, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 6, "selected": false, "text": "<p>I'd prefer <code>string</code> to <code>String</code>. choosing <code>string.Empty</code> over <code>\"\"</code> is a matter of choosing one and sticking with it. Advantage of using <code>string.Empty</code> is it is very obvious what you mean, and you don't accidentally copy over non-printable characters like <code>\"\\x003\"</code> in your <code>\"\"</code>.</p>\n" }, { "answer_id": 263207, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I doesn't make a difference. The last one is the quickest to type though :)</p>\n" }, { "answer_id": 263210, "author": "Silviu Niculita", "author_id": 34388, "author_profile": "https://Stackoverflow.com/users/34388", "pm_score": 4, "selected": false, "text": "<p><code>String.Empty</code> and <code>string.Empty</code> are equivalent. <code>String</code> is the BCL class name; <code>string</code> is its C# alias (or shortcut, if you will). Same as with <code>Int32</code> and <code>int</code>. See <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/built-in-types-table\" rel=\"noreferrer\">the docs</a> for more examples.</p>\n\n<p>As far as <code>\"\"</code> is concerned, I'm not really sure.</p>\n\n<p>Personally, I always use <code>string.Empty</code>.</p>\n" }, { "answer_id": 263214, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>Either of the first two would be acceptable to me. I would avoid the last one because it is relatively easy to introduce a bug by putting a space between the quotes. This particular bug would be difficult to find by observation. Assuming no typos, all are semantically equivalent.</p>\n\n<p>[EDIT]</p>\n\n<p>Also, you might want to always use either <code>string</code> or <code>String</code> for consistency, but that's just me.</p>\n" }, { "answer_id": 263231, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 3, "selected": false, "text": "<p><code>string</code> is synonym for <code>System.String</code> type, They are identical. </p>\n\n<p>Values are also identical: <code>string.Empty == String.Empty == \"\"</code></p>\n\n<p>I would not use character constant \"\" in code, rather <code>string.Empty</code> or <code>String.Empty</code> - easier to see what programmer meant.</p>\n\n<p>Between <code>string</code> and <code>String</code> I like lower case <code>string</code> more just because I used to work with Delphi for lot of years and Delphi style is lowercase <code>string</code>.</p>\n\n<p>So, if I was your boss, you would be writing <code>string.Empty</code></p>\n" }, { "answer_id": 263236, "author": "Calanus", "author_id": 445, "author_profile": "https://Stackoverflow.com/users/445", "pm_score": 2, "selected": false, "text": "<p>It doesn't matter - they are exactly the same thing.\nHowever, the main thing is that you <strong>must be consistent</strong></p>\n\n<p>p.s. I struggle with this sort of \"whats the right thing\" all the time.</p>\n" }, { "answer_id": 263247, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://www.codinghorror.com/blog/archives/000878.html\" rel=\"noreferrer\">The best code is no code at all</a>:</p>\n\n<blockquote>\n <p>The fundamental nature of coding is that our task, as programmers, is to recognize that every decision we make is a trade-off. […] <strong>Start with brevity. Increase the other dimensions as required by testing.</strong></p>\n</blockquote>\n\n<p>Consequently, less code is better code: Prefer <code>\"\"</code> to <code>string.Empty</code> or <code>String.Empty</code>. Those two are <strong>six times longer</strong> with no added benefit — certainly no added clarity, as they express the exact same information.</p>\n" }, { "answer_id": 263253, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": false, "text": "<p>I wasn't going to chime in, but I'm seeing some wrong info getting tossed out here.</p>\n\n<p>I, personally, prefer <code>string.Empty</code>. That's a personal preference, and I bend to the will of whatever team I work with on a case-by-case basis.</p>\n\n<p>As some others have mentioned, there is no difference at all between <code>string.Empty</code> and <code>String.Empty</code>. </p>\n\n<p>Additionally, and this is a little known fact, using \"\" is perfectly acceptable. Every instance of \"\" will, in other environments, create an object. However, .NET interns its strings, so future instances will pull the same immutable string from the intern pool, and any performance hit will be negligible. Source: <a href=\"http://blogs.msdn.com/brada/archive/2003/04/22/49997.aspx\" rel=\"noreferrer\">Brad Abrams</a>.</p>\n" }, { "answer_id": 263257, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 11, "selected": true, "text": "<p><strong>Use whatever you and your team find the most readable.</strong></p>\n\n<p>Other answers have suggested that a new string is created every time you use <code>\"\"</code>. This is not true - due to string interning, it will be created either once per assembly or once per AppDomain (or possibly once for the whole process - not sure on that front). This difference is negligible - massively, <em>massively</em> insignificant.</p>\n\n<p>Which you find more readable is a different matter, however. It's subjective and will vary from person to person - so I suggest you find out what most people on your team like, and all go with that for consistency. Personally I find <code>\"\"</code> easier to read.</p>\n\n<p>The argument that <code>\"\"</code> and <code>\" \"</code> are easily mistaken for each other doesn't really wash with me. Unless you're using a proportional font (and I haven't worked with <em>any</em> developers who do) it's pretty easy to tell the difference.</p>\n" }, { "answer_id": 264534, "author": "user34577", "author_id": 34577, "author_profile": "https://Stackoverflow.com/users/34577", "pm_score": 2, "selected": false, "text": "<p>While difference is very, VERY little, the difference still exists.</p>\n<ol>\n<li><p><code>&quot;&quot;</code> creates an object while <code>String.Empty</code> does not. But this object will be created once and will be referenced from the string pool later if you have another <code>&quot;&quot;</code> in the code.</p>\n</li>\n<li><p><code>String</code> and <code>string</code> are the same, but I would recommend to use <code>String.Empty</code> (as well as <code>String.Format</code>, <code>String.Copy</code> etc.) since dot notation indicates class, not operator, and having class starting with capital letter conforms to C# coding standards.</p>\n</li>\n</ol>\n" }, { "answer_id": 469974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I strongly prefer String.Empty, aside from the other reasons to ensure you know what it is and that you have not accidentally removed the contents,\nbut primarily for internationalization.\nIf I see a string in quotes then I always have to wonder whether that is new code and it should be put into a string table. So every time code gets changed/reviewed you need to look for \"something in quotes\" and yes you can filter out the empty strings but I tell people it is good practice to never put strings in quotes unless you know it won't get localized.</p>\n" }, { "answer_id": 932689, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 4, "selected": false, "text": "<p>Just about every developer out there will know what \"\" means. I personally encountered String.Empty the first time and had to spend some time searching google to figure out if they really <em>are</em> the exact same thing.</p>\n" }, { "answer_id": 1588678, "author": "aBetterGamer", "author_id": 192440, "author_profile": "https://Stackoverflow.com/users/192440", "pm_score": 9, "selected": false, "text": "<p>There really is no difference from a performance and code generated standpoint. In performance testing, they went back and forth between which one was faster vs the other, and only by milliseconds.</p>\n\n<p>In looking at the behind the scenes code, you really don't see any difference either. The only difference is in the IL, which <code>string.Empty</code> use the opcode <code>ldsfld</code>\nand <code>\"\"</code> uses the opcode <code>ldstr</code>, but that is only because <code>string.Empty</code> is static, and both instructions do the same thing.\nIf you look at the assembly that is produced, it is exactly the same.</p>\n\n<h2>C# Code</h2>\n\n<pre><code>private void Test1()\n{\n string test1 = string.Empty; \n string test11 = test1;\n}\n\nprivate void Test2()\n{\n string test2 = \"\"; \n string test22 = test2;\n}\n</code></pre>\n\n<h2>IL Code</h2>\n\n<pre><code>.method private hidebysig instance void \n Test1() cil managed\n{\n // Code size 10 (0xa)\n .maxstack 1\n .locals init ([0] string test1,\n [1] string test11)\n IL_0000: nop\n IL_0001: ldsfld string [mscorlib]System.String::Empty\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: stloc.1\n IL_0009: ret\n} // end of method Form1::Test1\n</code></pre>\n\n\n\n<pre><code>.method private hidebysig instance void \n Test2() cil managed\n{\n // Code size 10 (0xa)\n .maxstack 1\n .locals init ([0] string test2,\n [1] string test22)\n IL_0000: nop\n IL_0001: ldstr \"\"\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: stloc.1\n IL_0009: ret\n} // end of method Form1::Test2\n</code></pre>\n\n<h2>Assembly code</h2>\n\n<pre><code> string test1 = string.Empty;\n0000003a mov eax,dword ptr ds:[022A102Ch] \n0000003f mov dword ptr [ebp-40h],eax \n\n string test11 = test1;\n00000042 mov eax,dword ptr [ebp-40h] \n00000045 mov dword ptr [ebp-44h],eax \n</code></pre>\n\n\n\n<pre><code> string test2 = \"\";\n0000003a mov eax,dword ptr ds:[022A202Ch] \n00000040 mov dword ptr [ebp-40h],eax \n\n string test22 = test2;\n00000043 mov eax,dword ptr [ebp-40h] \n00000046 mov dword ptr [ebp-44h],eax \n</code></pre>\n" }, { "answer_id": 3613509, "author": "mckamey", "author_id": 43217, "author_profile": "https://Stackoverflow.com/users/43217", "pm_score": 3, "selected": false, "text": "<p>It is totally a code-style preference, do to how .NET handles strings. However, here are my opinions :)</p>\n\n<p>I always use the BCL Type names when accessing static methods, properties and fields: <code>String.Empty</code> or <code>Int32.TryParse(...)</code> or <code>Double.Epsilon</code></p>\n\n<p>I always use the C# keywords when declaring new instances: <code>int i = 0;</code> or <code>string foo = \"bar\";</code></p>\n\n<p>I rarely use undeclared string literals as I like to be able to scan the code to combine them into reusable named constants. The compiler replaces constants with the literals anyway so this is more of a way to avoid magic strings/numbers and to give a little more meaning to them with a name. Plus changing the values is easier.</p>\n" }, { "answer_id": 7202299, "author": "Mentoliptus", "author_id": 726978, "author_profile": "https://Stackoverflow.com/users/726978", "pm_score": 6, "selected": false, "text": "<p>One difference is that if you use a <code>switch-case</code> syntax, you can't write <code>case string.Empty:</code> because it's not a constant. You get a <code>Compilation error : A constant value is expected</code></p>\n\n<p>Look at this link for more info:\n<a href=\"http://web.archive.org/web/20131230161806/http://kossovsky.net/index.php/2009/06/string-empty-versus-empty-quotes/\" rel=\"noreferrer\">string-empty-versus-empty-quotes</a></p>\n" }, { "answer_id": 8145898, "author": "sergiol", "author_id": 383779, "author_profile": "https://Stackoverflow.com/users/383779", "pm_score": 1, "selected": false, "text": "<p>On <a href=\"http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx</a> :</p>\n\n<blockquote>\n <p>As David implies, there difference between <code>String.Empty</code> and <code>\"\"</code> are pretty small, but there is a difference. <code>\"\"</code> actually creates an object, it will likely be pulled out of the string intern pool, but still... while <code>String.Empty</code> creates no object... so if you are really looking for ultimately in memory efficiency, I suggest <code>String.Empty</code>. However, you should keep in mind the difference is so trival you will like never see it in your code...<br>\n As for <code>System.String.Empty</code> or <code>string.Empty</code> or <code>String.Empty</code>... my care level is low ;-)</p>\n</blockquote>\n" }, { "answer_id": 10741371, "author": "Dimitry", "author_id": 1415562, "author_profile": "https://Stackoverflow.com/users/1415562", "pm_score": 3, "selected": false, "text": "<p>No one mentioned that in VisualStudio String is color coded differently then string. Which is important for readability. Also, lower case is usually used for vars and type, not a big deal but String.Empty is a constant and not a var or type.</p>\n" }, { "answer_id": 30758914, "author": "Andrew", "author_id": 1803463, "author_profile": "https://Stackoverflow.com/users/1803463", "pm_score": 3, "selected": false, "text": "<p>I would favor <code>string.Empty</code> over <code>String.Empty</code> because you can use it without needing to include a <code>using System;</code> in your file.</p>\n\n<p>As for the picking <code>\"\"</code> over <code>string.Empty</code>, it is personal preference and should be decided by your team.</p>\n" }, { "answer_id": 36947473, "author": "Steve", "author_id": 1197518, "author_profile": "https://Stackoverflow.com/users/1197518", "pm_score": 4, "selected": false, "text": "<p>This topic is pretty old and long, so excuse me if this behavior has been mentioned somewhere else. (And point me to the answer that covers this) </p>\n\n<p>I have found a difference in the behavior of the compiler if you use <code>string.Empty</code> or double quotes. The difference shows itself if you don't use the string variable initialized with string.Empty or with double quotes. </p>\n\n<p>In case of initialization with <code>string.Empty</code> then the Compiler Warning </p>\n\n<pre><code>CS0219 - The variable 'x' is assigned but its value is never used\n</code></pre>\n\n<p>is never emitted while in case of initialization with double quotes you get the expected message. </p>\n\n<p>This behavior is explained in the Connect article at this link: <a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/799810/c-warning-cs0219-not-reported-when-assign-non-constant-value\">https://connect.microsoft.com/VisualStudio/feedback/details/799810/c-warning-cs0219-not-reported-when-assign-non-constant-value</a> </p>\n\n<p>Basically, if I get it right, they want to allow a programmer to set a variable with the return value of a function for debugging purposes without bothering him with a warning message and thus they limited the warning only in case of costant assignments and string.Empty is not a constant but a field.</p>\n" }, { "answer_id": 39998813, "author": "RBT", "author_id": 465053, "author_profile": "https://Stackoverflow.com/users/465053", "pm_score": 4, "selected": false, "text": "<p>I performed a simple test using following method in a .NET v4.5 console application:</p>\n<pre><code>private static void CompareStringConstants()\n{\n string str1 = &quot;&quot;;\n string str2 = string.Empty;\n string str3 = String.Empty;\n Console.WriteLine(object.ReferenceEquals(str1, str2)); //prints True\n Console.WriteLine(object.ReferenceEquals(str2, str3)); //prints True\n}\n</code></pre>\n<p>This suggests that all three variables namely <code>str1</code>, <code>str2</code> and <code>str3</code> though being initialized using different syntax are pointing to the same string (of zero length) object in memory .</p>\n<p>So internally they have no difference. And it all boils down to convenience of which one you or your team wants to use. This behavior of string class is known as <strong>string interning</strong> in .NET Framework. Eric Lippert has a very nice blog <a href=\"https://blogs.msdn.microsoft.com/ericlippert/2009/09/28/string-interning-and-string-empty/\" rel=\"nofollow noreferrer\">here</a> describing this concept.</p>\n" }, { "answer_id": 41573276, "author": "Remotec", "author_id": 169640, "author_profile": "https://Stackoverflow.com/users/169640", "pm_score": 2, "selected": false, "text": "<p>I was just looking at some code and this question popped into my mind which I had read some time before. This is certainly a question of readability.</p>\n\n<p>Consider the following C# code...</p>\n\n<pre><code>(customer == null) ? \"\" : customer.Name\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>(customer == null) ? string.empty : customer.Name\n</code></pre>\n\n<p>I personally find the latter less ambiguous and easier to read.</p>\n\n<p>As pointed out by others the actual differences are negligible.</p>\n" }, { "answer_id": 44052305, "author": "RhinoTX", "author_id": 7716023, "author_profile": "https://Stackoverflow.com/users/7716023", "pm_score": 2, "selected": false, "text": "<p>I have personally witnessed <code>&quot;&quot;</code> resulting in (minor) problems twice. Once was due to a mistake of a junior developer new to team-based programming, and the other was a simple typo, but the fact is using <code>string.Empty</code> would have avoided both issues.</p>\n<p>Yes, this is very much a judgement call, but when a language gives you multiple ways to do things, I tend to lean toward the one that has the most compiler oversight and strongest compile-time enforcement. That is <em>not</em> <code>&quot;&quot;</code>. It's all about expressing specific intent.</p>\n<p>If you type <code>string.EMpty</code> <strong>or</strong> <code>Strng.Empty</code>, the compiler lets you know you did it <strong>wrong</strong>. Immediately. It simply will not compile. As a developer you are citing <em>specific</em> intent that the compiler (or another developer) cannot in any way misinterpret, and when you do it wrong, you can't create a bug.</p>\n<p>If you type <code>&quot; &quot;</code> when you mean <code>&quot;&quot;</code> or vice-versa, the compiler happily does what you told it to do. Another developer may or may not be able to glean your specific intent. <strong>Bug created</strong>.</p>\n<p>Long before <code>string.Empty</code> was a thing I've used a standard library that defined the <code>EMPTY_STRING</code> constant. We still use that constant in <strong>case</strong> statements <strong>where</strong> <code>string.Empty</code> is <strong>not allowed</strong>.</p>\n<p>Whenever possible, put the compiler to work for you, and eliminate the possibility of human error, no matter how small. IMO, this trumps &quot;readability&quot; as others have cited.</p>\n<p>Specificity and compile time enforcement. It's what's for dinner.</p>\n" }, { "answer_id": 44164824, "author": "5argon", "author_id": 862147, "author_profile": "https://Stackoverflow.com/users/862147", "pm_score": 2, "selected": false, "text": "<p>I use \"\" because it will be colored distinctively yellow in my code... for some reason String.Empty is all white in my Visual Studio Code theme. And I believe that matters to me the most.</p>\n" }, { "answer_id": 47742744, "author": "Wouter", "author_id": 4491768, "author_profile": "https://Stackoverflow.com/users/4491768", "pm_score": 1, "selected": false, "text": "<p>The empty string is like empty set just a name that everybody uses to call <code>\"\"</code>. Also in formal languages strings created from an alphabet that have zero length are called the empty string. Both set and string have a special symbol for it. Empty string: ε and empty set: ∅. If you want to talk about this zero length string you will call it the empty string so everybody knows exactly what you are referring to. Now in case you name it the empty string why not use <code>string.Empty</code> in code, its shows the intention is explicit. Downside is that it’s not a constant and therefore not available everywhere, like in attributes. (It's not a constant for some technical reasons, see the reference source.)</p>\n" }, { "answer_id": 61044512, "author": "Keith Howard", "author_id": 4436927, "author_profile": "https://Stackoverflow.com/users/4436927", "pm_score": 0, "selected": false, "text": "<p>Possibly a controversial comment, but, generally, I find that my life is easier when I act consistently with Microsoft. We can't possibly know the full deeply embedded reasons (sometimes highly rigorous, and sometime kludgy, I imagine) for why they do things.</p>\n\n<p>They use \"\" in automatically generated files like the Assembly file, so that is what I do. In fact, when I try to replace any below \"\" with String.Empty, Visual Studio crashes on me. There is probably a logical explanation for this, but with my limited knowledge, if I just do what they do, most of the time, things work out. (Contra: I am aware they some automatically generated files also use String.Empty, which kind of shatters my point. :) )</p>\n\n<pre><code>&lt;Assembly: System.Reflection.AssemblyCulture(\"\")&gt;\n&lt;Assembly: System.Reflection.AssemblyDescription(\"\")&gt;\n&lt;Assembly: System.Reflection.AssemblyFileVersion(\"1.0.0.0\")&gt;\n&lt;Assembly: System.Reflection.AssemblyKeyFile(\"\")&gt;\n&lt;Assembly: System.Reflection.AssemblyProduct(\"\")&gt;\n&lt;Assembly: System.Reflection.AssemblyTitle(\"\")&gt;\n</code></pre>\n" }, { "answer_id": 73745047, "author": "Bolpat", "author_id": 3273130, "author_profile": "https://Stackoverflow.com/users/3273130", "pm_score": -1, "selected": false, "text": "<p>If you want to prank someone, put <code>&quot;‍&quot;</code> into their code. This is not the empty string, it’s <code>&quot;\\u200D&quot;</code>. You cannot fool someone using <code>string.Empty</code>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31406/" ]
In C#, I want to initialize a string value with an empty string. How should I do this? What is the right way, and why? ``` string willi = string.Empty; ``` or ``` string willi = String.Empty; ``` or ``` string willi = ""; ``` or what?
**Use whatever you and your team find the most readable.** Other answers have suggested that a new string is created every time you use `""`. This is not true - due to string interning, it will be created either once per assembly or once per AppDomain (or possibly once for the whole process - not sure on that front). This difference is negligible - massively, *massively* insignificant. Which you find more readable is a different matter, however. It's subjective and will vary from person to person - so I suggest you find out what most people on your team like, and all go with that for consistency. Personally I find `""` easier to read. The argument that `""` and `" "` are easily mistaken for each other doesn't really wash with me. Unless you're using a proportional font (and I haven't worked with *any* developers who do) it's pretty easy to tell the difference.
263,225
<p>I've done some Googling, and can't find anything, though maybe I'm just looking in the wrong places. I'm also not very adept at VBA, but I'm sure I can figure it out with the right pointers :)</p> <p>I have a string I'm building that's a concatenation of various cells, based on various conditions. I hit these in order.</p> <pre><code>=IF(A405&lt;&gt;A404,G405,G405&amp;H404) </code></pre> <p>What I want to do is go back through my concatenated list, removing a superseded value if the superseder is in the list.</p> <p>For example, see the following list:</p> <pre><code>A, D, G, Y, Z </code></pre> <p>I want to remove <code>D</code> <em>if</em> and <strong>only</strong> <em>if</em> <code>Y</code> is present.</p> <p>How would I go about this? (VBA or in-cell, though I'd prefer in-cell)</p>
[ { "answer_id": 263245, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "<p>It's probably easier to start at the end, make your additions to the beginning of the string, and only add D if Y is not present.</p>\n" }, { "answer_id": 263250, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 2, "selected": false, "text": "<p>Firstly, why not keep a string array instead as you go through all the cells, then concatenate it all at the end?</p>\n\n<p>Otherwise, you'll be using string functions like INSTR and MID to do something like:</p>\n\n<pre><code>start1 = instr(myLongString,\"Y, \")\nif start1 &gt; 0 Then\n start2 = instr(myLongString,\"D, \")\n if start2 &gt; 0 then\n newLongString = left(myLongString, start2 - 1) &amp; _\n mid(myLongString, start2 + 3)\n end if\nend if\n</code></pre>\n\n<p>But, as I said, I would keep an array that is easy to loop through, then once you have all the values you KNOW you will use, just concatenate them at the end.</p>\n" }, { "answer_id": 263275, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "<p>I guess D could appear anywhere, so how about:</p>\n\n<pre><code>If InStr(strString, \"Y\") &gt; 0 Then\n strString = Replace(strString, \"d\", \"\")\n strString = Replace(strString, \" \", \"\")\n strString = Replace(strString, \" ,\", \"\")\n strString = Replace(strString, \",,\", \",\")\nEnd If\n</code></pre>\n" }, { "answer_id": 263335, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": 3, "selected": false, "text": "<p>Try:</p>\n\n<pre><code>=IF(ISERROR(FIND(\"Y\",A1)),A1,SUBSTITUTE(A1,\"D, \",\"\"))\n</code></pre>\n\n<p>But that assumes you always have the comma and space following the D.</p>\n" }, { "answer_id": 263374, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 1, "selected": true, "text": "<p>I just got this as a possible solution via email, too:</p>\n\n<pre><code>=IF(A15&lt;&gt;A14,G15,IF(OR(AND(G15=\"CR247, \",ISNUMBER(FIND(\"CR247, \",H14))),AND(G15=\"CR149, \",ISNUMBER(FIND(\"CR215, \",H14))),AND(G15=\"CR149, \",ISNUMBER(FIND(\"CR180, \",H14))),AND(G15=\"CR180, \",ISNUMBER(FIND(\"CR215, \",H14))),G15=\"CR113, \"),H14,G15&amp;H14))\n</code></pre>\n\n<p>(this has the \"real\" values with precedence rules)</p>\n\n<p>It looks relatively similar to <a href=\"https://stackoverflow.com/questions/263225/string-manipulation-with-excel-how-to-remove-part-of-a-string-if-another-part-i#263335\">@Joseph</a>'s answer.</p>\n\n<p>Is there a better solution? </p>\n" }, { "answer_id": 263541, "author": "bjorsig", "author_id": 27195, "author_profile": "https://Stackoverflow.com/users/27195", "pm_score": 0, "selected": false, "text": "<p>If there are not too many of these combinations that you want to remove, you can use =IF(FIND(\"D\"; A2)> 0; REPLACE(A2;1;3;\"\");A2). </p>\n" }, { "answer_id": 267822, "author": "da_m_n", "author_id": 7165, "author_profile": "https://Stackoverflow.com/users/7165", "pm_score": 1, "selected": false, "text": "<p><strong>VBA</strong> : You can always use the regexp object.\nI think that gives you the ability to test anything on your script as long as you build correctly the regular expression. </p>\n\n<p>Check out : <a href=\"http://msdn.microsoft.com/en-us/library/yab2dx62(VS.85).aspx\" rel=\"nofollow noreferrer\" title=\"for regexp reference\">http://msdn.microsoft.com/en-us/library/yab2dx62(VS.85).aspx</a> ( for regexp reference )<br>\nand a simple tool to test your regexps : <a href=\"http://www.codehouse.com/webmaster_tools/regex/\" rel=\"nofollow noreferrer\">http://www.codehouse.com/webmaster_tools/regex/</a></p>\n\n<p><strong>In-cell</strong>: you could do it in a more excel friendly way:<br>\nsuppose on column A:A you have the values.<br>\nYou can add a new column where you perform the check<br>\n<code>if(indirect(\"A\"&amp;row()) &lt;&gt; indirect(\"A\"&amp;row()-1), indirect(\"G\"&amp;row()), indirect(\"G\"&amp;row())&amp; indirect(\"H\"&amp;row()))</code><br>\nor whatever the values are. I guess however that on one branch of the if statement the value should be blank. After that you concatenate only the B:B column values ( skipping blanks if needed ).</p>\n\n<p>Hope this helps.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4418/" ]
I've done some Googling, and can't find anything, though maybe I'm just looking in the wrong places. I'm also not very adept at VBA, but I'm sure I can figure it out with the right pointers :) I have a string I'm building that's a concatenation of various cells, based on various conditions. I hit these in order. ``` =IF(A405<>A404,G405,G405&H404) ``` What I want to do is go back through my concatenated list, removing a superseded value if the superseder is in the list. For example, see the following list: ``` A, D, G, Y, Z ``` I want to remove `D` *if* and **only** *if* `Y` is present. How would I go about this? (VBA or in-cell, though I'd prefer in-cell)
I just got this as a possible solution via email, too: ``` =IF(A15<>A14,G15,IF(OR(AND(G15="CR247, ",ISNUMBER(FIND("CR247, ",H14))),AND(G15="CR149, ",ISNUMBER(FIND("CR215, ",H14))),AND(G15="CR149, ",ISNUMBER(FIND("CR180, ",H14))),AND(G15="CR180, ",ISNUMBER(FIND("CR215, ",H14))),G15="CR113, "),H14,G15&H14)) ``` (this has the "real" values with precedence rules) It looks relatively similar to [@Joseph](https://stackoverflow.com/questions/263225/string-manipulation-with-excel-how-to-remove-part-of-a-string-if-another-part-i#263335)'s answer. Is there a better solution?
263,227
<p>Several times, while perusing the Boost library's documentation, I've run across return values that are marked "<a href="http://www.boost.org/doc/libs/1_36_0/libs/utility/Collection.html" rel="noreferrer">convertible to <code>bool</code></a>" (search that page for the phrase "convertible to bool", it's about a third of the way down). I once stumbled across an oblique reference to a paper explaining the reason for that, but have never been able to find said paper (and I can no longer find the page I saw the reference on either).</p> <p>Can anyone explain why (and when) you should return something that's "convertible to <code>bool</code>" rather than simply returning a <code>bool</code>?</p>
[ { "answer_id": 263279, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 0, "selected": false, "text": "<p>Maybe for performance? In C/C++ you can do an if statement on numbers (0 is false, anything else is true). Converting to a strict bool is an extra operation, which in many cases wouldn't be required.</p>\n\n<p>I haven't actually used boost, so that's just a guess, but it seems like a reasonable one to me.</p>\n" }, { "answer_id": 263303, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "<p><code>bool</code>s are promotable to <code>int</code>s and can participate in arithmetic operations. This is often not the desired outcome, when a value should just be used for truth testing.</p>\n\n<p>A convertible-to-<code>bool</code> is usually something like a <code>void*</code>, where the null pointer is false, and anything else is true, and yet can't be used for arithmetic operations.</p>\n" }, { "answer_id": 263313, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "<p>“convertible to bool” simply means anything which can meaningfully be used in a boolean context (e.g. in an <code>if</code> condition). This makes sense in implicit conversions. Imagine an object which you want to use in a boolean context, e.g. <code>std::fstream</code>:</p>\n\n<pre><code>ifstream ifs(\"filename\");\nwhile (ifs &gt;&gt; token)\n cout \"token \" &lt;&lt; token &lt;&lt; \" read.\" &lt;&lt; endl;\n</code></pre>\n\n<p>Here, <code>ifs</code> is convertible to boolean. Well, actually, it isn't. Rather, it is convertible to something that, in turn, is convertible to <code>bool</code>. This is to prevent such statements:</p>\n\n<pre><code>int b = ifs;\n</code></pre>\n\n<p>The reasoning is that such a statement is most probably not intended and the compiler should therefore prevent it. By returning a “convertible to bool” rather than a <code>bool</code>, this is achieved because two user-defined implicit conversions can't be chained in one expression.</p>\n\n<p>In this context, you might want to look up the <a href=\"http://www.artima.com/cppsource/safebool.html\" rel=\"noreferrer\">safe bool idiom</a>. Chris has already alluded to one possible implementation, using <code>void*</code> as a return type. Usually, the <code>this</code> pointer is then used to represent <code>true</code>. This is what gets used by the STL. However, this is unfortunately still flawed. Several alternatives have been proposed (neatly wrapped up in the article I've linked above) and as far as I know, have also been included into C++0x for consideration. I'm not aware of the current status of these proposals, though.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
Several times, while perusing the Boost library's documentation, I've run across return values that are marked "[convertible to `bool`](http://www.boost.org/doc/libs/1_36_0/libs/utility/Collection.html)" (search that page for the phrase "convertible to bool", it's about a third of the way down). I once stumbled across an oblique reference to a paper explaining the reason for that, but have never been able to find said paper (and I can no longer find the page I saw the reference on either). Can anyone explain why (and when) you should return something that's "convertible to `bool`" rather than simply returning a `bool`?
“convertible to bool” simply means anything which can meaningfully be used in a boolean context (e.g. in an `if` condition). This makes sense in implicit conversions. Imagine an object which you want to use in a boolean context, e.g. `std::fstream`: ``` ifstream ifs("filename"); while (ifs >> token) cout "token " << token << " read." << endl; ``` Here, `ifs` is convertible to boolean. Well, actually, it isn't. Rather, it is convertible to something that, in turn, is convertible to `bool`. This is to prevent such statements: ``` int b = ifs; ``` The reasoning is that such a statement is most probably not intended and the compiler should therefore prevent it. By returning a “convertible to bool” rather than a `bool`, this is achieved because two user-defined implicit conversions can't be chained in one expression. In this context, you might want to look up the [safe bool idiom](http://www.artima.com/cppsource/safebool.html). Chris has already alluded to one possible implementation, using `void*` as a return type. Usually, the `this` pointer is then used to represent `true`. This is what gets used by the STL. However, this is unfortunately still flawed. Several alternatives have been proposed (neatly wrapped up in the article I've linked above) and as far as I know, have also been included into C++0x for consideration. I'm not aware of the current status of these proposals, though.
263,228
<p>I've been using Flex Builder 3 to create Flex applications that are part of larger Flex / Java project using LiveCycle Data Services. Flex Builder creates and deploys the .war file, which is convenient for the development cycle, but I don't understand what the .war file has to contain in order to deploy and run.</p> <p>I've found through trial and error that changing certain properties of the Flex Project (i.e. the Context Root) can break or fix the application, and somehow those settings make it into the .war file.</p> <p>I need to get the entire build process implemented under Ant, and more importantly, I need to understand what the Flex part of the project depends on. I haven't been able to find any documentation that describes what a .war file has to include to deploy a Flex / Java application, however.</p> <p>For example, Flex Builder creates a web.xml file and populates it with the correct tags. but if I add other features do I need additional tags in web.xml?</p> <p>Does anyone know where I can find documentation on the .war file contents for a Flex / Java project?</p>
[ { "answer_id": 269800, "author": "Chris", "author_id": 9276, "author_profile": "https://Stackoverflow.com/users/9276", "pm_score": 0, "selected": false, "text": "<p>I don't know anything about LiveCycle Data Services, so that may be an issue. However, I have a flex app that interacts with a java server, and I didn't really have to do anything special for flex apart from what you would do for other static content.</p>\n\n<p>Specifically, I have my flex projects properties ~ Flex Build Path ~ Output folder set to the /flash folder within a java webapp, and ant handles everything else (compiling java files, assembling the class files, adding the web.xml, and turning the files into a war).</p>\n\n<p>Another approach, depending on how adobe handles livecycle, would be to have ant just invoke whatever command flex builder goes through to output a war.</p>\n" }, { "answer_id": 327281, "author": "cliff.meyers", "author_id": 41754, "author_profile": "https://Stackoverflow.com/users/41754", "pm_score": 2, "selected": false, "text": "<p>Check out the sample applications here:</p>\n\n<p><a href=\"http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/lcds/help.html?content=build_apps_3.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/lcds/help.html?content=build_apps_3.html</a></p>\n\n<p>Those apps will give you some idea of what needs to go in the WAR. In a nutshell there are four significant locations in a standard WAR and one additional significant location in WAR using LCDS or Blaze DS:</p>\n\n<pre><code>myapp.war/\n WEB-INF/ &lt;-- not accessible via the browser over HTTP\n classes/ &lt;-- compiled classes and configuration files (this is where your .class files and jdbc.properties would go)\n flex/ &lt;-- LCDS XML config files (services-config.xml)\n lib/ &lt;-- web application libraries (.jar files, for LCDS and other tools you might be using)\n web.xml &lt;-- web application configuration\n</code></pre>\n\n<p>The Flex application itself will likely sit in the root of myapp.war or in any subdirectory of your choosing except for WEB-INF.</p>\n\n<p>However if you study the sample apps and get your Ant script building the same structure that you see there you shouldn't have too many problems.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34372/" ]
I've been using Flex Builder 3 to create Flex applications that are part of larger Flex / Java project using LiveCycle Data Services. Flex Builder creates and deploys the .war file, which is convenient for the development cycle, but I don't understand what the .war file has to contain in order to deploy and run. I've found through trial and error that changing certain properties of the Flex Project (i.e. the Context Root) can break or fix the application, and somehow those settings make it into the .war file. I need to get the entire build process implemented under Ant, and more importantly, I need to understand what the Flex part of the project depends on. I haven't been able to find any documentation that describes what a .war file has to include to deploy a Flex / Java application, however. For example, Flex Builder creates a web.xml file and populates it with the correct tags. but if I add other features do I need additional tags in web.xml? Does anyone know where I can find documentation on the .war file contents for a Flex / Java project?
Check out the sample applications here: <http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/lcds/help.html?content=build_apps_3.html> Those apps will give you some idea of what needs to go in the WAR. In a nutshell there are four significant locations in a standard WAR and one additional significant location in WAR using LCDS or Blaze DS: ``` myapp.war/ WEB-INF/ <-- not accessible via the browser over HTTP classes/ <-- compiled classes and configuration files (this is where your .class files and jdbc.properties would go) flex/ <-- LCDS XML config files (services-config.xml) lib/ <-- web application libraries (.jar files, for LCDS and other tools you might be using) web.xml <-- web application configuration ``` The Flex application itself will likely sit in the root of myapp.war or in any subdirectory of your choosing except for WEB-INF. However if you study the sample apps and get your Ant script building the same structure that you see there you shouldn't have too many problems.
263,229
<p>In a tightly looped test application that prints out the value of <code>DateTime.UtcNow.Ticks</code>, I notice that the value will jump a remarkable amount once every hour or so. Look closely at the following sample data:</p> <pre><code>1:52:14.312 PM - 633614215343125000 1:52:14.359 PM - 633614215343593750 1:52:14.421 PM - 633614215344218750 1:52:14.468 PM - 633614215344687500 1:52:14.515 PM - 633614215998593750 &lt;-- WAY different </code></pre> <p>The delta is 653906250 ticks (65.390 seconds). The only reason I can come up with is that the Windows Time service is doing some synchronization from underneath my feet. </p> <ul> <li>Are there any experts out there that can confirm this? </li> <li>Drifting a minute or so in about an hour seems pretty bad to me, but is that the case here?</li> </ul>
[ { "answer_id": 263277, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 0, "selected": false, "text": "<p>Can you post code to show how you generated this data? And provide details about the machine you are running this on?</p>\n\n<p>Using the following, I'm not getting what you are getting.</p>\n\n<pre><code> for (int i = 0; i &lt; 10; i++)\n {\n\n Console.WriteLine(DateTime.Now.ToLongTimeString().ToString() + \" - \" + DateTime.UtcNow.Ticks.ToString());\n\n Thread.Sleep(10);\n }\n</code></pre>\n" }, { "answer_id": 263349, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 2, "selected": false, "text": "<p>Actually, just running some test with this loop:</p>\n\n<pre><code>static DateTime past = DateTime.UtcNow;\n static void PrintTime()\n {\n while (stopLoop == 0)\n {\n DateTime now = DateTime.UtcNow;\n Console.WriteLine(\"{0} - {1} d: {2}\", now, now.Ticks, now - past);\n Program.past = now;\n Thread.Sleep(2000);\n }\n }\n</code></pre>\n\n<p>If I changed my system's clock time in between calls, the delta would jump accordingly. So if you have time synchronization running or some other process that affects system time, then that will be reflected in the output.</p>\n" }, { "answer_id": 263409, "author": "Jeffrey LeCours", "author_id": 18051, "author_profile": "https://Stackoverflow.com/users/18051", "pm_score": 0, "selected": false, "text": "<p>Esteban is correct, a system clock change would cause a change in delta time between consecutive polls. Does the Windows Time service make these changes hourly? Is drifting a minute off within an hour likely?</p>\n\n<p>To catch this happening on your machine, if you kept track of the delta in change between checks, you can set a conditional breakpoint on an unusually high change in delta.</p>\n\n<pre><code>long delta = 0;\nlong ticks = 0;\nlong lastTicks = DateTime.UtcNow.Ticks;\nwhile (true)\n{\n ticks = DateTime.UtcNow.Ticks;\n delta = ticks - lastTicks;\n lastTicks = ticks;\n // Conditional breakpoint: delta &gt; 100000000 Is True\n Console.WriteLine(\"{0} - {1}\", ticks, delta);\n}\n</code></pre>\n" }, { "answer_id": 263434, "author": "Jeffrey LeCours", "author_id": 18051, "author_profile": "https://Stackoverflow.com/users/18051", "pm_score": 0, "selected": false, "text": "<p>The original output was caught in DebugView. My managed application was making a p/invoke OutputDebugString call, simply outputting DateTime.UtcNow.Ticks from a tight loop in a thread that also called Thread.Sleep(1).</p>\n\n<pre>\nSystem information for \\\\JLECOURSXP:\nUptime: 6 days 6 hours 22 minutes 53 seconds\nKernel version: Microsoft Windows XP, Multiprocessor Free\nProduct type: Professional\nProduct version: 5.1\nService pack: 3\nKernel build number: 2600\nRegistered organization:\nRegistered owner: setup\nInstall date: 6/15/2007, 3:35:29 PM\nIE version: 7.0000\nSystem root: C:\\WINDOWS\nProcessors: 2\nProcessor speed: 2.9 GHz\nProcessor type: Intel(R) Pentium(R) D CPU\nPhysical memory: 3070 MB\nVideo driver: RADEON 9250 - Secondary\n</pre>\n" }, { "answer_id": 265041, "author": "damageboy", "author_id": 9172, "author_profile": "https://Stackoverflow.com/users/9172", "pm_score": 1, "selected": false, "text": "<p>Ehm...</p>\n\n<p>How can you measure time this way when you can't tell for sure that you are not calling some blocking system call during this time (Like, potentially Console.WriteLine)?</p>\n\n<p>In order to have a \"working test\" you would have to at least make sure:</p>\n\n<ul>\n<li>NOTHING else is running on your machine</li>\n<li>The process/thread priority is set to High or something like that</li>\n<li>Call NO system call... Do only computationl tasks</li>\n<li>Set thread affinity to a specific CPU so you don't get switched between CPUs</li>\n</ul>\n\n<p>Even if you would do that, the OS would from time to time (15ms on a Windows Dual-Core desktop OS for example) preempt your thread....\nAnd you could still definitely see that sort of \"jump\" in UTC Time-Stamp.</p>\n\n<p>Just going from Userspace to Kernelspace (during a pre-emption / system call) and back, without doing any substantial kernel work, would take ~1000 CPU cycles...</p>\n\n<p>If you process is put into a wait state (by calling some blocking IO) it could even be MUCH MUCH worse...</p>\n\n<p>So I really don't get your \"test\". IMO this is perfectly normal.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18051/" ]
In a tightly looped test application that prints out the value of `DateTime.UtcNow.Ticks`, I notice that the value will jump a remarkable amount once every hour or so. Look closely at the following sample data: ``` 1:52:14.312 PM - 633614215343125000 1:52:14.359 PM - 633614215343593750 1:52:14.421 PM - 633614215344218750 1:52:14.468 PM - 633614215344687500 1:52:14.515 PM - 633614215998593750 <-- WAY different ``` The delta is 653906250 ticks (65.390 seconds). The only reason I can come up with is that the Windows Time service is doing some synchronization from underneath my feet. * Are there any experts out there that can confirm this? * Drifting a minute or so in about an hour seems pretty bad to me, but is that the case here?
Actually, just running some test with this loop: ``` static DateTime past = DateTime.UtcNow; static void PrintTime() { while (stopLoop == 0) { DateTime now = DateTime.UtcNow; Console.WriteLine("{0} - {1} d: {2}", now, now.Ticks, now - past); Program.past = now; Thread.Sleep(2000); } } ``` If I changed my system's clock time in between calls, the delta would jump accordingly. So if you have time synchronization running or some other process that affects system time, then that will be reflected in the output.
263,232
<p>I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it.</p> <p>I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.</p>
[ { "answer_id": 263240, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 9, "selected": true, "text": "<p>Use the <code>hasClass</code> method:</p>\n\n<pre><code>jQueryCollection.hasClass(className);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$(selector).hasClass(className);\n</code></pre>\n\n<p>The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).</p>\n\n<p><strong>Note:</strong> If you pass a <code>className</code> argument that contains whitespace, it will be matched literally against the collection's elements' <code>className</code> string. So if, for instance, you have an element,</p>\n\n<pre><code>&lt;span class=\"foo bar\" /&gt;\n</code></pre>\n\n<p>then this will return <code>true</code>:</p>\n\n<pre><code>$('span').hasClass('foo bar')\n</code></pre>\n\n<p>and these will return <code>false</code>:</p>\n\n<pre><code>$('span').hasClass('bar foo')\n$('span').hasClass('foo bar')\n</code></pre>\n" }, { "answer_id": 263246, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 4, "selected": false, "text": "<p>from the <a href=\"http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_test_whether_an_element_has_a_particular_class.3F\" rel=\"noreferrer\">FAQ</a></p>\n\n<pre><code>elem = $(\"#elemid\");\nif (elem.is (\".class\")) {\n // whatever\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>elem = $(\"#elemid\");\nif (elem.hasClass (\"class\")) {\n // whatever\n}\n</code></pre>\n" }, { "answer_id": 2285837, "author": "VinnyG", "author_id": 245836, "author_profile": "https://Stackoverflow.com/users/245836", "pm_score": 4, "selected": false, "text": "<p>As for the negation, if you want to know if an element hasn't a class you can simply do as Mark said.</p>\n\n<pre><code>if (!currentPage.parent().hasClass('home')) { do what you want }\n</code></pre>\n" }, { "answer_id": 20118093, "author": "Kedar.Aitawdekar", "author_id": 2599942, "author_profile": "https://Stackoverflow.com/users/2599942", "pm_score": 0, "selected": false, "text": "<p>Check the official jQuery FAQ page :</p>\n\n<p><a href=\"http://learn.jquery.com/using-jquery-core/faq/how-do-i-test-whether-an-element-has-a-particular-class/\" rel=\"nofollow\">How do I test whether an element has perticular class or not</a></p>\n" }, { "answer_id": 21043911, "author": "Ismael Miguel", "author_id": 2729937, "author_profile": "https://Stackoverflow.com/users/2729937", "pm_score": 2, "selected": false, "text": "<p>Without jQuery:</p>\n\n<pre><code>var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>function hasClass(e,c){\n return e&amp;&amp;(e instanceof HTMLElement)&amp;&amp;!!((' '+e.className+' ').indexOf(' '+c+' ')+1);\n}\n/*example of usage*/\nvar has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');\n</code></pre>\n\n<p>This is WAY faster than jQuery!</p>\n" }, { "answer_id": 34225071, "author": "vineet", "author_id": 3832217, "author_profile": "https://Stackoverflow.com/users/3832217", "pm_score": 0, "selected": false, "text": "<pre><code> $('.segment-name').click(function () {\n if($(this).hasClass('segment-a')){\n //class exist\n }\n});\n</code></pre>\n" }, { "answer_id": 38624900, "author": "Eduardo Paz", "author_id": 4530242, "author_profile": "https://Stackoverflow.com/users/4530242", "pm_score": 0, "selected": false, "text": "<p>In my case , I used the 'is' a jQuery function, I had a HTML element with different css classes added , I was looking for a specific class in the middle of these , so I used the \"is\" a good alternative to check a class dynamically added to an html element , which already has other css classes, it is another good alternative.</p>\n\n<p><strong>simple example :</strong> </p>\n\n<pre><code> &lt;!--element html--&gt;\n &lt;nav class=\"cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open\" id=\"menu\"&gt;somethings here... &lt;/nav&gt;\n\n &lt;!--jQuery \"is\"--&gt;\n $('#menu').is('.cbp-spmenu-open');\n</code></pre>\n\n<p><strong>advanced example :</strong> </p>\n\n<pre><code> &lt;!--element html--&gt;\n &lt;nav class=\"cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open\" id=\"menu\"&gt;somethings here... &lt;/nav&gt;\n\n &lt;!--jQuery \"is\"--&gt;\n if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){\n $(\"#menu\").show();\n }\n</code></pre>\n" }, { "answer_id": 42227240, "author": "Derek Ekins", "author_id": 98078, "author_profile": "https://Stackoverflow.com/users/98078", "pm_score": 2, "selected": false, "text": "<p>In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:</p>\n\n<pre><code>element.classList.contains('your-class-name')\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13279/" ]
I'm working with jQuery and looking to see if there is an easy way to determine if the element has a specific CSS class associated with it. I have the id of the element, and the CSS class that I'm looking for. I just need to be able to, in an if statement, do a comparison based on the existence of that class on the element.
Use the `hasClass` method: ``` jQueryCollection.hasClass(className); ``` or ``` $(selector).hasClass(className); ``` The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods). **Note:** If you pass a `className` argument that contains whitespace, it will be matched literally against the collection's elements' `className` string. So if, for instance, you have an element, ``` <span class="foo bar" /> ``` then this will return `true`: ``` $('span').hasClass('foo bar') ``` and these will return `false`: ``` $('span').hasClass('bar foo') $('span').hasClass('foo bar') ```
263,234
<p>I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form_Resize event. </p> <p>This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minimize resources when minimizing to system tray, just like Visual Studio does. If you are coding in Visual Studio, the memory usage can creep up (depending on project size) to above 500 MB, but when minimizing Visual Studio to the taskbar, the memory drastically decreases to (what I'm assuming) is the minimal amount. </p> <p>Does anyone have any clue as to how to accomplish this? </p> <p>Here's a short description of the application, if anyone finds it relevant: I have a windows form with a ListView that contains Work Orders for my IT department. The application has a "listener" that notifies when a new Work order is submitted. So, when the application is running in the system tray, all I really do is compare the count of items in the ListView to a count of rows in a SQL table every couple of minutes. </p> <p>EDIT: To be more specific, a windows form intrinsically has threads and resources being used by means of the controls, when the form is invisible (in the system tray) these resources are still being used. What can I do to minimize these resources, short of killing all the controls and redrawing them when the form is restored.</p>
[ { "answer_id": 263262, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>To clean up unused memory, use GC.Collect()... though you should read up on why to do it and why its usually a bad idea to use it often.</p>\n\n<p>If you mean other resources, you will need to be more specific. </p>\n" }, { "answer_id": 263297, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 2, "selected": false, "text": "<p>You're probably looking for this function call: <a href=\"http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx\" rel=\"nofollow noreferrer\">SetProcessWorkingSetSize</a></p>\n\n<p>If you execute the API call SetProcessWorkingSetSize with -1 as an argument, then Windows will trim the working set immediately.</p>\n\n<p>However, if most of the memory is still being held by resources you haven't released minimizing the working set will do nothing. This combined with the suggestion of forcing Garbage Collection might be your best bet.</p>\n\n<p>From your application description, you might want to also verify how much memory the ListView is consuming as well as the database access objects. I'm also not clear on how you're making those monitoring database calls. You might want to isolate that into a separate object and avoid touching any of the forms while minimized, otherwise the program will be forced to keep the controls loaded and accessible. You could start a separate thread for monitoring, and pass the ListView.Count as a parameter.</p>\n\n<p>Some sources:</p>\n\n<p><a href=\"http://www.ddj.com/windows/184416804\" rel=\"nofollow noreferrer\">.NET Applications and the Working Set</a></p>\n\n<p><a href=\"http://www.itwriting.com/dotnetmem.php\" rel=\"nofollow noreferrer\">How much memory does my .Net Application use?</a></p>\n" }, { "answer_id": 263459, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 4, "selected": true, "text": "<p>Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.</p>\n\n<pre><code>public static void MinimizeMemory()\n{\n GC.Collect(GC.MaxGeneration);\n GC.WaitForPendingFinalizers();\n SetProcessWorkingSetSize(\n Process.GetCurrentProcess().Handle,\n (UIntPtr)0xFFFFFFFF,\n (UIntPtr)0xFFFFFFFF);\n\n IntPtr heap = GetProcessHeap();\n\n if (HeapLock(heap))\n {\n try\n {\n if (HeapCompact(heap, 0) == 0)\n {\n // error condition ignored\n }\n }\n finally\n {\n HeapUnlock(heap);\n }\n }\n}\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool SetProcessWorkingSetSize(\n IntPtr process,\n UIntPtr minimumWorkingSetSize,\n UIntPtr maximumWorkingSetSize);\n\n[DllImport(\"kernel32.dll\", SetLastError = true)]\ninternal static extern IntPtr GetProcessHeap();\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapLock(IntPtr heap);\n\n[DllImport(\"kernel32.dll\")]\ninternal static extern uint HeapCompact(IntPtr heap, uint flags);\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapUnlock(IntPtr heap);\n</code></pre>\n" }, { "answer_id": 297225, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>While this is in C#, look at the source code, it will solve any issues you have:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/NotifyIconExample.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/NotifyIconExample.aspx</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25962/" ]
I have a WinForms application (I'm using VB) that can be minimized to the system tray. I used the "hackish" methods described in multiple posts utilizing a NotifyIcon and playing with the Form\_Resize event. This all works fine aesthetically, but the resources and memory used are unaffected. I want to be able to minimize resources when minimizing to system tray, just like Visual Studio does. If you are coding in Visual Studio, the memory usage can creep up (depending on project size) to above 500 MB, but when minimizing Visual Studio to the taskbar, the memory drastically decreases to (what I'm assuming) is the minimal amount. Does anyone have any clue as to how to accomplish this? Here's a short description of the application, if anyone finds it relevant: I have a windows form with a ListView that contains Work Orders for my IT department. The application has a "listener" that notifies when a new Work order is submitted. So, when the application is running in the system tray, all I really do is compare the count of items in the ListView to a count of rows in a SQL table every couple of minutes. EDIT: To be more specific, a windows form intrinsically has threads and resources being used by means of the controls, when the form is invisible (in the system tray) these resources are still being used. What can I do to minimize these resources, short of killing all the controls and redrawing them when the form is restored.
Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap. ``` public static void MinimizeMemory() { GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); SetProcessWorkingSetSize( Process.GetCurrentProcess().Handle, (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF); IntPtr heap = GetProcessHeap(); if (HeapLock(heap)) { try { if (HeapCompact(heap, 0) == 0) { // error condition ignored } } finally { HeapUnlock(heap); } } } [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetProcessWorkingSetSize( IntPtr process, UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize); [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetProcessHeap(); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapLock(IntPtr heap); [DllImport("kernel32.dll")] internal static extern uint HeapCompact(IntPtr heap, uint flags); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapUnlock(IntPtr heap); ```
263,249
<p>Are there any good <a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/ValueListHandler.html" rel="noreferrer">value list handler</a> implementations available?</p> <p>I've found <a href="http://valuelist.sourceforge.net/" rel="noreferrer">valuelist</a>, but it seems to be stagnating... besides I really need good control of links the taglib generates, because I need to call some JavaScript from it.</p> <p>Currently I solve it by rewriting the taglib in freemarker and using valuelist's backend.</p> <p>Does anyone know a better way?</p>
[ { "answer_id": 263262, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>To clean up unused memory, use GC.Collect()... though you should read up on why to do it and why its usually a bad idea to use it often.</p>\n\n<p>If you mean other resources, you will need to be more specific. </p>\n" }, { "answer_id": 263297, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 2, "selected": false, "text": "<p>You're probably looking for this function call: <a href=\"http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx\" rel=\"nofollow noreferrer\">SetProcessWorkingSetSize</a></p>\n\n<p>If you execute the API call SetProcessWorkingSetSize with -1 as an argument, then Windows will trim the working set immediately.</p>\n\n<p>However, if most of the memory is still being held by resources you haven't released minimizing the working set will do nothing. This combined with the suggestion of forcing Garbage Collection might be your best bet.</p>\n\n<p>From your application description, you might want to also verify how much memory the ListView is consuming as well as the database access objects. I'm also not clear on how you're making those monitoring database calls. You might want to isolate that into a separate object and avoid touching any of the forms while minimized, otherwise the program will be forced to keep the controls loaded and accessible. You could start a separate thread for monitoring, and pass the ListView.Count as a parameter.</p>\n\n<p>Some sources:</p>\n\n<p><a href=\"http://www.ddj.com/windows/184416804\" rel=\"nofollow noreferrer\">.NET Applications and the Working Set</a></p>\n\n<p><a href=\"http://www.itwriting.com/dotnetmem.php\" rel=\"nofollow noreferrer\">How much memory does my .Net Application use?</a></p>\n" }, { "answer_id": 263459, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 4, "selected": true, "text": "<p>Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.</p>\n\n<pre><code>public static void MinimizeMemory()\n{\n GC.Collect(GC.MaxGeneration);\n GC.WaitForPendingFinalizers();\n SetProcessWorkingSetSize(\n Process.GetCurrentProcess().Handle,\n (UIntPtr)0xFFFFFFFF,\n (UIntPtr)0xFFFFFFFF);\n\n IntPtr heap = GetProcessHeap();\n\n if (HeapLock(heap))\n {\n try\n {\n if (HeapCompact(heap, 0) == 0)\n {\n // error condition ignored\n }\n }\n finally\n {\n HeapUnlock(heap);\n }\n }\n}\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool SetProcessWorkingSetSize(\n IntPtr process,\n UIntPtr minimumWorkingSetSize,\n UIntPtr maximumWorkingSetSize);\n\n[DllImport(\"kernel32.dll\", SetLastError = true)]\ninternal static extern IntPtr GetProcessHeap();\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapLock(IntPtr heap);\n\n[DllImport(\"kernel32.dll\")]\ninternal static extern uint HeapCompact(IntPtr heap, uint flags);\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapUnlock(IntPtr heap);\n</code></pre>\n" }, { "answer_id": 297225, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>While this is in C#, look at the source code, it will solve any issues you have:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/NotifyIconExample.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/NotifyIconExample.aspx</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24443/" ]
Are there any good [value list handler](http://java.sun.com/blueprints/corej2eepatterns/Patterns/ValueListHandler.html) implementations available? I've found [valuelist](http://valuelist.sourceforge.net/), but it seems to be stagnating... besides I really need good control of links the taglib generates, because I need to call some JavaScript from it. Currently I solve it by rewriting the taglib in freemarker and using valuelist's backend. Does anyone know a better way?
Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap. ``` public static void MinimizeMemory() { GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); SetProcessWorkingSetSize( Process.GetCurrentProcess().Handle, (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF); IntPtr heap = GetProcessHeap(); if (HeapLock(heap)) { try { if (HeapCompact(heap, 0) == 0) { // error condition ignored } } finally { HeapUnlock(heap); } } } [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetProcessWorkingSetSize( IntPtr process, UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize); [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetProcessHeap(); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapLock(IntPtr heap); [DllImport("kernel32.dll")] internal static extern uint HeapCompact(IntPtr heap, uint flags); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapUnlock(IntPtr heap); ```
263,263
<p>I'm using Apache Subversion to manage and store a decent volume of code. Trying to get at it on a standard work machine using svn+ssh with TortoiseSVN on Windows Vista, I find that I can't actually bring all of it down to my local machine at once - the transfer stops after about 1 MB. I can grab it all in fits and starts by canceling the process and updating the incomplete working copy, but that's not the real problem.</p> <p>The real problem is, trying to merge multiple code branches requires enough data transfer to choke the connection, and as far as I can tell there's no such thing as resuming an incomplete merge. </p> <p>I have no idea why this is happening - the only resolution steps that have fixed the problem for anyone else on my Google crawl seems to indicate an aggressive antivirus might have something to do with it, but disabling the one that was installed on the work machine (Symantec Endpoint Protection) or ordering it to ignore the destination directory and transfer process doesn't seem to help any.</p> <p><strong>Anybody out there seen TortoiseSVN flat-out stop when transferring modest quantities of information, and what can I tweak to fix the problem?</strong> </p> <p>I'm pretty sure it's not Vista-specific, since my buddy with his Windows XP machine from the last rollout is having exactly the same problem.</p> <p>A little extra information:</p> <ul> <li><p>TortoiseSVN version 1.5.5, 32-bit on a 32-bit version of Vista.</p></li> <li><p>Connecting to a Solaris 9 box over SSH 1, running Subversion 1.5.3. The version of Solaris and SSH aren't negotiable, since this is a repurposed old server and we manage configurations pretty strictly. </p></li> <li><p>I've poked around on the Solaris machine and it doesn't look like there are problems at all, aside from the system trying to Kerberos-authenticate me and failing. The process is apparently just waiting for client-side input (in the middle of a checkout?) and Tortoise doesn't seem to be providing the right kind.</p></li> <li><p>Switching to, say, PLink from TortoisePLink doesn't seem to make any difference - the process begins, but when it stalls out I'm not seeing anything in the terminal window.</p></li> </ul> <p>Even some help on figuring out what's going wrong here would be appreciated.</p>
[ { "answer_id": 263262, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>To clean up unused memory, use GC.Collect()... though you should read up on why to do it and why its usually a bad idea to use it often.</p>\n\n<p>If you mean other resources, you will need to be more specific. </p>\n" }, { "answer_id": 263297, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 2, "selected": false, "text": "<p>You're probably looking for this function call: <a href=\"http://msdn.microsoft.com/en-us/library/ms686234(VS.85).aspx\" rel=\"nofollow noreferrer\">SetProcessWorkingSetSize</a></p>\n\n<p>If you execute the API call SetProcessWorkingSetSize with -1 as an argument, then Windows will trim the working set immediately.</p>\n\n<p>However, if most of the memory is still being held by resources you haven't released minimizing the working set will do nothing. This combined with the suggestion of forcing Garbage Collection might be your best bet.</p>\n\n<p>From your application description, you might want to also verify how much memory the ListView is consuming as well as the database access objects. I'm also not clear on how you're making those monitoring database calls. You might want to isolate that into a separate object and avoid touching any of the forms while minimized, otherwise the program will be forced to keep the controls loaded and accessible. You could start a separate thread for monitoring, and pass the ListView.Count as a parameter.</p>\n\n<p>Some sources:</p>\n\n<p><a href=\"http://www.ddj.com/windows/184416804\" rel=\"nofollow noreferrer\">.NET Applications and the Working Set</a></p>\n\n<p><a href=\"http://www.itwriting.com/dotnetmem.php\" rel=\"nofollow noreferrer\">How much memory does my .Net Application use?</a></p>\n" }, { "answer_id": 263459, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 4, "selected": true, "text": "<p>Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap.</p>\n\n<pre><code>public static void MinimizeMemory()\n{\n GC.Collect(GC.MaxGeneration);\n GC.WaitForPendingFinalizers();\n SetProcessWorkingSetSize(\n Process.GetCurrentProcess().Handle,\n (UIntPtr)0xFFFFFFFF,\n (UIntPtr)0xFFFFFFFF);\n\n IntPtr heap = GetProcessHeap();\n\n if (HeapLock(heap))\n {\n try\n {\n if (HeapCompact(heap, 0) == 0)\n {\n // error condition ignored\n }\n }\n finally\n {\n HeapUnlock(heap);\n }\n }\n}\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool SetProcessWorkingSetSize(\n IntPtr process,\n UIntPtr minimumWorkingSetSize,\n UIntPtr maximumWorkingSetSize);\n\n[DllImport(\"kernel32.dll\", SetLastError = true)]\ninternal static extern IntPtr GetProcessHeap();\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapLock(IntPtr heap);\n\n[DllImport(\"kernel32.dll\")]\ninternal static extern uint HeapCompact(IntPtr heap, uint flags);\n\n[DllImport(\"kernel32.dll\")]\n[return: MarshalAs(UnmanagedType.Bool)]\ninternal static extern bool HeapUnlock(IntPtr heap);\n</code></pre>\n" }, { "answer_id": 297225, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>While this is in C#, look at the source code, it will solve any issues you have:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/NotifyIconExample.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/NotifyIconExample.aspx</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34384/" ]
I'm using Apache Subversion to manage and store a decent volume of code. Trying to get at it on a standard work machine using svn+ssh with TortoiseSVN on Windows Vista, I find that I can't actually bring all of it down to my local machine at once - the transfer stops after about 1 MB. I can grab it all in fits and starts by canceling the process and updating the incomplete working copy, but that's not the real problem. The real problem is, trying to merge multiple code branches requires enough data transfer to choke the connection, and as far as I can tell there's no such thing as resuming an incomplete merge. I have no idea why this is happening - the only resolution steps that have fixed the problem for anyone else on my Google crawl seems to indicate an aggressive antivirus might have something to do with it, but disabling the one that was installed on the work machine (Symantec Endpoint Protection) or ordering it to ignore the destination directory and transfer process doesn't seem to help any. **Anybody out there seen TortoiseSVN flat-out stop when transferring modest quantities of information, and what can I tweak to fix the problem?** I'm pretty sure it's not Vista-specific, since my buddy with his Windows XP machine from the last rollout is having exactly the same problem. A little extra information: * TortoiseSVN version 1.5.5, 32-bit on a 32-bit version of Vista. * Connecting to a Solaris 9 box over SSH 1, running Subversion 1.5.3. The version of Solaris and SSH aren't negotiable, since this is a repurposed old server and we manage configurations pretty strictly. * I've poked around on the Solaris machine and it doesn't look like there are problems at all, aside from the system trying to Kerberos-authenticate me and failing. The process is apparently just waiting for client-side input (in the middle of a checkout?) and Tortoise doesn't seem to be providing the right kind. * Switching to, say, PLink from TortoisePLink doesn't seem to make any difference - the process begins, but when it stalls out I'm not seeing anything in the terminal window. Even some help on figuring out what's going wrong here would be appreciated.
Calling MiniMizeMemory() will do a garbage collection, trim the process working size, then compact the process' heap. ``` public static void MinimizeMemory() { GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); SetProcessWorkingSetSize( Process.GetCurrentProcess().Handle, (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF); IntPtr heap = GetProcessHeap(); if (HeapLock(heap)) { try { if (HeapCompact(heap, 0) == 0) { // error condition ignored } } finally { HeapUnlock(heap); } } } [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetProcessWorkingSetSize( IntPtr process, UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize); [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetProcessHeap(); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapLock(IntPtr heap); [DllImport("kernel32.dll")] internal static extern uint HeapCompact(IntPtr heap, uint flags); [DllImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool HeapUnlock(IntPtr heap); ```
263,267
<p>Is there a way, within the .net framework, to check to see if two different shared folders are actually pointing to the same physical directory? Do directories in Windows have some sort of unique identifier? Google-fu is failing me.</p> <p>(I mean, aside from writing a temp file to one and seeing if it appears in the other)</p> <p>Edit: I think I've discovered what I need,with thanks to Brody for getting me pointed in the right direction in the System.Management namespace.</p>
[ { "answer_id": 264280, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 0, "selected": false, "text": "<p>You can examine the share definition itself by using the System.Management namespace but it is not easy to use.</p>\n\n<p>it starts something like</p>\n\n<pre><code>ManagementClass management = new ManagementClass(\"\\\\\\\\.\\\\root\\\\cimv2\", \"Win32_Share\", null)\n</code></pre>\n\n<p>And it gets much worse after that. I have used it to create a share. Hopefully you can use it to the path for each share and compare.</p>\n" }, { "answer_id": 264650, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 0, "selected": false, "text": "<p>I think the .NET framework doesn't provide the information you need for comparing 2 directories ...\nYou have to take an unmanaged approach. This is how I did it:</p>\n\n<pre><code>class Program\n{\n struct BY_HANDLE_FILE_INFORMATION\n {\n public uint FileAttributes;\n public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;\n public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;\n public uint VolumeSerialNumber;\n public uint FileSizeHigh;\n public uint FileSizeLow;\n public uint NumberOfLinks;\n public uint FileIndexHigh;\n public uint FileIndexLow;\n }\n\n //\n // CreateFile constants\n //\n const uint FILE_SHARE_READ = 0x00000001;\n const uint FILE_SHARE_WRITE = 0x00000002;\n const uint FILE_SHARE_DELETE = 0x00000004;\n const uint OPEN_EXISTING = 3;\n\n const uint GENERIC_READ = (0x80000000);\n const uint GENERIC_WRITE = (0x40000000);\n\n const uint FILE_FLAG_NO_BUFFERING = 0x20000000;\n const uint FILE_READ_ATTRIBUTES = (0x0080);\n const uint FILE_WRITE_ATTRIBUTES = 0x0100;\n const uint ERROR_INSUFFICIENT_BUFFER = 122;\n const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;\n\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern IntPtr CreateFile(\n string lpFileName,\n uint dwDesiredAccess,\n uint dwShareMode,\n IntPtr lpSecurityAttributes,\n uint dwCreationDisposition,\n uint dwFlagsAndAttributes,\n IntPtr hTemplateFile);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);\n\n static void Main(string[] args)\n {\n string dir1 = @\"C:\\MyTestDir\";\n string dir2 = @\"\\\\myMachine\\MyTestDir\";\n Console.WriteLine(CompareDirectories(dir1, dir2));\n }\n\n static bool CompareDirectories(string dir1, string dir2)\n {\n BY_HANDLE_FILE_INFORMATION fileInfo1, fileInfo2;\n IntPtr ptr1 = CreateFile(dir1, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr1 == -1)\n {\n System.ComponentModel.Win32Exception t = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n Console.WriteLine(dir1 + \": \" + t.Message);\n return false;\n }\n IntPtr ptr2 = CreateFile(dir2, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);\n if ((int)ptr2 == -1)\n {\n System.ComponentModel.Win32Exception t = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n Console.WriteLine(dir2 + \": \" + t.Message);\n return false;\n }\n GetFileInformationByHandle(ptr1, out fileInfo1);\n GetFileInformationByHandle(ptr2, out fileInfo2);\n\n return ((fileInfo1.FileIndexHigh == fileInfo2.FileIndexHigh) &amp;&amp;\n (fileInfo1.FileIndexLow == fileInfo2.FileIndexLow));\n }\n}\n</code></pre>\n\n<p>It works! Hope this helps.</p>\n\n<p>Cheers.</p>\n" }, { "answer_id": 265997, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 1, "selected": true, "text": "<p>I believe using WMI queries will take care of what I need to do:</p>\n\n<pre><code>Connection options = new ConnectionOptions();\nManagementScope scpoe = new ManagementScope(\"\\\\\\\\Server\\\\root\\\\cimv2\", options);\nObjectQuery query = new ObjectQuery(\"SELECT * FROM Win32_Share WHERE Name = '\" + name +\"'\")\n\nManagementObjectSearcher searcher = new ManagementObjectSearch(scope, query);\nManagementObjectCollection qc = searcher.Get();\n\nforeach (ManagementObject m in qc) {\n Console.WriteLine(m[\"Path\"]);\n}\n</code></pre>\n\n<p>And the Path attribute will give me the physical path of the share, which I can use to compare the two shares.</p>\n" }, { "answer_id": 266040, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "<p>If you don't go WMI, the unmanaged call is <a href=\"http://msdn.microsoft.com/en-us/library/bb525387(VS.85).aspx\" rel=\"nofollow noreferrer\">NetShareEnum</a> with a servername of NULL (local computer) and a level of 502 to get a <a href=\"http://msdn.microsoft.com/en-us/library/bb525410(VS.85).aspx\" rel=\"nofollow noreferrer\">SHARE_INFO_502</a> struct. The local path is in shi502_path.</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/netapi32/NetShareEnum.html\" rel=\"nofollow noreferrer\">P/Invoke info</a>, as always, is over at pinvoke.net.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
Is there a way, within the .net framework, to check to see if two different shared folders are actually pointing to the same physical directory? Do directories in Windows have some sort of unique identifier? Google-fu is failing me. (I mean, aside from writing a temp file to one and seeing if it appears in the other) Edit: I think I've discovered what I need,with thanks to Brody for getting me pointed in the right direction in the System.Management namespace.
I believe using WMI queries will take care of what I need to do: ``` Connection options = new ConnectionOptions(); ManagementScope scpoe = new ManagementScope("\\\\Server\\root\\cimv2", options); ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Share WHERE Name = '" + name +"'") ManagementObjectSearcher searcher = new ManagementObjectSearch(scope, query); ManagementObjectCollection qc = searcher.Get(); foreach (ManagementObject m in qc) { Console.WriteLine(m["Path"]); } ``` And the Path attribute will give me the physical path of the share, which I can use to compare the two shares.
263,271
<p>I have a Ruby script that generates a UTF8 CSV file remotely in a Linux machine and then transfers the file to a Windows machine thru SFTP. </p> <p>I then need to open this file with Excel, but Excel doesn't get UTF8, so I always need to open the file in a text editor that has the capability to convert UTF8 to ANSI.</p> <p>I would love to do this programmatically using Ruby and avoid the manual conversion step. What's the easiest way to do it?</p> <p>PS: I tried using iconv but had no success.</p>
[ { "answer_id": 263324, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 5, "selected": true, "text": "<pre><code>ascii_str = yourUTF8text.unpack(\"U*\").map{|c|c.chr}.join\n</code></pre>\n\n<p>assuming that your text really does fit in the ascii character set.</p>\n" }, { "answer_id": 263326, "author": "Dema", "author_id": 407003, "author_profile": "https://Stackoverflow.com/users/407003", "pm_score": 4, "selected": false, "text": "<p>I finally managed to do it using iconv, I was just messing up the parameters. So, this is how you do it:</p>\n\n<pre><code>\nrequire 'iconv'\n\nutf8_csv = File.open(\"utf8file.csv\").read\n\n# gotta be careful with the weird parameters order: TO, FROM !\nansi_csv = Iconv.iconv(\"LATIN1\", \"UTF-8\", utf8_csv).join\n\nFile.open(\"ansifile.csv\", \"w\") { |f| f.puts ansi_csv }\n</code></pre>\n\n<p>That's it!</p>\n" }, { "answer_id": 32193780, "author": "markquezada", "author_id": 264230, "author_profile": "https://Stackoverflow.com/users/264230", "pm_score": 3, "selected": false, "text": "<p>I had a similar issue trying to generate CSV files from user-generated content on the server. I found the <a href=\"https://github.com/norman/unidecoder\" rel=\"noreferrer\">unidecoder</a> gem which does a nice job of transliterating unicode characters into ascii.</p>\n\n<p>Example:</p>\n\n<pre><code>\"olá, mundo!\".to_ascii #=&gt; \"ola, mundo!\"\n\"你好\".to_ascii #=&gt; \"Ni Hao \"\n\"Jürgen Müller\".to_ascii #=&gt; \"Jurgen Muller\"\n\"Jürgen Müller\".to_ascii(\"ü\" =&gt; \"ue\") #=&gt; \"Juergen Mueller\"\n</code></pre>\n\n<p>For our simple use case, this worked well.</p>\n\n<p>Pivotal Labs has a great blog post on <a href=\"http://blog.pivotal.io/labs/labs/unicode-transliteration-to-ascii\" rel=\"noreferrer\">unicode transliteration to ascii</a> discussing this in more detail.</p>\n" }, { "answer_id": 45765288, "author": "knut", "author_id": 676874, "author_profile": "https://Stackoverflow.com/users/676874", "pm_score": 3, "selected": false, "text": "<p>Since ruby 1.9 there is an easier way:</p>\n\n<pre><code>yourstring.encode('ASCII')\n</code></pre>\n\n<p>To avoid problems with invalid (non-ASCII) characters you can ignore the problems:</p>\n\n<pre><code>yourstring.encode('ASCII', invalid: :replace, undef: :replace, replace: \"_\")\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407003/" ]
I have a Ruby script that generates a UTF8 CSV file remotely in a Linux machine and then transfers the file to a Windows machine thru SFTP. I then need to open this file with Excel, but Excel doesn't get UTF8, so I always need to open the file in a text editor that has the capability to convert UTF8 to ANSI. I would love to do this programmatically using Ruby and avoid the manual conversion step. What's the easiest way to do it? PS: I tried using iconv but had no success.
``` ascii_str = yourUTF8text.unpack("U*").map{|c|c.chr}.join ``` assuming that your text really does fit in the ascii character set.
263,296
<p>I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial:</p> <p><a href="http://code.activestate.com/recipes/551780/" rel="noreferrer">http://code.activestate.com/recipes/551780/</a></p> <p>What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following:</p> <pre><code>mydaemon = Daemon __svc_regClass__(mydaemon, "foo", "foo display", "foo description") __svc_install__(mydaemon) </code></pre> <p>Where <strong>svc_install</strong>, handles the initalization, by calling Daemon.<strong>init</strong>() and passing some arguments to it. </p> <p>But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas?</p> <pre><code>class Daemon(win32serviceutil.ServiceFramework): def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcDoRun(self): self.run() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def start(self): pass def stop(self): self.SvcStop() def run(self): pass def __svc_install__(cls): win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType = win32service.SERVICE_AUTO_START ) print "Installed" except Exception, err: print str(err) def __svc_regClass__(cls, name, display_name, description): #Bind the values to the service name cls._svc_name_ = name cls._svc_display_name_ = display_name cls._svc_description_ = description try: module_path = sys.modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path = executable module_file = os.path.splitext(os.path.abspath(module_path))[0] cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__) </code></pre>
[ { "answer_id": 264871, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 4, "selected": true, "text": "<p>I've never used these APIs, but digging through the code, it looks like the class passed in is used to register the name of the class in the registry, so you can't do any initialization of your own. But there's a method called GetServiceCustomOption that may help:</p>\n\n<p><a href=\"http://mail.python.org/pipermail/python-win32/2006-April/004518.html\" rel=\"noreferrer\">http://mail.python.org/pipermail/python-win32/2006-April/004518.html</a></p>\n" }, { "answer_id": 900775, "author": "markuz", "author_id": 32526, "author_profile": "https://Stackoverflow.com/users/32526", "pm_score": 3, "selected": false, "text": "<p>I just create a simple \"how to\" where the program is in one module and the service is in another place, it uses py2exe to create the win32 service, which I believe is the best you can do for your users that don't want to mess with the python interpreter or other dependencies.</p>\n\n<p>You can check my tutorial here: <a href=\"http://islascruz.org/html/index.php?gadget=StaticPage&amp;action=Page&amp;id=6\" rel=\"noreferrer\">Create win32 services using Python and py2exe</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34395/" ]
I am currently trying to create a win32 service using pywin32. My main point of reference has been this tutorial: <http://code.activestate.com/recipes/551780/> What i don't understand is the initialization process, since the Daemon is never initialized directly by Daemon(), instead from my understanding its initialized by the following: ``` mydaemon = Daemon __svc_regClass__(mydaemon, "foo", "foo display", "foo description") __svc_install__(mydaemon) ``` Where **svc\_install**, handles the initalization, by calling Daemon.**init**() and passing some arguments to it. But how can i initialize the daemon object, without initalizing the service? I want to do a few things, before i init the service. Does anyone have any ideas? ``` class Daemon(win32serviceutil.ServiceFramework): def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcDoRun(self): self.run() def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def start(self): pass def stop(self): self.SvcStop() def run(self): pass def __svc_install__(cls): win32api.SetConsoleCtrlHandler(lambda x: True, True) try: win32serviceutil.InstallService( cls._svc_reg_class_, cls._svc_name_, cls._svc_display_name_, startType = win32service.SERVICE_AUTO_START ) print "Installed" except Exception, err: print str(err) def __svc_regClass__(cls, name, display_name, description): #Bind the values to the service name cls._svc_name_ = name cls._svc_display_name_ = display_name cls._svc_description_ = description try: module_path = sys.modules[cls.__module__].__file__ except AttributeError: from sys import executable module_path = executable module_file = os.path.splitext(os.path.abspath(module_path))[0] cls._svc_reg_class_ = '%s.%s' % (module_file, cls.__name__) ```
I've never used these APIs, but digging through the code, it looks like the class passed in is used to register the name of the class in the registry, so you can't do any initialization of your own. But there's a method called GetServiceCustomOption that may help: <http://mail.python.org/pipermail/python-win32/2006-April/004518.html>
263,322
<p>What is the best way to add "copy to clipboard" functionality to a ListView control in WPF?</p> <p>I tried adding an ApplicationCommands.Copy to either the ListView ContextMenu or the ListViewItem ContextMenu, but the command remains disabled.</p> <p>Thanks, Peter</p> <p>Here is an xaml sample of one of my attempts...</p> <pre><code> &lt;Window.Resources&gt; &lt;ContextMenu x:Key="SharedInstanceContextMenu" x:Shared="True"&gt; &lt;MenuItem Header="Copy" Command="ApplicationCommands.Copy"/&gt; &lt;/ContextMenu&gt; &lt;/Window.Resources&gt; &lt;ListBox Margin="12,233,225,68" Name="listBox1" &gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding Path=UpToSourceCategoryByCategoryId.Category}" ContextMenu="{DynamicResource ResourceKey=SharedInstanceContextMenu}"/&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>How should I set the CommandTarget in this case?</p> <p>Thanks,Peter</p>
[ { "answer_id": 263540, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 3, "selected": true, "text": "<p>It looks like you need a CommandBinding.</p>\n\n<p>Here is how I would probably go about doing what you trying to do.</p>\n\n<pre><code>&lt;Window.CommandBindings&gt;\n &lt;CommandBinding\n Command=\"ApplicationCommands.Copy\"\n Executed=\"CopyCommandHandler\"\n CanExecute=\"CanCopyExecuteHandler\" /&gt;\n&lt;/Window.CommandBindings&gt;\n\n&lt;Window.Resources&gt;\n &lt;ContextMenu x:Key=\"SharedInstanceContextMenu\"&gt;\n &lt;MenuItem Header=\"Copy\" Command=\"ApplicationCommands.Copy\"/&gt;\n &lt;/ContextMenu&gt;\n\n &lt;Style x:Key=\"MyItemContainerStyle\" TargetType=\"{x:Type ListBoxItem}\"&gt;\n &lt;Setter Property=\"ContextMenu\" Value=\"{StaticResource SharedInstanceContextMenu}\" /&gt;\n &lt;/Style&gt;\n&lt;/Window.Resources&gt;\n\n&lt;ListBox ItemContainerStyle=\"{StaticResource MyItemContainerStyle}\"&gt;\n &lt;ListBoxItem&gt;One&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Two&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Three&lt;/ListBoxItem&gt;\n &lt;ListBoxItem&gt;Four&lt;/ListBoxItem&gt;\n&lt;/ListBox&gt;\n</code></pre>\n" }, { "answer_id": 663944, "author": "jannmueller", "author_id": 80212, "author_profile": "https://Stackoverflow.com/users/80212", "pm_score": 1, "selected": false, "text": "<p>It is also possible to achieve this functionality via an attached property, as I described it on my <a href=\"http://jannsblog.wordpress.com/2009/03/10/copy-a-listview%E2%80%99s-items-to-the-clipboard/\" rel=\"nofollow noreferrer\">blog</a>. The idea is to register the ApplicationCommands.Copy command with the ListView and, when the command is executed, read the values from the data bindings.</p>\n\n<p>You'll find a downloadable sample on the blog entry, too.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34403/" ]
What is the best way to add "copy to clipboard" functionality to a ListView control in WPF? I tried adding an ApplicationCommands.Copy to either the ListView ContextMenu or the ListViewItem ContextMenu, but the command remains disabled. Thanks, Peter Here is an xaml sample of one of my attempts... ``` <Window.Resources> <ContextMenu x:Key="SharedInstanceContextMenu" x:Shared="True"> <MenuItem Header="Copy" Command="ApplicationCommands.Copy"/> </ContextMenu> </Window.Resources> <ListBox Margin="12,233,225,68" Name="listBox1" > <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Path=UpToSourceCategoryByCategoryId.Category}" ContextMenu="{DynamicResource ResourceKey=SharedInstanceContextMenu}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` How should I set the CommandTarget in this case? Thanks,Peter
It looks like you need a CommandBinding. Here is how I would probably go about doing what you trying to do. ``` <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Copy" Executed="CopyCommandHandler" CanExecute="CanCopyExecuteHandler" /> </Window.CommandBindings> <Window.Resources> <ContextMenu x:Key="SharedInstanceContextMenu"> <MenuItem Header="Copy" Command="ApplicationCommands.Copy"/> </ContextMenu> <Style x:Key="MyItemContainerStyle" TargetType="{x:Type ListBoxItem}"> <Setter Property="ContextMenu" Value="{StaticResource SharedInstanceContextMenu}" /> </Style> </Window.Resources> <ListBox ItemContainerStyle="{StaticResource MyItemContainerStyle}"> <ListBoxItem>One</ListBoxItem> <ListBoxItem>Two</ListBoxItem> <ListBoxItem>Three</ListBoxItem> <ListBoxItem>Four</ListBoxItem> </ListBox> ```
263,336
<p>I'm trying out asp.net mvc for a new project, and I ran across something odd. When I use the MVC UI helpers for textboxes, the values get persisted between calls. But, when I use a series of radio buttons, the checked state doesn't get persisted.</p> <p>Here's an example from my view.</p> <pre><code>&lt;li&gt; &lt;%=Html.RadioButton("providerType","1")%&gt;&lt;label&gt;Hospital&lt;/label&gt; &lt;%=Html.RadioButton("providerType","2")%&gt;&lt;label&gt;Facility&lt;/label&gt; &lt;%=Html.RadioButton("providerType","3")%&gt;&lt;label&gt;Physician&lt;/label&gt; &lt;/li&gt; </code></pre> <p>When the form gets posted back, I build up an object with "ProviderType" as one of it's properties. The value on the object is getting set, and then I RedirectToAction with the provider as a argument. All is well, and I end up at a URL like "<a href="http://localhost/Provider/List?ProviderType=1" rel="noreferrer">http://localhost/Provider/List?ProviderType=1</a>" with ProviderType showing. The value gets persisted to the URL, but the UI helper isn't picking up the checked state.</p> <p>I'm having this problem with listbox, <strike>dropdownlist</strike>, and radiobutton. Textboxes pick up the values just fine. Do you see something I'm doing wrong? I'm assuming that the helpers will do this for me, but maybe I'll just have to take care of this on my own. I'm just feeling my way through this, so your input is appreciated.</p> <p><strong>Edit:</strong> I just found the override for the SelectList constructor that takes a selected value. That took care of my dropdown issue I mentioned above.</p> <p><strong>Edit #2:</strong> I found something that works, but it pains me to do it this way. I feel like this should be inferred.</p> <pre><code>&lt;li&gt; &lt;%=Html.RadioButton("ProviderType","1",Request["ProviderType"]=="1")%&gt;&lt;label&gt;Hospital&lt;/label&gt; &lt;%=Html.RadioButton("ProviderType", "2", Request["ProviderType"] == "2")%&gt;&lt;label&gt;Facility&lt;/label&gt; &lt;%=Html.RadioButton("ProviderType", "3", Request["ProviderType"] == "3")%&gt;&lt;label&gt;Physician&lt;/label&gt; &lt;/li&gt; </code></pre> <p>Hopefully someone will come up with another way.</p>
[ { "answer_id": 263863, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 2, "selected": false, "text": "<p>The form shouldn't be posting to the querystring, unless you forgot to specify the form as method=\"POST\". How are you specifying the form? Are you using ASP.NET MVC Beta?</p>\n" }, { "answer_id": 543011, "author": "Al Katawazi", "author_id": 61962, "author_profile": "https://Stackoverflow.com/users/61962", "pm_score": 1, "selected": false, "text": "<p>Well logically it would not persist, there is no session state. Think of it as an entirely new page. In order to get your radio buttons to populate you need to persist back something like ViewData[\"ProviderType\"] = 3 to have the radiobutton repopulate with its data.</p>\n" }, { "answer_id": 622986, "author": "Jonathan Parker", "author_id": 4504, "author_profile": "https://Stackoverflow.com/users/4504", "pm_score": 2, "selected": false, "text": "<p>What you need is something like this in your view:</p>\n\n<pre><code>&lt;% foreach(var provider in (IEnumerable&lt;Provider&gt;)ViewData[\"Providers\"]) { %&gt;\n &lt;%=Html.RadioButton(\"ProviderType\", provider.ID.ToString(), provider.IsSelected)%&gt;&lt;label&gt;&lt;%=provider.Name%&gt;&lt;/label&gt;\n&lt;% } %&gt;\n</code></pre>\n\n<p>And then in your controller have this:</p>\n\n<pre><code>var providers = GetProviders();\nint selectedId = (int) Request[\"ProviderType\"]; // TODO: Use Int32.TryParse() instead\nforeach(var p in providers)\n{\n if (p.ID == selectedId)\n {\n p.IsSelected = true;\n break;\n }\n}\nViewData[\"Providers\"] = providers;\nreturn View();\n</code></pre>\n\n<p>The Provider class will be something like this:</p>\n\n<pre><code>public class Provider\n{\n public int ID { get; set; }\n public string Name { get; set; }\n public bool IsSelected { get; set; }\n}\n</code></pre>\n" }, { "answer_id": 1225841, "author": "David Gardiner", "author_id": 25702, "author_profile": "https://Stackoverflow.com/users/25702", "pm_score": 3, "selected": false, "text": "<p>If you give the radio buttons the same name as the property on your model, then MVC will automatically set the checked attribute on the appropriate button.</p>\n\n<p>I think this relies on having a strongly typed Model.</p>\n" }, { "answer_id": 2989460, "author": "Cheny", "author_id": 360415, "author_profile": "https://Stackoverflow.com/users/360415", "pm_score": 2, "selected": false, "text": "<p>I'm using vs2010 now, it works like:</p>\n\n<pre><code>&lt;%=Html.RadioButton(\"ProviderType\",\"1\",Model.ProviderType==1)%&gt;&lt;label&gt;Hospital&lt;/label&gt; \n</code></pre>\n\n<p>looks better?</p>\n" }, { "answer_id": 4416150, "author": "K.V. Sai Kishore", "author_id": 538781, "author_profile": "https://Stackoverflow.com/users/538781", "pm_score": -1, "selected": false, "text": "<p>View:</p>\n\n<pre><code>&lt;%=Html.RadioButton(\"providerType\",\"1\")%&gt;&lt;label&gt;Hospital&lt;/label&gt;\n&lt;%=Html.RadioButton(\"providerType\",\"2\")%&gt;&lt;label&gt;Facility&lt;/label&gt;\n&lt;%=Html.RadioButton(\"providerType\",\"3\")%&gt;&lt;label&gt;Physician&lt;/label&gt;\n</code></pre>\n\n<p>Controller:</p>\n\n<pre><code>public ActionResult GetType(FormCollection collection)\n{\n string type=collection.Get(\"providerType\");\n\n if(type==\"1\")\n //code\n else if(type==\"2\")\n //code\n else\n //code\n\n return View();\n}\n</code></pre>\n" }, { "answer_id": 4672183, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 1, "selected": false, "text": "<p>I've made this HTML Helper extension:</p>\n\n<pre><code> &lt;Extension()&gt; _\n Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal name As String, ByVal Items As IEnumerable(Of String)) As String\n Dim selectList = New SelectList(Items)\n Return helper.RadioButtonList(name, selectList)\n End Function\n\n &lt;Extension()&gt; _\n Public Function RadioButtonList(ByVal helper As HtmlHelper, ByVal Name As String, ByVal Items As IEnumerable(Of SelectListItem)) As String\n Dim sb As New StringBuilder\n sb.Append(\"&lt;table class=\"\"radiobuttonlist\"\"&gt;\")\n For Each item In Items\n sb.AppendFormat(\"&lt;tr&gt;&lt;td&gt;&lt;input id=\"\"{0}_{1}\"\" name=\"\"{0}\"\" type=\"\"radio\"\" value=\"\"{1}\"\" {2} /&gt;&lt;label for=\"\"{0}_{1}\"\" id=\"\"{0}_{1}_Label\"\"&gt;{3}&lt;/label&gt;&lt;/td&gt;&lt;tr&gt;\", Name, item.Value, If(item.Selected, \"selected\", \"\"), item.Text)\n Next\n sb.Append(\"&lt;/table&gt;\")\n Return sb.ToString()\n End Function\n</code></pre>\n\n<p>Then in the view:</p>\n\n<pre><code>&lt;%= Html.RadioButtonList(\"ProviderType\", Model.ProviderTypeSelectList) %&gt;\n</code></pre>\n\n<p>In the controller the option is mapped automagically using the standard:</p>\n\n<pre><code>UpdateModel(Provider)\n</code></pre>\n\n<p>Works like a charm. If you are tablephobic, change the markup generated.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672/" ]
I'm trying out asp.net mvc for a new project, and I ran across something odd. When I use the MVC UI helpers for textboxes, the values get persisted between calls. But, when I use a series of radio buttons, the checked state doesn't get persisted. Here's an example from my view. ``` <li> <%=Html.RadioButton("providerType","1")%><label>Hospital</label> <%=Html.RadioButton("providerType","2")%><label>Facility</label> <%=Html.RadioButton("providerType","3")%><label>Physician</label> </li> ``` When the form gets posted back, I build up an object with "ProviderType" as one of it's properties. The value on the object is getting set, and then I RedirectToAction with the provider as a argument. All is well, and I end up at a URL like "<http://localhost/Provider/List?ProviderType=1>" with ProviderType showing. The value gets persisted to the URL, but the UI helper isn't picking up the checked state. I'm having this problem with listbox, dropdownlist, and radiobutton. Textboxes pick up the values just fine. Do you see something I'm doing wrong? I'm assuming that the helpers will do this for me, but maybe I'll just have to take care of this on my own. I'm just feeling my way through this, so your input is appreciated. **Edit:** I just found the override for the SelectList constructor that takes a selected value. That took care of my dropdown issue I mentioned above. **Edit #2:** I found something that works, but it pains me to do it this way. I feel like this should be inferred. ``` <li> <%=Html.RadioButton("ProviderType","1",Request["ProviderType"]=="1")%><label>Hospital</label> <%=Html.RadioButton("ProviderType", "2", Request["ProviderType"] == "2")%><label>Facility</label> <%=Html.RadioButton("ProviderType", "3", Request["ProviderType"] == "3")%><label>Physician</label> </li> ``` Hopefully someone will come up with another way.
If you give the radio buttons the same name as the property on your model, then MVC will automatically set the checked attribute on the appropriate button. I think this relies on having a strongly typed Model.
263,339
<p>I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions.</p> <p>Example: "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc.</p> <p>The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions?</p> <p>Note: boost:: is most welcome! :-)</p> <p><strong>Update</strong> Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)</p>
[ { "answer_id": 263389, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 0, "selected": false, "text": "<p>How many evaluation expressions do intend to have? If it's small enough, you might just want to use brute force.</p>\n\n<p>For instance, if you have a <code>std::map&lt;string, string&gt;</code> that goes from your <code>key</code> to its <code>value</code>, for instance <code>user</code> to <code>Matt Cruikshank</code>, you might just want to iterate over your entire map and do a simple replace on your string of every <code>\"${\" + key + \"}\"</code> to its <code>value</code>.</p>\n" }, { "answer_id": 263391, "author": "Harper Shelby", "author_id": 21196, "author_profile": "https://Stackoverflow.com/users/21196", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.boost.org/doc/libs/1_37_0/libs/regex/doc/html/index.html\" rel=\"nofollow noreferrer\">Boost::Regex</a> would be the route I'd suggest. The <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/regex/doc/html/boost_regex/ref/regex_replace.html\" rel=\"nofollow noreferrer\">regex_replace</a> algorithm should do most of your heavy lifting.</p>\n" }, { "answer_id": 263397, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 0, "selected": false, "text": "<p>If you don't like my first answer, then dig in to Boost Regex - probably <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/regex/doc/html/index.html\" rel=\"nofollow noreferrer\">boost::regex_replace</a>.</p>\n" }, { "answer_id": 263417, "author": "Martin C. Martin", "author_id": 34382, "author_profile": "https://Stackoverflow.com/users/34382", "pm_score": 0, "selected": false, "text": "<p>How complex can the expressions get? Are they just identifiers, or can they be actual expressions like \"${numBad/(double)total*100.0}%\"?</p>\n" }, { "answer_id": 263418, "author": "Glenn", "author_id": 25191, "author_profile": "https://Stackoverflow.com/users/25191", "pm_score": 0, "selected": false, "text": "<p>Do you have to use the ${ and } delimiters or can you use other delimiters?</p>\n\n<p>You don't really care about parsing. You just want to generate and format strings with placeholder data in it. Right?</p>\n\n<p>For a platform neutral approach, consider the humble <strong>sprintf</strong> function. It is the most ubiquitous and does what I am assuming that you need. It works on \"char stars\" so you are going to have to get into some memory management.</p>\n\n<p>Are you using STL? Then consider the <strong>basic_string&amp; replace</strong> function. It doesn't do exactly what you want but you could make it work.</p>\n\n<p>If you are using ATL/MFC, then consider the <strong>CStringT::Format</strong> method.</p>\n" }, { "answer_id": 263431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;conio.h&gt;\n#include &lt;string&gt;\n#include &lt;map&gt;\n\nusing namespace std;\n\nstruct Token\n{\n enum E\n {\n Replace,\n Literal,\n Eos\n };\n};\n\nclass ParseExp\n{\nprivate:\n enum State\n {\n State_Begin,\n State_Literal,\n State_StartRep,\n State_RepWord,\n State_EndRep\n };\n\n string m_str;\n int m_char;\n unsigned int m_length;\n string m_lexme;\n Token::E m_token;\n State m_state;\n\npublic:\n void Parse(const string&amp; str)\n {\n m_char = 0;\n m_str = str;\n m_length = str.size();\n }\n\n Token::E NextToken()\n {\n if (m_char &gt;= m_length)\n m_token = Token::Eos;\n\n m_lexme = \"\";\n m_state = State_Begin;\n bool stop = false;\n while (m_char &lt;= m_length &amp;&amp; !stop)\n {\n char ch = m_str[m_char++];\n switch (m_state)\n {\n case State_Begin:\n if (ch == '$')\n {\n m_state = State_StartRep;\n m_token = Token::Replace;\n continue;\n }\n else\n {\n m_state = State_Literal;\n m_token = Token::Literal;\n }\n break;\n\n case State_StartRep:\n if (ch == '{')\n {\n m_state = State_RepWord;\n continue;\n }\n else\n continue;\n break;\n\n case State_RepWord:\n if (ch == '}')\n {\n stop = true;\n continue;\n }\n break;\n\n case State_Literal:\n if (ch == '$')\n {\n stop = true;\n m_char--;\n continue;\n }\n }\n\n m_lexme += ch;\n }\n\n return m_token;\n }\n\n const string&amp; Lexme() const\n {\n return m_lexme;\n }\n\n Token::E Token() const\n {\n return m_token;\n }\n};\n\nstring DoReplace(const string&amp; str, const map&lt;string, string&gt;&amp; dict)\n{\n ParseExp exp;\n exp.Parse(str);\n string ret = \"\";\n while (exp.NextToken() != Token::Eos)\n {\n if (exp.Token() == Token::Literal)\n ret += exp.Lexme();\n else\n {\n map&lt;string, string&gt;::const_iterator iter = dict.find(exp.Lexme());\n if (iter != dict.end())\n ret += (*iter).second;\n else\n ret += \"undefined(\" + exp.Lexme() + \")\";\n }\n }\n return ret;\n}\n\nint main()\n{\n map&lt;string, string&gt; words;\n words[\"hello\"] = \"hey\";\n words[\"test\"] = \"bla\";\n cout &lt;&lt; DoReplace(\"${hello} world ${test} ${undef}\", words);\n _getch();\n}\n</code></pre>\n\n<p>I will be happy to explain anything about this code :)</p>\n" }, { "answer_id": 263471, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 0, "selected": false, "text": "<p>If you are managing the variables separately, why not go the route of an embeddable interpreter. I have used <a href=\"http://www.tcl.tk\" rel=\"nofollow noreferrer\">tcl</a> in the past, but you might try <a href=\"http://www.lua.org/\" rel=\"nofollow noreferrer\">lua</a> which is designed for embedding. <a href=\"http://www.ruby-lang.org\" rel=\"nofollow noreferrer\">Ruby</a> and <a href=\"http://www.python.org/doc/2.5.2/ext/embedding.html\" rel=\"nofollow noreferrer\">Python</a> are two other embeddable interpreters that are easy to embed, but aren't quite as lightweight. The strategy is to instantiate an interpreter (a context), add variables to it, then evaluate strings within that context. An interpreter will properly handle malformed input that could lead to security or stability problems for your application.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20444/" ]
I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions. Example: "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc. The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions? Note: boost:: is most welcome! :-) **Update** Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)
``` #include <iostream> #include <conio.h> #include <string> #include <map> using namespace std; struct Token { enum E { Replace, Literal, Eos }; }; class ParseExp { private: enum State { State_Begin, State_Literal, State_StartRep, State_RepWord, State_EndRep }; string m_str; int m_char; unsigned int m_length; string m_lexme; Token::E m_token; State m_state; public: void Parse(const string& str) { m_char = 0; m_str = str; m_length = str.size(); } Token::E NextToken() { if (m_char >= m_length) m_token = Token::Eos; m_lexme = ""; m_state = State_Begin; bool stop = false; while (m_char <= m_length && !stop) { char ch = m_str[m_char++]; switch (m_state) { case State_Begin: if (ch == '$') { m_state = State_StartRep; m_token = Token::Replace; continue; } else { m_state = State_Literal; m_token = Token::Literal; } break; case State_StartRep: if (ch == '{') { m_state = State_RepWord; continue; } else continue; break; case State_RepWord: if (ch == '}') { stop = true; continue; } break; case State_Literal: if (ch == '$') { stop = true; m_char--; continue; } } m_lexme += ch; } return m_token; } const string& Lexme() const { return m_lexme; } Token::E Token() const { return m_token; } }; string DoReplace(const string& str, const map<string, string>& dict) { ParseExp exp; exp.Parse(str); string ret = ""; while (exp.NextToken() != Token::Eos) { if (exp.Token() == Token::Literal) ret += exp.Lexme(); else { map<string, string>::const_iterator iter = dict.find(exp.Lexme()); if (iter != dict.end()) ret += (*iter).second; else ret += "undefined(" + exp.Lexme() + ")"; } } return ret; } int main() { map<string, string> words; words["hello"] = "hey"; words["test"] = "bla"; cout << DoReplace("${hello} world ${test} ${undef}", words); _getch(); } ``` I will be happy to explain anything about this code :)
263,355
<p>Portfolio A → Fund 1</p> <p>Portfolio A → Fund 2</p> <p>Portfolio A → Fund 3</p> <p>I couldn't frame my sentence without not using is/has. But between 1 &amp; 2,</p> <p>1) has a:</p> <pre><code>class PortfolioA { List&lt;Fund&gt; obj; } </code></pre> <p>2) is a:</p> <pre><code>class PortfolioA : List&lt;Fund&gt; { } </code></pre> <p>which one do you think is better from the point of extensibility, usability? I can still access my funds either way, albeit with a small syntactical change.</p>
[ { "answer_id": 263366, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 3, "selected": false, "text": "<p>The first one, because you should try to favour composition over inheritance when you can.</p>\n" }, { "answer_id": 263369, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>I would go with option (1) - composition, since you may eventually have attributes specific to the portfolio, rather than the funds.</p>\n" }, { "answer_id": 263377, "author": "Black", "author_id": 25234, "author_profile": "https://Stackoverflow.com/users/25234", "pm_score": 2, "selected": false, "text": "<p>The first one, because it is <em>\"consists of\"</em>. => Composition</p>\n" }, { "answer_id": 263381, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "<p>do not 'always' favor composition or inheritance or vice-versa; they have different semantics (meanings); look carefully at the meanings, then decide - it doesn't matter if one is 'easier' than the other, for longevity it matters that you get the semantics right</p>\n\n<p>remember: is-a = type, has-a = containment</p>\n\n<p>so in this case, a portfolio logically is a collection of funds; a portfolio itself is <em>not a <strong>type</strong> of fund</em>, so composition is the correct relationship</p>\n\n<p>EDIT: I misread the question originally, but the answer is still the same. A Portfolio is not a type of list, it is a distinct entity with its own properties. For example, a portfolio is an aggregate of financial instruments with an initial investment cost, a total current value, a history of values over time, etc., while a List is a simple collection of objects. A portfolio is a 'type of list' only in the most abstract sense. </p>\n\n<p>EDIT 2: think about the definition of portfolio - it is, without exception, characterized as a collection of things. An artist's portfolio is a collection of their artwork, a web designer's portfolio is a collection of their web sites, an investor's portfolio consists of all of the financial instruments that they own, and so on. So clearly we need a list (or some kind) to represent a portfolio, but that in no way implies that a portfolio is a type of list! </p>\n\n<p>suppose we decide to let Portfolio inherit from List. This works until we add a Stock or Bond or Precious Metal to the Portfolio, and then suddenly the incorrect inheritance no longer works. Or suppose we are asked to model, say, Bill Gates' portfolio, and find that List will run out of memory ;-) More realistically, after future refactoring we will probably find that we should inherit from a base class like Asset, but if we've already inherited from List then we can't.</p>\n\n<p>Summary: distinguish between the data structures we choose to represent a concept, and the semantics (type hierarchy) of the concept itself.</p>\n" }, { "answer_id": 263401, "author": "Robert Wagner", "author_id": 10784, "author_profile": "https://Stackoverflow.com/users/10784", "pm_score": 2, "selected": false, "text": "<p>It depends whether the business defines a Portfolio as a group (and only a group) of funds. If there is even the remote possibility of that it could contain other objects, say \"property\", then go with option 1. Go with option 2 if there is a strong link between a group of funds and the concept of Portfolio.</p>\n\n<p>As far as extensibility and usefullness 1 has the slight advantage over 2. I really disagree with the concept that you should always favour one over the other. It really depends on what the actual real life concepts are. Remember, you can always^ refactor.</p>\n\n<p>^ For most instances of always. If it is exposed publicly, then obviously not.</p>\n" }, { "answer_id": 263437, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "<p>I vote with the other folks who say HAS-A is better in this case. You ask in a comment:</p>\n\n<blockquote>\n <p>when I say that a Portfolio is just a\n collection of funds, with a few\n attributes of its own like\n TotalPortfolio etc, does that\n fundamentally not become an \"is-a\"?</p>\n</blockquote>\n\n<p>I don't think so. If you say <code>Portfolio</code> IS-A <code>List&lt;Fund&gt;</code>, what about other properties of the Portfolio? Of course you can add properties to this class, but is it accurate to model those properties as properties of the List? Because that's basically what you're doing.</p>\n\n<p>Also what if a Portfolio is required to support more than one <code>List&lt;Fund&gt;</code>? For instance, you might have one List that shows the current balance of investments, but another List that shows how new contributions are invested. And what about when funds are discontinued, and a new set of funds is used to succeed them? Historical information is useful to track, as well as the current fund allocation.</p>\n\n<p>The point is that all these properties are not correctly properties of a List, though they may be properties of the Portfolio.</p>\n" }, { "answer_id": 263628, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 1, "selected": false, "text": "<p>I will differ with what appears to be the common opinion. In this case I think a portfolio is very little more than a collection of funds... By using inheritance you allow the use of multiple constructors, as in</p>\n\n<pre><code>public Portfolio(CLient client) {};\npublic Portfolio(Branch branch, bool Active, decimal valueThreshold)\n{\n // code to populate collection with all active portfolios at the specified branch whose total vlaue exceeds specified threshold \n}\n</code></pre>\n\n<p>and indexers as in:</p>\n\n<pre><code>public Fund this[int fundId] { get { return this.fundList[fundId]; } }\n</code></pre>\n\n<p>etc. etc.</p>\n\n<p>if you want to be able to treat variables of type Portfolio as a collection of funds, with the associated syntax, then this is the better approach.</p>\n\n<pre><code>Portfolio BobsPortfolio = new Portfolio(Bob); \n\nforeach (Fund fund in BobsPortfolio)\n{\n fund.SendStatement();\n}\n</code></pre>\n\n<p>or stuff like that</p>\n" }, { "answer_id": 45563619, "author": "Sheo Dayal Singh", "author_id": 5736534, "author_profile": "https://Stackoverflow.com/users/5736534", "pm_score": 0, "selected": false, "text": "<p><strong>IS-A relation ship</strong> represents inheritances and <strong>HAS-A relation ship</strong> represents composition. For above mentioned scenario we prefer composition as PortfolioA has a List and it is not the List type. Inheritances use when Portfolio A is a type of List but here it is not. Hence for this scenario we should prefer Composition. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31622/" ]
Portfolio A → Fund 1 Portfolio A → Fund 2 Portfolio A → Fund 3 I couldn't frame my sentence without not using is/has. But between 1 & 2, 1) has a: ``` class PortfolioA { List<Fund> obj; } ``` 2) is a: ``` class PortfolioA : List<Fund> { } ``` which one do you think is better from the point of extensibility, usability? I can still access my funds either way, albeit with a small syntactical change.
I vote with the other folks who say HAS-A is better in this case. You ask in a comment: > > when I say that a Portfolio is just a > collection of funds, with a few > attributes of its own like > TotalPortfolio etc, does that > fundamentally not become an "is-a"? > > > I don't think so. If you say `Portfolio` IS-A `List<Fund>`, what about other properties of the Portfolio? Of course you can add properties to this class, but is it accurate to model those properties as properties of the List? Because that's basically what you're doing. Also what if a Portfolio is required to support more than one `List<Fund>`? For instance, you might have one List that shows the current balance of investments, but another List that shows how new contributions are invested. And what about when funds are discontinued, and a new set of funds is used to succeed them? Historical information is useful to track, as well as the current fund allocation. The point is that all these properties are not correctly properties of a List, though they may be properties of the Portfolio.
263,359
<p>I'm writing some Javascript to resize the large image to fit into the user's browser window. (I don't control the size of the source images unfortunately.)</p> <p>So something like this would be in the HTML:</p> <pre><code>&lt;img id="photo" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /&gt; </code></pre> <p><strong>Is there a way for me to determine if the <code>src</code> image in an <code>img</code> tag has been downloaded?</strong></p> <p>I need this because I'm running into a problem if <code>$(document).ready()</code> is executed before the browser has loaded the image. <code>$("#photo").width()</code> and <code>$("#photo").height()</code> will return the size of the placeholder (the alt text). In my case this is something like 134 x 20.</p> <p>Right now I'm just checking if the photo's height is less than 150, and assuming that if so it is just alt text. But this is quite a hack, and it would break if a photo is less than 150 pixels tall (not likely in my particular case), or if the alt text is more than 150 pixels tall (could possibly happen on a small browser window).</p> <hr> <p><strong>Edit:</strong> For anyone wanting to see the code:</p> <pre><code>$(function() { var REAL_WIDTH = $("#photo").width(); var REAL_HEIGHT = $("#photo").height(); $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(REAL_HEIGHT &lt; 150) { REAL_WIDTH = $("#photo").width(); REAL_HEIGHT = $("#photo").height(); if(REAL_HEIGHT &lt; 150) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } } var new_width = . . . ; var new_height = . . . ; $("#photo").width(Math.round(new_width)); $("#photo").height(Math.round(new_height)); } }); </code></pre> <hr> <p><strong>Update</strong>: Thanks for the suggestions. There is a risk of the event not being fired if I set a callback for the <code>$("#photo").load</code> event, so I have defined an onLoad event directly on the image tag. For the record, here is the code I ended up going with:</p> <pre><code>&lt;img id="photo" onload="photoLoaded();" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /&gt; </code></pre> <p>Then in Javascript:</p> <pre><code>//This must be outside $() because it may get called first var isPhotoLoaded = false; function photoLoaded() { isPhotoLoaded = true; } $(function() { //Hides scrollbars, so we can resize properly. Set with JS instead of // CSS so that page doesn't break with JS disabled. $("body").css("overflow", "hidden"); var REAL_WIDTH = -1; var REAL_HEIGHT = -1; $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(!isPhotoLoaded) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } else if(REAL_WIDTH &lt; 0) { //first time in this function since photo loaded REAL_WIDTH = $("#photo").width(); REAL_HEIGHT = $("#photo").height(); } var new_width = . . . ; var new_height = . . . ; $("#photo").width(Math.round(new_width)); $("#photo").height(Math.round(new_height)); } }); </code></pre>
[ { "answer_id": 263447, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 6, "selected": true, "text": "<p>Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there.</p>\n\n<pre><code>&lt;img id=\"photo\"\n onload='loaded(this.id)'\n src=\"a_really_big_file.jpg\"\n alt=\"this is some alt text\"\n title=\"this is some title text\" /&gt;\n</code></pre>\n" }, { "answer_id": 263479, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 2, "selected": false, "text": "<p>Try something like:</p>\n\n<pre><code>$(\"#photo\").load(function() {\n alert(\"Hello from Image\");\n});\n</code></pre>\n" }, { "answer_id": 263512, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 3, "selected": false, "text": "<p>You want to do what Allain said, however be aware that sometimes the image loads before dom ready, which means your load handler won't fire. The best way is to do as Allain says, but set the src of the image with javascript after attaching the load hander. This way you can guarantee that it fires.</p>\n\n<p>In terms of accessibility, will your site still work for people without javascript? You may want to give the img tag the correct src, attach you dom ready handler to run your js: clear the image src (give it a fixed with and height with css to prevent the page flickering), then set your img load handler, then reset the src to the correct file. This way you cover all bases :)</p>\n" }, { "answer_id": 3817269, "author": "Jay", "author_id": 461113, "author_profile": "https://Stackoverflow.com/users/461113", "pm_score": 1, "selected": false, "text": "<p>Any comments on this one?</p>\n\n<p>...</p>\n\n<pre><code>doShow = function(){\n if($('#img_id').attr('complete')){\n alert('Image is loaded!');\n } else {\n window.setTimeout('doShow()',100);\n }\n};\n\n$('#img_id').attr('src','image.jpg');\n\ndoShow();\n</code></pre>\n\n<p>...</p>\n\n<p>Seems like works everywhere...</p>\n" }, { "answer_id": 3817290, "author": "Evan Carroll", "author_id": 124486, "author_profile": "https://Stackoverflow.com/users/124486", "pm_score": 4, "selected": false, "text": "<p>The right answer, is to use <a href=\"http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js\" rel=\"noreferrer\">event.special.load</a></p>\n\n<blockquote>\n <p>It is possible that the load event will not be triggered if the image is loaded from the browser cache. To account for this possibility, we can use a special load event that fires immediately if the image is ready. event.special.load is currently available as a plugin.</p>\n</blockquote>\n\n<p>Per the docs on <a href=\"http://api.jquery.com/load-event/\" rel=\"noreferrer\">.load()</a></p>\n" }, { "answer_id": 7852814, "author": "Mike Fogel", "author_id": 103909, "author_profile": "https://Stackoverflow.com/users/103909", "pm_score": 4, "selected": false, "text": "<p>Using the <a href=\"http://api.jquery.com/data/\" rel=\"nofollow noreferrer\">jquery data store</a> you can define a 'loaded' state.</p>\n\n<pre><code>&lt;img id=\"myimage\" onload=\"$(this).data('loaded', 'loaded');\" src=\"lolcats.jpg\" /&gt;\n</code></pre>\n\n<p>Then elsewhere you can do:</p>\n\n<pre><code>if ($('#myimage').data('loaded')) {\n // loaded, so do stuff\n}\n</code></pre>\n" }, { "answer_id": 9333069, "author": "roberkules", "author_id": 45948, "author_profile": "https://Stackoverflow.com/users/45948", "pm_score": 1, "selected": false, "text": "<p>I just created a jQuery function to load an image using <a href=\"http://api.jquery.com/category/deferred-object/\" rel=\"nofollow\">jQuerys Deferred Object</a> which makes it very easy to react on load/error event:</p>\n\n<pre><code>$.fn.extend({\n loadImg: function(url, timeout) {\n // init deferred object\n var defer = $.Deferred(),\n $img = this,\n img = $img.get(0),\n timer = null;\n\n // define load and error events BEFORE setting the src\n // otherwise IE might fire the event before listening to it\n $img.load(function(e) {\n var that = this;\n // defer this check in order to let IE catch the right image size\n window.setTimeout(function() {\n // make sure the width and height are &gt; 0\n ((that.width &gt; 0 &amp;&amp; that.height &gt; 0) ? \n defer.resolveWith : \n defer.rejectWith)($img);\n }, 1);\n }).error(function(e) {\n defer.rejectWith($img);\n });\n\n // start loading the image\n img.src = url;\n\n // check if it's already in the cache\n if (img.complete) {\n defer.resolveWith($img);\n } else if (0 !== timeout) {\n // add a timeout, by default 15 seconds\n timer = window.setTimeout(function() {\n defer.rejectWith($img);\n }, timeout || 15000);\n }\n\n // return the promise of the deferred object\n return defer.promise().always(function() {\n // stop the timeout timer\n window.clearTimeout(timer);\n timer = null;\n // unbind the load and error event\n this.off(\"load error\");\n });\n }\n});\n</code></pre>\n\n<p><strong>Usage:</strong></p>\n\n<pre><code>var image = $('&lt;img /&gt;').loadImg('http://www.google.com/intl/en_com/images/srpr/logo3w.png')\n.done(function() {\n alert('image loaded');\n $('body').append(this);\n}).fail(function(){\n alert('image failed');\n});\n</code></pre>\n\n<p>See it working at: <a href=\"http://jsfiddle.net/roberkules/AdWZj/\" rel=\"nofollow\">http://jsfiddle.net/roberkules/AdWZj/</a></p>\n" }, { "answer_id": 10671060, "author": "Ralph Ritoch", "author_id": 804575, "author_profile": "https://Stackoverflow.com/users/804575", "pm_score": 1, "selected": false, "text": "<p>This function checks if an image is loaded based on having measurable dimensions. This technique is useful if your script is executing after some of the images have already been loaded.</p>\n\n<pre><code>imageLoaded = function(node) {\n var w = 'undefined' != typeof node.clientWidth ? node.clientWidth : node.offsetWidth;\n var h = 'undefined' != typeof node.clientHeight ? node.clientHeight : node.offsetHeight;\n return w+h &gt; 0 ? true : false;\n};\n</code></pre>\n" }, { "answer_id": 16667388, "author": "jay", "author_id": 722890, "author_profile": "https://Stackoverflow.com/users/722890", "pm_score": 2, "selected": false, "text": "<p>There's a jQuery plugin called \"imagesLoaded\" that provides a cross-browser compatible method to check if an element's image(s) have been loaded.</p>\n\n<p>Site: <a href=\"https://github.com/desandro/imagesloaded/\" rel=\"nofollow\">https://github.com/desandro/imagesloaded/</a></p>\n\n<p>Usage for a container that has many images inside:</p>\n\n<pre><code>$('container').imagesLoaded(function(){\n console.log(\"I loaded!\");\n})\n</code></pre>\n\n<p>The plugin is great:</p>\n\n<ol>\n<li>works for checking a container with many images inside</li>\n<li>works for check an img to see if it has loaded</li>\n</ol>\n" }, { "answer_id": 22797974, "author": "commonpike", "author_id": 95733, "author_profile": "https://Stackoverflow.com/users/95733", "pm_score": 2, "selected": false, "text": "<p>As per one of the recent comments to your original question</p>\n\n<pre><code>$(function() {\n\n $(window).resize(adjust_photo_size);\n adjust_photo_size();\n\n function adjust_photo_size() {\n if (!$(\"#photo\").get(0).complete) {\n $(\"#photo\").load(function() {\n adjust_photo_size();\n });\n } else {\n ... \n }\n});\n</code></pre>\n\n<p><strong>Warning</strong> This answer could cause a serious loop in ie8 and lower, because img.complete is not always properly set by the browser. If you must support ie8, use a flag to remember the image is loaded. </p>\n" }, { "answer_id": 24785454, "author": "Armand", "author_id": 1703671, "author_profile": "https://Stackoverflow.com/users/1703671", "pm_score": 2, "selected": false, "text": "<p>I found this worked for me</p>\n\n<pre><code>document.querySelector(\"img\").addEventListener(\"load\", function() { alert('onload!'); });\n</code></pre>\n\n<p>Credit goes totaly to Frank Schwieterman, who commented on accepted answer. I had to put this here, it's too valuable...</p>\n" }, { "answer_id": 27280132, "author": "Octopus", "author_id": 1475548, "author_profile": "https://Stackoverflow.com/users/1475548", "pm_score": 0, "selected": false, "text": "<p>We developed a page where it loaded a number of images and then performed other functions only after the image was loaded. It was a busy site that generated a lot of traffic. It seems that the following simple script worked on practically all browsers:</p>\n\n<pre><code>$(elem).onload = function() {\n doSomething();\n}\n</code></pre>\n\n<p><strong>BUT THIS IS A POTENTIAL ISSUE FOR IE9!</strong></p>\n\n<p>The ONLY browser we had reported issues on is IE9. Are we not surprised? It seems that the best way to solve the issue there is to not assign a src to the image until AFTER the onload function has been defined, like so:</p>\n\n<pre><code>$(elem).onload = function() {\n doSomething();\n}\n$(elem).attr('src','theimage.png');\n</code></pre>\n\n<p>It seems that IE 9 will sometimes not throw the <code>onload</code> event for whatever reason. Other solutions on this page (such as the one from Evan Carroll, for example) still did not work. Logically, that checked if the load state was already successful and triggered the function and if it wasn't, then set the onload handler, but even when you do that we demonstrated in testing that the image could load between those two lines of js thereby appearing not loaded to the first line and then loading before the onload handler is set.</p>\n\n<p>We found that the best way to get what you want is to not define the image's src until you have set the <code>onload</code> event trigger.</p>\n\n<p>We only just recently stopped supporting IE8 so I can't speak for versions prior to IE9, otherwise, out of all the other browsers that were used on the site -- IE10 and 11 as well as Firefox, Chrome, Opera, Safari and whatever mobile browser people were using -- setting the <code>src</code> before assigning the <code>onload</code> handler was not even an issue.</p>\n" }, { "answer_id": 56366085, "author": "arunwithasmile", "author_id": 3126558, "author_profile": "https://Stackoverflow.com/users/3126558", "pm_score": 0, "selected": false, "text": "<p>May I suggest a pure CSS solution altogether?</p>\n\n<p>Just have a Div that you want to show the image in. Set the image as background. Then have the property <code>background-size: cover</code> or <code>background-size: contain</code> depending on how you want it.</p>\n\n<p><code>cover</code> will crop the image until smaller sides cover the box.\n<code>contain</code> will keep the entire image inside the div, leaving you with spaces on sides.</p>\n\n<p>Check the snippet below.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\r\n height: 300px;\r\n width: 300px;\r\n border: 3px dashed grey;\r\n background-position: center;\r\n background-repeat: no-repeat;\r\n}\r\n\r\n.cover-image {\r\n background-size: cover;\r\n}\r\n\r\n.contain-image {\r\n background-size: contain;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"cover-image\" style=\"background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)\"&gt;\r\n&lt;/div&gt;\r\n&lt;br/&gt;\r\n&lt;div class=\"contain-image\" style=\"background-image:url(https://assets1.ignimgs.com/2019/04/25/avengers-endgame-1280y-1556226255823_1280w.jpg)\"&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 60030287, "author": "Martin Francis", "author_id": 815790, "author_profile": "https://Stackoverflow.com/users/815790", "pm_score": 0, "selected": false, "text": "<p>I find that this simple solution works best for me:</p>\n\n<pre><code> function setEqualHeight(a, b) {\n if (!$(a).height()) {\n return window.setTimeout(function(){ setEqualHeight(a, b); }, 1000);\n }\n $(b).height($(a).height());\n }\n\n $(document).ready(function() {\n setEqualHeight('#image', '#description');\n $(window).resize(function(){setEqualHeight('#image', '#description')});\n });\n &lt;/script&gt;\n</code></pre>\n" }, { "answer_id": 67931637, "author": "Monkey Banana", "author_id": 16194186, "author_profile": "https://Stackoverflow.com/users/16194186", "pm_score": 0, "selected": false, "text": "<p><strong>image.complete</strong> might be another option <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/complete\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/complete</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
I'm writing some Javascript to resize the large image to fit into the user's browser window. (I don't control the size of the source images unfortunately.) So something like this would be in the HTML: ``` <img id="photo" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /> ``` **Is there a way for me to determine if the `src` image in an `img` tag has been downloaded?** I need this because I'm running into a problem if `$(document).ready()` is executed before the browser has loaded the image. `$("#photo").width()` and `$("#photo").height()` will return the size of the placeholder (the alt text). In my case this is something like 134 x 20. Right now I'm just checking if the photo's height is less than 150, and assuming that if so it is just alt text. But this is quite a hack, and it would break if a photo is less than 150 pixels tall (not likely in my particular case), or if the alt text is more than 150 pixels tall (could possibly happen on a small browser window). --- **Edit:** For anyone wanting to see the code: ``` $(function() { var REAL_WIDTH = $("#photo").width(); var REAL_HEIGHT = $("#photo").height(); $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(REAL_HEIGHT < 150) { REAL_WIDTH = $("#photo").width(); REAL_HEIGHT = $("#photo").height(); if(REAL_HEIGHT < 150) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } } var new_width = . . . ; var new_height = . . . ; $("#photo").width(Math.round(new_width)); $("#photo").height(Math.round(new_height)); } }); ``` --- **Update**: Thanks for the suggestions. There is a risk of the event not being fired if I set a callback for the `$("#photo").load` event, so I have defined an onLoad event directly on the image tag. For the record, here is the code I ended up going with: ``` <img id="photo" onload="photoLoaded();" src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /> ``` Then in Javascript: ``` //This must be outside $() because it may get called first var isPhotoLoaded = false; function photoLoaded() { isPhotoLoaded = true; } $(function() { //Hides scrollbars, so we can resize properly. Set with JS instead of // CSS so that page doesn't break with JS disabled. $("body").css("overflow", "hidden"); var REAL_WIDTH = -1; var REAL_HEIGHT = -1; $(window).resize(adjust_photo_size); adjust_photo_size(); function adjust_photo_size() { if(!isPhotoLoaded) { //image not loaded.. try again in a quarter-second setTimeout(adjust_photo_size, 250); return; } else if(REAL_WIDTH < 0) { //first time in this function since photo loaded REAL_WIDTH = $("#photo").width(); REAL_HEIGHT = $("#photo").height(); } var new_width = . . . ; var new_height = . . . ; $("#photo").width(Math.round(new_width)); $("#photo").height(Math.round(new_height)); } }); ```
Either add an event listener, or have the image announce itself with onload. Then figure out the dimensions from there. ``` <img id="photo" onload='loaded(this.id)' src="a_really_big_file.jpg" alt="this is some alt text" title="this is some title text" /> ```
263,367
<p>When supporting a new web app in an enterprise environment, it is often necessary to log in as a specific user in order to diagnose a real or perceived problem they are having. Two opposing issues apply here:</p> <ol> <li><p>Best practice is to use <strong>hashed or encrypted passwords</strong>, not clear text. Sometimes, there is a third-party SSO (single sign-on) in the middle. There is no way to retrieve the user's password. Unless the user provides it (not encouraged), there is no way to log in as that user.</p></li> <li><p>Many web app's have <strong>personalization and complex authorization</strong>. Different users have different roles (admin, manager, user) with different permissions. Sometimes users can only see their data -- their customers or tasks. Some users have read-only access, while others can edit. So, each user's view of the web app is unique.</p></li> </ol> <p>Assume that in an enterprise environment, it isn't feasible to go to the user's desk, or to connect directly to their machine.</p> <p>How do you handle this situation?</p> <p>Edit: I want to reiterate that in a large financial institution or typical Fortune 500 company with hundreds of thousands of employees all of the country, and around the world, it is not possible for a mere developer in some IT unit to be able to directly access a user's machine. Some of those are public-facing web apps used by customers (such as online banking and stock trading). And, many of those are intranet applications rely on Active Directory or an SSO, meaning that user credentials are the same for many applications. I do thank you all for your suggestions; some may be highly useful in other kinds of environments.</p>
[ { "answer_id": 263388, "author": "Matt Brunell", "author_id": 24970, "author_profile": "https://Stackoverflow.com/users/24970", "pm_score": 1, "selected": false, "text": "<p>An administrator should be able to change a user's password. Change the password for the user to something you know. You can then log in as that user. </p>\n\n<p>Tell the user to reset his/her password after you are done debugging.</p>\n" }, { "answer_id": 263393, "author": "fwzgekg", "author_id": 34116, "author_profile": "https://Stackoverflow.com/users/34116", "pm_score": 1, "selected": false, "text": "<p>Usually by some sort of remote control software that can be used to view their desktop. If they're on a Windows terminal server, then the built in admin tools can be used for that. Otherwise I'd use something like VNC across an internal network, or an external service like LogMeIn (<a href=\"http://www.logmein.com/\" rel=\"nofollow noreferrer\">http://www.logmein.com/</a>).</p>\n" }, { "answer_id": 263433, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 0, "selected": false, "text": "<ol>\n<li><p>Could you have a testing environment where there is a regular cut of live data copied to (obviously sanitised to meet any security or data protection issues). A user similar in setup to the one having trouble could be used to troubleshoot or indeed the very user if this is allowed.</p></li>\n<li><p>Use a remote desktop client as mentioned in other answers, but again this may not be practical for you. If you have these rights within the domain, I have heard of error handling even doing a screenscrape and including this in logs! but this sounds a little odd to me.</p></li>\n<li><p>Could you have an admin tool to clone a user into a demo account?</p></li>\n</ol>\n" }, { "answer_id": 263441, "author": "Noah Goodrich", "author_id": 20178, "author_profile": "https://Stackoverflow.com/users/20178", "pm_score": 3, "selected": false, "text": "<p>For our web applications we use a process that for lack of a better term is defined as 'hijacking' a user's account.</p>\n\n<p>Basically, administrators can 'hijack' a user's account with a simple button click. In the code, you simply use a unique identifier (user id works in a less secure environment) that then establishes the necessary credentials in the session so that they can then work within that user's profile. For a more secure environment you could use a unique hash for each user.</p>\n\n<p>In order to ensure that this hijack method is secure, it always first verifies that the request is being made by an authenticated administrator with the appropriate rights. Because of this it becomes necessary for either the administrator's session to be hijacked or for their authentication credentials to be captured in order for someone to ever exploit the hijack function within the application. </p>\n" }, { "answer_id": 263450, "author": "Markc", "author_id": 8609, "author_profile": "https://Stackoverflow.com/users/8609", "pm_score": 2, "selected": false, "text": "<p>I had 4 ideas. While I was typing 3 of them were already suggested (so I upvoted them)</p>\n\n<p>Variant on idea 3 - impersonation:</p>\n\n<p>To make this as \"identical as possible\" to a normal login with minimal code changes, you might add the ability to impersonate directly at login by supplying Admin credentials plus an alternate username, e.g. login as Admin:user, adminpassword. The system would treat this exactly as logging in as user with userpassword.</p>\n\n<p>Idea 4: Can you access the password store? If so, temporarily replace the user's hash with the hash of a known password. (the passwords are often stored online in a database. A SQL Query tool can do the swaps )</p>\n" }, { "answer_id": 263501, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 5, "selected": true, "text": "<p>A number of these ideas inconvenience the user, either by forcing them to change their password, or by occupying their desktop for your debugging session.</p>\n\n<p>Markc's idea is the best: augment your authentication logic to allow superusers to log in as a particular user by supplying not the user's credentials, but the user's name plus their superuser credentials.</p>\n\n<p>I've done it like this in the past (pseudo-ish python):</p>\n\n<pre><code>if is_user_authenticated(username, userpassword):\n login the user\nelse if ':' in userpassword:\n supername, superpassword = userpassword.split(':')\n if is_superuser_authenticated(supername, superpassword):\n login the user\n</code></pre>\n\n<p>In other words, if the username and password don't authenticate, if the password has a colon, then it's actually the admin username and admin password joined by a colon, so login as the username if they are the right admin username and password.</p>\n\n<p>This means you can login as the user without knowing their secrets, and without inconveniencing them.</p>\n" }, { "answer_id": 869921, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The solution we have used in our web apps is to have the authN/authZ return the desired user as the effective user. We do this by having an admin feature to setup a masquerade, and then when we ask for the currently logged in user (current_user), we handle the masquerade:</p>\n\n<pre><code> def current_user_with_effective_user\n if masked?\n current_user_without_effective_user.masquerade_as\n else\n current_user_without_effective_user\n end\n end\n alias_method_chain, :current_user, :effective_user\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27637/" ]
When supporting a new web app in an enterprise environment, it is often necessary to log in as a specific user in order to diagnose a real or perceived problem they are having. Two opposing issues apply here: 1. Best practice is to use **hashed or encrypted passwords**, not clear text. Sometimes, there is a third-party SSO (single sign-on) in the middle. There is no way to retrieve the user's password. Unless the user provides it (not encouraged), there is no way to log in as that user. 2. Many web app's have **personalization and complex authorization**. Different users have different roles (admin, manager, user) with different permissions. Sometimes users can only see their data -- their customers or tasks. Some users have read-only access, while others can edit. So, each user's view of the web app is unique. Assume that in an enterprise environment, it isn't feasible to go to the user's desk, or to connect directly to their machine. How do you handle this situation? Edit: I want to reiterate that in a large financial institution or typical Fortune 500 company with hundreds of thousands of employees all of the country, and around the world, it is not possible for a mere developer in some IT unit to be able to directly access a user's machine. Some of those are public-facing web apps used by customers (such as online banking and stock trading). And, many of those are intranet applications rely on Active Directory or an SSO, meaning that user credentials are the same for many applications. I do thank you all for your suggestions; some may be highly useful in other kinds of environments.
A number of these ideas inconvenience the user, either by forcing them to change their password, or by occupying their desktop for your debugging session. Markc's idea is the best: augment your authentication logic to allow superusers to log in as a particular user by supplying not the user's credentials, but the user's name plus their superuser credentials. I've done it like this in the past (pseudo-ish python): ``` if is_user_authenticated(username, userpassword): login the user else if ':' in userpassword: supername, superpassword = userpassword.split(':') if is_superuser_authenticated(supername, superpassword): login the user ``` In other words, if the username and password don't authenticate, if the password has a colon, then it's actually the admin username and admin password joined by a colon, so login as the username if they are the right admin username and password. This means you can login as the user without knowing their secrets, and without inconveniencing them.
263,376
<p>Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what's wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same result.</p> <pre><code>public static void main(String[] args) { String x = "10000000"; long l = new Long(x).longValue(); System.out.println("Long value: " + l); Calendar c = new GregorianCalendar(); c.setTimeInMillis(l); System.out.println("Calendar time in Millis: " + c.getTimeInMillis()); String origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH); System.out.println("Date in YYYY-MM-DD format: " + origDate); x = "1000000000000"; l = new Long(x).longValue(); System.out.println("\nLong value: " + l); c.setTimeInMillis(l); System.out.println("Calendar time in Millis: " + c.getTimeInMillis()); origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH); System.out.println("Date in YYYY-MM-DD format: " + origDate); } </code></pre> <blockquote> <p>Long value: 10000000</p> <p>Calendar time in Millis: 10000000</p> <p>Date in YYYY-MM-DD format: 1969-11-31</p> <p>Long value: 1000000000000</p> <p>Calendar time in Millis: 1000000000000</p> <p>Date in YYYY-MM-DD format: 2001-8-8</p> </blockquote>
[ { "answer_id": 263432, "author": "Davide", "author_id": 25891, "author_profile": "https://Stackoverflow.com/users/25891", "pm_score": 0, "selected": false, "text": "<p>You can figure out yourself if you change your first <code>c.setTimeInMillis(l);</code> in <code>c.clear();</code></p>\n" }, { "answer_id": 263439, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<p>The dates you print from <code>Calendar</code> are local to your timezone, whereas the epoch is defined to be midnight of 1970-01-01 in UTC. So if you live in a timezone west of UTC, then your date will show up as 1969-12-31, even though (in UTC) it's still 1970-01-01.</p>\n" }, { "answer_id": 263453, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 3, "selected": false, "text": "<p>First, <code>c.get(Calendar.MONTH)</code> returns 0 for Jan, 1 for Feb, etc.</p>\n\n<p>Second, use <code>DateFormat</code> to output dates. </p>\n\n<p>Third, your problems are a great example of how awkward Java's Date API is. Use Joda Time API if you can. It will make your life somewhat easier.</p>\n\n<p>Here's a better example of your code, which indicates the timezone:</p>\n\n<pre><code>public static void main(String[] args) {\n\n final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);\n\n long l = 10000000L;\n System.out.println(\"Long value: \" + l);\n Calendar c = new GregorianCalendar();\n c.setTimeInMillis(l);\n System.out.println(\"Date: \" + dateFormat.format(c.getTime()));\n\n l = 1000000000000L;\n System.out.println(\"\\nLong value: \" + l);\n c.setTimeInMillis(l);\n System.out.println(\"Date: \" + dateFormat.format(c.getTime()));\n}\n</code></pre>\n" }, { "answer_id": 263470, "author": "Mike", "author_id": 24316, "author_profile": "https://Stackoverflow.com/users/24316", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#setTimeInMillis(long)\" rel=\"noreferrer\">Calendar#setTimeInMillis()</a> sets the calendar's time to the number of milliseconds after Jan 1, 1970 <strong>GMT</strong>.</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/Calendar.html#get(int)\" rel=\"noreferrer\">Calendar#get()</a> returns the requested field adjusted for the calendar's timezone which, by default, is <strong>your machine's local timezone</strong>.</p>\n\n<p>This should work as you expect if you specify \"GMT\" timezone when you construct the calendar:</p>\n\n<pre><code>Calendar c = new GregorianCalendar(TimeZone.getTimeZone(\"GMT\"));\n</code></pre>\n" }, { "answer_id": 263973, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 1, "selected": false, "text": "<p>Your timezone is most likely lagging behind GMT (e.g., GMT-5), therefore 10,000,000ms from epoch is December 31 1969 in your timezone, but since months are zero-based in <code>java.util.Calendar</code> your <code>Calendar</code>-to-text conversion is flawed and you get 1969-11-31 instead of the expected 1969-12-31.</p>\n" }, { "answer_id": 263988, "author": "Julien Chastang", "author_id": 32174, "author_profile": "https://Stackoverflow.com/users/32174", "pm_score": 2, "selected": false, "text": "<p>Sadly, <code>java.util.Date</code> and <code>java.util.Calendar</code> were poorly designed leading to this sort of confusion.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34410/" ]
Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what's wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same result. ``` public static void main(String[] args) { String x = "10000000"; long l = new Long(x).longValue(); System.out.println("Long value: " + l); Calendar c = new GregorianCalendar(); c.setTimeInMillis(l); System.out.println("Calendar time in Millis: " + c.getTimeInMillis()); String origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH); System.out.println("Date in YYYY-MM-DD format: " + origDate); x = "1000000000000"; l = new Long(x).longValue(); System.out.println("\nLong value: " + l); c.setTimeInMillis(l); System.out.println("Calendar time in Millis: " + c.getTimeInMillis()); origDate = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH); System.out.println("Date in YYYY-MM-DD format: " + origDate); } ``` > > Long value: 10000000 > > > Calendar time in Millis: 10000000 > > > Date in YYYY-MM-DD format: 1969-11-31 > > > Long value: 1000000000000 > > > Calendar time in Millis: 1000000000000 > > > Date in YYYY-MM-DD format: 2001-8-8 > > >
The dates you print from `Calendar` are local to your timezone, whereas the epoch is defined to be midnight of 1970-01-01 in UTC. So if you live in a timezone west of UTC, then your date will show up as 1969-12-31, even though (in UTC) it's still 1970-01-01.
263,380
<p>I am building an ASP.NET web site where the users may upload photos of themselves. There could be thousands of photos uploaded every day. One thing my boss has asked a few time is if there is any way we could detect if any of the photos are showing too much 'skin' and automatically move flag these as 'Adults Only' before the editors make the final decision. </p>
[ { "answer_id": 263403, "author": "JSBձոգչ", "author_id": 8078, "author_profile": "https://Stackoverflow.com/users/8078", "pm_score": 4, "selected": false, "text": "<p>I doubt that there exists any off-the-shelf software that can determine if the user uploads a naughty picture. Your best bet is to let users flag images as 'Adults Only' with a button next to the picture. (Clarification: I mean users other than the one who uploaded the picture--similar to how posts can be marked offensive here on StackOverflow.)</p>\n\n<p>Also, consider this review of an attempt to do the same thing in a dedicated product: <a href=\"http://www.dansdata.com/pornsweeper.htm\" rel=\"noreferrer\">http://www.dansdata.com/pornsweeper.htm</a>.</p>\n\n<p>Link stolen from today's StackOverflow podcast, of course :).</p>\n" }, { "answer_id": 263407, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 4, "selected": false, "text": "<p>We can't even write filters that detect dirty words accurately in blog posts, and your boss is asking for a porno detector? <a href=\"http://thedailywtf.com/Articles/The-Clbuttic-Mistake-.aspx\" rel=\"noreferrer\">CLBUTTIC!</a></p>\n" }, { "answer_id": 263462, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 0, "selected": false, "text": "<p>I'm afraid I can't help point you in the right direction, but I do remember reading about this being done before. It was in the context of people complaining about baby pictures being caught and flagged mistakenly. If nothing else, I can give you the hope that you don't have to invent the wheel all by yourself... Someone else has been down this road!</p>\n" }, { "answer_id": 263482, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 5, "selected": false, "text": "<p>Your best bet is to deal with the image in the HSV colour space (see <a href=\"http://www.cs.rit.edu/~ncs/color/t_convert.html\" rel=\"noreferrer\">here</a> for rgb - hsv conversion). The colour of skin is pretty much the same between all races, its just the saturation that changes. By dealing with the image in HSV you can simply search for the colour of skin.</p>\n\n<p>You might do this by simply counting the number of pixel within a colour range, or you could <a href=\"http://www.cse.unr.edu/~bebis/CS791E/Notes/RegionGrowing.pdf\" rel=\"noreferrer\">perform region</a> growing around pixel to calculate the size of the areas the colour.</p>\n\n<p>Edit: for dealing with grainy images, you might want to perform a <a href=\"http://en.wikipedia.org/wiki/Median_filter\" rel=\"noreferrer\">median filter</a> on the image first, and then reduce the number of colours to segment the image first, you will have to play around with the settings on a large set of pre-classifed (adult or not) images and see how the values behave to get a satisfactory level of detection.</p>\n\n<p>EDIT: Heres some code that should do a simple count (not tested it, its a quick mashup of some code from <a href=\"http://www.obnoxiouslyverbose.com/8/c-image-processing-performance-unsafe-vs-safe-code-part-i\" rel=\"noreferrer\">here</a> and rgb to hsl <a href=\"http://en.wikipedia.org/wiki/HSL_color_space\" rel=\"noreferrer\">here</a>)</p>\n\n<pre><code>Bitmap b = new Bitmap(_image);\nBitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat);\nbyte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat);\nbyte* scan0 = (byte*)bData.Scan0.ToPointer();\n\nint count;\n\nfor (int i = 0; i &lt; bData.Height; ++i)\n{\n for (int j = 0; j &lt; bData.Width; ++j)\n {\n byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8;\n\n byte r = data[2];\n byte g = data[1];\n byte b = data[0];\n\n byte max = (byte)Math.Max(r, Math.Max(g, b));\n byte min = (byte)Math.Min(r, Math.Min(g, b));\n\n int h;\n\n if(max == min)\n h = 0;\n else if(r &gt; g &amp;&amp; r &gt; b)\n h = (60 * ((g - b) / (max - min))) % 360;\n else if (g &gt; r &amp;&amp; g &gt; b)\n h = 60 * ((b - r)/max - min) + 120;\n else if (b &gt; r &amp;&amp; b &gt; g)\n h = 60 * ((r - g) / max - min) + 240;\n\n\n if(h &gt; _lowerThresh &amp;&amp; h &lt; _upperThresh)\n count++;\n }\n}\nb.UnlockBits(bData);\n</code></pre>\n" }, { "answer_id": 263499, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "<p>Perhaps the <a href=\"http://yro.slashdot.org/yro/08/11/04/1746220.shtml\" rel=\"nofollow noreferrer\">Porn Breath Test</a> would be helpful - as reported on Slashdot.</p>\n" }, { "answer_id": 263519, "author": "conny", "author_id": 23023, "author_profile": "https://Stackoverflow.com/users/23023", "pm_score": 4, "selected": false, "text": "<p>I would say your answer lies in <strong>crowdsourcing</strong> the task. This almost always works and tends to scale <em>very</em> well. </p>\n\n<p>It doesn't have to involve making some users into \"admins\" and coming up with different permissions - it can be as simple as to enable an \"inappropriate\" link near each image and keeping a count.</p>\n" }, { "answer_id": 263538, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 3, "selected": false, "text": "<p>Interesting question from a theoretical / algorithmic standppoint. One approach to the problem would be to flag images that contain large skin-colored regions (as explained by Trull). </p>\n\n<p>However, the amount of skin shown is not a determinant of an offesive image, it's rather the <em>location</em> of the skin shown. Perhaps you can use face detection (search for algorithms) to refine the results -- determine how large the skin regions are relative to the face, and if they belong to the face (perhaps how far below it they are).</p>\n" }, { "answer_id": 263559, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>I know either Flickr or Picasa has implemented this. I believe the routine was called FleshFinder.</p>\n\n<p>A tip on the architecture of doing this:</p>\n\n<p>Run this as a windows service separate from the ASP.NET Pipeline, instead of analyzing images in real time, create a queue of new images that are uploaded for the service to work through. </p>\n\n<p>You can use the normal System.Drawing stuff if you want, but if you really need to process a lot of images, it would be better to use native code and a high performance graphics library and P/invoke the routine from your service.</p>\n\n<p>As resources are available, process images in the background and flag ones that are suspicious for editors review, this should prune down the number of images to review significantly, while not annoying people who upload pictures of skin colored houses.</p>\n" }, { "answer_id": 263579, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "<p>I would approach the problem from a statistical standpoint. Get a bunch of pictures that you consider safe, and a bunch that you don't (that will make for a fun day of research), and see what they have in common. Analyze them all for color range and saturation to see if you can pick out characteristics that all of the naughty photos, and few of the safe ones have.</p>\n" }, { "answer_id": 263580, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<p>Of course, this will fail for the first user who posts a close-up of someone's face (or hand, or foot, or whatnot). Ultimately, all these forms of automated censorship will fail until there's a real paradigm-shift in the way computers do object recognition.</p>\n\n<p>I'm not saying that you shouldn't attempt it nontheless; but I want to point to these problems. Do not expect a perfect (or even good) solution. It doesn't exist.</p>\n" }, { "answer_id": 265178, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.dlsu.edu.ph/faculty/fis/faculty_info.asp?fac_id=103945856\" rel=\"nofollow noreferrer\">Rigan Ap-apid</a> presented a paper at WorldComp '08 on just this problem space. The paper is allegedly <a href=\"http://serv1.ist.psu.edu:8080/viewdoc/download;jsessionid=92D8115F9C98B5DC6C8459E1A038AE46?doi=10.1.1.96.9872&amp;rep=rep1&amp;type=pdf\" rel=\"nofollow noreferrer\">here</a>, but the server was timing out for me. I attended the presentation of the paper and he covered comparable systems and their effectiveness as well as his own approach. You might contact him directly.</p>\n" }, { "answer_id": 270330, "author": "reconbot", "author_id": 339, "author_profile": "https://Stackoverflow.com/users/339", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://crowdsifter.com\" rel=\"nofollow noreferrer\">CrowdSifter</a> by <a href=\"http://doloreslabs.com\" rel=\"nofollow noreferrer\">Dolores Labs</a> might do the trick for you. I read their blog all the time as they seem to love statistics and crowdsourcing and like to talk about it. They use amazon's mechanical turk for a lot of their processing and know how to process the results to get the right answers out of things. Check out their blog at the very least to see some cool statistical experiments.</p>\n" }, { "answer_id": 558171, "author": "graveca", "author_id": 59893, "author_profile": "https://Stackoverflow.com/users/59893", "pm_score": 3, "selected": false, "text": "<p>See the seminal paper \"<strong>Finding Naked People</strong>\" by Fleck/Forsyth published in ECCV. (Advanced).</p>\n\n<p><a href=\"http://www.cs.hmc.edu/~fleck/naked.html\" rel=\"noreferrer\">http://www.cs.hmc.edu/~fleck/naked.html</a></p>\n" }, { "answer_id": 11376830, "author": "PTRMark", "author_id": 1253880, "author_profile": "https://Stackoverflow.com/users/1253880", "pm_score": 0, "selected": false, "text": "<p>As mentioned above by Bill (and Craig's google quote) statistical methods can be highly effective.</p>\n\n<p>Two approaches you might want to look into are:</p>\n\n<ul>\n<li>Neural Networks</li>\n<li>Multi Variate Analysis (MVA)</li>\n</ul>\n\n<p>The MVA approach would be to get a \"representative sample\" of acceptable pictures and of unacceptable pictures. The X data would be an array of bytes from each picture, the Y would be assigned by you as a 1 for unacceptable and a 0 for acceptable. Create a PLS model using this data. Run new data against the model and see how well it predicts the Y.</p>\n\n<p>Rather than this binary approach you could have multiple Y's (e.g. 0=acceptable, 1=swimsuit/underwear, 2=pornographic)</p>\n\n<p>To build the model you can look at open source software or there are a number of commercial packages available (although they are typically not cheap)</p>\n\n<p>Because even the best statistical approaches are not perfect the idea of also including user feedback would probably be a good idea.</p>\n\n<p>Good luck (and worst case you get to spend time collecting naughty pictures as an approved and paid activity!)</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27294/" ]
I am building an ASP.NET web site where the users may upload photos of themselves. There could be thousands of photos uploaded every day. One thing my boss has asked a few time is if there is any way we could detect if any of the photos are showing too much 'skin' and automatically move flag these as 'Adults Only' before the editors make the final decision.
Your best bet is to deal with the image in the HSV colour space (see [here](http://www.cs.rit.edu/~ncs/color/t_convert.html) for rgb - hsv conversion). The colour of skin is pretty much the same between all races, its just the saturation that changes. By dealing with the image in HSV you can simply search for the colour of skin. You might do this by simply counting the number of pixel within a colour range, or you could [perform region](http://www.cse.unr.edu/~bebis/CS791E/Notes/RegionGrowing.pdf) growing around pixel to calculate the size of the areas the colour. Edit: for dealing with grainy images, you might want to perform a [median filter](http://en.wikipedia.org/wiki/Median_filter) on the image first, and then reduce the number of colours to segment the image first, you will have to play around with the settings on a large set of pre-classifed (adult or not) images and see how the values behave to get a satisfactory level of detection. EDIT: Heres some code that should do a simple count (not tested it, its a quick mashup of some code from [here](http://www.obnoxiouslyverbose.com/8/c-image-processing-performance-unsafe-vs-safe-code-part-i) and rgb to hsl [here](http://en.wikipedia.org/wiki/HSL_color_space)) ``` Bitmap b = new Bitmap(_image); BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat); byte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat); byte* scan0 = (byte*)bData.Scan0.ToPointer(); int count; for (int i = 0; i < bData.Height; ++i) { for (int j = 0; j < bData.Width; ++j) { byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8; byte r = data[2]; byte g = data[1]; byte b = data[0]; byte max = (byte)Math.Max(r, Math.Max(g, b)); byte min = (byte)Math.Min(r, Math.Min(g, b)); int h; if(max == min) h = 0; else if(r > g && r > b) h = (60 * ((g - b) / (max - min))) % 360; else if (g > r && g > b) h = 60 * ((b - r)/max - min) + 120; else if (b > r && b > g) h = 60 * ((r - g) / max - min) + 240; if(h > _lowerThresh && h < _upperThresh) count++; } } b.UnlockBits(bData); ```
263,392
<p>Trends data from Twitter Search API in JSON.</p> <p>Grabbing the file using:</p> <pre><code>$jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); </code></pre> <p>How do I work with data from this object. As an array? Only really need to extract data from the [name] values.</p> <p>JSON object contains:</p> <pre><code>stdClass Object ( [trends] =&gt; Array ( [0] =&gt; stdClass Object ( [name] =&gt; Vote [url] =&gt; http://search.twitter.com/search?q=Vote ) [1] =&gt; stdClass Object ( [name] =&gt; Halloween [url] =&gt; http://search.twitter.com/search?q=Halloween ) [2] =&gt; stdClass Object ( [name] =&gt; Starbucks [url] =&gt; http://search.twitter.com/search?q=Starbucks ) [3] =&gt; stdClass Object ( [name] =&gt; #flylady [url] =&gt; http://search.twitter.com/search?q=%23flylady ) [4] =&gt; stdClass Object ( [name] =&gt; #votereport [url] =&gt; http://search.twitter.com/search?q=%23votereport ) [5] =&gt; stdClass Object ( [name] =&gt; Election Day [url] =&gt; http://search.twitter.com/search?q=%22Election+Day%22 ) [6] =&gt; stdClass Object ( [name] =&gt; #PubCon [url] =&gt; http://search.twitter.com/search?q=%23PubCon ) [7] =&gt; stdClass Object ( [name] =&gt; #defrag08 [url] =&gt; http://search.twitter.com/search?q=%23defrag08 ) [8] =&gt; stdClass Object ( [name] =&gt; Melbourne Cup [url] =&gt; http://search.twitter.com/search?q=%22Melbourne+Cup%22 ) [9] =&gt; stdClass Object ( [name] =&gt; Cheney [url] =&gt; http://search.twitter.com/search?q=Cheney ) ) [as_of] =&gt; Mon, 03 Nov 2008 21:49:36 +0000 ) </code></pre>
[ { "answer_id": 263426, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 8, "selected": true, "text": "<p>You mean something like this?</p>\n\n<pre><code>&lt;?php\n\n$jsonurl = \"http://search.twitter.com/trends.json\";\n$json = file_get_contents($jsonurl,0,null,null);\n$json_output = json_decode($json);\n\nforeach ( $json_output-&gt;trends as $trend )\n{\n echo \"{$trend-&gt;name}\\n\";\n}\n</code></pre>\n" }, { "answer_id": 263443, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 3, "selected": false, "text": "<p>Just use it like it was an object you defined. i.e.</p>\n\n<pre><code>$trends = $json_output-&gt;trends;\n</code></pre>\n" }, { "answer_id": 4087249, "author": "Sven", "author_id": 360348, "author_profile": "https://Stackoverflow.com/users/360348", "pm_score": 5, "selected": false, "text": "<p>If you use <code>json_decode($string, true)</code>, you will get no objects, but everything as an associative or number indexed array. Way easier to handle, as the stdObject provided by PHP is nothing but a dumb container with public properties, which cannot be extended with your own functionality.</p>\n\n<pre><code>$array = json_decode($string, true);\n\necho $array['trends'][0]['name'];\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Trends data from Twitter Search API in JSON. Grabbing the file using: ``` $jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); ``` How do I work with data from this object. As an array? Only really need to extract data from the [name] values. JSON object contains: ``` stdClass Object ( [trends] => Array ( [0] => stdClass Object ( [name] => Vote [url] => http://search.twitter.com/search?q=Vote ) [1] => stdClass Object ( [name] => Halloween [url] => http://search.twitter.com/search?q=Halloween ) [2] => stdClass Object ( [name] => Starbucks [url] => http://search.twitter.com/search?q=Starbucks ) [3] => stdClass Object ( [name] => #flylady [url] => http://search.twitter.com/search?q=%23flylady ) [4] => stdClass Object ( [name] => #votereport [url] => http://search.twitter.com/search?q=%23votereport ) [5] => stdClass Object ( [name] => Election Day [url] => http://search.twitter.com/search?q=%22Election+Day%22 ) [6] => stdClass Object ( [name] => #PubCon [url] => http://search.twitter.com/search?q=%23PubCon ) [7] => stdClass Object ( [name] => #defrag08 [url] => http://search.twitter.com/search?q=%23defrag08 ) [8] => stdClass Object ( [name] => Melbourne Cup [url] => http://search.twitter.com/search?q=%22Melbourne+Cup%22 ) [9] => stdClass Object ( [name] => Cheney [url] => http://search.twitter.com/search?q=Cheney ) ) [as_of] => Mon, 03 Nov 2008 21:49:36 +0000 ) ```
You mean something like this? ``` <?php $jsonurl = "http://search.twitter.com/trends.json"; $json = file_get_contents($jsonurl,0,null,null); $json_output = json_decode($json); foreach ( $json_output->trends as $trend ) { echo "{$trend->name}\n"; } ```
263,400
<p>In .NET, the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode" rel="noreferrer"><code>GetHashCode</code> method</a> is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality.</p> <p>Is there a standard algorithm or best practice on how to implement <code>GetHashCode</code> for my custom classes so I don't degrade performance?</p>
[ { "answer_id": 263416, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 12, "selected": true, "text": "<p>I usually go with something like the implementation given in Josh Bloch's <em>fabulous</em> <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321356683\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective Java</a>. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:</p>\n<pre><code>public override int GetHashCode()\n{\n unchecked // Overflow is fine, just wrap\n {\n int hash = 17;\n // Suitable nullity checks etc, of course :)\n hash = hash * 23 + field1.GetHashCode();\n hash = hash * 23 + field2.GetHashCode();\n hash = hash * 23 + field3.GetHashCode();\n return hash;\n }\n}\n</code></pre>\n<p>As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-<a href=\"https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function\" rel=\"noreferrer\">FNV</a> example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant <em>is</em> prime though. I don't know quite how important that is.)</p>\n<p>This is better than the common practice of <code>XOR</code>ing hashcodes for two main reasons. Suppose we have a type with two <code>int</code> fields:</p>\n<pre><code>XorHash(x, x) == XorHash(y, y) == 0 for all x, y\nXorHash(x, y) == XorHash(y, x) for all x, y\n</code></pre>\n<p>By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.</p>\n<p><a href=\"http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx\" rel=\"noreferrer\">This page</a> gives quite a few options. I think for most cases the above is &quot;good enough&quot; and it's incredibly easy to remember and get right. The <a href=\"http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx#fnv\" rel=\"noreferrer\">FNV</a> alternative is similarly simple, but uses different constants and <code>XOR</code> instead of <code>ADD</code> as a combining operation. It looks <em>something</em> like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.</p>\n<pre><code>// Note: Not quite FNV!\npublic override int GetHashCode()\n{\n unchecked // Overflow is fine, just wrap\n {\n int hash = (int) 2166136261;\n // Suitable nullity checks etc, of course :)\n hash = (hash * 16777619) ^ field1.GetHashCode();\n hash = (hash * 16777619) ^ field2.GetHashCode();\n hash = (hash * 16777619) ^ field3.GetHashCode();\n return hash;\n }\n}\n</code></pre>\n<p>Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.</p>\n<p>As per the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode#notes-to-inheritors\" rel=\"noreferrer\">documentation</a>:</p>\n<blockquote>\n<p>You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:</p>\n<ul>\n<li>You can compute the hash code from fields that are not mutable; or</li>\n<li>You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.</li>\n</ul>\n</blockquote>\n<p>The link to the <a href=\"http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx\" rel=\"noreferrer\">FNV</a> article is broken but here is a copy in the Internet Archive: <a href=\"https://archive.vn/KJeJy\" rel=\"noreferrer\">Eternally Confuzzled - The Art of Hashing</a></p>\n" }, { "answer_id": 264383, "author": "Mark G", "author_id": 34556, "author_profile": "https://Stackoverflow.com/users/34556", "pm_score": 2, "selected": false, "text": "<p>Most of my work is done with database connectivity which means that my classes all have a unique identifier from the database. I always use the ID from the database to generate the hashcode.</p>\n\n<pre><code>// Unique ID from database\nprivate int _id;\n\n... \n{\n return _id.GetHashCode();\n}\n</code></pre>\n" }, { "answer_id": 577380, "author": "Wahid Shalaly", "author_id": 49508, "author_profile": "https://Stackoverflow.com/users/49508", "pm_score": 6, "selected": false, "text": "<p>I have a Hashing class in Helper library that I use it for this purpose.</p>\n\n<pre><code>/// &lt;summary&gt; \n/// This is a simple hashing function from Robert Sedgwicks Hashing in C book.\n/// Also, some simple optimizations to the algorithm in order to speed up\n/// its hashing process have been added. from: www.partow.net\n/// &lt;/summary&gt;\n/// &lt;param name=\"input\"&gt;array of objects, parameters combination that you need\n/// to get a unique hash code for them&lt;/param&gt;\n/// &lt;returns&gt;Hash code&lt;/returns&gt;\npublic static int RSHash(params object[] input)\n{\n const int b = 378551;\n int a = 63689;\n int hash = 0;\n\n // If it overflows then just wrap around\n unchecked\n {\n for (int i = 0; i &lt; input.Length; i++)\n {\n if (input[i] != null)\n {\n hash = hash * a + input[i].GetHashCode();\n a = a * b;\n }\n }\n }\n\n return hash;\n}\n</code></pre>\n\n<p>Then, simply you can use it as:</p>\n\n<pre><code>public override int GetHashCode()\n{\n return Hashing.RSHash(_field1, _field2, _field3);\n}\n</code></pre>\n\n<p>I didn't assess its performance, so any feedback is welcomed.</p>\n" }, { "answer_id": 577405, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 5, "selected": false, "text": "<p>In most cases where Equals() compares multiple fields it doesn't really matter if your GetHash() hashes on one field or on many. You just have to make sure that calculating the hash is really cheap (<B>No allocations</b>, please) and fast (<B>No heavy computations</B> and certainly no database connections) and provides a good distribution.</p>\n\n<p>The heavy lifting should be part of the Equals() method; the hash should be a very cheap operation to enable calling Equals() on as few items as possible.</p>\n\n<p>And one final tip: <B>Don't rely on GetHashCode() being stable over multiple aplication runs</B>. Many .Net types don't guarantee their hash codes to stay the same after a restart, so you should only use the value of GetHashCode() for in memory data structures.</p>\n" }, { "answer_id": 2575444, "author": "nightcoder", "author_id": 94990, "author_profile": "https://Stackoverflow.com/users/94990", "pm_score": 7, "selected": false, "text": "<p>Here is my hashcode helper.<br>\nIt's advantage is that it uses generic type arguments and therefore will not cause boxing:</p>\n\n<pre><code>public static class HashHelper\n{\n public static int GetHashCode&lt;T1, T2&gt;(T1 arg1, T2 arg2)\n {\n unchecked\n {\n return 31 * arg1.GetHashCode() + arg2.GetHashCode();\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3&gt;(T1 arg1, T2 arg2, T3 arg3)\n {\n unchecked\n {\n int hash = arg1.GetHashCode();\n hash = 31 * hash + arg2.GetHashCode();\n return 31 * hash + arg3.GetHashCode();\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3, T4&gt;(T1 arg1, T2 arg2, T3 arg3, \n T4 arg4)\n {\n unchecked\n {\n int hash = arg1.GetHashCode();\n hash = 31 * hash + arg2.GetHashCode();\n hash = 31 * hash + arg3.GetHashCode();\n return 31 * hash + arg4.GetHashCode();\n }\n }\n\n public static int GetHashCode&lt;T&gt;(T[] list)\n {\n unchecked\n {\n int hash = 0;\n foreach (var item in list)\n {\n hash = 31 * hash + item.GetHashCode();\n }\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T&gt;(IEnumerable&lt;T&gt; list)\n {\n unchecked\n {\n int hash = 0;\n foreach (var item in list)\n {\n hash = 31 * hash + item.GetHashCode();\n }\n return hash;\n }\n }\n\n /// &lt;summary&gt;\n /// Gets a hashcode for a collection for that the order of items \n /// does not matter.\n /// So {1, 2, 3} and {3, 2, 1} will get same hash code.\n /// &lt;/summary&gt;\n public static int GetHashCodeForOrderNoMatterCollection&lt;T&gt;(\n IEnumerable&lt;T&gt; list)\n {\n unchecked\n {\n int hash = 0;\n int count = 0;\n foreach (var item in list)\n {\n hash += item.GetHashCode();\n count++;\n }\n return 31 * hash + count.GetHashCode();\n }\n }\n\n /// &lt;summary&gt;\n /// Alternative way to get a hashcode is to use a fluent \n /// interface like this:&lt;br /&gt;\n /// return 0.CombineHashCode(field1).CombineHashCode(field2).\n /// CombineHashCode(field3);\n /// &lt;/summary&gt;\n public static int CombineHashCode&lt;T&gt;(this int hashCode, T arg)\n {\n unchecked\n {\n return 31 * hashCode + arg.GetHashCode(); \n }\n }\n</code></pre>\n\n<p>Also it has extension method to provide a fluent interface, so you can use it like this:</p>\n\n<pre><code>public override int GetHashCode()\n{\n return HashHelper.GetHashCode(Manufacturer, PartN, Quantity);\n}\n</code></pre>\n\n<p>or like this: </p>\n\n<pre><code>public override int GetHashCode()\n{\n return 0.CombineHashCode(Manufacturer)\n .CombineHashCode(PartN)\n .CombineHashCode(Quantity);\n}\n</code></pre>\n" }, { "answer_id": 3880895, "author": "Magnus", "author_id": 468973, "author_profile": "https://Stackoverflow.com/users/468973", "pm_score": 4, "selected": false, "text": "<p>This is a good one:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Helper class for generating hash codes suitable \n/// for use in hashing algorithms and data structures like a hash table. \n/// &lt;/summary&gt;\npublic static class HashCodeHelper\n{\n private static int GetHashCodeInternal(int key1, int key2)\n {\n unchecked\n {\n var num = 0x7e53a269;\n num = (-1521134295 * num) + key1;\n num += (num &lt;&lt; 10);\n num ^= (num &gt;&gt; 6);\n\n num = ((-1521134295 * num) + key2);\n num += (num &lt;&lt; 10);\n num ^= (num &gt;&gt; 6);\n\n return num;\n }\n }\n\n /// &lt;summary&gt;\n /// Returns a hash code for the specified objects\n /// &lt;/summary&gt;\n /// &lt;param name=\"arr\"&gt;An array of objects used for generating the \n /// hash code.&lt;/param&gt;\n /// &lt;returns&gt;\n /// A hash code, suitable for use in hashing algorithms and data \n /// structures like a hash table. \n /// &lt;/returns&gt;\n public static int GetHashCode(params object[] arr)\n {\n int hash = 0;\n foreach (var item in arr)\n hash = GetHashCodeInternal(hash, item.GetHashCode());\n return hash;\n }\n\n /// &lt;summary&gt;\n /// Returns a hash code for the specified objects\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj1\"&gt;The first object.&lt;/param&gt;\n /// &lt;param name=\"obj2\"&gt;The second object.&lt;/param&gt;\n /// &lt;param name=\"obj3\"&gt;The third object.&lt;/param&gt;\n /// &lt;param name=\"obj4\"&gt;The fourth object.&lt;/param&gt;\n /// &lt;returns&gt;\n /// A hash code, suitable for use in hashing algorithms and\n /// data structures like a hash table.\n /// &lt;/returns&gt;\n public static int GetHashCode&lt;T1, T2, T3, T4&gt;(T1 obj1, T2 obj2, T3 obj3,\n T4 obj4)\n {\n return GetHashCode(obj1, GetHashCode(obj2, obj3, obj4));\n }\n\n /// &lt;summary&gt;\n /// Returns a hash code for the specified objects\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj1\"&gt;The first object.&lt;/param&gt;\n /// &lt;param name=\"obj2\"&gt;The second object.&lt;/param&gt;\n /// &lt;param name=\"obj3\"&gt;The third object.&lt;/param&gt;\n /// &lt;returns&gt;\n /// A hash code, suitable for use in hashing algorithms and data \n /// structures like a hash table. \n /// &lt;/returns&gt;\n public static int GetHashCode&lt;T1, T2, T3&gt;(T1 obj1, T2 obj2, T3 obj3)\n {\n return GetHashCode(obj1, GetHashCode(obj2, obj3));\n }\n\n /// &lt;summary&gt;\n /// Returns a hash code for the specified objects\n /// &lt;/summary&gt;\n /// &lt;param name=\"obj1\"&gt;The first object.&lt;/param&gt;\n /// &lt;param name=\"obj2\"&gt;The second object.&lt;/param&gt;\n /// &lt;returns&gt;\n /// A hash code, suitable for use in hashing algorithms and data \n /// structures like a hash table. \n /// &lt;/returns&gt;\n public static int GetHashCode&lt;T1, T2&gt;(T1 obj1, T2 obj2)\n {\n return GetHashCodeInternal(obj1.GetHashCode(), obj2.GetHashCode());\n }\n}\n</code></pre>\n\n<p>And here is how to use it:</p>\n\n<pre><code>private struct Key\n{\n private Type _type;\n private string _field;\n\n public Type Type { get { return _type; } }\n public string Field { get { return _field; } }\n\n public Key(Type type, string field)\n {\n _type = type;\n _field = field;\n }\n\n public override int GetHashCode()\n {\n return HashCodeHelper.GetHashCode(_field, _type);\n }\n\n public override bool Equals(object obj)\n {\n if (!(obj is Key))\n return false;\n var tf = (Key)obj;\n return tf._field.Equals(_field) &amp;&amp; tf._type.Equals(_type);\n }\n}\n</code></pre>\n" }, { "answer_id": 4630550, "author": "Rick Love", "author_id": 567524, "author_profile": "https://Stackoverflow.com/users/567524", "pm_score": 9, "selected": false, "text": "<h1>ValueTuple - Update for C# 7</h1>\n<p>As @cactuaroid mentions in the comments, a value tuple can be used. This saves a few keystrokes and more importantly executes purely on the stack (no Garbage):</p>\n<pre><code>(PropA, PropB, PropC, PropD).GetHashCode();\n</code></pre>\n<p>(Note: The original technique using anonymous types seems to create an object on the heap, i.e. garbage, since anonymous types are implemented as classes, though this might be optimized out by the compiler. It would be interesting to benchmark these options, but the tuple option should be superior.)</p>\n<h1>Anonymous Type (Original Answer)</h1>\n<p>Microsoft already provides a good generic HashCode generator: Just copy your property/field values to an anonymous type and hash it:</p>\n<pre><code>new { PropA, PropB, PropC, PropD }.GetHashCode();\n</code></pre>\n<p>This will work for any number of properties. It does not use boxing. It just uses the algorithm already implemented in the framework for anonymous types.</p>\n" }, { "answer_id": 5391034, "author": "bitbonk", "author_id": 4227, "author_profile": "https://Stackoverflow.com/users/4227", "pm_score": 3, "selected": false, "text": "<p>Here is my simplistic approach. I am using the classic builder pattern for this. It is typesafe (no boxing/unboxing) and also compatbile with .NET 2.0 (no extension methods etc.).</p>\n\n<p>It is used like this:</p>\n\n<pre><code>public override int GetHashCode()\n{\n HashBuilder b = new HashBuilder();\n b.AddItems(this.member1, this.member2, this.member3);\n return b.Result;\n} \n</code></pre>\n\n<p>And here is the acutal builder class:</p>\n\n<pre><code>internal class HashBuilder\n{\n private const int Prime1 = 17;\n private const int Prime2 = 23;\n private int result = Prime1;\n\n public HashBuilder()\n {\n }\n\n public HashBuilder(int startHash)\n {\n this.result = startHash;\n }\n\n public int Result\n {\n get\n {\n return this.result;\n }\n }\n\n public void AddItem&lt;T&gt;(T item)\n {\n unchecked\n {\n this.result = this.result * Prime2 + item.GetHashCode();\n }\n }\n\n public void AddItems&lt;T1, T2&gt;(T1 item1, T2 item2)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n }\n\n public void AddItems&lt;T1, T2, T3&gt;(T1 item1, T2 item2, T3 item3)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n this.AddItem(item3);\n }\n\n public void AddItems&lt;T1, T2, T3, T4&gt;(T1 item1, T2 item2, T3 item3, \n T4 item4)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n this.AddItem(item3);\n this.AddItem(item4);\n }\n\n public void AddItems&lt;T1, T2, T3, T4, T5&gt;(T1 item1, T2 item2, T3 item3, \n T4 item4, T5 item5)\n {\n this.AddItem(item1);\n this.AddItem(item2);\n this.AddItem(item3);\n this.AddItem(item4);\n this.AddItem(item5);\n } \n\n public void AddItems&lt;T&gt;(params T[] items)\n {\n foreach (T item in items)\n {\n this.AddItem(item);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 13651902, "author": "Hassan Faghihi", "author_id": 1260751, "author_profile": "https://Stackoverflow.com/users/1260751", "pm_score": 2, "selected": false, "text": "<p>Microsoft lead for several way of hashing...</p>\n\n<pre><code>//for classes that contain a single int value\nreturn this.value;\n\n//for classes that contain multiple int value\nreturn x ^ y;\n\n//for classes that contain single number bigger than int \nreturn ((int)value ^ (int)(value &gt;&gt; 32)); \n\n//for classes that contain class instance fields which inherit from object\nreturn obj1.GetHashCode();\n\n//for classes that contain multiple class instance fields which inherit from object\nreturn obj1.GetHashCode() ^ obj2.GetHashCode() ^ obj3.GetHashCode(); \n</code></pre>\n\n<p>I can guess that for multiple big int you can use this:</p>\n\n<pre><code>int a=((int)value1 ^ (int)(value1 &gt;&gt; 32));\nint b=((int)value2 ^ (int)(value2 &gt;&gt; 32));\nint c=((int)value3 ^ (int)(value3 &gt;&gt; 32));\nreturn a ^ b ^ c;\n</code></pre>\n\n<p>And same for multi-type: all converted first to <code>int</code> using <code>GetHashCode()</code>\nthen the int values will be xor'ed and the result is your hash.</p>\n\n<p>For those who use hash as ID (I mean an unique value), hash is naturally limited to a number of digits, I think it was 5 bytes for hashing algorithm, at least MD5.</p>\n\n<p>You may turn multiple values to a hashed value and some of them be same, so don't use it as an identifier. (maybe some day I am going to use your component)</p>\n" }, { "answer_id": 18613926, "author": "Şafak Gür", "author_id": 704144, "author_profile": "https://Stackoverflow.com/users/704144", "pm_score": 6, "selected": false, "text": "<p>Here's my helper class using <a href=\"https://stackoverflow.com/a/263416/704144\">Jon Skeet's implementation</a>.</p>\n\n<pre><code>public static class HashCode\n{\n public const int Start = 17;\n\n public static int Hash&lt;T&gt;(this int hash, T obj)\n {\n var h = EqualityComparer&lt;T&gt;.Default.GetHashCode(obj);\n return unchecked((hash * 31) + h);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public override int GetHashCode()\n{\n return HashCode.Start\n .Hash(_field1)\n .Hash(_field2)\n .Hash(_field3);\n}\n</code></pre>\n\n<p>If you want to avoid writing an extension method for System.Int32:</p>\n\n<pre><code>public readonly struct HashCode\n{\n private readonly int _value;\n\n public HashCode(int value) =&gt; _value = value;\n\n public static HashCode Start { get; } = new HashCode(17);\n\n public static implicit operator int(HashCode hash) =&gt; hash._value;\n\n public HashCode Hash&lt;T&gt;(T obj)\n {\n var h = EqualityComparer&lt;T&gt;.Default.GetHashCode(obj);\n return unchecked(new HashCode((_value * 31) + h));\n }\n\n public override int GetHashCode() =&gt; _value;\n}\n</code></pre>\n\n<p>It still avoids any heap allocation and is used exactly the same way:</p>\n\n<pre><code>public override int GetHashCode()\n{\n // This time `HashCode.Start` is not an `Int32`, it's a `HashCode` instance.\n // And the result is implicitly converted to `Int32`.\n return HashCode.Start\n .Hash(_field1)\n .Hash(_field2) \n .Hash(_field3);\n}\n</code></pre>\n\n<p>Edit (May 2018): <code>EqualityComparer&lt;T&gt;.Default</code> getter is now a JIT intrinsic - the <a href=\"https://github.com/dotnet/coreclr/pull/14125\" rel=\"nofollow noreferrer\">pull request</a> is mentioned by Stephen Toub in <a href=\"https://blogs.msdn.microsoft.com/dotnet/2018/04/18/performance-improvements-in-net-core-2-1\" rel=\"nofollow noreferrer\">this blog post</a>.</p>\n" }, { "answer_id": 21115750, "author": "Jon Hanna", "author_id": 400547, "author_profile": "https://Stackoverflow.com/users/400547", "pm_score": 5, "selected": false, "text": "<p>Up until recently my answer would have been very close to Jon Skeet's here. However, I recently started a project which used power-of-two hash tables, that is hash tables where the size of the internal table is 8, 16, 32, etc. There's a good reason for favouring prime-number sizes, but there are some advantages to power-of-two sizes too.</p>\n\n<p>And it pretty much sucked. So after a bit of experimentation and research I started re-hashing my hashes with the following:</p>\n\n<pre><code>public static int ReHash(int source)\n{\n unchecked\n {\n ulong c = 0xDEADBEEFDEADBEEF + (ulong)source;\n ulong d = 0xE2ADBEEFDEADBEEF ^ c;\n ulong a = d += c = c &lt;&lt; 15 | c &gt;&gt; -15;\n ulong b = a += d = d &lt;&lt; 52 | d &gt;&gt; -52;\n c ^= b += a = a &lt;&lt; 26 | a &gt;&gt; -26;\n d ^= c += b = b &lt;&lt; 51 | b &gt;&gt; -51;\n a ^= d += c = c &lt;&lt; 28 | c &gt;&gt; -28;\n b ^= a += d = d &lt;&lt; 9 | d &gt;&gt; -9;\n c ^= b += a = a &lt;&lt; 47 | a &gt;&gt; -47;\n d ^= c += b &lt;&lt; 54 | b &gt;&gt; -54;\n a ^= d += c &lt;&lt; 32 | c &gt;&gt; 32;\n a += d &lt;&lt; 25 | d &gt;&gt; -25;\n return (int)(a &gt;&gt; 1);\n }\n}\n</code></pre>\n\n<p>And then my power-of-two hash table didn't suck any more.</p>\n\n<p>This disturbed me though, because the above shouldn't work. Or more precisely, it shouldn't work unless the original <code>GetHashCode()</code> was poor in a very particular way.</p>\n\n<p>Re-mixing a hashcode can't improve a great hashcode, because the only possible effect is that we introduce a few more collisions.</p>\n\n<p>Re-mixing a hash code can't improve a terrible hash code, because the only possible effect is we change e.g. a large number of collisions on value 53 to a large number of value 18,3487,291.</p>\n\n<p>Re-mixing a hash code can only improve a hash code that did at least fairly well in avoiding absolute collisions throughout its range (2<sup>32</sup> possible values) but badly at avoiding collisions when modulo'd down for actual use in a hash table. While the simpler modulo of a power-of-two table made this more apparent, it was also having a negative effect with the more common prime-number tables, that just wasn't as obvious (the extra work in rehashing would outweigh the benefit, but the benefit would still be there).</p>\n\n<p>Edit: I was also using open-addressing, which would also have increased the sensitivity to collision, perhaps more so than the fact it was power-of-two.</p>\n\n<p>And well, it was disturbing how much the <code>string.GetHashCode()</code> implementations in <a href=\"https://referencesource.microsoft.com/#mscorlib/System/string.cs,789\" rel=\"noreferrer\">.NET</a> (or study <a href=\"https://stackoverflow.com/a/48775953/147511\">here</a>) could be improved this way (on the order of tests running about 20-30 times faster due to fewer collisions) and more disturbing how much my own hash codes could be improved (much more than that).</p>\n\n<p><strong>All the GetHashCode() implementations I'd coded in the past, and indeed used as the basis of answers on this site, were much worse than I'd throught</strong>. Much of the time it was \"good enough\" for much of the uses, but I wanted something better.</p>\n\n<p>So I put that project to one side (it was a pet project anyway) and started looking at how to produce a good, well-distributed hash code in .NET quickly.</p>\n\n<p>In the end I settled on porting <a href=\"http://burtleburtle.net/bob/hash/spooky.html\" rel=\"noreferrer\">SpookyHash</a> to .NET. Indeed the code above is a fast-path version of using SpookyHash to produce a 32-bit output from a 32-bit input.</p>\n\n<p>Now, SpookyHash is not a nice quick to remember piece of code. My port of it is even less so because I hand-inlined a lot of it for better speed*. But that's what code reuse is for.</p>\n\n<p>Then I put <em>that</em> project to one side, because just as the original project had produced the question of how to produce a better hash code, so that project produced the question of how to produce a better .NET memcpy.</p>\n\n<p>Then I came back, and produced a lot of overloads to easily feed just about all of the native types (except <code>decimal</code>†) into a hash code.</p>\n\n<p>It's fast, for which Bob Jenkins deserves most of the credit because his original code I ported from is faster still, especially on 64-bit machines which the algorithm is optimised for‡.</p>\n\n<p>The full code can be seen at <a href=\"https://bitbucket.org/JonHanna/spookilysharp/src\" rel=\"noreferrer\">https://bitbucket.org/JonHanna/spookilysharp/src</a> but consider that the code above is a simplified version of it.</p>\n\n<p>However, since it's now already written, one can make use of it more easily:</p>\n\n<pre><code>public override int GetHashCode()\n{\n var hash = new SpookyHash();\n hash.Update(field1);\n hash.Update(field2);\n hash.Update(field3);\n return hash.Final().GetHashCode();\n}\n</code></pre>\n\n<p>It also takes seed values, so if you need to deal with untrusted input and want to protect against Hash DoS attacks you can set a seed based on uptime or similar, and make the results unpredictable by attackers:</p>\n\n<pre><code>private static long hashSeed0 = Environment.TickCount;\nprivate static long hashSeed1 = DateTime.Now.Ticks;\npublic override int GetHashCode()\n{\n //produce different hashes ever time this application is restarted\n //but remain consistent in each run, so attackers have a harder time\n //DoSing the hash tables.\n var hash = new SpookyHash(hashSeed0, hashSeed1);\n hash.Update(field1);\n hash.Update(field2);\n hash.Update(field3);\n return hash.Final().GetHashCode();\n}\n</code></pre>\n\n<p>*A big surprise in this is that hand-inlining a rotation method that returned <code>(x &lt;&lt; n) | (x &gt;&gt; -n)</code> improved things. I would have been sure that the jitter would have inlined that for me, but profiling showed otherwise.</p>\n\n<p>†<code>decimal</code> isn't native from the .NET perspective though it is from the C#. The problem with it is that its own <code>GetHashCode()</code> treats precision as significant while its own <code>Equals()</code> does not. Both are valid choices, but not mixed like that. In implementing your own version, you need to choose to do one, or the other, but I can't know which you'd want.</p>\n\n<p>‡By way of comparison. If used on a string, the SpookyHash on 64 bits is considerably faster than <code>string.GetHashCode()</code> on 32 bits which is slightly faster than <code>string.GetHashCode()</code> on 64 bits, which is considerably faster than SpookyHash on 32 bits, though still fast enough to be a reasonable choice.</p>\n" }, { "answer_id": 21246408, "author": "Scott Wegner", "author_id": 33791, "author_profile": "https://Stackoverflow.com/users/33791", "pm_score": 4, "selected": false, "text": "<p>Here is another fluent implementation of <a href=\"https://stackoverflow.com/a/263416/33791\">the algorithm posted above by Jon Skeet</a>, but which includes no allocations or boxing operations:</p>\n\n<pre><code>public static class Hash\n{\n public const int Base = 17;\n\n public static int HashObject(this int hash, object obj)\n {\n unchecked { return hash * 23 + (obj == null ? 0 : obj.GetHashCode()); }\n }\n\n public static int HashValue&lt;T&gt;(this int hash, T value)\n where T : struct\n {\n unchecked { return hash * 23 + value.GetHashCode(); }\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>public class MyType&lt;T&gt;\n{\n public string Name { get; set; }\n\n public string Description { get; set; }\n\n public int Value { get; set; }\n\n public IEnumerable&lt;T&gt; Children { get; set; }\n\n public override int GetHashCode()\n {\n return Hash.Base\n .HashObject(this.Name)\n .HashObject(this.Description)\n .HashValue(this.Value)\n .HashObject(this.Children);\n }\n}\n</code></pre>\n\n<p>The compiler will ensure <code>HashValue</code> is not called with a class due to the generic type constraint. But there is no compiler support for <code>HashObject</code> since adding a generic argument also adds a boxing operation.</p>\n" }, { "answer_id": 26087186, "author": "HokieMike", "author_id": 110736, "author_profile": "https://Stackoverflow.com/users/110736", "pm_score": 0, "selected": false, "text": "<p>I ran into an issue with floats and decimals using the implementation selected as the answer above. </p>\n\n<p>This test fails (floats; hash is the same even though I switched 2 values to be negative):</p>\n\n<pre><code> var obj1 = new { A = 100m, B = 100m, C = 100m, D = 100m};\n var obj2 = new { A = 100m, B = 100m, C = -100m, D = -100m};\n var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);\n var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);\n Assert.IsFalse(hash1 == hash2, string.Format(\"Hashcode values should be different hash1:{0} hash2:{1}\",hash1,hash2));\n</code></pre>\n\n<p>But this test passes (with ints):</p>\n\n<pre><code> var obj1 = new { A = 100m, B = 100m, C = 100, D = 100};\n var obj2 = new { A = 100m, B = 100m, C = -100, D = -100};\n var hash1 = ComputeHash(obj1.A, obj1.B, obj1.C, obj1.D);\n var hash2 = ComputeHash(obj2.A, obj2.B, obj2.C, obj2.D);\n Assert.IsFalse(hash1 == hash2, string.Format(\"Hashcode values should be different hash1:{0} hash2:{1}\",hash1,hash2));\n</code></pre>\n\n<p>I changed my implementation to not use GetHashCode for the primitive types and it seems to work better</p>\n\n<pre><code> private static int InternalComputeHash(params object[] obj)\n {\n unchecked\n {\n var result = (int)SEED_VALUE_PRIME;\n for (uint i = 0; i &lt; obj.Length; i++)\n {\n var currval = result;\n var nextval = DetermineNextValue(obj[i]);\n result = (result * MULTIPLIER_VALUE_PRIME) + nextval;\n\n }\n return result;\n }\n }\n\n\n\n private static int DetermineNextValue(object value)\n {\n unchecked\n {\n\n int hashCode;\n if (value is short\n || value is int\n || value is byte\n || value is sbyte\n || value is uint\n || value is ushort\n || value is ulong\n || value is long\n || value is float\n || value is double\n || value is decimal)\n {\n return Convert.ToInt32(value);\n }\n else\n {\n return value != null ? value.GetHashCode() : 0;\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 26493039, "author": "Dbl", "author_id": 1786596, "author_profile": "https://Stackoverflow.com/users/1786596", "pm_score": 2, "selected": false, "text": "<p>Pretty much similar to nightcoder's solution except it's easier to raise primes if you want to. </p>\n\n<p>PS: This is one of those times where you puke a little in your mouth, knowing that this could be refactored into one method with 9 default's but it would be slower, so you just close your eyes and try to forget about it.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Try not to look at the source code. It works. Just rely on it.\n/// &lt;/summary&gt;\npublic static class HashHelper\n{\n private const int PrimeOne = 17;\n private const int PrimeTwo = 23;\n\n public static int GetHashCode&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9, T10&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n hash = hash * PrimeTwo + arg8.GetHashCode();\n hash = hash * PrimeTwo + arg9.GetHashCode();\n hash = hash * PrimeTwo + arg10.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3, T4, T5, T6, T7, T8, T9&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n hash = hash * PrimeTwo + arg8.GetHashCode();\n hash = hash * PrimeTwo + arg9.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3, T4, T5, T6, T7, T8&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n hash = hash * PrimeTwo + arg8.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3, T4, T5, T6, T7&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n hash = hash * PrimeTwo + arg7.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3, T4, T5, T6&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n hash = hash * PrimeTwo + arg6.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3, T4, T5&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n hash = hash * PrimeTwo + arg5.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3, T4&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n hash = hash * PrimeTwo + arg4.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2, T3&gt;(T1 arg1, T2 arg2, T3 arg3)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n hash = hash * PrimeTwo + arg3.GetHashCode();\n\n return hash;\n }\n }\n\n public static int GetHashCode&lt;T1, T2&gt;(T1 arg1, T2 arg2)\n {\n unchecked\n {\n int hash = PrimeOne;\n hash = hash * PrimeTwo + arg1.GetHashCode();\n hash = hash * PrimeTwo + arg2.GetHashCode();\n\n return hash;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 39279329, "author": "Charles Burns", "author_id": 161816, "author_profile": "https://Stackoverflow.com/users/161816", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://www.jetbrains.com/resharper/\" rel=\"nofollow noreferrer\">ReSharper</a> users can generate GetHashCode, Equals, and others with <code>ReSharper -&gt; Edit -&gt; Generate Code -&gt; Equality Members</code>.</p>\n\n<pre><code>// ReSharper's GetHashCode looks like this\npublic override int GetHashCode() {\n unchecked {\n int hashCode = Id;\n hashCode = (hashCode * 397) ^ IntMember;\n hashCode = (hashCode * 397) ^ OtherIntMember;\n hashCode = (hashCode * 397) ^ (RefMember != null ? RefMember.GetHashCode() : 0);\n // ...\n return hashCode;\n }\n}\n</code></pre>\n" }, { "answer_id": 47458496, "author": "James Ko", "author_id": 4077294, "author_profile": "https://Stackoverflow.com/users/4077294", "pm_score": 5, "selected": false, "text": "<p>As of <a href=\"https://github.com/dotnet/coreclr/pull/14863\" rel=\"noreferrer\">https://github.com/dotnet/coreclr/pull/14863</a>, there is a new way to generate hash codes that is super simple! Just write</p>\n\n<pre><code>public override int GetHashCode()\n =&gt; HashCode.Combine(field1, field2, field3);\n</code></pre>\n\n<p>This will generate a quality hash code without you having to worry about the implementation details.</p>\n" }, { "answer_id": 50349672, "author": "Timo", "author_id": 543814, "author_profile": "https://Stackoverflow.com/users/543814", "pm_score": 3, "selected": false, "text": "<p>If we have no more than 8 properties (hopefully), here is another alternative.</p>\n\n<p><code>ValueTuple</code> is a struct and appears to have a solid <code>GetHashCode</code> implementation.</p>\n\n<p>That means we could simply do this:</p>\n\n<pre><code>// Yay, no allocations and no custom implementations!\npublic override int GetHashCode() =&gt; (this.PropA, this.PropB).GetHashCode();\n</code></pre>\n\n<p>Let's take a look at .NET Core's current implementation for <code>ValueTuple</code>'s <code>GetHashCode</code>.</p>\n\n<p>This is from <a href=\"https://github.com/dotnet/corefx/blob/master/src/System.ValueTuple/src/System/ValueTuple/ValueTuple.cs\" rel=\"noreferrer\"><code>ValueTuple</code></a>:</p>\n\n<pre><code> internal static int CombineHashCodes(int h1, int h2)\n {\n return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);\n }\n\n internal static int CombineHashCodes(int h1, int h2, int h3)\n {\n return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);\n }\n</code></pre>\n\n<p>And this is from <a href=\"https://github.com/dotnet/corefx/blob/master/src/Common/src/System/Numerics/Hashing/HashHelpers.cs\" rel=\"noreferrer\"><code>HashHelper</code></a>:</p>\n\n<pre><code> public static readonly int RandomSeed = Guid.NewGuid().GetHashCode();\n\n public static int Combine(int h1, int h2)\n {\n unchecked\n {\n // RyuJIT optimizes this to use the ROL instruction\n // Related GitHub pull request: dotnet/coreclr#1830\n uint rol5 = ((uint)h1 &lt;&lt; 5) | ((uint)h1 &gt;&gt; 27);\n return ((int)rol5 + h1) ^ h2;\n }\n }\n</code></pre>\n\n<p>In English:</p>\n\n<ul>\n<li>Left rotate (circular shift) h1 by 5 positions.</li>\n<li>Add the result and h1 together.</li>\n<li>XOR the result with h2.</li>\n<li>Start by performing the above operation on { static random seed, h1 }.</li>\n<li>For each further item, perform the operation on the previous result and the next item (e.g. h2).</li>\n</ul>\n\n<p>It would be nice to know more about the properties of this ROL-5 hash code algorithm.</p>\n\n<p>Regrettably, deferring to <code>ValueTuple</code> for our own <code>GetHashCode</code> may not be as fast as we would like and expect. <a href=\"https://github.com/dotnet/corefx/issues/8034#issuecomment-260759796\" rel=\"noreferrer\">This comment</a> in a related discussion illustrates that directly calling <code>HashHelpers.Combine</code> is more performant. On the flip side, that one is internal, so we'd have to copy the code, sacrificing much of what we had gained here. Also, we'd be responsible for remembering to first <code>Combine</code> with the random seed. I don't know what the consequences are if we skip that step.</p>\n" }, { "answer_id": 55887202, "author": "Steven Coco", "author_id": 4061898, "author_profile": "https://Stackoverflow.com/users/4061898", "pm_score": 1, "selected": false, "text": "<p>This is a static helper class that implements Josh Bloch's implementation; and provides explicit overloads to \"prevent\" boxing, and also to implement the hash specifically for the long primitives.</p>\n\n<p>You can pass a string comparison that matches your equals implementation.</p>\n\n<p>Because the Hash output is always an int, you can just chain Hash calls.</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n\nnamespace Sc.Util.System\n{\n /// &lt;summary&gt;\n /// Static methods that allow easy implementation of hashCode. Example usage:\n /// &lt;code&gt;\n /// public override int GetHashCode()\n /// =&gt; HashCodeHelper.Seed\n /// .Hash(primitiveField)\n /// .Hsh(objectField)\n /// .Hash(iEnumerableField);\n /// &lt;/code&gt;\n /// &lt;/summary&gt;\n public static class HashCodeHelper\n {\n /// &lt;summary&gt;\n /// An initial value for a hashCode, to which is added contributions from fields.\n /// Using a non-zero value decreases collisions of hashCode values.\n /// &lt;/summary&gt;\n public const int Seed = 23;\n\n private const int oddPrimeNumber = 37;\n\n\n /// &lt;summary&gt;\n /// Rotates the seed against a prime number.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The hash's first term.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private static int rotateFirstTerm(int aSeed)\n {\n unchecked {\n return HashCodeHelper.oddPrimeNumber * aSeed;\n }\n }\n\n\n /// &lt;summary&gt;\n /// Contributes a boolean to the developing HashCode seed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aBoolean\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, bool aBoolean)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + (aBoolean\n ? 1\n : 0);\n }\n }\n\n /// &lt;summary&gt;\n /// Contributes a char to the developing HashCode seed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aChar\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, char aChar)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + aChar;\n }\n }\n\n /// &lt;summary&gt;\n /// Contributes an int to the developing HashCode seed.\n /// Note that byte and short are handled by this method, through implicit conversion.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aInt\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, int aInt)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + aInt;\n }\n }\n\n /// &lt;summary&gt;\n /// Contributes a long to the developing HashCode seed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aLong\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, long aLong)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + (int)(aLong ^ (aLong &gt;&gt; 32));\n }\n }\n\n /// &lt;summary&gt;\n /// Contributes a float to the developing HashCode seed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aFloat\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, float aFloat)\n {\n unchecked {\n return HashCodeHelper.rotateFirstTerm(aSeed)\n + Convert.ToInt32(aFloat);\n }\n }\n\n /// &lt;summary&gt;\n /// Contributes a double to the developing HashCode seed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aDouble\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, double aDouble)\n =&gt; aSeed.Hash(Convert.ToInt64(aDouble));\n\n /// &lt;summary&gt;\n /// Contributes a string to the developing HashCode seed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aString\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;param name=\"stringComparison\"&gt;Optional comparison that creates the hash.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(\n this int aSeed,\n string aString,\n StringComparison stringComparison = StringComparison.Ordinal)\n {\n if (aString == null)\n return aSeed.Hash(0);\n switch (stringComparison) {\n case StringComparison.CurrentCulture :\n return StringComparer.CurrentCulture.GetHashCode(aString);\n case StringComparison.CurrentCultureIgnoreCase :\n return StringComparer.CurrentCultureIgnoreCase.GetHashCode(aString);\n case StringComparison.InvariantCulture :\n return StringComparer.InvariantCulture.GetHashCode(aString);\n case StringComparison.InvariantCultureIgnoreCase :\n return StringComparer.InvariantCultureIgnoreCase.GetHashCode(aString);\n case StringComparison.OrdinalIgnoreCase :\n return StringComparer.OrdinalIgnoreCase.GetHashCode(aString);\n default :\n return StringComparer.Ordinal.GetHashCode(aString);\n }\n }\n\n /// &lt;summary&gt;\n /// Contributes a possibly-null array to the developing HashCode seed.\n /// Each element may be a primitive, a reference, or a possibly-null array.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aArray\"&gt;CAN be null.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, IEnumerable aArray)\n {\n if (aArray == null)\n return aSeed.Hash(0);\n int countPlusOne = 1; // So it differs from null\n foreach (object item in aArray) {\n ++countPlusOne;\n if (item is IEnumerable arrayItem) {\n if (!object.ReferenceEquals(aArray, arrayItem))\n aSeed = aSeed.Hash(arrayItem); // recursive call!\n } else\n aSeed = aSeed.Hash(item);\n }\n return aSeed.Hash(countPlusOne);\n }\n\n /// &lt;summary&gt;\n /// Contributes a possibly-null array to the developing HashCode seed.\n /// You must provide the hash function for each element.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aArray\"&gt;CAN be null.&lt;/param&gt;\n /// &lt;param name=\"hashElement\"&gt;Required: yields the hash for each element\n /// in &lt;paramref name=\"aArray\"/&gt;.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash&lt;T&gt;(this int aSeed, IEnumerable&lt;T&gt; aArray, Func&lt;T, int&gt; hashElement)\n {\n if (aArray == null)\n return aSeed.Hash(0);\n int countPlusOne = 1; // So it differs from null\n foreach (T item in aArray) {\n ++countPlusOne;\n aSeed = aSeed.Hash(hashElement(item));\n }\n return aSeed.Hash(countPlusOne);\n }\n\n /// &lt;summary&gt;\n /// Contributes a possibly-null object to the developing HashCode seed.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"aObject\"&gt;CAN be null.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int Hash(this int aSeed, object aObject)\n {\n switch (aObject) {\n case null :\n return aSeed.Hash(0);\n case bool b :\n return aSeed.Hash(b);\n case char c :\n return aSeed.Hash(c);\n case int i :\n return aSeed.Hash(i);\n case long l :\n return aSeed.Hash(l);\n case float f :\n return aSeed.Hash(f);\n case double d :\n return aSeed.Hash(d);\n case string s :\n return aSeed.Hash(s);\n case IEnumerable iEnumerable :\n return aSeed.Hash(iEnumerable);\n }\n return aSeed.Hash(aObject.GetHashCode());\n }\n\n\n /// &lt;summary&gt;\n /// This utility method uses reflection to iterate all specified properties that are readable\n /// on the given object, excluding any property names given in the params arguments, and\n /// generates a hashcode.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing hash code, or the seed: if you have no seed, use\n /// the &lt;see cref=\"Seed\"/&gt;.&lt;/param&gt;\n /// &lt;param name=\"aObject\"&gt;CAN be null.&lt;/param&gt;\n /// &lt;param name=\"propertySelector\"&gt;&lt;see cref=\"BindingFlags\"/&gt; to select the properties to hash.&lt;/param&gt;\n /// &lt;param name=\"ignorePropertyNames\"&gt;Optional.&lt;/param&gt;\n /// &lt;returns&gt;A hash from the properties contributed to &lt;c&gt;aSeed&lt;/c&gt;.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int HashAllProperties(\n this int aSeed,\n object aObject,\n BindingFlags propertySelector\n = BindingFlags.Instance\n | BindingFlags.Public\n | BindingFlags.GetProperty,\n params string[] ignorePropertyNames)\n {\n if (aObject == null)\n return aSeed.Hash(0);\n if ((ignorePropertyNames != null)\n &amp;&amp; (ignorePropertyNames.Length != 0)) {\n foreach (PropertyInfo propertyInfo in aObject.GetType()\n .GetProperties(propertySelector)) {\n if (!propertyInfo.CanRead\n || (Array.IndexOf(ignorePropertyNames, propertyInfo.Name) &gt;= 0))\n continue;\n aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));\n }\n } else {\n foreach (PropertyInfo propertyInfo in aObject.GetType()\n .GetProperties(propertySelector)) {\n if (propertyInfo.CanRead)\n aSeed = aSeed.Hash(propertyInfo.GetValue(aObject));\n }\n }\n return aSeed;\n }\n\n\n /// &lt;summary&gt;\n /// NOTICE: this method is provided to contribute a &lt;see cref=\"KeyValuePair{TKey,TValue}\"/&gt; to\n /// the developing HashCode seed; by hashing the key and the value independently. HOWEVER,\n /// this method has a different name since it will not be automatically invoked by\n /// &lt;see cref=\"Hash(int,object)\"/&gt;, &lt;see cref=\"Hash(int,IEnumerable)\"/&gt;,\n /// or &lt;see cref=\"HashAllProperties\"/&gt; --- you MUST NOT mix this method with those unless\n /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise\n /// the generated hash code will not be consistent. This method itself ALSO will not invoke\n /// this method on the Key or Value here if that itself is a KeyValuePair.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"keyValuePair\"&gt;The value to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int HashKeyAndValue&lt;TKey, TValue&gt;(this int aSeed, KeyValuePair&lt;TKey, TValue&gt; keyValuePair)\n =&gt; aSeed.Hash(keyValuePair.Key)\n .Hash(keyValuePair.Value);\n\n /// &lt;summary&gt;\n /// NOTICE: this method is provided to contribute a collection of &lt;see cref=\"KeyValuePair{TKey,TValue}\"/&gt;\n /// to the developing HashCode seed; by hashing the key and the value independently. HOWEVER,\n /// this method has a different name since it will not be automatically invoked by\n /// &lt;see cref=\"Hash(int,object)\"/&gt;, &lt;see cref=\"Hash(int,IEnumerable)\"/&gt;,\n /// or &lt;see cref=\"HashAllProperties\"/&gt; --- you MUST NOT mix this method with those unless\n /// you are sure that no KeyValuePair instances will be passed to those methods; or otherwise\n /// the generated hash code will not be consistent. This method itself ALSO will not invoke\n /// this method on a Key or Value here if that itself is a KeyValuePair or an Enumerable of\n /// KeyValuePair.\n /// &lt;/summary&gt;\n /// &lt;param name=\"aSeed\"&gt;The developing HashCode value or seed.&lt;/param&gt;\n /// &lt;param name=\"keyValuePairs\"&gt;The values to contribute.&lt;/param&gt;\n /// &lt;returns&gt;The new hash code.&lt;/returns&gt;\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n public static int HashKeysAndValues&lt;TKey, TValue&gt;(\n this int aSeed,\n IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; keyValuePairs)\n {\n if (keyValuePairs == null)\n return aSeed.Hash(null);\n foreach (KeyValuePair&lt;TKey, TValue&gt; keyValuePair in keyValuePairs) {\n aSeed = aSeed.HashKeyAndValue(keyValuePair);\n }\n return aSeed;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 56539595, "author": "Muhammad Rehan Saeed", "author_id": 1212017, "author_profile": "https://Stackoverflow.com/users/1212017", "pm_score": 7, "selected": false, "text": "<h1>Using <code>System.HashCode</code></h1>\n<p>If you are using .NET Standard 2.1 or above, you can use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.hashcode?view=netcore-2.1\" rel=\"noreferrer\">System.HashCode</a> struct. On earlier frameworks it is available from the <a href=\"https://www.nuget.org/packages/Microsoft.Bcl.HashCode/\" rel=\"noreferrer\"><code>Microsoft.Bcl.HashCode</code></a> package. There are two methods of using it:</p>\n<h3>HashCode.Combine</h3>\n<p>The <code>Combine</code> method can be used to create a hash code, given up to eight objects.</p>\n<pre><code>public override int GetHashCode() =&gt; HashCode.Combine(this.object1, this.object2);\n</code></pre>\n<h3>HashCode.Add</h3>\n<p>The <code>Add</code> method helps you to deal with collections:</p>\n<pre><code>public override int GetHashCode()\n{\n var hashCode = new HashCode();\n hashCode.Add(this.object1);\n foreach (var item in this.collection)\n {\n hashCode.Add(item);\n }\n return hashCode.ToHashCode();\n}\n</code></pre>\n<h1>GetHashCode Made Easy</h1>\n<p>An alternative to <code>System.HashCode</code> that is super easy to use while still being fast. You can read the full blog post '<a href=\"https://rehansaeed.com/gethashcode-made-easy/\" rel=\"noreferrer\">GetHashCode Made Easy</a>' for more details and comments.</p>\n<h3>Usage Example</h3>\n<pre><code>public class SuperHero\n{\n public int Age { get; set; }\n public string Name { get; set; }\n public List&lt;string&gt; Powers { get; set; }\n\n public override int GetHashCode() =&gt;\n HashCode.Of(this.Name).And(this.Age).AndEach(this.Powers);\n}\n</code></pre>\n<h3>Implementation</h3>\n<pre><code>public struct HashCode : IEquatable&lt;HashCode&gt;\n{\n private const int EmptyCollectionPrimeNumber = 19;\n private readonly int value;\n\n private HashCode(int value) =&gt; this.value = value;\n\n public static implicit operator int(HashCode hashCode) =&gt; hashCode.value;\n\n public static bool operator ==(HashCode left, HashCode right) =&gt; left.Equals(right);\n\n public static bool operator !=(HashCode left, HashCode right) =&gt; !(left == right);\n\n public static HashCode Of&lt;T&gt;(T item) =&gt; new HashCode(GetHashCode(item));\n\n public static HashCode OfEach&lt;T&gt;(IEnumerable&lt;T&gt; items) =&gt;\n items == null ? new HashCode(0) : new HashCode(GetHashCode(items, 0));\n\n public HashCode And&lt;T&gt;(T item) =&gt; \n new HashCode(CombineHashCodes(this.value, GetHashCode(item)));\n\n public HashCode AndEach&lt;T&gt;(IEnumerable&lt;T&gt; items)\n {\n if (items == null)\n {\n return new HashCode(this.value);\n }\n\n return new HashCode(GetHashCode(items, this.value));\n }\n\n public bool Equals(HashCode other) =&gt; this.value.Equals(other.value);\n\n public override bool Equals(object obj)\n {\n if (obj is HashCode)\n {\n return this.Equals((HashCode)obj);\n }\n\n return false;\n }\n\n public override int GetHashCode() =&gt; this.value.GetHashCode();\n\n private static int CombineHashCodes(int h1, int h2)\n {\n unchecked\n {\n // Code copied from System.Tuple a good way to combine hashes.\n return ((h1 &lt;&lt; 5) + h1) ^ h2;\n }\n }\n\n private static int GetHashCode&lt;T&gt;(T item) =&gt; item?.GetHashCode() ?? 0;\n\n private static int GetHashCode&lt;T&gt;(IEnumerable&lt;T&gt; items, int startHashCode)\n {\n var temp = startHashCode;\n\n var enumerator = items.GetEnumerator();\n if (enumerator.MoveNext())\n {\n temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));\n\n while (enumerator.MoveNext())\n {\n temp = CombineHashCodes(temp, GetHashCode(enumerator.Current));\n }\n }\n else\n {\n temp = CombineHashCodes(temp, EmptyCollectionPrimeNumber);\n }\n\n return temp;\n }\n}\n</code></pre>\n<h1>What Makes a Good Algorithm?</h1>\n<h2>Performance</h2>\n<p>The algorithm that calculates a hash code needs to be fast. A simple algorithm is usually going to be a faster one. One that does not allocate extra memory will also reduce need for garbage collection, which will in turn also improve performance.</p>\n<p>In C# hash functions specifically, you often use the <code>unchecked</code> keyword which stops overflow checking to improve performance.</p>\n<h2>Deterministic</h2>\n<p>The hashing algorithm needs to be <a href=\"https://en.wikipedia.org/wiki/Deterministic_algorithm\" rel=\"noreferrer\">deterministic</a> i.e. given the same input it must always produce the same output.</p>\n<h2>Reduce Collisions</h2>\n<p>The algorithm that calculates a hash code needs to keep <a href=\"http://crppit.epfl.ch/documentation/Hash_Function/WiKi/Hash_collision.htm\" rel=\"noreferrer\">hash collisions</a> to a minumum. A hash collision is a situation that occurs when two calls to <code>GetHashCode</code> on two different objects produce identical hash codes. Note that collisions are allowed (some have the misconceptions that they are not) but they should be kept to a minimum.</p>\n<p>A lot of hash functions contain magic numbers like <code>17</code> or <code>23</code>. These are special <a href=\"https://en.wikipedia.org/wiki/Prime_number\" rel=\"noreferrer\">prime numbers</a> which due to their mathematical properties help to reduce hash collisions as compared to using non-prime numbers.</p>\n<h2>Hash Uniformity</h2>\n<p>A good hash function should map the expected inputs as evenly as possible over its output range i.e. it should output a wide range of hashes based on its inputs that are evenly spread. It should have hash uniformity.</p>\n<h2>Prevent's DoS</h2>\n<p>In .NET Core each time you restart an application you will get different hash codes. This is a security feature to prevent Denial of Service attacks (DoS). For .NET Framework you <strong>should</strong> enable this feature by adding the following App.config file:</p>\n<pre><code>&lt;?xml version =&quot;1.0&quot;?&gt; \n&lt;configuration&gt; \n &lt;runtime&gt; \n &lt;UseRandomizedStringHashAlgorithm enabled=&quot;1&quot; /&gt; \n &lt;/runtime&gt; \n&lt;/configuration&gt;\n</code></pre>\n<p>Because of this feature, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection and they should never be persisted.</p>\n<p>Read more about this <a href=\"https://andrewlock.net/why-is-string-gethashcode-different-each-time-i-run-my-program-in-net-core/\" rel=\"noreferrer\">here</a>.</p>\n<h1>Cryptographically Secure?</h1>\n<p>The algorithm does not have to be a <a href=\"https://en.wikipedia.org/wiki/Cryptographic_hash_function\" rel=\"noreferrer\">Cryptographic hash function</a>. Meaning it does not have to satisfy the following conditions:</p>\n<ul>\n<li>It is infeasible to generate a message that yields a given hash value.</li>\n<li>It is infeasible to find two different messages with the same hash value.</li>\n<li>A small change to a message should change the hash value so extensively that the new hash value appears uncorrelated with the old hash value (avalanche effect).</li>\n</ul>\n" }, { "answer_id": 61315345, "author": "Ivan Sanz Carasa", "author_id": 6314639, "author_profile": "https://Stackoverflow.com/users/6314639", "pm_score": 0, "selected": false, "text": "<p>In case you want to polyfill <code>HashCode</code> from <code>netstandard2.1</code></p>\n\n<pre><code>public static class HashCode\n{\n public static int Combine(params object[] instances)\n {\n int hash = 17;\n\n foreach (var i in instances)\n {\n hash = unchecked((hash * 31) + (i?.GetHashCode() ?? 0));\n }\n\n return hash;\n }\n}\n</code></pre>\n\n<p>Note: If used with <code>struct</code>, it will allocate memory due to boxing</p>\n" }, { "answer_id": 65891351, "author": "ivan.ukr", "author_id": 1540501, "author_profile": "https://Stackoverflow.com/users/1540501", "pm_score": 0, "selected": false, "text": "<p>Can try to adopt approach from C++ Boost libraries. Something like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class HashUtil\n{\n public static int HashCombine(int seed, int other)\n {\n unchecked\n {\n return other + 0x9e3779b9 + (seed &lt;&lt; 6) + (seed &gt;&gt; 2);\n }\n }\n}\n</code></pre>\n<p>and then:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class MyClass\n{\n private string _field1;\n private int _field2;\n private AnotherClass _field3;\n private YetAnotherClass _field4;\n\n public override int GetHashCode()\n {\n int result = HashUtil.HashCombine(_field1.GetHashCode(), _field2);\n result = HashUtil.HashCombine(result, _field3.GetHashCode());\n return HashUtil.HashCombine(result, _field4.GetHashCode());\n }\n}\n</code></pre>\n" }, { "answer_id": 66261584, "author": "t0b4cc0", "author_id": 5196012, "author_profile": "https://Stackoverflow.com/users/5196012", "pm_score": -1, "selected": false, "text": "<p>I want to add my newest findings to this thread I came back to so often.</p>\n<p>My current visual studio / project setup provides the functionallity to automatically refactors tuples to structs. This will generate a GetHashCode function like so:</p>\n<pre><code> public override int GetHashCode()\n {\n int hashCode = -2088324004;\n hashCode = hashCode * -1521134295 + AuftragGesperrt.GetHashCode();\n hashCode = hashCode * -1521134295 + Auftrag_gesperrt_von.GetHashCode();\n hashCode = hashCode * -1521134295 + Auftrag_gesperrt_am.GetHashCode();\n return hashCode;\n }\n</code></pre>\n<p>EDIT: to clarify AuftragGesperrt, Auftrag_gesperrt_von and Auftrag_gesperrt_am are properties. If the microsoft devs use this function its probably not too bad of a solution.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4227/" ]
In .NET, the [`GetHashCode` method](https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode) is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when determining equality. Is there a standard algorithm or best practice on how to implement `GetHashCode` for my custom classes so I don't degrade performance?
I usually go with something like the implementation given in Josh Bloch's *fabulous* [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683). It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do: ``` public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = 17; // Suitable nullity checks etc, of course :) hash = hash * 23 + field1.GetHashCode(); hash = hash * 23 + field2.GetHashCode(); hash = hash * 23 + field3.GetHashCode(); return hash; } } ``` As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-[FNV](https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function) example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant *is* prime though. I don't know quite how important that is.) This is better than the common practice of `XOR`ing hashcodes for two main reasons. Suppose we have a type with two `int` fields: ``` XorHash(x, x) == XorHash(y, y) == 0 for all x, y XorHash(x, y) == XorHash(y, x) for all x, y ``` By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types. [This page](http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx) gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The [FNV](http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx#fnv) alternative is similarly simple, but uses different constants and `XOR` instead of `ADD` as a combining operation. It looks *something* like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above. ``` // Note: Not quite FNV! public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = (int) 2166136261; // Suitable nullity checks etc, of course :) hash = (hash * 16777619) ^ field1.GetHashCode(); hash = (hash * 16777619) ^ field2.GetHashCode(); hash = (hash * 16777619) ^ field3.GetHashCode(); return hash; } } ``` Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code. As per the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode#notes-to-inheritors): > > You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if: > > > * You can compute the hash code from fields that are not mutable; or > * You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code. > > > The link to the [FNV](http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx) article is broken but here is a copy in the Internet Archive: [Eternally Confuzzled - The Art of Hashing](https://archive.vn/KJeJy)
263,402
<p>Imagine the following REBOL code:</p> <pre>foo: context [bar: 3]</pre> <p>I now have a context <code>foo</code> in which <code>'bar</code> is defined. How can I dynamically inject a new word into this context? Is it possible?</p> <p>I've tried:</p> <pre>set/any in foo 'baz 3</pre> <p>But that doesn't work because the expression <code>in foo 'baz</code> fails because there is no word <code>'baz</code> defined in the <code>foo</code> context.</p> <p>I should add that I realize one way to do this is as follows:</p> <pre>foo-prototype: [bar: 3] foo: context foo-prototype foo: context head append foo-prototype [baz: 3]</pre> <p>But what if you don't have access to <code>foo</code>'s prototype block?</p>
[ { "answer_id": 430848, "author": "Peter W A Wood", "author_id": 53663, "author_profile": "https://Stackoverflow.com/users/53663", "pm_score": 4, "selected": true, "text": "<p>You can achieve the same by using the existing object as a prototype to create a new object. </p>\n\n<pre><code>&gt;&gt; foo: make object! [bar: 3]\n&gt;&gt; foo: make foo [baz: 3]\n&gt;&gt; probe foo\nmake object! [\n bar: 3\n baz: 3\n]\n</code></pre>\n" }, { "answer_id": 431609, "author": "Christian Ensel", "author_id": 53748, "author_profile": "https://Stackoverflow.com/users/53748", "pm_score": 2, "selected": false, "text": "<p>There are several ways to work around the fact that in REBOL/2 it's just not posssible to extend object contexts. </p>\n\n<p>Probably you can just use BLOCK!s instead of OBJECT!s:</p>\n\n<pre><code>&gt;&gt; blobject: [foo 1]\n== [foo 1]\n&gt;&gt; blobject/bar\n** Script Error: Invalid path value: bar\n** Near: blobject/bar\n&gt;&gt; append blobject [bar 2]\n== [foo 1 bar 2]\n&gt;&gt; blobject/bar: 3\n== 3\n</code></pre>\n\n<p>You can even make 'self working by just appending the object itself:</p>\n\n<pre><code>&gt;&gt; insert blobject reduce ['self blobject]\n== [[...] foo 1 bar 2]\n&gt;&gt; same? blobject blobject/self\n== true\n</code></pre>\n\n<p>But as you've asked for extending <em>OBJECT!s</em>, you may go for Peter W A Wood's solution to simply clone the object. Just keep in mind that with this approach the resulting clone really is a different thing than the original object. </p>\n\n<p>So, if some word has been set to hold the object prior to cloning/extending, after cloning the object that word will still hold the unextended object: </p>\n\n<pre><code>&gt;&gt; remember: object: make object! [foo: 1]\n&gt;&gt; object: make object [bar: 2]\n&gt;&gt; same? remember object\n== false\n&gt;&gt; probe remember\nmake object! [\n foo: 1\n]\n</code></pre>\n\n<p>In case it's essential for you to keep \"references\" to the object intact, you might want to wrap the object you need to extend in an outer object as in</p>\n\n<pre><code>&gt;&gt; remember: object: make object! [access: make object! [foo: 1]]\n&gt;&gt; object/access: make object/access [bar: 2]\n&gt;&gt; same? remember object\n== true\n</code></pre>\n\n<p>You can then safley extend the object while keeping, given you only store references to the container.</p>\n\n<p>REBOL/3, btw, will allow adding words to OBJECT!s.</p>\n" }, { "answer_id": 4212414, "author": "liumengjiang", "author_id": 248039, "author_profile": "https://Stackoverflow.com/users/248039", "pm_score": 1, "selected": false, "text": "<p>Said in REBOL/Core User Guide:\n\"Many blocks contain other blocks and strings. When such a block is copied, its \nsub-series are not copied. The sub-series are referred to directly and are the same \nseries data as the original block.\"</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27779/" ]
Imagine the following REBOL code: ``` foo: context [bar: 3] ``` I now have a context `foo` in which `'bar` is defined. How can I dynamically inject a new word into this context? Is it possible? I've tried: ``` set/any in foo 'baz 3 ``` But that doesn't work because the expression `in foo 'baz` fails because there is no word `'baz` defined in the `foo` context. I should add that I realize one way to do this is as follows: ``` foo-prototype: [bar: 3] foo: context foo-prototype foo: context head append foo-prototype [baz: 3] ``` But what if you don't have access to `foo`'s prototype block?
You can achieve the same by using the existing object as a prototype to create a new object. ``` >> foo: make object! [bar: 3] >> foo: make foo [baz: 3] >> probe foo make object! [ bar: 3 baz: 3 ] ```
263,404
<p>I have a unique development situation and would like some input from others.</p> <p>I have a situation where I need to load loose xaml files within a rich client application. A given loose xaml file may have references to an assembly not currently loaded in memory so the referenced assembly is loaded before the loading the loose xaml. The loose xaml and tied assemblies are stored on different backend servers which are downloaded to the client and loaded dynamically.</p> <p>The loose xaml and/or assemblies are version specific and unfortunately the application can not be shutdown between rendering xaml.<strong>v1</strong> with assembly.<strong>v1</strong> from server A and xaml.<strong>v1</strong> with assembly.<strong>v2</strong> on server B. Both assemblies use the same namespace declaration so "older" assemblies can still work with "newer" ones for any given loose xaml.</p> <p>The problem is, I do not get a reference to assembly.v2 if I load xaml.v2 which contains references to "newer" features in assembly.v2.</p> <p>I obviously cannot unload assembly.v1 from the app domain and I'm not sure if I can reference items in xaml that are loaded within a different app domain through marshalling.</p> <p>Any Ideas other than using different namespace references?</p>
[ { "answer_id": 520969, "author": "fubaar", "author_id": 59083, "author_profile": "https://Stackoverflow.com/users/59083", "pm_score": 1, "selected": false, "text": "<p>I'm guessing that you are already doing dynamic assembly resolution and loading? If so, then you could try substituting a fake assembly name in place of the real assembly name i n the Xaml - you can then use that in your assembly resolution code to load up and return the right assembly. e.g. if your original source Xaml is:</p>\n\n<pre><code>xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly\"\n</code></pre>\n\n<p>and you know that Xaml wants v2 of MyAssembly, replace the assembly ref in the Xaml string before parsing it to:</p>\n\n<pre><code>xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2\"\n</code></pre>\n\n<p>.. then in your assembly resolution / load code, when you see the \".v2\" bit on the end you look for and load that assembly instead.</p>\n\n<p>Please let me know if I've misunderstood the question, or you aren't current doing any custom assembly resolution - that would certainly be the key in this situation I think.</p>\n" }, { "answer_id": 872016, "author": "Greg Bacchus", "author_id": 48225, "author_profile": "https://Stackoverflow.com/users/48225", "pm_score": 0, "selected": false, "text": "<p>I haven't confirmed if this would work, but I believe that it may. You could use the XmlnsDefinitionAttribute (at assembly level). E.g.</p>\n\n<p>Assembly V1 -> AssemblyInfo.cs</p>\n\n<pre><code>[assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v1\", \"MyCompany.MyProject\" )]\n</code></pre>\n\n<p>Assembly V2 -> AssemblyInfo.cs</p>\n\n<pre><code>[assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v2\", \"MyCompany.MyProject\" )]\n</code></pre>\n\n<p>And then in xaml:</p>\n\n<pre><code>xmlns:myassembly=\"http://schema.mycompany.com/myproject/v2\"\n</code></pre>\n" }, { "answer_id": 872185, "author": "Greg Bacchus", "author_id": 48225, "author_profile": "https://Stackoverflow.com/users/48225", "pm_score": 1, "selected": false, "text": "<p>Another option (assuming that you are versioning your assemblies properly) is to simply include the assembly version in the ns declaration, like so:</p>\n\n<pre><code>xmlns:ns0=\"clr-namespace:MyCompany.MyProject.MyNameSpace; Assembly=MyCompany.MyProject, Version=1.0.0.0\"\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34413/" ]
I have a unique development situation and would like some input from others. I have a situation where I need to load loose xaml files within a rich client application. A given loose xaml file may have references to an assembly not currently loaded in memory so the referenced assembly is loaded before the loading the loose xaml. The loose xaml and tied assemblies are stored on different backend servers which are downloaded to the client and loaded dynamically. The loose xaml and/or assemblies are version specific and unfortunately the application can not be shutdown between rendering xaml.**v1** with assembly.**v1** from server A and xaml.**v1** with assembly.**v2** on server B. Both assemblies use the same namespace declaration so "older" assemblies can still work with "newer" ones for any given loose xaml. The problem is, I do not get a reference to assembly.v2 if I load xaml.v2 which contains references to "newer" features in assembly.v2. I obviously cannot unload assembly.v1 from the app domain and I'm not sure if I can reference items in xaml that are loaded within a different app domain through marshalling. Any Ideas other than using different namespace references?
I'm guessing that you are already doing dynamic assembly resolution and loading? If so, then you could try substituting a fake assembly name in place of the real assembly name i n the Xaml - you can then use that in your assembly resolution code to load up and return the right assembly. e.g. if your original source Xaml is: ``` xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly" ``` and you know that Xaml wants v2 of MyAssembly, replace the assembly ref in the Xaml string before parsing it to: ``` xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2" ``` .. then in your assembly resolution / load code, when you see the ".v2" bit on the end you look for and load that assembly instead. Please let me know if I've misunderstood the question, or you aren't current doing any custom assembly resolution - that would certainly be the key in this situation I think.
263,406
<p>I have a Java server that accepts SSL connections using JSSE and uses a simple XML message format inside the stream. I would like the server to read a complete message and then send a reply. This turns out to be quite difficult because org.xml.sax.XMLReader wants to read the entire stream and then call close(). I know it seems strange, but in Java 6 with the Sun JSSE provider this really does close both ends of the SSLSocket so no message can go back. I tried using the shutdownOutput() method of Socket on the client side, but this is unsupported with JSSE.</p> <p>My solution was to pass an InputStream wrapped in a custom class that silently ignores close requests and indicates that the stream is closed when it encounters the first blank line. This constrains the XML beyond what is normally valid, but the client can easily filter out blank lines in the input if necessary. Is there a better solution?</p>
[ { "answer_id": 520969, "author": "fubaar", "author_id": 59083, "author_profile": "https://Stackoverflow.com/users/59083", "pm_score": 1, "selected": false, "text": "<p>I'm guessing that you are already doing dynamic assembly resolution and loading? If so, then you could try substituting a fake assembly name in place of the real assembly name i n the Xaml - you can then use that in your assembly resolution code to load up and return the right assembly. e.g. if your original source Xaml is:</p>\n\n<pre><code>xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly\"\n</code></pre>\n\n<p>and you know that Xaml wants v2 of MyAssembly, replace the assembly ref in the Xaml string before parsing it to:</p>\n\n<pre><code>xmlns:myassembly=\"clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2\"\n</code></pre>\n\n<p>.. then in your assembly resolution / load code, when you see the \".v2\" bit on the end you look for and load that assembly instead.</p>\n\n<p>Please let me know if I've misunderstood the question, or you aren't current doing any custom assembly resolution - that would certainly be the key in this situation I think.</p>\n" }, { "answer_id": 872016, "author": "Greg Bacchus", "author_id": 48225, "author_profile": "https://Stackoverflow.com/users/48225", "pm_score": 0, "selected": false, "text": "<p>I haven't confirmed if this would work, but I believe that it may. You could use the XmlnsDefinitionAttribute (at assembly level). E.g.</p>\n\n<p>Assembly V1 -> AssemblyInfo.cs</p>\n\n<pre><code>[assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v1\", \"MyCompany.MyProject\" )]\n</code></pre>\n\n<p>Assembly V2 -> AssemblyInfo.cs</p>\n\n<pre><code>[assembly: XmlnsDefinition( \"http://schema.mycompany.com/myproject/v2\", \"MyCompany.MyProject\" )]\n</code></pre>\n\n<p>And then in xaml:</p>\n\n<pre><code>xmlns:myassembly=\"http://schema.mycompany.com/myproject/v2\"\n</code></pre>\n" }, { "answer_id": 872185, "author": "Greg Bacchus", "author_id": 48225, "author_profile": "https://Stackoverflow.com/users/48225", "pm_score": 1, "selected": false, "text": "<p>Another option (assuming that you are versioning your assemblies properly) is to simply include the assembly version in the ns declaration, like so:</p>\n\n<pre><code>xmlns:ns0=\"clr-namespace:MyCompany.MyProject.MyNameSpace; Assembly=MyCompany.MyProject, Version=1.0.0.0\"\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34416/" ]
I have a Java server that accepts SSL connections using JSSE and uses a simple XML message format inside the stream. I would like the server to read a complete message and then send a reply. This turns out to be quite difficult because org.xml.sax.XMLReader wants to read the entire stream and then call close(). I know it seems strange, but in Java 6 with the Sun JSSE provider this really does close both ends of the SSLSocket so no message can go back. I tried using the shutdownOutput() method of Socket on the client side, but this is unsupported with JSSE. My solution was to pass an InputStream wrapped in a custom class that silently ignores close requests and indicates that the stream is closed when it encounters the first blank line. This constrains the XML beyond what is normally valid, but the client can easily filter out blank lines in the input if necessary. Is there a better solution?
I'm guessing that you are already doing dynamic assembly resolution and loading? If so, then you could try substituting a fake assembly name in place of the real assembly name i n the Xaml - you can then use that in your assembly resolution code to load up and return the right assembly. e.g. if your original source Xaml is: ``` xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly" ``` and you know that Xaml wants v2 of MyAssembly, replace the assembly ref in the Xaml string before parsing it to: ``` xmlns:myassembly="clr-namespace:MyApp.MyAssembly;assembly=MyAssembly.v2" ``` .. then in your assembly resolution / load code, when you see the ".v2" bit on the end you look for and load that assembly instead. Please let me know if I've misunderstood the question, or you aren't current doing any custom assembly resolution - that would certainly be the key in this situation I think.
263,419
<p>I'm planning to add XML support to application, but I'm not familiar with XML programming in Delphi. Basically I need to create objects based on XML nodes and generate XML file based on objects.</p> <p>Which XML component library I should use? Are there any good tutorials for XML with Delphi?</p>
[ { "answer_id": 263492, "author": "Steve", "author_id": 22712, "author_profile": "https://Stackoverflow.com/users/22712", "pm_score": 3, "selected": false, "text": "<p>You could try the following book :\n<a href=\"https://rads.stackoverflow.com/amzn/click/com/1591098629\" rel=\"noreferrer\" rel=\"nofollow noreferrer\" title=\"Delphi Developers Guide to XML\">Delphi Developers Guide to XML</a></p>\n\n<p>Basically I would recommend you use Microsoft's DOM. You'll need to import the library as with any other COM object.</p>\n" }, { "answer_id": 263521, "author": "DiGi", "author_id": 12042, "author_profile": "https://Stackoverflow.com/users/12042", "pm_score": 3, "selected": false, "text": "<p>You can use Delphi's <a href=\"http://www.drbob42.com/examine/examin23.htm\" rel=\"noreferrer\">XML Data Binding</a> (File - New - Other - XML Mapping (I don't know path exactly, I'm at home without Delphi)).</p>\n\n<p>It creates objects/interfaces over XML provider so you can work with objects/structures instead of plain xml text file.</p>\n\n<p>You don't have to make hard work by reading and writing each XML Element - you're just working with collections of objects and theirs properties.</p>\n" }, { "answer_id": 263522, "author": "Mattias Andersson", "author_id": 32841, "author_profile": "https://Stackoverflow.com/users/32841", "pm_score": 3, "selected": false, "text": "<p>Here are a couple of tutorials:</p>\n\n<ul>\n<li><a href=\"http://delphi.about.com/od/windowsshellapi/a/xml_delphi.htm\" rel=\"nofollow noreferrer\">Creating, Parsing and Manipulating XML Documents with Delphi</a></li>\n<li><a href=\"http://web.archive.org/web/20080608184001/http://homepages.borland.com/ccalvert/TechPapers/Delphi/XMLSimple/XMLSimple.html\" rel=\"nofollow noreferrer\">Basic XML Parsing in Delphi</a></li>\n</ul>\n\n<p>Additionally, you may want to look into the <a href=\"http://delphi.wikia.com/wiki/Category:XMLIntf_Unit\" rel=\"nofollow noreferrer\">XMLIntf unit</a> (although this linked Delphi Wikia page is very light on content).</p>\n" }, { "answer_id": 263533, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>You can start by looking at Delphi's TXMLDocument component. This will provide you with the basics of working with XML/DOM. It's simple and can be added by dropping it onto your Form. It has LoadFromFile and SaveToFile methods and is easily navigated.</p>\n\n<p>However, at some point you will exhaust TXMLDocument's features, especially if you want to work with things like XPath.</p>\n\n<p>I suggest you look at IXMLDOMDocument2 which is part of MSXML2_TLB, e.g.</p>\n\n<pre><code> XML := CreateOleObject('MSXML2.DOMDocument.3.0') as IXMLDOMDocument2;\n XML.async := false;\n XML.SetProperty('SelectionLanguage','XPath');\n</code></pre>\n\n<p>You will need to add msxmldom, xmldom, XMLIntf, XMLDoc &amp; MSXML2_TLB to your uses section.</p>\n\n<p>There are a few component libraries out there but I would suggest writing your own helper class or functions. Here's an example of one we wrote and use:</p>\n\n<pre><code>function XMLCreateRoot(var xml: IXMLDOMDocument2; RootName: string; xsl: string = ''; encoding: string = 'ISO-8859-1'; language: string = 'XPath'): IXMLDOMNode;\nvar\n NewPI: IXMLDOMProcessingInstruction;\nbegin\n\n if language&lt;&gt;'' then\n xml.SetProperty('SelectionLanguage','XPath');\n\n if encoding&lt;&gt;'' then begin\n NewPI:=xml.createProcessingInstruction('xml', 'version=\"1.0\" encoding=\"'+encoding+'\"');\n xml.appendChild(NewPI);\n end;\n\n if xsl&lt;&gt;'' then begin\n NewPI:=xml.createProcessingInstruction('xml-stylesheet','type=\"text/xsl\" href=\"'+xsl+'\"');\n xml.appendChild(NewPI)\n end;\n\n xml.async := false;\n xml.documentElement:=xml.createElement(RootName);\n Result:=xml.documentElement;\nend;\n</code></pre>\n\n<p>Take it from there.</p>\n" }, { "answer_id": 264619, "author": "davehay", "author_id": 34607, "author_profile": "https://Stackoverflow.com/users/34607", "pm_score": 4, "selected": false, "text": "<p>I use <a href=\"http://www.simdesign.nl/xml.html\" rel=\"nofollow noreferrer\">nativeXML</a> from simdesign. It takes all the pain out of working with XML you will be up and running in minutes.</p>\n" }, { "answer_id": 266192, "author": "jrodenhi", "author_id": 25315, "author_profile": "https://Stackoverflow.com/users/25315", "pm_score": 2, "selected": false, "text": "<p>I have been working with nativeXML for about a year now. My needs are fairly simple. XML fluency is a small part of a larger application for me, but I have been able to implement the pieces I need almost as fast as I can code them, the online help is good and my needs were met in a day rather than a week or longer. I second davehay's vote for nativeXML.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7735/" ]
I'm planning to add XML support to application, but I'm not familiar with XML programming in Delphi. Basically I need to create objects based on XML nodes and generate XML file based on objects. Which XML component library I should use? Are there any good tutorials for XML with Delphi?
You can start by looking at Delphi's TXMLDocument component. This will provide you with the basics of working with XML/DOM. It's simple and can be added by dropping it onto your Form. It has LoadFromFile and SaveToFile methods and is easily navigated. However, at some point you will exhaust TXMLDocument's features, especially if you want to work with things like XPath. I suggest you look at IXMLDOMDocument2 which is part of MSXML2\_TLB, e.g. ``` XML := CreateOleObject('MSXML2.DOMDocument.3.0') as IXMLDOMDocument2; XML.async := false; XML.SetProperty('SelectionLanguage','XPath'); ``` You will need to add msxmldom, xmldom, XMLIntf, XMLDoc & MSXML2\_TLB to your uses section. There are a few component libraries out there but I would suggest writing your own helper class or functions. Here's an example of one we wrote and use: ``` function XMLCreateRoot(var xml: IXMLDOMDocument2; RootName: string; xsl: string = ''; encoding: string = 'ISO-8859-1'; language: string = 'XPath'): IXMLDOMNode; var NewPI: IXMLDOMProcessingInstruction; begin if language<>'' then xml.SetProperty('SelectionLanguage','XPath'); if encoding<>'' then begin NewPI:=xml.createProcessingInstruction('xml', 'version="1.0" encoding="'+encoding+'"'); xml.appendChild(NewPI); end; if xsl<>'' then begin NewPI:=xml.createProcessingInstruction('xml-stylesheet','type="text/xsl" href="'+xsl+'"'); xml.appendChild(NewPI) end; xml.async := false; xml.documentElement:=xml.createElement(RootName); Result:=xml.documentElement; end; ``` Take it from there.
263,457
<p>I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators.</p> <p>Example - I have the following list:</p> <pre><code>array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] </code></pre> <p>I want to have</p> <pre><code>result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] </code></pre> <p>So far what I've come up with is:</p> <pre><code>def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result </code></pre> <p>But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?</p>
[ { "answer_id": 263465, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 7, "selected": true, "text": "<pre><code>[sum(a) for a in zip(*array)]\n</code></pre>\n" }, { "answer_id": 263523, "author": "Charles Merriam", "author_id": 1320510, "author_profile": "https://Stackoverflow.com/users/1320510", "pm_score": 6, "selected": false, "text": "<p>[sum(value) for value in zip(*array)] is pretty standard.</p>\n\n<p>This might help you understand it:</p>\n\n<pre><code>In [1]: array=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\nIn [2]: array\nOut[2]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\nIn [3]: *array\n------------------------------------------------------------\n File \"&lt;ipython console&gt;\", line 1\n *array\n ^\n&lt;type 'exceptions.SyntaxError'&gt;: invalid syntax\n</code></pre>\n\n<p><em>The unary star is not an operator by itself. It unwraps array elements into arguments into function calls.</em></p>\n\n<pre><code>In [4]: zip(*array)\nOut[4]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]\n</code></pre>\n\n<p><em>zip() is a built-in function</em></p>\n\n<pre><code>In [5]: zip(*array)[0]\nOut[5]: (1, 4, 7)\n</code></pre>\n\n<p><em>each element for the list returned by zip is a set of numbers you want.</em></p>\n\n<pre><code>In [6]: sum(zip(*array)[0])\nOut[6]: 12\n\nIn [7]: [sum(values) for values in zip(*array)]\nOut[7]: [12, 15, 18]\n</code></pre>\n" }, { "answer_id": 265472, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 3, "selected": false, "text": "<p>If you're doing a lot of this kind of thing, you want to learn about <a href=\"http://scipy.org/\" rel=\"noreferrer\"><code>scipy</code>.</a></p>\n\n<pre><code>&gt;&gt;&gt; import scipy\n&gt;&gt;&gt; sum(scipy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))\narray([12, 15, 18])\n</code></pre>\n\n<p>All array sizes are checked for you automatically. The sum is done in pure C, so it's very fast. <code>scipy</code> arrays are also very memory efficient.</p>\n\n<p>The drawback is you're dependent on a fairly complex third-party module. But that's a very good tradeoff for many purposes.</p>\n" }, { "answer_id": 265495, "author": "ngn", "author_id": 23109, "author_profile": "https://Stackoverflow.com/users/23109", "pm_score": 4, "selected": false, "text": "<p>An alternative way:</p>\n\n<pre><code>map(sum, zip(*array))\n</code></pre>\n" }, { "answer_id": 5113719, "author": "heltonbiker", "author_id": 401828, "author_profile": "https://Stackoverflow.com/users/401828", "pm_score": 2, "selected": false, "text": "<p>Agree with fivebells, but you could also use Numpy, which is a smaller (quicker import) and more generic implementation of array-like stuff. (actually, it is a dependency of scipy). These are great tools which, as have been said, are a 'must use' if you deal with this kind of manipulations.</p>\n" }, { "answer_id": 13240341, "author": "mgilson", "author_id": 748858, "author_profile": "https://Stackoverflow.com/users/748858", "pm_score": 2, "selected": false, "text": "<p>Late to the game, and it's not as good of an answer as some of the others, but I thought it was kind of cute:</p>\n\n<pre><code>map(lambda *x:sum(x),*array)\n</code></pre>\n\n<p>it's too bad that <code>sum(1,2,3)</code> doesn't work. If it did, we could eliminate the silly <code>lambda</code> in there, but I suppose that would make it difficult to discern which (if any) of the elements is the \"start\" of the sum. You'd have to change that to a keyword only arguement which would break a lot of scripts ... Oh well. I guess we'll just live with <code>lambda</code>.</p>\n" }, { "answer_id": 29433541, "author": "F1Rumors", "author_id": 1636289, "author_profile": "https://Stackoverflow.com/users/1636289", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>[sum(a) for a in zip(*array)]</p>\n</blockquote>\n\n<p>I like that. I needed something related for interleaving objects in to a list of items, came up with something similar but more concise for even length lists:</p>\n\n<pre><code>sum(zip(*array),())\n</code></pre>\n\n<p>for example, interleaving two lists:</p>\n\n<pre><code>a = [1,2,3]\nb = ['a','b','c']\nsum(zip(a,b),())\n(1, 'a', 2, 'b', 3, 'c')\n</code></pre>\n" }, { "answer_id": 29439639, "author": "Saksham Varma", "author_id": 4596008, "author_profile": "https://Stackoverflow.com/users/4596008", "pm_score": 0, "selected": false, "text": "<p>You can simply do this:</p>\n\n<pre><code>print [sum(x) for x in zip(*array)]\n</code></pre>\n\n<p>If you wish to iterate through lists in this fashion, you can use <code>chain</code> of the <code>itertools</code> module:</p>\n\n<pre><code>from itertools import chain\n\nfor x in array.chain.from_iterable(zip(*array)):\n print x \n# prints 1, 4, 7, 2, 5, 8, ...\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20670/" ]
I'm pretty sure there should be a more Pythonic way of doing this - but I can't think of one: How can I merge a two-dimensional list into a one-dimensional list? Sort of like zip/map but with more than two iterators. Example - I have the following list: ``` array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` I want to have ``` result = [12, 15, 18] # [1+4+7, 2+5+8, 3+6+9] ``` So far what I've come up with is: ``` def add_list(array): number_items = len(array[0]) result = [0] * number_items for index in range(number_items): for line in array: result[index] += line[index] return result ``` But that doesn't look very elegant/Pythonic to me. Aside from not checking if all the "lines" in the 2D array are of the same length, can be added to each other, etc. What would be a better way to do it?
``` [sum(a) for a in zip(*array)] ```
263,469
<p>I have a C# .NET web project that I'm currently working on. What I'm trying to do is read some files that I dropped into a dir which is at the same level as fileReader.cs which is attempting to read them. On a normal desktop app the following would work:</p> <pre><code>DirectoryInfo di = new DirectoryInfo(./myDir); </code></pre> <p>However because it's a web project the execution context is different, and I don't know how to access these files?</p> <p>Eventually fileReader will be called in an installation routine. I intend to override one of the Installer.cs' abstract methods so will this affect the execution context?</p>
[ { "answer_id": 263474, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://msdn.microsoft.com/library/ms178116.aspx\" rel=\"nofollow noreferrer\"><code>Server.MapPath</code></a> to get the local path for the currently executing page.</p>\n" }, { "answer_id": 263480, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "<p>Use the Server.MapPath method whichs maps the specified relative or virtual path to the corresponding physical directory on the server.</p>\n\n<pre><code>Server.MapPath(\"mydir/file.some\")\n</code></pre>\n\n<p>This returns: <em>C:\\site\\scripts\\mydir\\file.some</em></p>\n\n<p>Script also can call the MapPath with full virtual path:</p>\n\n<pre><code>Server.MapPath(\"/scripts/mydir/file.some\")\n</code></pre>\n\n<p>Here is the <a href=\"http://msdn.microsoft.com/en-us/library/0e7ykf56.aspx\" rel=\"nofollow noreferrer\">link to the MSDN documentation of MapPath</a>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16684/" ]
I have a C# .NET web project that I'm currently working on. What I'm trying to do is read some files that I dropped into a dir which is at the same level as fileReader.cs which is attempting to read them. On a normal desktop app the following would work: ``` DirectoryInfo di = new DirectoryInfo(./myDir); ``` However because it's a web project the execution context is different, and I don't know how to access these files? Eventually fileReader will be called in an installation routine. I intend to override one of the Installer.cs' abstract methods so will this affect the execution context?
Use [`Server.MapPath`](http://msdn.microsoft.com/library/ms178116.aspx) to get the local path for the currently executing page.
263,477
<p>I have a gridview like below:</p> <pre><code> &lt;asp:GridView DataKeyNames="TransactionID" AllowSorting="True" AllowPaging="True"ID="grvBrokerage" runat="server" AutoGenerateColumns="False" CssClass="datatable" Width="100%" &lt;Columns&gt; &lt;asp:BoundField DataField="BrkgAccountNameOutput" HeaderText="Account Name"/&gt; &lt;asp:BoundField DataField="TransactionAmount" HeaderText="Transaction Amount" SortExpression="TransactionAmount" /&gt; &lt;asp:BoundField DataField="TransType" HeaderText="Transaction Type" SortExpression="TransType"/&gt; &lt;asp:BoundField DataField="AccountBalance" HeaderText="Account Balance"/&gt; &lt;asp:BoundField DataField="CreateDt" HeaderText="Transaction Date" /&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>I have a page with a gridview and a objectdatasource control. AllowPaging and AllowSorting is enabled. Here is the method I use that gets the data and binds the objectdatasource to the grid:</p> <pre><code> protected void BindBrokerageDetails() { HomePage master = (HomePage)Page.Master; BrokerageAccount brokerageAccount = new BrokerageAccount(); brokerageAccount.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString()); ddlBrokerageDetails.DataSource = brokerageAccount.GetAll(); ddlBrokerageDetails.DataTextField = "Account Name"; ddlBrokerageDetails.DataValueField = "Account Name"; ddlBrokerageDetails.DataBind(); if (ddlBrokerageDetails.Items.Count &gt; 0) { BrokerageTransactions brokerageaccountdetails = new BrokerageTransactions(); DataSet ds = BrokerageAccount.GetBrkID2( new Guid(Membership .GetUser() .ProviderUserKey .ToString()), ddlBrokerageDetails .SelectedItem .Text .ToString()); foreach (DataRow dr in ds.Tables[0].Rows) { brokerageaccountdetails.BrokerageId = new Guid(dr["BrkrgId"].ToString()); } ddlBrokerageDetails.SelectedItem.Value = brokerageaccountdetails.BrokerageId.ToString(); grvBrokerage.DataSource = ObjectDataSource1; grvBrokerage.DataBind(); } } </code></pre> <p>I have a sorting event, but when I check the grvBrokerage.DataSource, it is null. I am curious as to why? Here is the code for that?</p> <pre><code> protected void grvBrokerage_Sorting(object sender, GridViewSortEventArgs e) { DataTable dt = grvBrokerage.DataSource as DataTable; if (dt != null) { DataView dv = new DataView(dt); dv.Sort = e.SortExpression + " " + e.SortDirection; grvBrokerage.DataSource = dv; grvBrokerage.DataBind(); } } </code></pre> <p>Here is the ObjectDataSource declaration:</p> <pre><code>&lt;asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetAllWithId" TypeName="BrokerageTransactions"&gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter ControlID="ddlBrokerageDetails" Name="brokid" PropertyName="SelectedValue" Type="Object" /&gt; &lt;/SelectParameters&gt; &lt;/asp:ObjectDataSource&gt; </code></pre> <p>Thanks, X</p>
[ { "answer_id": 263797, "author": "Eddie Deyo", "author_id": 9323, "author_profile": "https://Stackoverflow.com/users/9323", "pm_score": 4, "selected": true, "text": "<p>When you are using an ObjectDataSource (or any other *DataSource), you set the DataSourceID for your GridView, not the DataSource. The DataSourceID should be whatever the ID of your ObjectDataSource is. If you provide the declaration of your ObjectDataSource, I might be able to help more.</p>\n\n<p>As to why your DataSource is null in your Sorting event, it's because you set the DataSource, sent the page to the client, clicked on a column header, posted back to the server, and now have a brand new GridView instance that has never had its DataSource property set. The old GridView instance (and the data table you bound to) have been thrown away.</p>\n" }, { "answer_id": 263805, "author": "AndyG", "author_id": 27678, "author_profile": "https://Stackoverflow.com/users/27678", "pm_score": 2, "selected": false, "text": "<p>Your datasource no longer exists when you're posting back.</p>\n\n<p>Try creating your datasources in your Page_Init function, then hooking your gridview up to it. Has always worked for me (Using SQLDataSources).</p>\n\n<p>EDIT: Alternatively, you could re-create your datasource for the grid on each postback. That might work.</p>\n\n<p>EDIT2: Or, you could save your DataSource to the ViewState (If it's not that large), then reset the grid to whatever datasource is in the viewstate on postback (again, I stress that the dataset not be magnificently large or else you'll have slow load times)</p>\n" }, { "answer_id": 290767, "author": "Scott Ivey", "author_id": 36297, "author_profile": "https://Stackoverflow.com/users/36297", "pm_score": 2, "selected": false, "text": "<p>Along with the other 2 answers, another thing to keep in mind is that when using ObjectDataSource, you need to have a parameter on your method that will do the sort. ObjectDataSources just pass a sort expression to your object as a string, and its up to your object to handle the sort on its own. In the ObjectDataSource, you set the SortParameterName to the value of the sort parameter name. See <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.sortparametername.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.sortparametername.aspx</a> for more information.</p>\n" }, { "answer_id": 635431, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<pre><code>Protected Sub gvRevstatus_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvRevstatus.Sorting\n Dim instance As GridView = gvRevstatus Dim cmd As String\n\n cmd = \"SELECT Status,CONVERT(VARCHAR(10),StatusDate,101) AS StatusDate,RevNo,CommentBY FROM tabStatus WHERE ID =\" &amp; CInt(lblId.Text.Trim) &amp; _\n \" Order by StatusDate\"\n dim gvtab as datatable = BOClaim.GVBoundTab(cnstr, cmd, gvstatus) ' my own classto databind\n Dim dv As New DataView(gvtab)\n dv.Sort = e.SortExpression\n\n gvRevstatus.DataSource = dv\n gvRevstatus.DataBind()\nEnd Sub\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33690/" ]
I have a gridview like below: ``` <asp:GridView DataKeyNames="TransactionID" AllowSorting="True" AllowPaging="True"ID="grvBrokerage" runat="server" AutoGenerateColumns="False" CssClass="datatable" Width="100%" <Columns> <asp:BoundField DataField="BrkgAccountNameOutput" HeaderText="Account Name"/> <asp:BoundField DataField="TransactionAmount" HeaderText="Transaction Amount" SortExpression="TransactionAmount" /> <asp:BoundField DataField="TransType" HeaderText="Transaction Type" SortExpression="TransType"/> <asp:BoundField DataField="AccountBalance" HeaderText="Account Balance"/> <asp:BoundField DataField="CreateDt" HeaderText="Transaction Date" /> </Columns> </asp:GridView> ``` I have a page with a gridview and a objectdatasource control. AllowPaging and AllowSorting is enabled. Here is the method I use that gets the data and binds the objectdatasource to the grid: ``` protected void BindBrokerageDetails() { HomePage master = (HomePage)Page.Master; BrokerageAccount brokerageAccount = new BrokerageAccount(); brokerageAccount.UserID = new Guid(Membership.GetUser().ProviderUserKey.ToString()); ddlBrokerageDetails.DataSource = brokerageAccount.GetAll(); ddlBrokerageDetails.DataTextField = "Account Name"; ddlBrokerageDetails.DataValueField = "Account Name"; ddlBrokerageDetails.DataBind(); if (ddlBrokerageDetails.Items.Count > 0) { BrokerageTransactions brokerageaccountdetails = new BrokerageTransactions(); DataSet ds = BrokerageAccount.GetBrkID2( new Guid(Membership .GetUser() .ProviderUserKey .ToString()), ddlBrokerageDetails .SelectedItem .Text .ToString()); foreach (DataRow dr in ds.Tables[0].Rows) { brokerageaccountdetails.BrokerageId = new Guid(dr["BrkrgId"].ToString()); } ddlBrokerageDetails.SelectedItem.Value = brokerageaccountdetails.BrokerageId.ToString(); grvBrokerage.DataSource = ObjectDataSource1; grvBrokerage.DataBind(); } } ``` I have a sorting event, but when I check the grvBrokerage.DataSource, it is null. I am curious as to why? Here is the code for that? ``` protected void grvBrokerage_Sorting(object sender, GridViewSortEventArgs e) { DataTable dt = grvBrokerage.DataSource as DataTable; if (dt != null) { DataView dv = new DataView(dt); dv.Sort = e.SortExpression + " " + e.SortDirection; grvBrokerage.DataSource = dv; grvBrokerage.DataBind(); } } ``` Here is the ObjectDataSource declaration: ``` <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetAllWithId" TypeName="BrokerageTransactions"> <SelectParameters> <asp:ControlParameter ControlID="ddlBrokerageDetails" Name="brokid" PropertyName="SelectedValue" Type="Object" /> </SelectParameters> </asp:ObjectDataSource> ``` Thanks, X
When you are using an ObjectDataSource (or any other \*DataSource), you set the DataSourceID for your GridView, not the DataSource. The DataSourceID should be whatever the ID of your ObjectDataSource is. If you provide the declaration of your ObjectDataSource, I might be able to help more. As to why your DataSource is null in your Sorting event, it's because you set the DataSource, sent the page to the client, clicked on a column header, posted back to the server, and now have a brand new GridView instance that has never had its DataSource property set. The old GridView instance (and the data table you bound to) have been thrown away.
263,478
<p>Given a result set, how can I determin the actual names of the fields specified in the query (NOT their aliases).</p> <pre><code>$query = "SELECT first AS First_Name, last AS Last_Name FROM people"; $dbResult = mysql_query($query); $fieldCount = mysql_num_fields($dbResult); for ($i=0; $i&lt;$fieldCount; $i++) { // Set some values $fieldName = mysql_field_name($dbResult, $i); } </code></pre> <p>This example returns field names, but in this example it returns the alias "First_Name" instead of the actual field name "first".</p> <p>Is it possible to get the actual field name from such a query. Particularly if I am writing a function and have no idea what query will be thrown at it.</p>
[ { "answer_id": 263489, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 4, "selected": false, "text": "<p>If you are using MySQLi:</p>\n\n<p><a href=\"http://www.php.net/manual/en/mysqli-result.fetch-field.php\" rel=\"noreferrer\">http://www.php.net/manual/en/mysqli-result.fetch-field.php</a></p>\n\n<p>The field object has a \"orgname\" property.</p>\n\n<p>The \"classic\" MySQL equivalent function doesn't report back the original column names.</p>\n" }, { "answer_id": 263490, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "<p>I'm not 100% sure about this, but I would say: there is no way.</p>\n\n<p>The MySQL gives you back the result set, nothing more. It does not return the select statement nor any details about it.</p>\n\n<p>So you cannot get the original field names because the server will provide you the information you asked: alias names.</p>\n" }, { "answer_id": 263494, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "<p>Short answer: you don't.</p>\n\n<p>Long answer: Once the dataset is pulled by MySQL and sent back to PHP, the only information PHP now has is the columns, or aliases if you used them. There is no way to look at a result set and determine what the original column names were. You have to switch to another DB driver like mysqli to obtain this info.</p>\n" }, { "answer_id": 263669, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 1, "selected": false, "text": "<p>Your question doesn't make sense.\nWhat are you going to do if you get a derived column i.e.</p>\n\n<p>select column_a + column_b as order_total from orders;</p>\n\n<p>are you saying you want to know that the original query was column_a + column b ??</p>\n\n<p>if so, you probably need to write a query parser, or get one off the internet.</p>\n\n<p>I think the implementation of that is beyond the scope of your question though :)</p>\n" }, { "answer_id": 263846, "author": "TonyUser", "author_id": 22873, "author_profile": "https://Stackoverflow.com/users/22873", "pm_score": 0, "selected": false, "text": "<p>If you don't mind making a second query (and your using MySQL 5 or greater) you can ask <code>information_schema</code> for the names.\nCheck out <a href=\"http://dev.mysql.com/doc/refman/5.1/en/columns-table.html\" rel=\"nofollow noreferrer\">MySQL Reference</a> for the details:</p>\n\n<blockquote>\n <p>SHOW COLUMNS FROM tbl_name;</p>\n</blockquote>\n" }, { "answer_id": 263993, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 0, "selected": false, "text": "<p>if you have access to the string of the query you could try a regular expression to parse it.\nI'm no regex master but you could chop up the string by looking at the text between 'select' and 'from' then grabbing all the field names as either</p>\n\n<pre><code> field FieldAlias\n</code></pre>\n\n<p>or</p>\n\n<pre><code> field as FieldAlias\n</code></pre>\n" }, { "answer_id": 264135, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 0, "selected": false, "text": "<p>If you're trying to write some functionality to let you know what fields are being fetched for handling updates - the only way to do this correctly is for it to present an SQL-less interface to the code above and manage all SQL generation itself. This is called a data abstraction layer.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34418/" ]
Given a result set, how can I determin the actual names of the fields specified in the query (NOT their aliases). ``` $query = "SELECT first AS First_Name, last AS Last_Name FROM people"; $dbResult = mysql_query($query); $fieldCount = mysql_num_fields($dbResult); for ($i=0; $i<$fieldCount; $i++) { // Set some values $fieldName = mysql_field_name($dbResult, $i); } ``` This example returns field names, but in this example it returns the alias "First\_Name" instead of the actual field name "first". Is it possible to get the actual field name from such a query. Particularly if I am writing a function and have no idea what query will be thrown at it.
If you are using MySQLi: <http://www.php.net/manual/en/mysqli-result.fetch-field.php> The field object has a "orgname" property. The "classic" MySQL equivalent function doesn't report back the original column names.
263,486
<p>In a forms model, I used to get the current logged-in user by:</p> <pre><code>Page.CurrentUser </code></pre> <p>How do I get the current user inside a controller class in ASP.NET MVC?</p>
[ { "answer_id": 263502, "author": "Sean", "author_id": 29941, "author_profile": "https://Stackoverflow.com/users/29941", "pm_score": 4, "selected": false, "text": "<p>I use:</p>\n\n<pre><code>Membership.GetUser().UserName\n</code></pre>\n\n<p>I am not sure this will work in ASP.NET MVC, but it's worth a shot :)</p>\n" }, { "answer_id": 263508, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 6, "selected": false, "text": "<p>Try <code>HttpContext.Current.User</code>.</p>\n\n<blockquote>\n <p>Public Shared Property Current() As\n System.Web.HttpContext<br>\n Member of System.Web.HttpContext </p>\n \n <p>Summary:<br>\n Gets or sets the System.Web.HttpContext object for the current HTTP request. </p>\n \n <p>Return Values:<br>\n The System.Web.HttpContext for the current\n HTTP request</p>\n</blockquote>\n" }, { "answer_id": 263853, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 9, "selected": true, "text": "<p>If you need to get the user from within the controller, use the <code>User</code> property of Controller. If you need it from the view, I would populate what you specifically need in the <code>ViewData</code>, or you could just call User as I think it's a property of <code>ViewPage</code>.</p>\n" }, { "answer_id": 679924, "author": "jrb", "author_id": 82332, "author_profile": "https://Stackoverflow.com/users/82332", "pm_score": 4, "selected": false, "text": "<p>I realize this is really old, but I'm just getting started with ASP.NET MVC, so I thought I'd stick my two cents in:</p>\n\n<ul>\n<li><code>Request.IsAuthenticated</code> tells you if the user is authenticated.</li>\n<li><code>Page.User.Identity</code> gives you the identity of the logged-in user.</li>\n</ul>\n" }, { "answer_id": 916264, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>I found that <code>User</code> works, that is, <code>User.Identity.Name</code> or <code>User.IsInRole(\"Administrator\")</code>.</p>\n" }, { "answer_id": 3667881, "author": "tifoz", "author_id": 442425, "author_profile": "https://Stackoverflow.com/users/442425", "pm_score": 4, "selected": false, "text": "<p>getting logged in username: <code>System.Web.HttpContext.Current.User.Identity.Name</code></p>\n" }, { "answer_id": 5790729, "author": "Gediminas Bukauskas", "author_id": 683517, "author_profile": "https://Stackoverflow.com/users/683517", "pm_score": 2, "selected": false, "text": "<pre><code>IPrincipal currentUser = HttpContext.Current.User;\nbool writeEnable = currentUser.IsInRole(\"Administrator\") ||\n ...\n currentUser.IsInRole(\"Operator\");\n</code></pre>\n" }, { "answer_id": 7407144, "author": "Pieter", "author_id": 182739, "author_profile": "https://Stackoverflow.com/users/182739", "pm_score": 2, "selected": false, "text": "<p>For what it's worth, in ASP.NET MVC 3 you can just use User which returns the user for the current request.</p>\n" }, { "answer_id": 8080415, "author": "live-love", "author_id": 436341, "author_profile": "https://Stackoverflow.com/users/436341", "pm_score": 2, "selected": false, "text": "<p>If you are inside your login page, in LoginUser_LoggedIn event for instance, Current.User.Identity.Name will return an empty value, so you have to use yourLoginControlName.UserName property.</p>\n\n<pre><code>MembershipUser u = Membership.GetUser(LoginUser.UserName);\n</code></pre>\n" }, { "answer_id": 8110578, "author": "heriawan", "author_id": 1043990, "author_profile": "https://Stackoverflow.com/users/1043990", "pm_score": 3, "selected": false, "text": "<p>This page could be what you looking for:<br>\n<a href=\"https://stackoverflow.com/questions/4613992/using-page-user-identity-name-in-mvc3\">Using Page.User.Identity.Name in MVC3</a></p>\n\n<p>You just need <code>User.Identity.Name</code>.</p>\n" }, { "answer_id": 17254386, "author": "MattC", "author_id": 1118428, "author_profile": "https://Stackoverflow.com/users/1118428", "pm_score": 3, "selected": false, "text": "<p>In order to reference a user ID created using simple authentication built into ASP.NET MVC 4 in a controller for filtering purposes (which is helpful if you are using database first and Entity Framework 5 to generate code-first bindings and your tables are structured so that a foreign key to the userID is used), you can use</p>\n\n<pre><code>WebSecurity.CurrentUserId\n</code></pre>\n\n<p>once you add a using statement</p>\n\n<pre><code>using System.Web.Security;\n</code></pre>\n" }, { "answer_id": 18947973, "author": "radbyx", "author_id": 306028, "author_profile": "https://Stackoverflow.com/users/306028", "pm_score": 5, "selected": false, "text": "<p>You can get the name of the user in ASP.NET MVC4 like this:</p>\n\n<pre><code>System.Web.HttpContext.Current.User.Identity.Name\n</code></pre>\n" }, { "answer_id": 31020699, "author": "Ognyan Dimitrov", "author_id": 1042934, "author_profile": "https://Stackoverflow.com/users/1042934", "pm_score": 2, "selected": false, "text": "<pre><code>var ticket = FormsAuthentication.Decrypt(\n HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);\n\nif (ticket.Expired)\n{\n throw new InvalidOperationException(\"Ticket expired.\");\n}\n\nIPrincipal user = (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));\n</code></pre>\n" }, { "answer_id": 32056880, "author": "Clay Smith", "author_id": 947978, "author_profile": "https://Stackoverflow.com/users/947978", "pm_score": 3, "selected": false, "text": "<p>Use <code>System.Security.Principal.WindowsIdentity.GetCurrent().Name</code>.</p>\n\n<p>This will get the current logged-in Windows user.</p>\n" }, { "answer_id": 34951257, "author": "Beau D'Amore", "author_id": 1744254, "author_profile": "https://Stackoverflow.com/users/1744254", "pm_score": 2, "selected": false, "text": "<p>If you happen to be working in Active Directory on an intranet, here are some tips:</p>\n\n<p>(Windows Server 2012)</p>\n\n<p>Running anything that talks to AD on a web server requires a bunch of changes and patience. Since when running on a web server vs. local IIS/IIS Express it runs in the AppPool's identity so, you have to set it up to impersonate whoever hits the site.</p>\n\n<p>How to get the current logged-in user in an active directory when your ASP.NET MVC application is running on a web server inside the network:</p>\n\n<pre><code>// Find currently logged in user\nUserPrincipal adUser = null;\nusing (HostingEnvironment.Impersonate())\n{\n var userContext = System.Web.HttpContext.Current.User.Identity;\n PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings[\"AllowedDomain\"], null,\n ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);\n adUser = UserPrincipal.FindByIdentity(ctx, userContext.Name);\n}\n//Then work with 'adUser' from here...\n</code></pre>\n\n<p>You must wrap any calls having to do with 'active directory context' in the following so it's acting as the hosting environment to get the AD information:</p>\n\n<pre><code>using (HostingEnvironment.Impersonate()){ ... }\n</code></pre>\n\n<p>You must also have <code>impersonate</code> set to true in your web.config:</p>\n\n<pre><code>&lt;system.web&gt;\n &lt;identity impersonate=\"true\" /&gt;\n</code></pre>\n\n<p>You must have Windows authentication on in web.config:</p>\n\n<pre><code>&lt;authentication mode=\"Windows\" /&gt;\n</code></pre>\n" }, { "answer_id": 41614794, "author": "Gilberto B. Terra Jr.", "author_id": 1890549, "author_profile": "https://Stackoverflow.com/users/1890549", "pm_score": 3, "selected": false, "text": "<p>UserName with: </p>\n\n<pre><code>User.Identity.Name\n</code></pre>\n\n<p>But if you need to get just the ID, you can use:</p>\n\n<pre><code>using Microsoft.AspNet.Identity;\n</code></pre>\n\n<p>So, you can get directly the User ID:</p>\n\n<pre><code>User.Identity.GetUserId();\n</code></pre>\n" }, { "answer_id": 45673764, "author": "Rajeev Jayaswal", "author_id": 2155858, "author_profile": "https://Stackoverflow.com/users/2155858", "pm_score": 2, "selected": false, "text": "<p>You can use following code:</p>\n\n<pre><code>Request.LogonUserIdentity.Name;\n</code></pre>\n" }, { "answer_id": 46490789, "author": "Fereydoon Barikzehy", "author_id": 3569825, "author_profile": "https://Stackoverflow.com/users/3569825", "pm_score": 2, "selected": false, "text": "<p>In Asp.net Mvc Identity 2,You can get the current user name by:</p>\n\n<pre><code>var username = System.Web.HttpContext.Current.User.Identity.Name;\n</code></pre>\n" }, { "answer_id": 48412527, "author": "Raj Baral", "author_id": 6348730, "author_profile": "https://Stackoverflow.com/users/6348730", "pm_score": 3, "selected": false, "text": "<p>We can use following code to get the current logged in User in ASP.Net MVC:</p>\n\n<pre><code>var user= System.Web.HttpContext.Current.User.Identity.GetUserName();\n</code></pre>\n\n<p>Also </p>\n\n<pre><code>var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'\n\nEnvironment.UserName - Will Display format : 'Username'\n</code></pre>\n" }, { "answer_id": 55939966, "author": "Daniel King", "author_id": 3207739, "author_profile": "https://Stackoverflow.com/users/3207739", "pm_score": 1, "selected": false, "text": "<p>In the IIS Manager, under Authentication, disable:\n1) Anonymous Authentication\n2) Forms Authentication</p>\n\n<p>Then add the following to your controller, to handle testing versus server deployment:</p>\n\n<pre><code>string sUserName = null;\nstring url = Request.Url.ToString();\n\nif (url.Contains(\"localhost\"))\n sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;\nelse\n sUserName = User.Identity.Name;\n</code></pre>\n" }, { "answer_id": 64514714, "author": "Samif", "author_id": 13428645, "author_profile": "https://Stackoverflow.com/users/13428645", "pm_score": 1, "selected": false, "text": "<p>If any one still reading this then, to access in cshtml file I used in following way.</p>\n<pre><code>&lt;li&gt;Hello @User.Identity.Name&lt;/li&gt;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
In a forms model, I used to get the current logged-in user by: ``` Page.CurrentUser ``` How do I get the current user inside a controller class in ASP.NET MVC?
If you need to get the user from within the controller, use the `User` property of Controller. If you need it from the view, I would populate what you specifically need in the `ViewData`, or you could just call User as I think it's a property of `ViewPage`.
263,503
<p>I am using the following code to determine free space on a volume. The folder was provided using NSOpenPanel. The item selected was a mounted volume and the path returned is \Volumes\Name</p> <pre><code>NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder]; unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue]; </code></pre> <p>Is there a better method to determine the free space on a mounted volume using Cocoa?</p> <p>Update: This is in fact the best way to determine the free space on a volume. It appeared it wasn't working but that was due to the fact that folder was actually /Volumes rather than /Volume/VolumeName</p>
[ { "answer_id": 264486, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 1, "selected": false, "text": "<p>statfs is consistent with results from df. In theory NSFileSystemFreeSize comes from statfs, so your problem should not exist.</p>\n\n<p>You may want to run statfs as below as a replacement for NSFileSystemFreeSize:</p>\n\n<pre><code>#include &lt;sys/param.h&gt;\n#include &lt;sys/mount.h&gt;\n\nint main()\n{\n struct statfs buf;\n\n int retval = statfs(\"/Volumes/KINGSTON\", &amp;buf);\n\n printf(\"KINGSTON Retval: %d, fundamental file system block size %ld, total data blocks %d, total in 512 blocks: %ld\\n\",\n retval, buf.f_bsize, buf.f_blocks, (buf.f_bsize / 512) * buf.f_blocks); \n printf(\"Free 512 blocks: %ld\\n\", (buf.f_bsize / 512) * buf.f_bfree); \n exit(0);\n}\n</code></pre>\n" }, { "answer_id": 269161, "author": "AlanKley", "author_id": 8761, "author_profile": "https://Stackoverflow.com/users/8761", "pm_score": 2, "selected": false, "text": "<p>The code provided IS the best way in Cocoa to determine the free space on a volume.\nJust make sure that the path provided to [NSFileManagerObj fileSystemAttributesAtPath] includes the full path of the volume. I was deleting the last path component to assure that a folder rather than a file was passed in which resulted in /Volumes being used as the folder which does not give the right results.</p>\n\n<pre><code>NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder];\n\nunsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue]; \n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761/" ]
I am using the following code to determine free space on a volume. The folder was provided using NSOpenPanel. The item selected was a mounted volume and the path returned is \Volumes\Name ``` NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder]; unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue]; ``` Is there a better method to determine the free space on a mounted volume using Cocoa? Update: This is in fact the best way to determine the free space on a volume. It appeared it wasn't working but that was due to the fact that folder was actually /Volumes rather than /Volume/VolumeName
The code provided IS the best way in Cocoa to determine the free space on a volume. Just make sure that the path provided to [NSFileManagerObj fileSystemAttributesAtPath] includes the full path of the volume. I was deleting the last path component to assure that a folder rather than a file was passed in which resulted in /Volumes being used as the folder which does not give the right results. ``` NSDictionary* fileAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath:folder]; unsigned long long size = [[fileAttributes objectForKey:NSFileSystemFreeSize] longLongValue]; ```
263,507
<p>I'm trying to get the zoom controls to show up in a <code>mapview</code>, the following code almost works, but the zoom controls appear in the top left of the <code>mapview</code>, not the bottom center like I'm specifying via <code>setGravity()</code>. Can someone enlighten me as to what I'm missing?</p> <pre><code>zoomView = (LinearLayout) mapView.getZoomControls(); zoomView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); zoomView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); mapView.addView(zoomView); </code></pre> <p>These views/layouts are all constructed programmatically, there is no layout file to tweak.</p>
[ { "answer_id": 275145, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Reto - the problem with using FILL_PARENT is that the zoom control then \"steals\" all of the touch events; so that you can't pan the map while the zoom controls are visible. Do you know how to prevent this?</p>\n" }, { "answer_id": 280237, "author": "Reto Meier", "author_id": 822, "author_profile": "https://Stackoverflow.com/users/822", "pm_score": 4, "selected": false, "text": "<p>The trick here is to place another Layout container where you want to put the ZoomControls and then insert the ZoomControls into that.</p>\n\n<p>The real trick is to use the <code>RelativeLayout</code> rather than <code>LinearLayout</code> to position the elements, as shown in this sample <code>layout.xml</code>:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" \n android:layout_width=\"fill_parent\" \n android:layout_height=\"fill_parent\"&gt; \n &lt;com.google.android.maps.MapView\n android:id=\"@+id/myMapView\"\n android:layout_width=\"fill_parent\" \n android:layout_height=\"fill_parent\"\n android:enabled=\"true\"\n android:clickable=\"true\"\n android:apiKey=\"MY_MAP_API_KEY\"\n /&gt;\n &lt;LinearLayout android:id=\"@+id/layout_zoom\" \n android:layout_width=\"wrap_content\" \n android:layout_height=\"wrap_content\" \n android:layout_alignParentBottom=\"true\" \n android:layout_centerHorizontal=\"true\" \n /&gt; \n&lt;/RelativeLayout&gt; \n</code></pre>\n\n<p>The <em>layout_zoom</em> LinearLayout element is positioned in the bottom center of the screen, placing it over the middle/bottom of the <code>MapView</code>. </p>\n\n<p>Then within your Activity's <code>onCreate</code>, get a reference to the <em>layout_zoom</em> element and insert the ZoomControl into it, much like you've already done:</p>\n\n<pre><code>LinearLayout zoomLayout =(LinearLayout)findViewById(R.id.layout_zoom); \nView zoomView = myMapView.getZoomControls(); \nzoomLayout.addView(zoomView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); \nmyMapView.displayZoomControls(true);\n</code></pre>\n\n<p>The ZoomControls should now appear on a long click, without stealing the map touch events.</p>\n" }, { "answer_id": 325159, "author": "jasonhudgins", "author_id": 24590, "author_profile": "https://Stackoverflow.com/users/24590", "pm_score": 2, "selected": false, "text": "<p>Reto : thanks for your reply, but the idea was to do it <em>without</em> using XML layouts.</p>\n\n<p>I eventually worked out the problem. Because a MapView is a subclass of ViewGroup, you can easily add child views (like the zoom controls). All you need is a MapView.LayoutParams instance and you're good to go. I did something like this (puts zoom controls in the bottom center of the mapview).</p>\n\n<pre><code> // layout to insert zoomcontrols at the bottom center of a mapview\n MapView.LayoutParams params = MapView.LayoutParams(\n LayoutParams.WRAP_CONTENT,\n LayoutParams.WRAP_CONTENT,\n mapViewWidth / 2, mapViewHeight,\n MapView.LayoutParams.BOTTOM_CENTER);\n\n // add zoom controls\n mapView.addView(mapView.getZoomControls(), params);\n</code></pre>\n" }, { "answer_id": 471155, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Unfortunately I cant add a comment to Jason Hudgins approved solution from Nov 28 at 6:32 but I got a tiny error with his code:</p>\n\n<p>In this line:</p>\n\n<pre><code>MapView.LayoutParams params = MapView.LayoutParams(\n</code></pre>\n\n<p>The error Eclipse gave me was </p>\n\n<blockquote>\n <p>\"The method LayoutParams(int, int,\n int, int, int) is undefined for the\n type MapView\"</p>\n</blockquote>\n\n<p>instead, creating a new MapView.LayoutParams object fixed it, like this:</p>\n\n<pre><code>MapView.LayoutParams params = **new** MapView.LayoutParams(\n</code></pre>\n\n<p>It took me some time to find out, as I am a n00b :D</p>\n" }, { "answer_id": 594435, "author": "magegu", "author_id": 71828, "author_profile": "https://Stackoverflow.com/users/71828", "pm_score": 2, "selected": false, "text": "<p>from the <a href=\"http://groups.google.com/group/android-developers/browse_thread/thread/b4a12843cd33497b\" rel=\"nofollow noreferrer\">google groups thread</a> i found this:</p>\n\n<p>ZoomControls without XML:</p>\n\n<pre><code> public class MyMapActivity extends MapActivity { public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n RelativeLayout relativeLayout = new RelativeLayout(this);\n setContentView(relativeLayout);\n\n final MapView mapView = new MapView(this, DEBUG_MAP_API_KEY);\n RelativeLayout.LayoutParams mapViewLayoutParams = new\nRelativeLayout.LayoutParams\n(RelativeLayout.LayoutParams.FILL_PARENT,RelativeLayout.LayoutParams.FILL_PARENT );\n relativeLayout.addView(mapView, mapViewLayoutParams);\n\n RelativeLayout.LayoutParams zoomControlsLayoutParams = new\nRelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,\nRelativeLayout.LayoutParams.WRAP_CONTENT );\n zoomControlsLayoutParams.addRule\n(RelativeLayout.ALIGN_PARENT_BOTTOM);\n zoomControlsLayoutParams.addRule\n(RelativeLayout.CENTER_HORIZONTAL);\n\n relativeLayout.addView(mapView.getZoomControls(),\nzoomControlsLayoutParams);\n\n mapView.setClickable(true);\n mapView.setEnabled(true);\n\n } \n</code></pre>\n\n<p>was 100% working for me with SDK1.1</p>\n" }, { "answer_id": 2499889, "author": "jcrowson", "author_id": 296810, "author_profile": "https://Stackoverflow.com/users/296810", "pm_score": 5, "selected": false, "text": "<p>Add the following line to the <code>OnCreate()</code> method of your <code>MapView</code> Class:</p>\n\n<p><code>view.setBuiltInZoomControls(true);</code></p>\n" }, { "answer_id": 5985426, "author": "George", "author_id": 321984, "author_profile": "https://Stackoverflow.com/users/321984", "pm_score": 3, "selected": false, "text": "<p>The above didn't work for me, but this does (to place the control on the bottom right):</p>\n\n<pre><code>mapView.setBuiltInZoomControls(true);\nZoomButtonsController zbc = mapView.getZoomButtonsController();\nViewGroup container = zbc.getContainer();\nfor (int i = 0; i &lt; container.getChildCount(); i++) {\n View child = container.getChildAt(i);\n if (child instanceof ZoomControls) {\n FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) child.getLayoutParams();\n lp.gravity = Gravity.RIGHT | Gravity.BOTTOM;\n child.requestLayout();\n break;\n } \n}\n</code></pre>\n" }, { "answer_id": 52492336, "author": "Manoj Reddy", "author_id": 7135592, "author_profile": "https://Stackoverflow.com/users/7135592", "pm_score": 2, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>MapView map = (MapView)findViewById(R.id.mapview);\nmap.setBuiltInZoomControls(true);\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24590/" ]
I'm trying to get the zoom controls to show up in a `mapview`, the following code almost works, but the zoom controls appear in the top left of the `mapview`, not the bottom center like I'm specifying via `setGravity()`. Can someone enlighten me as to what I'm missing? ``` zoomView = (LinearLayout) mapView.getZoomControls(); zoomView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)); zoomView.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL); mapView.addView(zoomView); ``` These views/layouts are all constructed programmatically, there is no layout file to tweak.
Add the following line to the `OnCreate()` method of your `MapView` Class: `view.setBuiltInZoomControls(true);`
263,518
<p>Currently I have an application that receives an uploaded file from my web application. I now need to transfer that file to a file server which happens to be located on the same network (however this might not always be the case).</p> <p>I was attempting to use the webclient class in C# .NET.</p> <pre><code> string filePath = "C:\\test\\564.flv"; try { WebClient client = new WebClient(); NetworkCredential nc = new NetworkCredential(uName, password); Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv"); client.Credentials = nc; byte[] arrReturn = client.UploadFile(addy, filePath); Console.WriteLine(arrReturn.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); } </code></pre> <p>The machine located at 192.168.1.28 is a file server and has a share c:\Files. As of right now I am receiving an error of Login failed bad user name or password, but I can open explorer and type in that path login successfully. I can also login using remote desktop, so I know the user account works.</p> <p>Any ideas on this error? Is it possible to transfer a file directly like that? With the webclient class or maybe some other class?</p>
[ { "answer_id": 263525, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 5, "selected": true, "text": "<p>Just use </p>\n\n<pre><code>File.Copy(filepath, \"\\\\\\\\192.168.1.28\\\\Files\");\n</code></pre>\n\n<p>A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.</p>\n\n<p>The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.</p>\n\n<p>You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). <strong>If at all possible, use the server name!</strong></p>\n\n<p>If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as \"[domain_or_machine]\\[username]\"</p>\n\n<p>If you need to specify explicit credentials, you'll need to look into <a href=\"http://www.codeproject.com/KB/cs/cpimpersonation1.aspx\" rel=\"noreferrer\">coding an impersonation solution</a>.</p>\n" }, { "answer_id": 263532, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 1, "selected": false, "text": "<p>when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.</p>\n\n<p>When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).</p>\n" }, { "answer_id": 2938207, "author": "Erandika Sandaruwan", "author_id": 353936, "author_profile": "https://Stackoverflow.com/users/353936", "pm_score": 2, "selected": false, "text": "<pre><code>namespace FileUpload\n{\npublic partial class Form1 : Form\n{\n string fileName = \"\";\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n\n string path = \"\";\n OpenFileDialog fDialog = new OpenFileDialog();\n fDialog.Title = \"Attach customer proposal document\";\n fDialog.Filter = \"Doc Files|*.doc|Docx File|*.docx|PDF doc|*.pdf\";\n fDialog.InitialDirectory = @\"C:\\\";\n if (fDialog.ShowDialog() == DialogResult.OK)\n {\n fileName = System.IO.Path.GetFileName(fDialog.FileName);\n path = Path.GetDirectoryName(fDialog.FileName);\n textBox1.Text = path + \"\\\\\" + fileName;\n\n }\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n try\n {\n WebClient client = new WebClient();\n\n NetworkCredential nc = new NetworkCredential(\"erandika1986\", \"123\");\n\n Uri addy = new Uri(@\"\\\\192.168.2.4\\UploadDocs\\\"+fileName);\n\n client.Credentials = nc;\n byte[] arrReturn = client.UploadFile(addy, textBox1.Text);\n MessageBox.Show(arrReturn.ToString());\n\n }\n catch (Exception ex1)\n {\n MessageBox.Show(ex1.Message);\n }\n }\n}\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21664/" ]
Currently I have an application that receives an uploaded file from my web application. I now need to transfer that file to a file server which happens to be located on the same network (however this might not always be the case). I was attempting to use the webclient class in C# .NET. ``` string filePath = "C:\\test\\564.flv"; try { WebClient client = new WebClient(); NetworkCredential nc = new NetworkCredential(uName, password); Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv"); client.Credentials = nc; byte[] arrReturn = client.UploadFile(addy, filePath); Console.WriteLine(arrReturn.ToString()); } catch (Exception ex) { Console.WriteLine(ex.Message); } ``` The machine located at 192.168.1.28 is a file server and has a share c:\Files. As of right now I am receiving an error of Login failed bad user name or password, but I can open explorer and type in that path login successfully. I can also login using remote desktop, so I know the user account works. Any ideas on this error? Is it possible to transfer a file directly like that? With the webclient class or maybe some other class?
Just use ``` File.Copy(filepath, "\\\\192.168.1.28\\Files"); ``` A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web. The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done. You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). **If at all possible, use the server name!** If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain\_or\_machine]\[username]" If you need to specify explicit credentials, you'll need to look into [coding an impersonation solution](http://www.codeproject.com/KB/cs/cpimpersonation1.aspx).
263,550
<p>I'm sorry I could not think of a better title.</p> <p>The problem is the following:</p> <p>For our customer we have created (as part of a larger application) a graphical designer which they can use to build "scenario's".</p> <p>These scenario's consist of "Composites" which in turn consist of "Commands". These command objects all derive from CommandBase and implement an interface called ICompilable.</p> <p>The scenario class also implements ICompilable. When Compile() is called on a command an array of bytes is returned which can then be send to the device for which they are intended (can't disclose to much info about that hardware, sorry)</p> <p>Just to give you an idea:</p> <pre><code>var scenario = new Scenario(); scenario.Add(new DelayCommand(1)); scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new WaitCommand(3)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10)); scenario.Add(new JumpCommand(2)); byte[] compiledData = scenario.Compile(); </code></pre> <p>The graphical designer abstracts all this from the user and allows him (or her) to simply drag en drop composites onto the designer surface. (Composites can group commands so we can provide building blocks for returning tasks)</p> <p>Recently our customer came to us and said, "well the designer is really cool, but we have some people who would rather have some kind of programming language, just something simple."</p> <p>(Simple to them of course)</p> <p>I would very much like to provide them with a simple language, that can call various commmands and also replace SkipIfCommand with a nicer structure, etc...</p> <p>I have no idea where to start or what my options are (without breaking what we have)</p> <p>I have heard about people embedding languages such as Python, people writing their own language an parsers, etc...</p> <p>Any suggestions?</p> <p>PS: Users only work with composites, never with commands. Composites are loaded dynamically at runtime (along with their graphical designer) and may be provided by third parties in seperate assemblies.</p>
[ { "answer_id": 263583, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "<p>From what i think i've understood you have two options</p>\n\n<p>you could either use an XML style \"markup\" to let them define entities and their groupings, but that may not be best.</p>\n\n<p>Your alternatives are yes, yoou could embedd a language, but do you really need to, wouldnt that be overkill, and how can you control it?</p>\n\n<p>If you only need really simple syntax then perhaps write your own language. Its actually not that hard to create a simple interpreter, as long as you have a strict, unambiguous language. Have a look for some examples of compilers in whatever youre using, c#?</p>\n\n<p>I wrote a very simple interperter in java at uni, it wasnt as hard as you'd think.</p>\n" }, { "answer_id": 263664, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": 2, "selected": false, "text": "<p>This looks like a perfect scenario for a simple DSL. See <a href=\"http://msdn.microsoft.com/en-us/library/bb126235(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb126235(VS.80).aspx</a> for some information.</p>\n\n<p>You could also use a scripting language such as lua.Net. </p>\n" }, { "answer_id": 263675, "author": "Charles Merriam", "author_id": 1320510, "author_profile": "https://Stackoverflow.com/users/1320510", "pm_score": 3, "selected": true, "text": "<p>If you really just want a dirt simple language, you want a 'recursive descent parser'.</p>\n\n<p>For example, a language like this:</p>\n\n<pre><code>SCENARIO MyScenario\nDELAY 1\nCOUNT 1 ADD 1\nDIRECT_POWER 23, False, 150\nWAIT 3\n...\nEND_SCENARIO\n</code></pre>\n\n<p>You might have a grammar like:</p>\n\n<pre><code>scenario :: 'SCENARIO' label newline _cmds END_SCENARIO\ncmds:: _delay or _count or _direct_power or...\ndelay:: 'DELAY' number\n</code></pre>\n\n<p>Which gives code like:</p>\n\n<pre><code>def scenario():\n match_word('SCENARIO')\n scenario_name = match_label()\n emit('var scenario = new Scenario();')\n cmds()\n match_word('END_SCENARIO')\n emit('byte[] ' + scenario_name + ' = scenario.Compile();')\n\ndef delay():\n match_word('DELAY')\n length = match_number()\n emit('scenario.Add(new DelayCommand('+ length +'))')\n\ndef cmds():\n word = peek_next_word()\n if word == 'DELAY':\n delay()\n elif ...\n</code></pre>\n" }, { "answer_id": 263727, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>Here's a Pythonic solution for building a DSL that you can use to compile and create byte code arrays.</p>\n\n<ol>\n<li><p>Write a simple module that makes your C# structures available to Python. The goal is to define each C# class that users are allowed to work with (Composites or Commands or whatever) as a Python class.</p>\n\n<p>Usually, this involves implementing a minimal set of methods with different conversions from C# types to native Python types and vice versa.</p></li>\n<li><p>Write some nice demos showing how to use these Python class definitions to create their scripts. You should be able to create things like this in Python.</p>\n\n<pre><code>import * from someInterfaceModule\nscenario= Scenario(\n Delay(1),\n Repeat( Range(10),\n DirectPower( 23, False, 150),\n Wait(3),\n DirectPower( 23, False, 150)\n )\n)\nscenario.compile()\n</code></pre></li>\n</ol>\n\n<p>These are relatively simple classes to define. Each class here be reasonably easy to implement as Python modules that directly call your base C# modules.</p>\n\n<p>The syntax is pure Python with no additional parsing or lexical scanning required.</p>\n" }, { "answer_id": 263742, "author": "Chui Tey", "author_id": 34461, "author_profile": "https://Stackoverflow.com/users/34461", "pm_score": 1, "selected": false, "text": "<p>To add to S.Lott's comment, here's how you <a href=\"http://www.redmountainsw.com/wordpress/archives/embedding-ironpython-c-calling-python-script\" rel=\"nofollow noreferrer\">eval a Python script from C# </a></p>\n" }, { "answer_id": 263931, "author": "Huntrods", "author_id": 33977, "author_profile": "https://Stackoverflow.com/users/33977", "pm_score": 0, "selected": false, "text": "<p>While it might be great fun to create this mini-language and code it all up, the real questions you need to ask are:</p>\n\n<ol>\n<li>What is the business case for adding this feature / facility?</li>\n<li>Who is going to pay for this feature?</li>\n<li>Who is going to \"sign off\" on this feature if you build it?</li>\n</ol>\n\n<p>\"Really neat\" features have a way of getting built when the reality might indicate the true answer to such a request is \"no\".</p>\n\n<p>See if you have a stakeholder willing to sponsor this before proceeding. Then check with the end users to see what they really want before committing to the project.</p>\n\n<p>Cheers,</p>\n\n<p>-R</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
I'm sorry I could not think of a better title. The problem is the following: For our customer we have created (as part of a larger application) a graphical designer which they can use to build "scenario's". These scenario's consist of "Composites" which in turn consist of "Commands". These command objects all derive from CommandBase and implement an interface called ICompilable. The scenario class also implements ICompilable. When Compile() is called on a command an array of bytes is returned which can then be send to the device for which they are intended (can't disclose to much info about that hardware, sorry) Just to give you an idea: ``` var scenario = new Scenario(); scenario.Add(new DelayCommand(1)); scenario.Add(new CountWithValueCommand(1,ActionEnum.Add,1)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new WaitCommand(3)); scenario.Add(new DirectPowerCommand(23,false,150)); scenario.Add(new SkipIfCommand(1,OperatorEnum.SmallerThan,10)); scenario.Add(new JumpCommand(2)); byte[] compiledData = scenario.Compile(); ``` The graphical designer abstracts all this from the user and allows him (or her) to simply drag en drop composites onto the designer surface. (Composites can group commands so we can provide building blocks for returning tasks) Recently our customer came to us and said, "well the designer is really cool, but we have some people who would rather have some kind of programming language, just something simple." (Simple to them of course) I would very much like to provide them with a simple language, that can call various commmands and also replace SkipIfCommand with a nicer structure, etc... I have no idea where to start or what my options are (without breaking what we have) I have heard about people embedding languages such as Python, people writing their own language an parsers, etc... Any suggestions? PS: Users only work with composites, never with commands. Composites are loaded dynamically at runtime (along with their graphical designer) and may be provided by third parties in seperate assemblies.
If you really just want a dirt simple language, you want a 'recursive descent parser'. For example, a language like this: ``` SCENARIO MyScenario DELAY 1 COUNT 1 ADD 1 DIRECT_POWER 23, False, 150 WAIT 3 ... END_SCENARIO ``` You might have a grammar like: ``` scenario :: 'SCENARIO' label newline _cmds END_SCENARIO cmds:: _delay or _count or _direct_power or... delay:: 'DELAY' number ``` Which gives code like: ``` def scenario(): match_word('SCENARIO') scenario_name = match_label() emit('var scenario = new Scenario();') cmds() match_word('END_SCENARIO') emit('byte[] ' + scenario_name + ' = scenario.Compile();') def delay(): match_word('DELAY') length = match_number() emit('scenario.Add(new DelayCommand('+ length +'))') def cmds(): word = peek_next_word() if word == 'DELAY': delay() elif ... ```
263,551
<p>Does anyone know how to databind the .Source property of the WebBrowser in WPF ( 3.5SP1 )? I have a listview that I want to have a small WebBrowser on the left, and content on the right, and to databind the source of each WebBrowser with the URI in each object bound to the list item.</p> <p>This is what I have as a proof of concept so far, but the "<code>&lt;WebBrowser Source="{Binding Path=WebAddress}"</code>" does not compile.</p> <pre><code>&lt;DataTemplate x:Key="dealerLocatorLayout" DataType="DealerLocatorAddress"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;!--Web Control Here--&gt; &lt;WebBrowser Source="{Binding Path=WebAddress}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled" Width="300" Height="200" /&gt; &lt;StackPanel Orientation="Vertical"&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;Label Content="{Binding Path=CompanyName}" FontWeight="Bold" Foreground="Blue" /&gt; &lt;TextBox Text="{Binding Path=DisplayName}" FontWeight="Bold" /&gt; &lt;/StackPanel&gt; &lt;TextBox Text="{Binding Path=Street[0]}" /&gt; &lt;TextBox Text="{Binding Path=Street[1]}" /&gt; &lt;TextBox Text="{Binding Path=PhoneNumber}"/&gt; &lt;TextBox Text="{Binding Path=FaxNumber}"/&gt; &lt;TextBox Text="{Binding Path=Email}"/&gt; &lt;TextBox Text="{Binding Path=WebAddress}"/&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; </code></pre>
[ { "answer_id": 265648, "author": "Todd White", "author_id": 30833, "author_profile": "https://Stackoverflow.com/users/30833", "pm_score": 8, "selected": true, "text": "<p>The problem is that <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.webbrowser.source?view=netframework-4.8\" rel=\"noreferrer\"><code>WebBrowser.Source</code></a> is not a <code>DependencyProperty</code>. One workaround would be to use some <code>AttachedProperty</code> magic to enable this ability.</p>\n\n<pre><code>public static class WebBrowserUtility\n{\n public static readonly DependencyProperty BindableSourceProperty =\n DependencyProperty.RegisterAttached(\"BindableSource\", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));\n\n public static string GetBindableSource(DependencyObject obj)\n {\n return (string) obj.GetValue(BindableSourceProperty);\n }\n\n public static void SetBindableSource(DependencyObject obj, string value)\n {\n obj.SetValue(BindableSourceProperty, value);\n }\n\n public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n WebBrowser browser = o as WebBrowser;\n if (browser != null)\n {\n string uri = e.NewValue as string;\n browser.Source = !String.IsNullOrEmpty(uri) ? new Uri(uri) : null;\n }\n }\n\n}\n</code></pre>\n\n<p>Then in your xaml do:</p>\n\n<pre><code>&lt;WebBrowser ns:WebBrowserUtility.BindableSource=\"{Binding WebAddress}\"/&gt;\n</code></pre>\n" }, { "answer_id": 976289, "author": "RoelF", "author_id": 120480, "author_profile": "https://Stackoverflow.com/users/120480", "pm_score": 5, "selected": false, "text": "<p>I wrote a wrapper usercontrol, which makes use of the DependencyProperties:</p>\n\n<p>XAML:</p>\n\n<pre><code>&lt;UserControl x:Class=\"HtmlBox\"&gt;\n &lt;WebBrowser x:Name=\"browser\" /&gt;\n&lt;/UserControl&gt;\n</code></pre>\n\n<p>C#:</p>\n\n<pre><code>public static readonly DependencyProperty HtmlTextProperty = DependencyProperty.Register(\"HtmlText\", typeof(string), typeof(HtmlBox));\n\npublic string HtmlText {\n get { return (string)GetValue(HtmlTextProperty); }\n set { SetValue(HtmlTextProperty, value); }\n}\n\nprotected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {\n base.OnPropertyChanged(e);\n if (e.Property == HtmlTextProperty) {\n DoBrowse();\n }\n}\n private void DoBrowse() {\n if (!string.IsNullOrEmpty(HtmlText)) {\n browser.NavigateToString(HtmlText);\n }\n}\n</code></pre>\n\n<p>and use it like so:</p>\n\n<pre><code>&lt;Controls:HtmlBox HtmlText=\"{Binding MyHtml}\" /&gt;\n</code></pre>\n\n<p>The only trouble with this one is that the WebBrowser control is not \"pure\" wpf... it is actually just a wrapper for a win32 component. This means that the control won't respect the z-index, and will always overlay other element (eg: in a scrollviewer this might cause some trouble)\nmore info about these win32-wpf issues on <a href=\"http://msdn.microsoft.com/en-us/library/ms742522.aspx\" rel=\"noreferrer\">MSDN</a></p>\n" }, { "answer_id": 2791680, "author": "Olaf Japp", "author_id": 2607769, "author_profile": "https://Stackoverflow.com/users/2607769", "pm_score": 2, "selected": false, "text": "<p>Cool idea Todd.</p>\n\n<p>I have done similar with the RichTextBox.Selection.Text in Silverlight 4 now.\nThanks for your post. Works fine.</p>\n\n<pre><code>public class RichTextBoxHelper\n{\n public static readonly DependencyProperty BindableSelectionTextProperty =\n DependencyProperty.RegisterAttached(\"BindableSelectionText\", typeof(string), \n typeof(RichTextBoxHelper), new PropertyMetadata(null, BindableSelectionTextPropertyChanged));\n\n public static string GetBindableSelectionText(DependencyObject obj)\n {\n return (string)obj.GetValue(BindableSelectionTextProperty);\n }\n\n public static void SetBindableSelectionText(DependencyObject obj, string value)\n {\n obj.SetValue(BindableSelectionTextProperty, value);\n }\n\n public static void BindableSelectionTextPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n RichTextBox rtb = o as RichTextBox;\n if (rtb != null)\n {\n string text = e.NewValue as string;\n if (text != null)\n rtb.Selection.Text = text;\n }\n }\n} \n</code></pre>\n\n<p>Here is the Xaml-Code.</p>\n\n<pre><code>&lt;RichTextBox IsReadOnly='False' TextWrapping='Wrap' utilities:RichTextBoxHelper.BindableSelectionText=\"{Binding Content}\"/&gt;\n</code></pre>\n" }, { "answer_id": 6613466, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 5, "selected": false, "text": "<p>I've amended Todd's excellent answer a little to produce a version that copes with either strings or Uris from the Binding source:</p>\n\n<pre><code>public static class WebBrowserBehaviors\n{\n public static readonly DependencyProperty BindableSourceProperty =\n DependencyProperty.RegisterAttached(\"BindableSource\", typeof(object), typeof(WebBrowserBehaviors), new UIPropertyMetadata(null, BindableSourcePropertyChanged));\n\n public static object GetBindableSource(DependencyObject obj)\n {\n return (string)obj.GetValue(BindableSourceProperty);\n }\n\n public static void SetBindableSource(DependencyObject obj, object value)\n {\n obj.SetValue(BindableSourceProperty, value);\n }\n\n public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n WebBrowser browser = o as WebBrowser;\n if (browser == null) return;\n\n Uri uri = null;\n\n if (e.NewValue is string )\n {\n var uriString = e.NewValue as string;\n uri = string.IsNullOrWhiteSpace(uriString) ? null : new Uri(uriString);\n }\n else if (e.NewValue is Uri)\n {\n uri = e.NewValue as Uri;\n }\n\n browser.Source = uri;\n }\n</code></pre>\n" }, { "answer_id": 13408103, "author": "William", "author_id": 1828205, "author_profile": "https://Stackoverflow.com/users/1828205", "pm_score": -1, "selected": false, "text": "<p>You need to declare it at the first few lines of the <code>xaml</code> file which is pointing to the class file </p>\n\n<pre><code>xmlns:reportViewer=\"clr-namespace:CoMS.Modules.Report\" \n</code></pre>\n" }, { "answer_id": 37354907, "author": "ΩmegaMan", "author_id": 285795, "author_profile": "https://Stackoverflow.com/users/285795", "pm_score": 0, "selected": false, "text": "<p>This is a refinement to Todd's and Samuel's answer to take advantage of some basic logic premises as well as use the null coalescing operator..</p>\n\n<pre><code>public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)\n{\n WebBrowser browser = o as WebBrowser;\n\n if ((browser != null) &amp;&amp; (e.NewValue != null))\n browser.Source = e.NewValue as Uri ?? new Uri((string)e.NewValue);\n\n}\n</code></pre>\n\n<ol>\n<li>If the browser is null or the location is null, we cannot use or navigate to a null page.</li>\n<li>When the items in #1 are not null then when assigning, if the new value is a URI then use it. If not and the URI is null, then coalesce for it has to be a string which can be put into a URI; since #1 enforces that the string cannot be null.</li>\n</ol>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32772/" ]
Does anyone know how to databind the .Source property of the WebBrowser in WPF ( 3.5SP1 )? I have a listview that I want to have a small WebBrowser on the left, and content on the right, and to databind the source of each WebBrowser with the URI in each object bound to the list item. This is what I have as a proof of concept so far, but the "`<WebBrowser Source="{Binding Path=WebAddress}"`" does not compile. ``` <DataTemplate x:Key="dealerLocatorLayout" DataType="DealerLocatorAddress"> <StackPanel Orientation="Horizontal"> <!--Web Control Here--> <WebBrowser Source="{Binding Path=WebAddress}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled" Width="300" Height="200" /> <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <Label Content="{Binding Path=CompanyName}" FontWeight="Bold" Foreground="Blue" /> <TextBox Text="{Binding Path=DisplayName}" FontWeight="Bold" /> </StackPanel> <TextBox Text="{Binding Path=Street[0]}" /> <TextBox Text="{Binding Path=Street[1]}" /> <TextBox Text="{Binding Path=PhoneNumber}"/> <TextBox Text="{Binding Path=FaxNumber}"/> <TextBox Text="{Binding Path=Email}"/> <TextBox Text="{Binding Path=WebAddress}"/> </StackPanel> </StackPanel> </DataTemplate> ```
The problem is that [`WebBrowser.Source`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.controls.webbrowser.source?view=netframework-4.8) is not a `DependencyProperty`. One workaround would be to use some `AttachedProperty` magic to enable this ability. ``` public static class WebBrowserUtility { public static readonly DependencyProperty BindableSourceProperty = DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged)); public static string GetBindableSource(DependencyObject obj) { return (string) obj.GetValue(BindableSourceProperty); } public static void SetBindableSource(DependencyObject obj, string value) { obj.SetValue(BindableSourceProperty, value); } public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { WebBrowser browser = o as WebBrowser; if (browser != null) { string uri = e.NewValue as string; browser.Source = !String.IsNullOrEmpty(uri) ? new Uri(uri) : null; } } } ``` Then in your xaml do: ``` <WebBrowser ns:WebBrowserUtility.BindableSource="{Binding WebAddress}"/> ```
263,578
<p>I am using the ReportViewer control from Visual Studio 2008 in Local Mode with objects as the data source. My classes are mapped to data tables in my database. In the objects, it loads related objects as needed. So it leaves the reference null until you try to use the property, then it tries to load it from the database automatically. The classes use the System.Data.SqlClient namespace.</p> <p>When I interact with the objects in my Windows Forms application, everything works as expected. But when I pass the object to be used as a Report Data Source and it tries to automatically load the related object, it fails. The code creates a SqlConnection object and when I call GetCommand() on it, the following exception is thrown:</p> <pre><code>[System.Security.SecurityException] { "Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed." } System.Security.SecurityException </code></pre> <p>I've tried searching for the error, but all the results that show up are for CLR assemblies running on a SQL Server or ASP.Net. I've tried adding the following call in my code (as suggested in the search results) before creating the SqlConnection objects, but it didn't apparently do anything:</p> <pre><code>System.Data.SqlClient.SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert(); </code></pre> <p>Any ideas?</p>
[ { "answer_id": 265207, "author": "James Osborn", "author_id": 6686, "author_profile": "https://Stackoverflow.com/users/6686", "pm_score": 0, "selected": false, "text": "<p>One quick thought, although this isn't an error I've seen, make sure that your Assert is in the same method as the code that is setting the resource data source:</p>\n\n<pre><code>System.Data.SqlClient.SqlClientPermission mPermission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);\ntry\n{\n mPermission.Assert();\n //rest of your code\n}\n//Handle Exceptions\n</code></pre>\n\n<p>Permission Asserts don't hang around for long, they can be a security issue, so doing them as near as possible to the code that needs them is most likely to work.</p>\n" }, { "answer_id": 321678, "author": "CuppM", "author_id": 34440, "author_profile": "https://Stackoverflow.com/users/34440", "pm_score": 3, "selected": true, "text": "<p>I've found the solution. You specify System.Security.Policy.Evidence of you executing assembly (or one that has sufficient rights) to the LocalReport for use during execution.</p>\n\n<pre><code>reportViewer.LocalReport.ExecuteReportInCurrentAppDomain(System.Reflection.Assembly.GetExecutingAssembly().Evidence);\n</code></pre>\n" }, { "answer_id": 479796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Just in case someone stumbles upon this like I did while searching for this Permission-Error.\nI got this error using a <strong>Windows-Forms-Application</strong> because the customer had linked a shortcut to my Application-Exe on his machine with \"\\COMPUTERNAME\\C$\\Application.exe\" instead of \"C:\\Application.exe.\" - This caused the failure of the System.Security.Permission because of the untrusted intranet use.</p>\n\n<p>See <a href=\"http://www.duelec.de/blog/?p=236\" rel=\"nofollow noreferrer\">http://www.duelec.de/blog/?p=236</a> for more Information.</p>\n" }, { "answer_id": 6106005, "author": "Artem Koshelev", "author_id": 55209, "author_profile": "https://Stackoverflow.com/users/55209", "pm_score": 3, "selected": false, "text": "<p>In addition to the answer of CuppM.\nThe <code>ExecuteReportInCurrentAppDomain</code> method is deprecated since .NET4, and <code>LocalReport.SetBasePermissionsForSandboxAppDomain</code> should be used instead, as ReportViewer is now <em>always</em> executed in sandboxed domain:</p>\n\n<pre><code>PermissionSet permissions = new PermissionSet(PermissionState.None);\npermissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));\npermissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));\nReportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions);\n</code></pre>\n\n<p>See details <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.reporting.winforms.localreport.setbasepermissionsforsandboxappdomain.aspx\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 20885970, "author": "pseudocoder", "author_id": 724088, "author_profile": "https://Stackoverflow.com/users/724088", "pm_score": 1, "selected": false, "text": "<p>A footnote to Artem's answer above...</p>\n\n<p>I had this problem when adding Windows Authentication to my asp.net app. Targeting Framework 4.5 and using Reporting components 11. When I was allowing anonymous users (in early dev) I had no problems using the ReportViewer. As soon as I enabled Windows auth I would either get \"#Error\" on Grouping expressions, or not be able to run the report at all, giving the exception listed above.</p>\n\n<p>I was able to work around the problem but with a slightly modified version of what Artem posted. I am not completely sure what the code does other than a general sense that it allows CAS to trust the sandboxed ReportViewer code. Any comments with a little explanation would be appreciated.</p>\n\n<pre><code> Dim permissions As PermissionSet = New PermissionSet(PermissionState.Unrestricted)\n myReportViewer.LocalReport.SetBasePermissionsForSandboxAppDomain(permissions)\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34440/" ]
I am using the ReportViewer control from Visual Studio 2008 in Local Mode with objects as the data source. My classes are mapped to data tables in my database. In the objects, it loads related objects as needed. So it leaves the reference null until you try to use the property, then it tries to load it from the database automatically. The classes use the System.Data.SqlClient namespace. When I interact with the objects in my Windows Forms application, everything works as expected. But when I pass the object to be used as a Report Data Source and it tries to automatically load the related object, it fails. The code creates a SqlConnection object and when I call GetCommand() on it, the following exception is thrown: ``` [System.Security.SecurityException] { "Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed." } System.Security.SecurityException ``` I've tried searching for the error, but all the results that show up are for CLR assemblies running on a SQL Server or ASP.Net. I've tried adding the following call in my code (as suggested in the search results) before creating the SqlConnection objects, but it didn't apparently do anything: ``` System.Data.SqlClient.SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert(); ``` Any ideas?
I've found the solution. You specify System.Security.Policy.Evidence of you executing assembly (or one that has sufficient rights) to the LocalReport for use during execution. ``` reportViewer.LocalReport.ExecuteReportInCurrentAppDomain(System.Reflection.Assembly.GetExecutingAssembly().Evidence); ```
263,582
<p>In the following table structure:</p> <pre><code>Fruits ( fruit_id, fruitName ) Vegetables ( vegetable_id, vegetableName ) favoriteFoods ( food_id, foodName, type_id (References either a fruit or a vegetable) ) </code></pre> <p>I realize that I could forgo using a foreign key constraint on the favoriteFoods table and then simply add a type field to the favoriteFoods table to differentiate between fruits and vegetables. But how would you structure the tables so that you could actually create the necessary foreign key constraints? </p>
[ { "answer_id": 263593, "author": "wonderchook", "author_id": 32113, "author_profile": "https://Stackoverflow.com/users/32113", "pm_score": 3, "selected": true, "text": "<p>I would only use 2 tables instead. Instead of having a separate Fruits and Vegetables table, why not have a table of Foods. Then have a foreign key constraint on fkfood_id to food_id. Then if for some reason you ever have to add meat, it would be much easier to maintain the application that uses this.</p>\n\n<pre><code>Food\n (\n food_id,\n foodName,\n foodType\n )\n\nfavoriteFoods\n (\n favoritefood_id,\n fkfood_id\n )\n</code></pre>\n" }, { "answer_id": 265653, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 0, "selected": false, "text": "<p>It depends on what you are going to do with the data.</p>\n\n<p>If for some reason normalization is important to you, the following works quite well.</p>\n\n<pre><code>Fruits ( \n fruit_id,\n food_id references favoritefoods.food_id,\n fruitName)\nVegetables(\n vegetable_id,\n food_id references favoritefoods.food_id,\n vegetableName)\nfavoriteFoods (\n food_id,\n foodName)\n</code></pre>\n\n<p>The favoriteFoods table doesn't need to \"know\" what type of food it is, if any. Each fruit and each vegetable is bound to the corresponding favorite food.</p>\n\n<p>If you want to select all the fruits from favoriteFoods, just join the fruits table and the favoriteFoods table. You could even include a tomato as both a vegetable and a fruit, if that suits your fancy. </p>\n\n<p>The above is predicated on the assumption that joins are cheap. In many situations, joins really are cheap. Check it out before you alter your design to avoid joins. </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20178/" ]
In the following table structure: ``` Fruits ( fruit_id, fruitName ) Vegetables ( vegetable_id, vegetableName ) favoriteFoods ( food_id, foodName, type_id (References either a fruit or a vegetable) ) ``` I realize that I could forgo using a foreign key constraint on the favoriteFoods table and then simply add a type field to the favoriteFoods table to differentiate between fruits and vegetables. But how would you structure the tables so that you could actually create the necessary foreign key constraints?
I would only use 2 tables instead. Instead of having a separate Fruits and Vegetables table, why not have a table of Foods. Then have a foreign key constraint on fkfood\_id to food\_id. Then if for some reason you ever have to add meat, it would be much easier to maintain the application that uses this. ``` Food ( food_id, foodName, foodType ) favoriteFoods ( favoritefood_id, fkfood_id ) ```
263,585
<p>I have over the course of a few projects developed a pattern for creating immutable (readonly) objects and immutable object graphs. Immutable objects carry the benefit of being 100% thread safe and can therefore be reused across threads. In my work I very often use this pattern in Web applications for configuration settings and other objects that I load and cache in memory. Cached objects should always be immutable as you want to guarantee they are not unexpectedly changed.</p> <p>Now, you can of course easily design immutable objects as in the following example:</p> <pre><code>public class SampleElement { private Guid id; private string name; public SampleElement(Guid id, string name) { this.id = id; this.name = name; } public Guid Id { get { return id; } } public string Name { get { return name; } } } </code></pre> <p>This is fine for simple classes - but for more complex classes I do not fancy the concept of passing all values through a constructor. Having setters on the properties is more desirable and your code constructing a new object gets easier to read. </p> <p>So how do you create immutable objects with setters?</p> <p>Well, in my pattern objects start out as being fully mutable until you freeze them with a single method call. Once an object is frozen it will stay immutable forever - it cannot be turned into a mutable object again. If you need a mutable version of the object, you simply clone it.</p> <p>Ok, now on to some code. I have in the following code snippets tried to boil the pattern down to its simplest form. The IElement is the base interface that all immutable objects must ultimately implement. </p> <pre><code>public interface IElement : ICloneable { bool IsReadOnly { get; } void MakeReadOnly(); } </code></pre> <p>The Element class is the default implementation of the IElement interface:</p> <pre><code>public abstract class Element : IElement { private bool immutable; public bool IsReadOnly { get { return immutable; } } public virtual void MakeReadOnly() { immutable = true; } protected virtual void FailIfImmutable() { if (immutable) throw new ImmutableElementException(this); } ... } </code></pre> <p>Let's refactor the SampleElement class above to implement the immutable object pattern:</p> <pre><code>public class SampleElement : Element { private Guid id; private string name; public SampleElement() {} public Guid Id { get { return id; } set { FailIfImmutable(); id = value; } } public string Name { get { return name; } set { FailIfImmutable(); name = value; } } } </code></pre> <p>You can now change the Id property and the Name property as long as the object has not been marked as immutable by calling the MakeReadOnly() method. Once it is immutable, calling a setter will yield an ImmutableElementException.</p> <p>Final note: The full pattern is more complex than the code snippets shown here. It also contains support for collections of immutable objects and complete object graphs of immutable object graphs. The full pattern enables you to turn an entire object graph immutable by calling the MakeReadOnly() method on the outermost object. Once you start creating larger object models using this pattern the risk of leaky objects increases. A leaky object is an object that fails to call the FailIfImmutable() method before making a change to the object. To test for leaks I have also developed a generic leak detector class for use in unit tests. It uses reflection to test if all properties and methods throw the ImmutableElementException in the immutable state. In other words TDD is used here.</p> <p>I have grown to like this pattern a lot and find great benefits in it. So what I would like to know is if any of you are using similar patterns? If yes, do you know of any good resources that document it? I am essentially looking for potential improvements and for any standards that might already exist on this topic.</p>
[ { "answer_id": 263604, "author": "Cory Foy", "author_id": 4083, "author_profile": "https://Stackoverflow.com/users/4083", "pm_score": 3, "selected": false, "text": "<p>You are still dealing with state, and thus can still be bitten if your objects are parallelized before being made immutable. </p>\n\n<p>A more functional way might be to return a new instance of the object with each setter. Or create a mutable object and pass that in to the constructor. </p>\n" }, { "answer_id": 263613, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 2, "selected": false, "text": "<p>System.String is a good example of a immutable class with setters and mutating methods, only that each mutating method returns a new instance.</p>\n" }, { "answer_id": 263617, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "<p>I dont like the idea of being able to change an object from a mutable to an immutable state, that kind of seems to defeat the point of design to me. When are you needing to do that? Only objects which represent VALUES should be immutable</p>\n" }, { "answer_id": 263626, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>After my initial discomfort about the fact that I had to create a new <code>System.Drawing.Point</code> on each modification, I've wholly embraced the concept some years ago. In fact, I now create every field as <code>readonly</code> by default and only change it to be mutable if there's a compelling reason – which there is surprisingly rarely.</p>\n\n<p>I don't care very much about cross-threading issues, though (I rarely use code where this is relevant). I just find it much, much better because of the semantic expressiveness. Immutability is the very epitome of an interface which is hard to use incorrectly.</p>\n" }, { "answer_id": 263630, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 4, "selected": false, "text": "<p>Another option would be to create some kind of Builder class.</p>\n\n<p>For an example, in Java (and C# and many other languages) String is immutable. If you want to do multiple operations to create a String you use a StringBuilder. This is mutable, and then once you're done you have it return to you the final String object. From then on it's immutable.</p>\n\n<p>You could do something similar for your other classes. You have your immutable Element, and then an ElementBuilder. All the builder would do is store the options you set, then when you finalize it it constructs and returns the immutable Element.</p>\n\n<p>It's a little more code, but I think it's cleaner than having setters on a class that's supposed to be immutable.</p>\n" }, { "answer_id": 263715, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 3, "selected": false, "text": "<p>The (relatively) new Software Design paradigm called Domain Driven design, makes the distinction between entity objects and value objects. </p>\n\n<p>Entity Objects are defined as anything that has to map to a key-driven object in a persistent data store, like an employee, or a client, or an invoice, etc... where changing the properties of the object implies that you need to save the change to a data store somewhere, and the existence of multiple instances of a class with the same \"key\" imnplies a need to synchronize them, or coordinate their persistence to the data store so that one instance' changes do not overwrite the others. Changing the properties of an entity object implies you are changing something about the object - not changing WHICH object you are referencing... </p>\n\n<p>Value objects otoh, are objects that can be considered immutable, whose utility is defined strictly by their property values, and for which multiple instances, do not need to be coordinated in any way... like addresses, or telephone numbers, or the wheels on a car, or the letters in a document... these things are totally defined by their properties... an uppercase 'A' object in an text editor can be interchanged transparently with any other uppercase 'A' object throughout the document, you don't need a key to distinguish it from all the other 'A's In this sense it is immutable, because if you change it to a 'B' (just like changing the phone number string in a phone number object, you are not changing the data associated with some mutable entity, you are switching from one value to another... just as when you change the value of a string... </p>\n" }, { "answer_id": 263719, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "<p>For info, the second approach is called \"popsicle immutability\".</p>\n\n<p>Eric Lippert has a series of blog entries on immutability starting <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability\" rel=\"nofollow noreferrer\">here</a>. I'm still getting to grips with the CTP (C# 4.0), but it looks interesting what optional / named parameters (to the .ctor) might do here (when mapped to readonly fields)...\n[update: I've blogged on this <a href=\"https://blog.marcgravell.com/2008/11/immutability-and-optional-parameters.html\" rel=\"nofollow noreferrer\">here</a>]</p>\n\n<p>For info, I probably wouldn't make those methods <code>virtual</code> - we probably don't want subclasses being able to make it non-freezable. If you want them to be able to add extra code, I'd suggest something like:</p>\n\n<pre><code>[public|protected] void Freeze()\n{\n if(!frozen)\n {\n frozen = true;\n OnFrozen();\n }\n}\nprotected virtual void OnFrozen() {} // subclass can add code here.\n</code></pre>\n\n<p>Also - AOP (such as PostSharp) might be a viable option for adding all those ThrowIfFrozen() checks.</p>\n\n<p>(apologies if I have changed terminology / method names - SO doesn't keep the original post visible when composing replies)</p>\n" }, { "answer_id": 263912, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 3, "selected": false, "text": "<p>Expanding on the point by @Cory Foy and @Charles Bretana where there is a difference between entities and values. Whereas value-objects should always be immutable, I really don't think that an object should be able to freeze themselves, or allow themselves to be frozen arbitrarily in the codebase. It has a really bad smell to it, and I worry that it could get hard to track down where exactly an object was frozen, and why it was frozen, and the fact that between calls to an object it could change state from thawed to frozen. </p>\n\n<p>That isn't to say that sometimes you want to give a (mutable) entity to something and ensure it isn't going to be changed. </p>\n\n<p>So, instead of freezing the object itself, another possibility is to copy the semantics of ReadOnlyCollection&lt; T ></p>\n\n<pre><code>List&lt;int&gt; list = new List&lt;int&gt; { 1, 2, 3};\nReadOnlyCollection&lt;int&gt; readOnlyList = list.AsReadOnly();\n</code></pre>\n\n<p>Your object can take a part as mutable when it needs it, and then be immutable when you desire it to be.</p>\n\n<p>Note that ReadOnlyCollection&lt; T > also implements ICollection&lt; T > which has an <code>Add( T item)</code> method in the interface. However there is also <code>bool IsReadOnly { get; }</code> defined in the interface so that consumers can check before calling a method that will throw an exception.</p>\n\n<p>The difference is that you can't just set IsReadOnly to false. A collection either is or isn't read only, and that never changes for the lifetime of the collection.</p>\n\n<p>It would be nice at time to have the const-correctness that C++ gives you at compile time, but that starts to have it's own set of problems and I'm glad C# doesn't go there.</p>\n\n<hr>\n\n<p><strong>ICloneable</strong> - I thought I'd just refer back to the following:</p>\n\n<blockquote>\n <p>Do not implement ICloneable</p>\n \n <p>Do not use ICloneable in public APIs</p>\n</blockquote>\n\n<p><a href=\"http://blogs.msdn.com/brada/archive/2003/04/09/49935.aspx\" rel=\"noreferrer\">Brad Abrams - Design Guidelines, Managed code and the .NET Framework</a></p>\n" }, { "answer_id": 265025, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 2, "selected": false, "text": "<p>Just a tip to simplify the element properties: Use <a href=\"http://blogesh.wordpress.com/2008/02/09/property-shortcuts-in-c-30/\" rel=\"nofollow noreferrer\">automatic properties</a> with <code>private set</code> and avoid explicitly declaring the data field. e.g.</p>\n\n<pre><code>public class SampleElement {\n public SampleElement(Guid id, string name) {\n Id = id;\n Name = name;\n }\n\n public Guid Id {\n get; private set;\n }\n\n public string Name {\n get; private set;\n }\n}\n</code></pre>\n" }, { "answer_id": 623323, "author": "Lars Fastrup", "author_id": 27393, "author_profile": "https://Stackoverflow.com/users/27393", "pm_score": 2, "selected": false, "text": "<p>Here is a new video on Channel 9 where Anders Hejlsberg from 36:30 in the interview starts talking about immutability in C#. He gives a very good use case for popsicle immutability and explains how this is something you are currently required to implement yourself. It was music to my ears hearing him say it is worth thinking about better support for creating immutable object graphs in future versions of C#</p>\n\n<p><a href=\"http://channel9.msdn.com/shows/Going+Deep/Expert-to-Expert-Anders-Hejlsberg-The-Future-of-C/\" rel=\"nofollow noreferrer\">Expert to Expert: Anders Hejlsberg - The Future of C#</a></p>\n" }, { "answer_id": 1034956, "author": "Neil", "author_id": 24315, "author_profile": "https://Stackoverflow.com/users/24315", "pm_score": 2, "selected": false, "text": "<p>Two other options for your particular problem that haven't been discussed: </p>\n\n<ol>\n<li><p>Build your own deserializer, one that can call a private property setter. While the effort in building the deserializer at the beginning will be much more, it makes things cleaner. The compiler will keep you from even attempting to call the setters and the code in your classes will be easier to read.</p></li>\n<li><p>Put a constructor in each class that takes an XElement (or some other flavor of XML object model) and populates itself from it. Obviously as the number of classes increases, this quickly becomes less desirable as a solution.</p></li>\n</ol>\n" }, { "answer_id": 4091679, "author": "Merlyn Morgan-Graham", "author_id": 232593, "author_profile": "https://Stackoverflow.com/users/232593", "pm_score": 2, "selected": false, "text": "<p>This is an important problem, and I've love to see more direct framework/language support to solve it. The solution you have requires a lot of boilerplate. It might be simple to automate some of the boilerplate by using code generation.</p>\n\n<p>You'd generate a partial class that contains all the freezable properties. It would be fairly simple to make a reusable T4 template for this.</p>\n\n<p>The template would take this for input:</p>\n\n<ul>\n<li>namespace</li>\n<li>class name</li>\n<li>list of property name/type tuples</li>\n</ul>\n\n<p>And would output a C# file, containing:</p>\n\n<ul>\n<li>namespace declaration</li>\n<li>partial class</li>\n<li>each of the properties, with the corresponding types, a backing field, a getter, and a setter which invokes the FailIfFrozen method</li>\n</ul>\n\n<p>AOP tags on freezable properties could also work, but it would require more dependencies, whereas T4 is built into newer versions of Visual Studio.</p>\n\n<p>Another scenario which is very much like this is the <code>INotifyPropertyChanged</code> interface. Solutions for that problem are likely to be applicable to this problem.</p>\n" }, { "answer_id": 4318490, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "<p>How about having an abstract class ThingBase, with subclasses MutableThing and ImmutableThing? ThingBase would contain all the data in a protected structure, providing public read-only properties for the fields and protected read-only property for its structure. It would also provide an overridable AsImmutable method which would return an ImmutableThing.</p>\n\n<p>MutableThing would shadow the properties with read/write properties, and provide both a default constructor and a constructor that accepts a ThingBase.</p>\n\n<p>Immutable thing would be a sealed class that overrides AsImmutable to simply return itself. It would also provide a constructor that accepts a ThingBase.</p>\n" }, { "answer_id": 15929373, "author": "bradgonesurfing", "author_id": 158285, "author_profile": "https://Stackoverflow.com/users/158285", "pm_score": 2, "selected": false, "text": "<p>You can use optional named arguments together with nullables to make an immutable setter with very little boilerplate. If you really do want to set a property to null then you may have some more troubles.</p>\n\n<pre><code>class Foo{ \n ...\n public Foo \n Set\n ( double? majorBar=null\n , double? minorBar=null\n , int? cats=null\n , double? dogs=null)\n {\n return new Foo\n ( majorBar ?? MajorBar\n , minorBar ?? MinorBar\n , cats ?? Cats\n , dogs ?? Dogs);\n }\n\n public Foo\n ( double R\n , double r\n , int l\n , double e\n ) \n {\n ....\n }\n}\n</code></pre>\n\n<p>You would use it like so</p>\n\n<pre><code>var f = new Foo(10,20,30,40);\nvar g = f.Set(cat:99);\n</code></pre>\n" }, { "answer_id": 21604550, "author": "Jos Bosmans", "author_id": 3005076, "author_profile": "https://Stackoverflow.com/users/3005076", "pm_score": 2, "selected": false, "text": "<p>My problem with this pattern is that you're not imposing any compile-time restraints upon immutability. The coder is responsible for making sure an object is set to immutable before for example adding it to a cache or another non-thread-safe structure. </p>\n\n<p>That's why I would extend this coding pattern with a compile-time restraint in the form of a generic class, like this:</p>\n\n<pre><code>public class Immutable&lt;T&gt; where T : IElement\n{\n private T value;\n\n public Immutable(T mutable) \n {\n this.value = (T) mutable.Clone();\n this.value.MakeReadOnly();\n }\n\n public T Value \n {\n get \n {\n return this.value;\n }\n }\n\n public static implicit operator Immutable&lt;T&gt;(T mutable) \n {\n return new Immutable&lt;T&gt;(mutable);\n }\n\n public static implicit operator T(Immutable&lt;T&gt; immutable)\n {\n return immutable.value;\n }\n}\n</code></pre>\n\n<p>Here's a sample how you would use this:</p>\n\n<pre><code>// All elements of this list are guaranteed to be immutable\nList&lt;Immutable&lt;SampleElement&gt;&gt; elements = \n new List&lt;Immutable&lt;SampleElement&gt;&gt;();\n\nfor (int i = 1; i &lt; 10; i++) \n{\n SampleElement newElement = new SampleElement();\n newElement.Id = Guid.NewGuid();\n newElement.Name = \"Sample\" + i.ToString();\n\n // The compiler will automatically convert to Immutable&lt;SampleElement&gt; for you\n // because of the implicit conversion operator\n elements.Add(newElement);\n}\n\nforeach (SampleElement element in elements)\n Console.Out.WriteLine(element.Name);\n\nelements[3].Value.Id = Guid.NewGuid(); // This will throw an ImmutableElementException\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27393/" ]
I have over the course of a few projects developed a pattern for creating immutable (readonly) objects and immutable object graphs. Immutable objects carry the benefit of being 100% thread safe and can therefore be reused across threads. In my work I very often use this pattern in Web applications for configuration settings and other objects that I load and cache in memory. Cached objects should always be immutable as you want to guarantee they are not unexpectedly changed. Now, you can of course easily design immutable objects as in the following example: ``` public class SampleElement { private Guid id; private string name; public SampleElement(Guid id, string name) { this.id = id; this.name = name; } public Guid Id { get { return id; } } public string Name { get { return name; } } } ``` This is fine for simple classes - but for more complex classes I do not fancy the concept of passing all values through a constructor. Having setters on the properties is more desirable and your code constructing a new object gets easier to read. So how do you create immutable objects with setters? Well, in my pattern objects start out as being fully mutable until you freeze them with a single method call. Once an object is frozen it will stay immutable forever - it cannot be turned into a mutable object again. If you need a mutable version of the object, you simply clone it. Ok, now on to some code. I have in the following code snippets tried to boil the pattern down to its simplest form. The IElement is the base interface that all immutable objects must ultimately implement. ``` public interface IElement : ICloneable { bool IsReadOnly { get; } void MakeReadOnly(); } ``` The Element class is the default implementation of the IElement interface: ``` public abstract class Element : IElement { private bool immutable; public bool IsReadOnly { get { return immutable; } } public virtual void MakeReadOnly() { immutable = true; } protected virtual void FailIfImmutable() { if (immutable) throw new ImmutableElementException(this); } ... } ``` Let's refactor the SampleElement class above to implement the immutable object pattern: ``` public class SampleElement : Element { private Guid id; private string name; public SampleElement() {} public Guid Id { get { return id; } set { FailIfImmutable(); id = value; } } public string Name { get { return name; } set { FailIfImmutable(); name = value; } } } ``` You can now change the Id property and the Name property as long as the object has not been marked as immutable by calling the MakeReadOnly() method. Once it is immutable, calling a setter will yield an ImmutableElementException. Final note: The full pattern is more complex than the code snippets shown here. It also contains support for collections of immutable objects and complete object graphs of immutable object graphs. The full pattern enables you to turn an entire object graph immutable by calling the MakeReadOnly() method on the outermost object. Once you start creating larger object models using this pattern the risk of leaky objects increases. A leaky object is an object that fails to call the FailIfImmutable() method before making a change to the object. To test for leaks I have also developed a generic leak detector class for use in unit tests. It uses reflection to test if all properties and methods throw the ImmutableElementException in the immutable state. In other words TDD is used here. I have grown to like this pattern a lot and find great benefits in it. So what I would like to know is if any of you are using similar patterns? If yes, do you know of any good resources that document it? I am essentially looking for potential improvements and for any standards that might already exist on this topic.
For info, the second approach is called "popsicle immutability". Eric Lippert has a series of blog entries on immutability starting [here](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability). I'm still getting to grips with the CTP (C# 4.0), but it looks interesting what optional / named parameters (to the .ctor) might do here (when mapped to readonly fields)... [update: I've blogged on this [here](https://blog.marcgravell.com/2008/11/immutability-and-optional-parameters.html)] For info, I probably wouldn't make those methods `virtual` - we probably don't want subclasses being able to make it non-freezable. If you want them to be able to add extra code, I'd suggest something like: ``` [public|protected] void Freeze() { if(!frozen) { frozen = true; OnFrozen(); } } protected virtual void OnFrozen() {} // subclass can add code here. ``` Also - AOP (such as PostSharp) might be a viable option for adding all those ThrowIfFrozen() checks. (apologies if I have changed terminology / method names - SO doesn't keep the original post visible when composing replies)
263,586
<p>I'm writing an implementation of a virtual machine in C#, and I need to implement the VM's stack, which can contain two types of entry - return entries or backtrack entries. What is the best way of implementing this?</p> <p>I'm currently using a base type, as follows:</p> <pre><code>class StackEntry { } class Return : StackEntry { uint pc; } class Backtrack : StackEntry { uint pc; object backtrack; } Stack&lt;StackEntry&gt; stack; </code></pre> <p>This works OK, but the resulting type testing and downcasting feels clumsy.</p> <p>Is there a better way of handling this type of construction?</p>
[ { "answer_id": 263601, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 2, "selected": false, "text": "<p>Why should you need to down cast? If your base class exposes abstract or virtual members, or is instead an interface, you should have no problem. This principle is the foundation of OOP.</p>\n\n<p>If that doesn't work for you then you do a switch on myStack[x].GetType()</p>\n" }, { "answer_id": 263602, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "<p>What's wrong with putting the BackTrack object in anyway and have it be null if there is no back track? You can add a helpful property like bool IsBacktrack { get { return _backTrack != null; } }</p>\n\n<p>Can the backtrack be validly null? If yes, then use a bool flag for it.</p>\n" }, { "answer_id": 263635, "author": "Mike Burton", "author_id": 22225, "author_profile": "https://Stackoverflow.com/users/22225", "pm_score": 4, "selected": true, "text": "<p>I'm having a hard time imagining how you're going to use this, but the basic answer is that you use a single type with a default operation for post-pop processing</p>\n\n<pre><code>StackEntry { protected virtual void PostPop(); }\nReturn : StackEntry { protected override void PostPop(); }\nBacktrack : StackEntry { protected override void PostPop(); }\n</code></pre>\n\n<p>Does that make sense?</p>\n" }, { "answer_id": 263643, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>It depends on the level of abstraction that you expect. The base class method is quite nice. Only when benchmarks reveal that too much performance is lost this way, I would try to drill deeper, perhaps using a custom-tailored structure with explicit memory layout that acts similar to a C <code>union</code>.</p>\n\n<p>How does your code affect usability in a negative way?</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34438/" ]
I'm writing an implementation of a virtual machine in C#, and I need to implement the VM's stack, which can contain two types of entry - return entries or backtrack entries. What is the best way of implementing this? I'm currently using a base type, as follows: ``` class StackEntry { } class Return : StackEntry { uint pc; } class Backtrack : StackEntry { uint pc; object backtrack; } Stack<StackEntry> stack; ``` This works OK, but the resulting type testing and downcasting feels clumsy. Is there a better way of handling this type of construction?
I'm having a hard time imagining how you're going to use this, but the basic answer is that you use a single type with a default operation for post-pop processing ``` StackEntry { protected virtual void PostPop(); } Return : StackEntry { protected override void PostPop(); } Backtrack : StackEntry { protected override void PostPop(); } ``` Does that make sense?
263,599
<p>I'm wondering how slow it's going to be switching between 2 databases on every call of every page of a site. The site has many different databases for different clients, along with a "global" database that is used for some general settings. I'm wondering if there would be much time added for the execution of each script if it has to connect to the database, select a DB, do a query or 2, switch to another DB and then complete the page generation. I could also have the data repeated in each DB, I just need to mantain it (will only change when upgrading).</p> <p>So, in the end, how fast is <code>mysql_select_db()</code>?</p> <p><strong>Edit:</strong> Yes, I could connect to each DB separately, but as this is often the slowest part of any PHP script, I'd like to avoid this, especially since it's on every page. (It's slow because PHP has to do some kind of address resolution (be it an IP or host name) and then MySQL has to check the login parameters both times.)</p>
[ { "answer_id": 263634, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 4, "selected": true, "text": "<p>Assuming that both databases are on the same machine, you don't need to do the mysql_select_db. You can just specify the database in the queries. For example;</p>\n\n<pre><code>SELECT * FROM db1.table1;\n</code></pre>\n\n<p>You could also open two connections and use the DB object that is returned from the connect call and use those two objects to select the databases and pass into all of the calls. The database connection is an optional parameter on all of the mysql db calls, just check the docs.</p>\n" }, { "answer_id": 264129, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 1, "selected": false, "text": "<p>You're asking two quite different questions.</p>\n\n<ol>\n<li><p>Connecting to multiple database instances</p></li>\n<li><p>Switching default database schemas.</p></li>\n</ol>\n\n<p>MySQL is known to have quite fast connection setup time; making two <code>mysql_connect()</code> calls to different servers is barely more expensive than one.</p>\n\n<p>The call <code>mysql_select_db()</code> is exactly the same as the <code>USE</code> statement and simply changes the default database schema for unqualified table references.</p>\n\n<p>Be careful with your use of the term 'database' around MySQL: it has two different meanings.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
I'm wondering how slow it's going to be switching between 2 databases on every call of every page of a site. The site has many different databases for different clients, along with a "global" database that is used for some general settings. I'm wondering if there would be much time added for the execution of each script if it has to connect to the database, select a DB, do a query or 2, switch to another DB and then complete the page generation. I could also have the data repeated in each DB, I just need to mantain it (will only change when upgrading). So, in the end, how fast is `mysql_select_db()`? **Edit:** Yes, I could connect to each DB separately, but as this is often the slowest part of any PHP script, I'd like to avoid this, especially since it's on every page. (It's slow because PHP has to do some kind of address resolution (be it an IP or host name) and then MySQL has to check the login parameters both times.)
Assuming that both databases are on the same machine, you don't need to do the mysql\_select\_db. You can just specify the database in the queries. For example; ``` SELECT * FROM db1.table1; ``` You could also open two connections and use the DB object that is returned from the connect call and use those two objects to select the databases and pass into all of the calls. The database connection is an optional parameter on all of the mysql db calls, just check the docs.
263,612
<p>Earlier today I was hunting down a very weird bug... I finally traced it down to what seems to be causing the problem.</p> <p>The original report can be found here: <a href="https://stackoverflow.com/questions/262017/weird-behaviour-when-running-clickonce-deployed-version-of-wpf-application">original question</a></p> <p>The details have changed enough to warrant a new question.</p> <p>It would seem my application sometimes, NOT ALL OF THE TIME, freezes when it reaches the following LINQ query:</p> <pre><code>using (NetworkDatabaseContext db = new NetworkDatabaseContext(UISession.ConnectionString)) { Ballast ballast = db.Ballasts.FirstOrDefault(b =&gt; b.NetworkId == UISession.NetworkId &amp;&amp; b.ShortAddress == this.innerBallast.ShortAddress &amp;&amp; b.ControllerSerial == this.controllerSerial); </code></pre> <p>This is what it looks like:</p> <p><a href="https://i.stack.imgur.com/w8OYA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/w8OYA.jpg" alt="Not Responding"></a></p> <p>Most of the time this works just fine... but every now and then it will lock up. This code is part of a BallastListItem class. Items of this class are bound to a ListBox on the Page:</p> <pre><code>&lt;ListView Name="lstBallasts" Margin="5" DockPanel.Dock="Top" MinHeight="100"&gt;&lt;!-- The MinHeight is used to get a good view in the designer --&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn Header="Address" DisplayMemberBinding="{Binding InnerBallast.ShortAddress}" Width="70"/&gt; &lt;GridViewColumn Header="Name" Width="300"&gt; &lt;GridViewColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;TextBox Name="txtBallastDisplayName" Text="{Binding DisplayName}" Width="270" MaxWidth="270" MaxLength="100"/&gt; &lt;/DataTemplate&gt; &lt;/GridViewColumn.CellTemplate&gt; &lt;/GridViewColumn&gt; &lt;GridViewColumn Header="Type" DisplayMemberBinding="{Binding DeviceType}" Width="150"/&gt; &lt;GridViewColumn Header="Status" DisplayMemberBinding="{Binding InnerBallast.StandardVersion}" Width="150"/&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; </code></pre> <p>The code is part of the DisplayName property getter:</p> <pre><code>public string DisplayName { get { using (NetworkDatabaseContext db = new NetworkDatabaseContext(UISession.ConnectionString)) { Ballast ballast = db.Ballasts.FirstOrDefault(b =&gt; b.NetworkId == UISession.NetworkId &amp;&amp; b.ShortAddress == this.innerBallast.ShortAddress &amp;&amp; b.ControllerSerial == this.controllerSerial); </code></pre> <p>So this code is called when databinding occurs, should have realized that before. Still I have no idea why this would sometimes cause problems...</p> <p><strong>UPDATE</strong></p> <p>In both cases (when the application freezes and when it does not) the state of the connection is "Closed" just before the query code, as I can see from:</p> <pre><code>db.Connection.State.ToString() </code></pre> <p><strong>UPDATE 2</strong> I forgot to mention I moved that code out of the getter, so it is only fetched once. Must have been sleeping while implementing this the first time. The code works fine now, although on XP... every now and then, but much less often the problem still occurs.</p> <p><strong>* UPDATE 3 *</strong> Just to be clear, I'm using an SQL Compact database with very little data</p>
[ { "answer_id": 266815, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 2, "selected": false, "text": "<p>Having a property open a database connection and run a query is not a good pattern. </p>\n\n<p>A better approach would be to query a set of objects from LINQ to SQL and bind those to the WPF control instead.</p>\n" }, { "answer_id": 266859, "author": "mwjackson", "author_id": 12948, "author_profile": "https://Stackoverflow.com/users/12948", "pm_score": 1, "selected": false, "text": "<p>I agree with Damien, why dont you execute the DB call asynchronously? That way the UI stays responsive and you can handle DB errors in the background gracefully without the user knowing...</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
Earlier today I was hunting down a very weird bug... I finally traced it down to what seems to be causing the problem. The original report can be found here: [original question](https://stackoverflow.com/questions/262017/weird-behaviour-when-running-clickonce-deployed-version-of-wpf-application) The details have changed enough to warrant a new question. It would seem my application sometimes, NOT ALL OF THE TIME, freezes when it reaches the following LINQ query: ``` using (NetworkDatabaseContext db = new NetworkDatabaseContext(UISession.ConnectionString)) { Ballast ballast = db.Ballasts.FirstOrDefault(b => b.NetworkId == UISession.NetworkId && b.ShortAddress == this.innerBallast.ShortAddress && b.ControllerSerial == this.controllerSerial); ``` This is what it looks like: [![Not Responding](https://i.stack.imgur.com/w8OYA.jpg)](https://i.stack.imgur.com/w8OYA.jpg) Most of the time this works just fine... but every now and then it will lock up. This code is part of a BallastListItem class. Items of this class are bound to a ListBox on the Page: ``` <ListView Name="lstBallasts" Margin="5" DockPanel.Dock="Top" MinHeight="100"><!-- The MinHeight is used to get a good view in the designer --> <ListView.View> <GridView> <GridViewColumn Header="Address" DisplayMemberBinding="{Binding InnerBallast.ShortAddress}" Width="70"/> <GridViewColumn Header="Name" Width="300"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBox Name="txtBallastDisplayName" Text="{Binding DisplayName}" Width="270" MaxWidth="270" MaxLength="100"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="Type" DisplayMemberBinding="{Binding DeviceType}" Width="150"/> <GridViewColumn Header="Status" DisplayMemberBinding="{Binding InnerBallast.StandardVersion}" Width="150"/> </GridView> </ListView.View> </ListView> ``` The code is part of the DisplayName property getter: ``` public string DisplayName { get { using (NetworkDatabaseContext db = new NetworkDatabaseContext(UISession.ConnectionString)) { Ballast ballast = db.Ballasts.FirstOrDefault(b => b.NetworkId == UISession.NetworkId && b.ShortAddress == this.innerBallast.ShortAddress && b.ControllerSerial == this.controllerSerial); ``` So this code is called when databinding occurs, should have realized that before. Still I have no idea why this would sometimes cause problems... **UPDATE** In both cases (when the application freezes and when it does not) the state of the connection is "Closed" just before the query code, as I can see from: ``` db.Connection.State.ToString() ``` **UPDATE 2** I forgot to mention I moved that code out of the getter, so it is only fetched once. Must have been sleeping while implementing this the first time. The code works fine now, although on XP... every now and then, but much less often the problem still occurs. **\* UPDATE 3 \*** Just to be clear, I'm using an SQL Compact database with very little data
Having a property open a database connection and run a query is not a good pattern. A better approach would be to query a set of objects from LINQ to SQL and bind those to the WPF control instead.
263,623
<p>Is there any Ruby equivalent for Python's builtin <code>zip</code> function? If not, what is a concise way of doing the same thing?</p> <p>A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had <code>zip</code>, I could have written something like:</p> <pre><code>zip(a, b).all? {|pair| pair[0] === pair[1]} </code></pre> <p>I'd also accept a clean way of doing this without anything resembling <code>zip</code> (where "clean" means "without an explicit loop").</p>
[ { "answer_id": 263652, "author": "dgtized", "author_id": 34450, "author_profile": "https://Stackoverflow.com/users/34450", "pm_score": 6, "selected": true, "text": "<p>Ruby has a zip function:</p>\n\n<pre><code>[1,2].zip([3,4]) =&gt; [[1,3],[2,4]]\n</code></pre>\n\n<p>so your code example is actually:</p>\n\n<pre><code>a.zip(b).all? {|pair| pair[0] === pair[1]}\n</code></pre>\n\n<p>or perhaps more succinctly:</p>\n\n<pre><code>a.zip(b).all? {|a,b| a === b }\n</code></pre>\n" }, { "answer_id": 263670, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "<p>Could you not do:</p>\n\n<pre><code>a.eql?(b)\n</code></pre>\n\n<p>Edited to add an example:</p>\n\n<pre><code>a = %w[a b c]\nb = %w[1 2 3]\nc = ['a', 'b', 'c']\n\na.eql?(b) # =&gt; false\na.eql?(c) # =&gt; true\na.eql?(c.reverse) # =&gt; false\n</code></pre>\n" }, { "answer_id": 266848, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": -1, "selected": false, "text": "<p>This is from the ruby spec:</p>\n\n<pre><code>it \"returns true if other has the same length and each pair of corresponding elements are eql\" do\n a = [1, 2, 3, 4]\n b = [1, 2, 3, 4]\n a.should eql(b)\n [].should eql([])\nend\n</code></pre>\n\n<p>So you should it should work for the example you mentioned.</p>\n\n<p>If you're not using integers, but custom objects I <em>think</em> you need to override eql?.</p>\n\n<p>The spec for this method is here:</p>\n\n<p><a href=\"http://github.com/rubyspec/rubyspec/tree/master/1.8/core/array/eql_spec.rb\" rel=\"nofollow noreferrer\">http://github.com/rubyspec/rubyspec/tree/master/1.8/core/array/eql_spec.rb</a></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34443/" ]
Is there any Ruby equivalent for Python's builtin `zip` function? If not, what is a concise way of doing the same thing? A bit of context: this came up when I was trying to find a clean way of doing a check involving two arrays. If I had `zip`, I could have written something like: ``` zip(a, b).all? {|pair| pair[0] === pair[1]} ``` I'd also accept a clean way of doing this without anything resembling `zip` (where "clean" means "without an explicit loop").
Ruby has a zip function: ``` [1,2].zip([3,4]) => [[1,3],[2,4]] ``` so your code example is actually: ``` a.zip(b).all? {|pair| pair[0] === pair[1]} ``` or perhaps more succinctly: ``` a.zip(b).all? {|a,b| a === b } ```
263,697
<p>I have a multidimensional array. I need to search it for a specific range of values, edit those values and return the edited data.</p> <p>Example array:</p> <pre><code>array(3) { ["first"]=&gt; array(1) { [0]=&gt; string(4) "baz1" } ["second"]=&gt; array(1) { [0]=&gt; string(4) "foo1" } ["third"]=&gt; array(1) { [0]=&gt; string(4) "foo2" } </code></pre> <p>Now I want to find any values that match foo (foo1 and foo2 in the example array), insert "-bar" into them (foo-bar1, foo-bar2) and return that value. What are the best ways to approach this? </p> <p><em>EDIT</em> I should have mentioned that foo could actually be anythingfoo (ex. examplefoo1, somethingelsefoo2, blahblahfoo3). I think this rules out str_replace.</p>
[ { "answer_id": 263713, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 3, "selected": false, "text": "<p>How about something like this:</p>\n\n<pre><code>function addDashBar($arr)\n{\n foreach ($arr as $key =&gt; $value)\n {\n if (is_array($value))\n $arr[$key] = addDashBar($value)\n else\n {\n $arr[$key] = str_replace($value, \"foo\", \"foo-bar\");\n }\n }\n\n return $arr;\n}\n</code></pre>\n" }, { "answer_id": 263728, "author": "Marek", "author_id": 34452, "author_profile": "https://Stackoverflow.com/users/34452", "pm_score": 4, "selected": true, "text": "<p>If your array will not be extremely deep, this can work.\n($array being what you want to replace later with yours)</p>\n\n<pre><code>$array= array('first' =&gt; array('bazi1'), 'second' =&gt; array('foo1'), 'third' =&gt; array('foo2') );\nfunction modify_foo(&amp;$item, $key)\n{\n $item = str_replace('foo', 'foo-bar', $item);\n}\narray_walk_recursive( $array, 'modify_foo' );\n</code></pre>\n\n<p>If you want foo to be replaced even in somethingelsefoo2, then str_replace will be just fine.</p>\n" }, { "answer_id": 264955, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 1, "selected": false, "text": "<pre><code> function test_replace1(&amp;$input, $search, $replace) {\n $result = array();\n $numReplacements = 0;\n foreach ($input as &amp;$value) {\n if (is_array($value)) {\n $result = array_merge($result, test_replace1($value, $search, $replace));\n } else {\n $value = str_replace($search, $replace, $value, $numReplacements);\n if ($numReplacements) {\n $result[] = $value;\n }\n }\n }\n return $result;\n }\n\n $changed_values = test_replace1($arr, 'foo', 'foo-bar');\n</code></pre>\n" }, { "answer_id": 267601, "author": "Vinh", "author_id": 34561, "author_profile": "https://Stackoverflow.com/users/34561", "pm_score": 1, "selected": false, "text": "<p>If you have a 1 dimensional array, you should be able to use array_map();</p>\n\n<p>** Edit: I had some code here but, after testing , it doesn't work. </p>\n\n<p>In regards to your edit.\nJust because Foo is at the end of the string, does not mean str_replace will no longer work.</p>\n\n<pre><code>echo str_replace(\"foo\",\"foo-bar\",\"mycrazystringwithfoorightinthemiddleofit\");\n</code></pre>\n\n<p>will still return </p>\n\n<pre><code>mycrazystringwithfoo-barrightinthemiddleofit\n</code></pre>\n\n<p>if your array is a tree structure of arbitrary depth, then it is unavoidable that you will have to use recursion and the problem becomes non-trivial. You might want to check out the </p>\n\n<p>array_recursive_walk() function. \n<a href=\"http://us.php.net/manual/en/function.array-walk-recursive.php\" rel=\"nofollow noreferrer\">here</a>\nHope this helps.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11252/" ]
I have a multidimensional array. I need to search it for a specific range of values, edit those values and return the edited data. Example array: ``` array(3) { ["first"]=> array(1) { [0]=> string(4) "baz1" } ["second"]=> array(1) { [0]=> string(4) "foo1" } ["third"]=> array(1) { [0]=> string(4) "foo2" } ``` Now I want to find any values that match foo (foo1 and foo2 in the example array), insert "-bar" into them (foo-bar1, foo-bar2) and return that value. What are the best ways to approach this? *EDIT* I should have mentioned that foo could actually be anythingfoo (ex. examplefoo1, somethingelsefoo2, blahblahfoo3). I think this rules out str\_replace.
If your array will not be extremely deep, this can work. ($array being what you want to replace later with yours) ``` $array= array('first' => array('bazi1'), 'second' => array('foo1'), 'third' => array('foo2') ); function modify_foo(&$item, $key) { $item = str_replace('foo', 'foo-bar', $item); } array_walk_recursive( $array, 'modify_foo' ); ``` If you want foo to be replaced even in somethingelsefoo2, then str\_replace will be just fine.
263,730
<p>In eclipse, I have a javaproject (not a web project), though it does provide reusable tag files.</p> <p>layout</p> <p>+src<br> +++META-INF<br> ----my.tld<br> +++++++++++tags<br> ---------------include.jsp<br></p> <p>I keep on getting Fragment "/META-INF/tags/include.jsp" was not be found at expected path /Project/META-INF/tags/taginclude.jsp</p> <p>How can I modify the path eclipse is looking for? I need to tell it to include "src" in the lookup</p>
[ { "answer_id": 263930, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Josh, if you're working with .jsp and .tld files, then you really shouldn't be doing this as a \"Java Project\", but instead a \"Dynamic Web Project\" in Eclipse. Nonetheless, I'll try to answer your question.</p>\n\n<p>Based on the diagram of your file system, your files are laid out incorrectly. If you're trying to create a web app (a .war file), then you need a WEB-INF directory. Under the WEB-INF directory you'll need a web.xml file (google for web.xml to see what needs to be in there), a tags directory, and a classes and lib directory.</p>\n\n<p>Compiled class files must go in the WEB-INF/classes directory.\nJar files that you depend on must go in the WEB-INF/lib directory.\nTablibs must go in the WEB-INF/tags directory.\nFinally, your .jsp files must go in src directory (the parent dir of WEB-INF).</p>\n\n<p>So, your layout should look like this:</p>\n\n<pre>\nmyproject/\n`-- src\n |-- WEB-INF\n | |-- classes\n | | `-- MyClass.class\n | |-- lib\n | | `-- my.jar\n | |-- tags\n | | `-- my.tld\n | `-- web.xml\n `-- include.jsp\n</pre>\n\n<p>Hope this helps.</p>\n\n<p>-Bryan</p>\n" }, { "answer_id": 1679113, "author": "nitind", "author_id": 27905, "author_profile": "https://Stackoverflow.com/users/27905", "pm_score": 1, "selected": false, "text": "<p>I'm afraid I don't understand the ascii representation in the original post, but the validator can make use of any project with a ModuleCore Nature and its .settings/org.eclipse.wst.common.component file to find out what \"/\" means. Creating a Dynamic Web Project and inspecting that file and .project might help you piece together the right contents to make this work in your Java project.</p>\n" }, { "answer_id": 27312773, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Maybe the path of the jsp page is incorrect!You can check it using ctrl+left click,if can't open the jsp file,I suggest you check the path.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20641/" ]
In eclipse, I have a javaproject (not a web project), though it does provide reusable tag files. layout +src +++META-INF ----my.tld +++++++++++tags ---------------include.jsp I keep on getting Fragment "/META-INF/tags/include.jsp" was not be found at expected path /Project/META-INF/tags/taginclude.jsp How can I modify the path eclipse is looking for? I need to tell it to include "src" in the lookup
Josh, if you're working with .jsp and .tld files, then you really shouldn't be doing this as a "Java Project", but instead a "Dynamic Web Project" in Eclipse. Nonetheless, I'll try to answer your question. Based on the diagram of your file system, your files are laid out incorrectly. If you're trying to create a web app (a .war file), then you need a WEB-INF directory. Under the WEB-INF directory you'll need a web.xml file (google for web.xml to see what needs to be in there), a tags directory, and a classes and lib directory. Compiled class files must go in the WEB-INF/classes directory. Jar files that you depend on must go in the WEB-INF/lib directory. Tablibs must go in the WEB-INF/tags directory. Finally, your .jsp files must go in src directory (the parent dir of WEB-INF). So, your layout should look like this: ``` myproject/ `-- src |-- WEB-INF | |-- classes | | `-- MyClass.class | |-- lib | | `-- my.jar | |-- tags | | `-- my.tld | `-- web.xml `-- include.jsp ``` Hope this helps. -Bryan
263,735
<p>Problem: How can I tell if a selection of text in the CRichEditCtrl has multiple font sizes in it?</p> <hr> <p>Goal: I am sort of making my own RichEdit toolbar (bold, italic, font type, font size, etc). I want to emulate what MS Word does when a selection of text has more than a single font size spanning the selection.</p> <p>Ex - You have a line of text with the first 10 characters 9 pt font and the next 15 characters 14 pt font. If you highlight the first 5 characters, the "Font Pt Selection" drop down displays "9". If you then select the first 20 characters, the same drop down should have a empty/blank display.</p> <hr> <p>What I have going so far: I am getting the necessary notification when the selection changes inside of the CRichEditCtrl. Also, if there is only a single font size in the selection I am able to figure that out</p> <pre><code>CHARFORMAT cf; cf.cbSize = sizeof(CHARFORMAT); CRichEditCtrl ctrl; ctrl.GetSelectionCharFormat( cf ); int nFontPtSize = cf.yHeight / 20; </code></pre> <p>This will give me the needed info for the first case of my example above. Unfortunately, what I seem to get for the second part of my example only gives me back the info for where the selection ends (instead of the entire selection).</p> <p>In conclusion, is there some info I am missing in the CHARFORMAT or some other struct I can get from the CRichEditCtrl or some kind of interesting calculation I can do to make the decision that there are multiple sizes in the selection? So far my only idea is to chug through the selection a character at a time and see if the current font size of that character is different than any of the previous characters. I am mostly just hoping the info I need is there, and I just don't see it (In a similar way that from the CHARFORMAT's dwMask member tells me that any or all of Bold, Italic, Underline, etc are turned on).</p>
[ { "answer_id": 265414, "author": "DavidK", "author_id": 31394, "author_profile": "https://Stackoverflow.com/users/31394", "pm_score": 2, "selected": true, "text": "<p>As the above answer notes, the easiest way I can think of to do this is to use the Text Object Model (TOM), which is accessed through the ITextDocument COM interface. To get at this from your rich edit control (note code not tested, but should work):</p>\n\n<pre><code>CComPtr&lt;IRichEditOle&gt; richOle;\nrichOle.Attach(edit.GetIRichEditOle());\nCComQIPtr&lt;ITextDocument&gt; textDoc(richOle);\n</code></pre>\n\n<p>Then get a range. Here this is for the selected text, but one of the advantages of TOM is that you can operate on any range, not just what's selected.</p>\n\n<pre><code>CComPtr&lt;ITextSelection&gt; range;\ntextDoc-&gt;GetSelection(&amp;range);\n</code></pre>\n\n<p>Then get the font for the range, and see what its characteristics are, e.g.</p>\n\n<pre><code>CComPtr&lt;ITextFont&gt; font;\nrange-&gt;GetFont(&amp;font);\nlong size;\nfont-&gt;GetSize(&amp;size);\n</code></pre>\n\n<p>If the range is formatted with a single font size, you'll get that back in \"size\". If there's multiple font sizes, you'll get the value \"tomUndefined\" instead.</p>\n" }, { "answer_id": 272182, "author": "Scott", "author_id": 34460, "author_profile": "https://Stackoverflow.com/users/34460", "pm_score": 0, "selected": false, "text": "<p>Been juggling a couple things, but I was finally able to work.\nThis is how I finally was able to get everything to compile and run:</p>\n\n<pre><code>HWND hwnd;\nITextDocument* pDoc;\nIUnknown* pUnk = NULL;\nfloat size = 0;\nhwnd = GetSafeHwnd();\n::SendMessage( hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&amp;pUnk );\n if ( pUnk &amp;&amp; pUnk-&gt;QueryInterface( __uuidof(ITextDocument), (void**)&amp;pDoc ) == NOERROR )\n {\n CComPtr&lt;ITextSelection&gt; range;\n pDoc-&gt;GetSelection( &amp;range );\n CComPtr&lt;ITextFont&gt; font;\n range-&gt;GetFont( &amp;font ); \n // If there are multiple font sizes in the selection, \"size\" comes back as -9999 \n font-&gt;GetSize(&amp;size);\n }\nreturn size;\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34460/" ]
Problem: How can I tell if a selection of text in the CRichEditCtrl has multiple font sizes in it? --- Goal: I am sort of making my own RichEdit toolbar (bold, italic, font type, font size, etc). I want to emulate what MS Word does when a selection of text has more than a single font size spanning the selection. Ex - You have a line of text with the first 10 characters 9 pt font and the next 15 characters 14 pt font. If you highlight the first 5 characters, the "Font Pt Selection" drop down displays "9". If you then select the first 20 characters, the same drop down should have a empty/blank display. --- What I have going so far: I am getting the necessary notification when the selection changes inside of the CRichEditCtrl. Also, if there is only a single font size in the selection I am able to figure that out ``` CHARFORMAT cf; cf.cbSize = sizeof(CHARFORMAT); CRichEditCtrl ctrl; ctrl.GetSelectionCharFormat( cf ); int nFontPtSize = cf.yHeight / 20; ``` This will give me the needed info for the first case of my example above. Unfortunately, what I seem to get for the second part of my example only gives me back the info for where the selection ends (instead of the entire selection). In conclusion, is there some info I am missing in the CHARFORMAT or some other struct I can get from the CRichEditCtrl or some kind of interesting calculation I can do to make the decision that there are multiple sizes in the selection? So far my only idea is to chug through the selection a character at a time and see if the current font size of that character is different than any of the previous characters. I am mostly just hoping the info I need is there, and I just don't see it (In a similar way that from the CHARFORMAT's dwMask member tells me that any or all of Bold, Italic, Underline, etc are turned on).
As the above answer notes, the easiest way I can think of to do this is to use the Text Object Model (TOM), which is accessed through the ITextDocument COM interface. To get at this from your rich edit control (note code not tested, but should work): ``` CComPtr<IRichEditOle> richOle; richOle.Attach(edit.GetIRichEditOle()); CComQIPtr<ITextDocument> textDoc(richOle); ``` Then get a range. Here this is for the selected text, but one of the advantages of TOM is that you can operate on any range, not just what's selected. ``` CComPtr<ITextSelection> range; textDoc->GetSelection(&range); ``` Then get the font for the range, and see what its characteristics are, e.g. ``` CComPtr<ITextFont> font; range->GetFont(&font); long size; font->GetSize(&size); ``` If the range is formatted with a single font size, you'll get that back in "size". If there's multiple font sizes, you'll get the value "tomUndefined" instead.
263,741
<p>I built a <strong>[widget][1]</strong> that grabs the URL from the frontmost window in Safari, then allows you to shorten it using the tr.im API. Works sweet as.</p> <p>I want to make this more flexible, so am investigating how to grab an URL from other browsers. Here's the AppleScript that works in Safari:</p> <pre><code>tell application "Safari" return URL of front document as string end tell </code></pre> <p>After <a href="https://web.archive.org/web/20141112082406/http://hintsforums.macworld.com/showthread.php?t=32237" rel="nofollow noreferrer">some digging</a>, I determined that the following <em>might</em> work for Firefox (though one person has told me it doesn't work for him, possibly a conflict with some extension?):</p> <pre><code>tell application "Firefox" set myFirefox to properties of front window as list return item 3 of myFirefox end tell </code></pre> <p><em>Note: The above is an example of a less-than-best practice, relying on the position of list items. See below for a better solution for Firefox.</em></p> <p>What I'd like to do is build a list here of the definitive equivalents for every modern browser on the Mac: Opera, Camino, Flock, etc.</p> <p><strong>Update:</strong> In my research on the subject, I came across a helpful thread on <a href="http://www.macosxhints.com/article.php?story=20060325015454467" rel="nofollow noreferrer">MacOSXHints.com</a>. Most of my answers below are based on that discussion.</p> <p><strong>Update 2:</strong> I've incorporated the AppleScript on this page into the [widget][1]. It seems to be working swell.</p>
[ { "answer_id": 268195, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>Opera (tested on versions 9.21 and 9.62):</p>\n\n<pre><code>tell application \"Opera\"\n return URL of front document as string\nend tell\n</code></pre>\n" }, { "answer_id": 268197, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 2, "selected": false, "text": "<p>Firefox (tested on versions 2.0.0.14 and 3.0.1):</p>\n\n<pre><code>tell application \"Firefox\"\n set myURL to «class curl» of window 1\n return myURL\nend tell\n</code></pre>\n" }, { "answer_id": 268212, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>Camino (tested on version 1.6.4):</p>\n\n<pre><code>tell application \"Camino\"\n set p to properties of front tab of front window\n return |currentURI| of p as string\nend tell\n</code></pre>\n" }, { "answer_id": 268222, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>Flock (tested on version 2.0):</p>\n\n<pre><code>tell application \"Flock\"\n set p to properties of front window as list\n return item 3 of p\nend tell\n</code></pre>\n\n<p>This relies on the position of the list item, but as far as I can tell, this is the only way to get at this value. The property is named <code>address</code> which, though Apple's documentation doesn't say so, appears to be a reserved word in AppleScript.</p>\n" }, { "answer_id": 268264, "author": "Andrew Hedges", "author_id": 11577, "author_profile": "https://Stackoverflow.com/users/11577", "pm_score": 0, "selected": false, "text": "<p>OmniWeb (tested on version 5.8):</p>\n\n<pre><code>tell application \"OmniWeb\"\n set myInfo to GetWindowInfo\n return item 1 of myInfo\nend tell\n</code></pre>\n" }, { "answer_id": 271684, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>There is currently a bug in Firefox 3.03, that will hide from AppleScript all of the window properties including «class curl», if you have used a statement like the following before :</p>\n\n<pre><code>tell application \"Firefox\" to activate\n</code></pre>\n\n<p>or</p>\n\n<pre><code>tell application \"Firefox\"\n if (front window) exists then do_something()\nend tell\n</code></pre>\n\n<p>the work around is to use the following code instead :</p>\n\n<pre><code>tell application \"System Events\"\n tell process \"Firefox\"\n set frontmost to true\n set xsist to (front window) exists\n (* keep xsist value to test later on *)\n end tell\nend tell\n</code></pre>\n\n<p><strong>Note :</strong> the window's properties will remain unavailable until next relaunch of Firefox</p>\n" }, { "answer_id": 287381, "author": "piero", "author_id": 37358, "author_profile": "https://Stackoverflow.com/users/37358", "pm_score": 2, "selected": false, "text": "<p>This is Piero again back with a new id (I lost my cookies while trying to reinstal Firefox !!!).</p>\n\n<p>I just tried Firefox 3.04 nothing changed about appleScript support and relyability.\nStill the same bug ...</p>\n\n<p>My test and searches over the web, brought me to the conclusion that you cannot access the name of the window, and other properties of the window, such as «class curl», in the same script.</p>\n\n<p>If you are working with the name of the window, and that, suddently, you cannot access it anymore (getting random binary like strings), you have to call this code again :</p>\n\n<pre><code>tell application \"Firefox\" to activate\n</code></pre>\n\n<p>using any statement that will generate an error in Firefox will also work just fine, to make window name available again, but restarting your Mac won't change anything !</p>\n\n<p>Once you have done that, as I mentioned before, you cannot access «class curl» anymore, until next Firefox restart ...</p>\n\n<p>writing scripts for Firefox on Macs is really mission impossible !</p>\n\n<p>If you would like AppleScript to be supported on Firefox tell it, and vote for this bug !!!</p>\n\n<p><a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=464701\" rel=\"nofollow noreferrer\">https://bugzilla.mozilla.org/show_bug.cgi?id=464701</a></p>\n" }, { "answer_id": 800452, "author": "smorgan", "author_id": 96811, "author_profile": "https://Stackoverflow.com/users/96811", "pm_score": 1, "selected": false, "text": "<p>Camino 1.6 and above:</p>\n\n<pre><code>tell application \"Camino\"\n return URL of current tab of front browser window as text\nend tell\n</code></pre>\n\n<p>Unlike the earlier answer, this will get the focused tab's URL.</p>\n" }, { "answer_id": 1598732, "author": "Brian", "author_id": 193561, "author_profile": "https://Stackoverflow.com/users/193561", "pm_score": 2, "selected": false, "text": "<p>Activate UI scripting and run the code below. You will then have the URL in the clipboard and you can paste it.</p>\n\n<pre><code>tell application \"Firefox\" to activate\ntell application \"System Events\"\n keystroke \"l\" using command down\n keystroke \"c\" using command down\nend tell\n</code></pre>\n" }, { "answer_id": 5216379, "author": "Neffster", "author_id": 265861, "author_profile": "https://Stackoverflow.com/users/265861", "pm_score": 2, "selected": false, "text": "<p>Google Chrome for Mac has added the AppleScripting method for getting the URL.</p>\n\n<h2>Here's the Chromium AppleScript SDK</h2>\n\n<p><a href=\"https://sites.google.com/a/chromium.org/dev/developers/design-documents/applescript\" rel=\"nofollow\">https://sites.google.com/a/chromium.org/dev/developers/design-documents/applescript</a></p>\n\n<h2>Example from the page linked below:</h2>\n\n<pre><code> tell application \"Google Chrome\"\n get URL of active tab of window 1\n end tell\n</code></pre>\n\n<h2>More examples here:</h2>\n\n<p><a href=\"http://laclefyoshi.blogspot.com/2010/10/google-chrome-ver.html\" rel=\"nofollow\">http://laclefyoshi.blogspot.com/2010/10/google-chrome-ver.html</a></p>\n" }, { "answer_id": 14162637, "author": "Fred", "author_id": 1949435, "author_profile": "https://Stackoverflow.com/users/1949435", "pm_score": 1, "selected": false, "text": "<p>Thanks to Brian above, this is the bullet proof version. </p>\n\n<p>His code asks you to paste the URL, but this one sets the URL to \"FrontDocumentURL\" which you can then use as a variable in your scripts.</p>\n\n<pre><code>tell application \"Firefox\" to activate\n\ntell application \"System Events\"\nkeystroke \"l\" using command down\nkeystroke \"c\" using command down\nend tell\n\nset FrontDocumentURL to the clipboard\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
I built a **[widget][1]** that grabs the URL from the frontmost window in Safari, then allows you to shorten it using the tr.im API. Works sweet as. I want to make this more flexible, so am investigating how to grab an URL from other browsers. Here's the AppleScript that works in Safari: ``` tell application "Safari" return URL of front document as string end tell ``` After [some digging](https://web.archive.org/web/20141112082406/http://hintsforums.macworld.com/showthread.php?t=32237), I determined that the following *might* work for Firefox (though one person has told me it doesn't work for him, possibly a conflict with some extension?): ``` tell application "Firefox" set myFirefox to properties of front window as list return item 3 of myFirefox end tell ``` *Note: The above is an example of a less-than-best practice, relying on the position of list items. See below for a better solution for Firefox.* What I'd like to do is build a list here of the definitive equivalents for every modern browser on the Mac: Opera, Camino, Flock, etc. **Update:** In my research on the subject, I came across a helpful thread on [MacOSXHints.com](http://www.macosxhints.com/article.php?story=20060325015454467). Most of my answers below are based on that discussion. **Update 2:** I've incorporated the AppleScript on this page into the [widget][1]. It seems to be working swell.
Firefox (tested on versions 2.0.0.14 and 3.0.1): ``` tell application "Firefox" set myURL to «class curl» of window 1 return myURL end tell ```
263,743
<p>How do you get the caret position in a <code>&lt;textarea&gt;</code> using JavaScript?</p> <p>For example: <code>This is| a text</code></p> <p>This should return <code>7</code>.</p> <p>How would you get it to return the strings surrounding the cursor / selection?</p> <p>E.g.: <code>'This is', '', ' a text'</code>.</p> <p>If the word “is” is highlighted, then it would return <code>'This ', 'is', ' a text'</code>.</p>
[ { "answer_id": 263796, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 8, "selected": true, "text": "<p>With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:</p>\n\n<pre><code>function getCaret(node) {\n if (node.selectionStart) {\n return node.selectionStart;\n } else if (!document.selection) {\n return 0;\n }\n\n var c = \"\\001\",\n sel = document.selection.createRange(),\n dul = sel.duplicate(),\n len = 0;\n\n dul.moveToElementText(node);\n sel.text = c;\n len = dul.text.indexOf(c);\n sel.moveStart('character',-1);\n sel.text = \"\";\n return len;\n}\n</code></pre>\n\n<p>(<a href=\"http://web.archive.org/web/20080214051356/http://www.csie.ntu.edu.tw/~b88039/html/jslib/caret.html\" rel=\"noreferrer\">complete code here</a>)</p>\n\n<p>I also recommend you to check the jQuery <a href=\"https://github.com/localhost/jquery-fieldselection\" rel=\"noreferrer\">FieldSelection</a> Plugin, it allows you to do that and much more...</p>\n\n<p><strong>Edit:</strong> I actually re-implemented the above code: </p>\n\n<pre><code>function getCaret(el) { \n if (el.selectionStart) { \n return el.selectionStart; \n } else if (document.selection) { \n el.focus(); \n\n var r = document.selection.createRange(); \n if (r == null) { \n return 0; \n } \n\n var re = el.createTextRange(), \n rc = re.duplicate(); \n re.moveToBookmark(r.getBookmark()); \n rc.setEndPoint('EndToStart', re); \n\n return rc.text.length; \n } \n return 0; \n}\n</code></pre>\n\n<p>Check an example <a href=\"http://jsbin.com/iwopa\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 2735606, "author": "mark", "author_id": 328628, "author_profile": "https://Stackoverflow.com/users/328628", "pm_score": 2, "selected": false, "text": "<p>I modified the above function to account for carriage returns in IE. It's untested but I did something similar with it in my code so it should be workable.</p>\n\n<pre><code>function getCaret(el) {\n if (el.selectionStart) { \n return el.selectionStart; \n } else if (document.selection) { \n el.focus(); \n\n var r = document.selection.createRange(); \n if (r == null) { \n return 0; \n } \n\n var re = el.createTextRange(), \n rc = re.duplicate(); \n re.moveToBookmark(r.getBookmark()); \n rc.setEndPoint('EndToStart', re); \n\n var add_newlines = 0;\n for (var i=0; i&lt;rc.text.length; i++) {\n if (rc.text.substr(i, 2) == '\\r\\n') {\n add_newlines += 2;\n i++;\n }\n }\n\n //return rc.text.length + add_newlines;\n\n //We need to substract the no. of lines\n return rc.text.length - add_newlines; \n } \n return 0; \n}\n</code></pre>\n" }, { "answer_id": 3373056, "author": "Tim Down", "author_id": 96100, "author_profile": "https://Stackoverflow.com/users/96100", "pm_score": 6, "selected": false, "text": "<p><strong>Updated 5 September 2010</strong></p>\n\n<p>Seeing as everyone seems to get directed here for this issue, I'm adding my answer to a similar question, which contains the same code as this answer but with full background for those who are interested:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3622818/ies-document-selection-createrange-doesnt-include-leading-or-trailing-blank-li\">IE&#39;s document.selection.createRange doesn&#39;t include leading or trailing blank lines</a></p>\n\n<p>To account for trailing line breaks is tricky in IE, and I haven't seen any solution that does this correctly, including any other answers to this question. It is possible, however, using the following function, which will return you the start and end of the selection (which are the same in the case of a caret) within a <code>&lt;textarea&gt;</code> or text <code>&lt;input&gt;</code>.</p>\n\n<p>Note that the textarea must have focus for this function to work properly in IE. If in doubt, call the textarea's <code>focus()</code> method first.</p>\n\n<pre><code>function getInputSelection(el) {\n var start = 0, end = 0, normalizedValue, range,\n textInputRange, len, endRange;\n\n if (typeof el.selectionStart == \"number\" &amp;&amp; typeof el.selectionEnd == \"number\") {\n start = el.selectionStart;\n end = el.selectionEnd;\n } else {\n range = document.selection.createRange();\n\n if (range &amp;&amp; range.parentElement() == el) {\n len = el.value.length;\n normalizedValue = el.value.replace(/\\r\\n/g, \"\\n\");\n\n // Create a working TextRange that lives only in the input\n textInputRange = el.createTextRange();\n textInputRange.moveToBookmark(range.getBookmark());\n\n // Check if the start and end of the selection are at the very end\n // of the input, since moveStart/moveEnd doesn't return what we want\n // in those cases\n endRange = el.createTextRange();\n endRange.collapse(false);\n\n if (textInputRange.compareEndPoints(\"StartToEnd\", endRange) &gt; -1) {\n start = end = len;\n } else {\n start = -textInputRange.moveStart(\"character\", -len);\n start += normalizedValue.slice(0, start).split(\"\\n\").length - 1;\n\n if (textInputRange.compareEndPoints(\"EndToEnd\", endRange) &gt; -1) {\n end = len;\n } else {\n end = -textInputRange.moveEnd(\"character\", -len);\n end += normalizedValue.slice(0, end).split(\"\\n\").length - 1;\n }\n }\n }\n }\n\n return {\n start: start,\n end: end\n };\n}\n</code></pre>\n" }, { "answer_id": 34466831, "author": "Michał Perłakowski", "author_id": 3853934, "author_profile": "https://Stackoverflow.com/users/3853934", "pm_score": 2, "selected": false, "text": "<p>If you don't have to support IE, you can use <code>selectionStart</code> and <code>selectionEnd</code> attributes of <code>textarea</code>.</p>\n\n<p>To get caret position just use <code>selectionStart</code>:</p>\n\n<pre><code>function getCaretPosition(textarea) {\n return textarea.selectionStart\n}\n</code></pre>\n\n<p>To get the strings surrounding the selection, use following code:</p>\n\n<pre><code>function getSurroundingSelection(textarea) {\n return [textarea.value.substring(0, textarea.selectionStart)\n ,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)\n ,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]\n}\n</code></pre>\n\n<p><a href=\"https://jsfiddle.net/vs9Lpp23/\" rel=\"nofollow\">Demo on JSFiddle</a>.</p>\n\n<p>See also <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement\" rel=\"nofollow\">HTMLTextAreaElement docs</a>.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32941/" ]
How do you get the caret position in a `<textarea>` using JavaScript? For example: `This is| a text` This should return `7`. How would you get it to return the strings surrounding the cursor / selection? E.g.: `'This is', '', ' a text'`. If the word “is” is highlighted, then it would return `'This ', 'is', ' a text'`.
With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this: ``` function getCaret(node) { if (node.selectionStart) { return node.selectionStart; } else if (!document.selection) { return 0; } var c = "\001", sel = document.selection.createRange(), dul = sel.duplicate(), len = 0; dul.moveToElementText(node); sel.text = c; len = dul.text.indexOf(c); sel.moveStart('character',-1); sel.text = ""; return len; } ``` ([complete code here](http://web.archive.org/web/20080214051356/http://www.csie.ntu.edu.tw/~b88039/html/jslib/caret.html)) I also recommend you to check the jQuery [FieldSelection](https://github.com/localhost/jquery-fieldselection) Plugin, it allows you to do that and much more... **Edit:** I actually re-implemented the above code: ``` function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; } ``` Check an example [here](http://jsbin.com/iwopa).
263,748
<p>I normally store all my configs in the registry. Even though I have started using LINQ I would not like to have the DSN in the web.config, but rather let it stay in the registry and attach it (maybe in the Application Start Event) to the System Config.</p> <p>How can this be done?</p> <p>Thanx for any ideas!</p> <p>edit: to make it clear: I do not want to write to the web.config file, I just want to keep the dsn (encrypted) anywhere else than the web.config, so I have the same web.config on all development stages (local, staginf, live, backup).</p> <p>Christoph</p> <p><strong>Solution Code in VB.Net:</strong></p> <p>1) Add a new Class, with one method, which inherits from the original Datacontext:</p> <pre><code>Public Class MyDatabaseDataContext Inherits DatabaseDataContext Public Sub New() MyBase.New(Settings.DSN) End Sub End Class </code></pre> <p>2) Use this Class in all Linq Datasources instead of the original Context.</p> <pre><code> ContextTypeName="MyProject.MyDatabaseDataContext </code></pre>
[ { "answer_id": 264255, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>Why not just keep it encrypted in the web.config? It's fairly easy to encrypt just the connection strings in the web.config on <code>Application_Start</code>, if you don't want to use <code>aspreg_iis</code>. You can even edit the encrypted web.config afterwards using the IIS Admin tool.</p>\n\n<pre><code>Configuration config = WebConfigurationManager.OpenWebConfiguration(\n HttpContext.Current.Request.ApplicationPath );\nConfigurationSection section = config.Sections[\"connectionStrings\"];\nif (!section.SectionInformation.IsProtected\n &amp;&amp; !GlobalConfiguration.ApplicationVersion.EndsWith( \"dev\" )) // don't encrypt dev\n{\n section.SectionInformation.ProtectSection( \"DataProtectionConfigurationProvider\" );\n config.Save();\n}\n</code></pre>\n\n<p>If you must store it in the registry. You can always use the constructor on the DataContext that takes a connection string and pass in the value you read from the registry. Presumably you'd store this in the Application store so you only have to read from the registry once.</p>\n\n<p>Scott Guthrie has a good <a href=\"http://weblogs.asp.net/scottgu/archive/2006/01/09/434893.aspx\" rel=\"nofollow noreferrer\">references</a> page for encrypting your web config, though most of the examples use <code>aspreg_iis</code>. I prefer to do it on <code>Application_Start</code> so I don't forget to encrypt it on accident.</p>\n" }, { "answer_id": 265446, "author": "Keltex", "author_id": 28260, "author_profile": "https://Stackoverflow.com/users/28260", "pm_score": 2, "selected": true, "text": "<p>Here's what I do. I have a a base class for my DataContext. It's called DataContextBase and is generated by sqlmetal.exe. I have a derived class called DataContext which is what is used in my Linq calls. It looks like this:</p>\n\n<pre><code>public class DataContext : DataContextBase\n{\n public DataContext()\n : base(ConnectionHolder.ConnectionString)\n {\n }\n}\n</code></pre>\n\n<p>I have a static class in my library called ConnectionHolder which stores the connection string:</p>\n\n<pre><code>public static class ConnectionHolder\n{\n static string _ConnectionString;\n\n public static string ConnectionString\n {\n get { return _ConnectionString; }\n set { _ConnectionString = value; }\n }\n}\n</code></pre>\n\n<p>(note: this is separate from DataContext because there are places in my app outside of Linq that I use the connection string). At app startup I say ConnectionHolder.ConnectionString = (wherever you store the connection string).</p>\n" }, { "answer_id": 267907, "author": "Frank Schwieterman", "author_id": 32203, "author_profile": "https://Stackoverflow.com/users/32203", "pm_score": 0, "selected": false, "text": "<p>This is a fairly reasonable requirement when working with legacy code.</p>\n\n<p>The DataContext class is a partial class, so I just add a static factory method that loads the configuration setting and creates the datacontext result.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34464/" ]
I normally store all my configs in the registry. Even though I have started using LINQ I would not like to have the DSN in the web.config, but rather let it stay in the registry and attach it (maybe in the Application Start Event) to the System Config. How can this be done? Thanx for any ideas! edit: to make it clear: I do not want to write to the web.config file, I just want to keep the dsn (encrypted) anywhere else than the web.config, so I have the same web.config on all development stages (local, staginf, live, backup). Christoph **Solution Code in VB.Net:** 1) Add a new Class, with one method, which inherits from the original Datacontext: ``` Public Class MyDatabaseDataContext Inherits DatabaseDataContext Public Sub New() MyBase.New(Settings.DSN) End Sub End Class ``` 2) Use this Class in all Linq Datasources instead of the original Context. ``` ContextTypeName="MyProject.MyDatabaseDataContext ```
Here's what I do. I have a a base class for my DataContext. It's called DataContextBase and is generated by sqlmetal.exe. I have a derived class called DataContext which is what is used in my Linq calls. It looks like this: ``` public class DataContext : DataContextBase { public DataContext() : base(ConnectionHolder.ConnectionString) { } } ``` I have a static class in my library called ConnectionHolder which stores the connection string: ``` public static class ConnectionHolder { static string _ConnectionString; public static string ConnectionString { get { return _ConnectionString; } set { _ConnectionString = value; } } } ``` (note: this is separate from DataContext because there are places in my app outside of Linq that I use the connection string). At app startup I say ConnectionHolder.ConnectionString = (wherever you store the connection string).
263,782
<p>Currently I have subversion set up so that when I make changes in Eclipse PDT, I can commit the changes and they will be saved in /home/administrator/<em>Project File</em>. This file has the /branches /tags and /trunk directories recommended by subversion. I have no problem properly uploading files to the repository, but do I have to "mv" the files in Linux to /var/www in order to make them live on the server? Is there an automatic process to do this that I am missing? I'm assuming we don't want to make the /var/www directory (which is live on the machine) the repository, but I don't know.</p>
[ { "answer_id": 263791, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": true, "text": "<p>You can do an <code>svn export</code> into your www directory. That will give you a \"clean\" version of your repo, without the .svn directories.</p>\n\n<pre><code>cd /var/www\nsvn export /home/administrator/MyProject/trunk MyProject\n</code></pre>\n\n<hr>\n\n<p>Edit: adding in some good ideas from the comments...</p>\n\n<p>Some options for when you want to update your exported copy:</p>\n\n<ul>\n<li>run <code>svn export --force /home/...../ MyProject</code> this will stop it complaining about overwriting the existing files. This method will mean that if you delete a file from your repository, it'll still remain in your www folder.</li>\n<li>change your SVN command to export into a new directory each time:<br>\n<code>svn export /home/..../ MyProject_20081105</code><br>\nand then create a symlink to that folder:<br>\n<code>ln -s MyProject_20081105 MyProject</code><br>\nJust delete and recreate the symlink each time you \"release\". In this case, the export directory doesn't need to be in the <code>www</code> folder at all.</li>\n</ul>\n" }, { "answer_id": 263793, "author": "JamShady", "author_id": 11905, "author_profile": "https://Stackoverflow.com/users/11905", "pm_score": 2, "selected": false, "text": "<p>You can simply check out a copy of the repository in the /var/www folder, and then run <b>svn update</b> on it whenever you require (or switch it to a new branch/tag, etc). Thus you have one copy of the respository checked out on your local machine where you make changes and updates, and another copy on your webserver.</p>\n\n<p>Using an SVN repository also gives you the ability to revert to earlier versions as well.</p>\n" }, { "answer_id": 263812, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 1, "selected": false, "text": "<p>You can also make a post-commit hook that moves all the files changed by the commit to the /var/www directory.</p>\n\n<p>Here is an example written in python that uploads the changed files to a remote host via ftp:</p>\n\n<p><a href=\"http://svn.haxx.se/dev/archive-2007-08/0287.shtml\" rel=\"nofollow noreferrer\">http://svn.haxx.se/dev/archive-2007-08/0287.shtml</a></p>\n" }, { "answer_id": 263814, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 0, "selected": false, "text": "<p>You'll probably want to remember what files you have on production at any given time - so keep a \"release\" tag (e.g. in /project/tags/release). When you want to make a release, copy your trunk into there. Then svn export that release tag.</p>\n\n<p>Or something.</p>\n" }, { "answer_id": 263819, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>I've seen many people <a href=\"https://stackoverflow.com/questions/tagged/capistrano\">on here</a> and other forums talk about using <a href=\"http://www.capify.org/\" rel=\"nofollow noreferrer\">Capistrano</a> for deployment, but I don't have any personal experience with it.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27673/" ]
Currently I have subversion set up so that when I make changes in Eclipse PDT, I can commit the changes and they will be saved in /home/administrator/*Project File*. This file has the /branches /tags and /trunk directories recommended by subversion. I have no problem properly uploading files to the repository, but do I have to "mv" the files in Linux to /var/www in order to make them live on the server? Is there an automatic process to do this that I am missing? I'm assuming we don't want to make the /var/www directory (which is live on the machine) the repository, but I don't know.
You can do an `svn export` into your www directory. That will give you a "clean" version of your repo, without the .svn directories. ``` cd /var/www svn export /home/administrator/MyProject/trunk MyProject ``` --- Edit: adding in some good ideas from the comments... Some options for when you want to update your exported copy: * run `svn export --force /home/...../ MyProject` this will stop it complaining about overwriting the existing files. This method will mean that if you delete a file from your repository, it'll still remain in your www folder. * change your SVN command to export into a new directory each time: `svn export /home/..../ MyProject_20081105` and then create a symlink to that folder: `ln -s MyProject_20081105 MyProject` Just delete and recreate the symlink each time you "release". In this case, the export directory doesn't need to be in the `www` folder at all.
263,801
<p>I have 15 stored procedures that return data from a common table and then join that table with a specific table to retrieve inventory.</p> <p>Example:</p> <pre><code>Common: tblCommon Specific: tblSpecific </code></pre> <p>Is there way I can pass the name "tblSpecific" into a single stored procedure as a variable, like the following?</p> <pre><code>SELECT .... FROM tblCommon c INNER JOIN @TABLE s on c.primaryKey = s.foreignKey </code></pre>
[ { "answer_id": 263822, "author": "Eoin Campbell", "author_id": 30155, "author_profile": "https://Stackoverflow.com/users/30155", "pm_score": 2, "selected": false, "text": "<p>Yep, you can generate an SQL statement dynamically and then execute it.</p>\n\n<p>For example,</p>\n\n<pre><code>DECLARE @specificTableName nvarchar(50)\nDECLARE @specificColumnName nvarchar(50)\n\nSET @specificTableName = 'tblSpecific'\nSET @specificColumnName = 'colSpecific'\n\nDECLARE @sql nvarchar(4000)\n\nset @sql = 'SELECT ... FROM tblCommon c INNER JOIN ' +\n@specificTableName + ' s ON c.PrimaryKey = s.' + @specificColumnName\n\n\nexec (@sql)\n</code></pre>\n" }, { "answer_id": 263825, "author": "Peter M", "author_id": 31326, "author_profile": "https://Stackoverflow.com/users/31326", "pm_score": 4, "selected": false, "text": "<p>The way you do this is with dynamically generated SQL which is run through the sp_executesql() stored procedure.</p>\n\n<p>In general you pass in your required table name to your master procedure, build an ncharvar string of the SQL you want to execute, and pass that to sp_executesql. </p>\n\n<p><a href=\"http://www.sommarskog.se/dynamic_sql.html\" rel=\"noreferrer\">The curse and blessing of Dynamic SQL</a> is about the best page I have seen for describing all the in's and out's. </p>\n\n<p>One of the biggest gotchas is that if you use dynamic SQL then the user who calls your stored procedure not only has to have execute permission on that procedure, but also has to have permission to access the underlying tables. The link I gave also describes how to get around that issue.</p>\n" }, { "answer_id": 263830, "author": "John Lemp", "author_id": 12915, "author_profile": "https://Stackoverflow.com/users/12915", "pm_score": 0, "selected": false, "text": "<p>An alternative, if the amount of data isn't too large you may want want to consider a user defined function, which can return a table variable which you could use to join to.</p>\n\n<pre><code>SELECT ....\nFROM tblCommon c\nINNER JOIN dbo.SomeFuntionThatReturnsData(@someparam) s on c.primaryKey = s.foreignKey\n</code></pre>\n" }, { "answer_id": 264264, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>Dynamic SQL is dangerous. You <strong>never</strong> want to substitute passed values directly into an SQL string. Fortunately, it sounds like you already know that.</p>\n\n<p>Unfortunately, in this case you've discovered the problem that you can't use an SQL parameter for the table name. So, what to do? You don't want to use the passed value in dynamically generated SQL, but you can't put it in a query in the normal safe way.</p>\n\n<p>The answer is a lookup table. Create a 'tables' table that holds the name of each of your specific tables. It should look kind of like this:</p>\n\n<pre><code>CREATE TABLE [tables] (table_name sysname)\n</code></pre>\n\n<p>Then you can write a query that looks something like this:</p>\n\n<pre><code>SELECT @tblSpecific = table_name FROM [tables] WHERE table_name = @tblSpecific\n</code></pre>\n\n<p>Now you just have to check whether <code>@tblSpecific</code> is <code>NULL</code>. If it's not, then it's safe to use in a dynamic SQL statement (and dynamic SQL is ultimately your <em>only</em> option here: even the user defined function has you doing that at some level).</p>\n\n<p>Oh, and one more thing--my choice of names and types for the lookup table is not an accident. The SQL Standard already has a table like this (well, a view anyway). Just use <code>INFORMATION_SCHEMA.Tables</code>.</p>\n" }, { "answer_id": 264394, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 0, "selected": false, "text": "<p>I would save them each as a distinct stored procedure.</p>\n\n<p>As much as possible, I like to keep my stored procedures bare and simple. They're hard enough to grok with a glance, because the expressions stretch out so much anyway, and adding a bunch of procedural code intermingled with the fragments of declarative code just makes it more difficult.</p>\n\n<p>You're either going to end up with a list of 15 invocations of a more complex stored procedure with parameters, or you're going to end up with an equivalent list of simpler stored procedures. And if your parameter is a table name, it won't be the kind of parameterized sp that executes efficiently. As for the table driven approach, it is still the less efficient and more dangerous dynamic stored procedure. The table entries are as likely to be mis-entered, except in a table, any table-name errors would be even less visible. And coupling has gone up, and gohesiveness has gone down (both headed in the wrong direction).</p>\n" }, { "answer_id": 16689252, "author": "mugume david", "author_id": 692650, "author_profile": "https://Stackoverflow.com/users/692650", "pm_score": 1, "selected": false, "text": "<p>Formulate/manipulate your query as a string, then call <code>EXECUTE(@SQLStatement)</code></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have 15 stored procedures that return data from a common table and then join that table with a specific table to retrieve inventory. Example: ``` Common: tblCommon Specific: tblSpecific ``` Is there way I can pass the name "tblSpecific" into a single stored procedure as a variable, like the following? ``` SELECT .... FROM tblCommon c INNER JOIN @TABLE s on c.primaryKey = s.foreignKey ```
The way you do this is with dynamically generated SQL which is run through the sp\_executesql() stored procedure. In general you pass in your required table name to your master procedure, build an ncharvar string of the SQL you want to execute, and pass that to sp\_executesql. [The curse and blessing of Dynamic SQL](http://www.sommarskog.se/dynamic_sql.html) is about the best page I have seen for describing all the in's and out's. One of the biggest gotchas is that if you use dynamic SQL then the user who calls your stored procedure not only has to have execute permission on that procedure, but also has to have permission to access the underlying tables. The link I gave also describes how to get around that issue.
263,815
<p>I have a model being populated by my data layer and then I have a partial view which is rendering an instance of that model.</p> <pre><code>&lt;li class="&lt;%= td.Active ? "youarehere" : string.Empty %&gt; &lt;%= i == ViewData.Model.Count() - 1 ? "last" : string.Empty %&gt;"&gt; </code></pre> <p>The problem is that <code>class=""</code> is invalid XHTML and I will need more complex logic to output the class attribute. What would be the proper way to go about this using ASP.NET MVC. Should the logic live in the view or the model?</p> <p>I'm just starting out with MVC and I guess I'm still struggling on where exactly to draw the lines as far as where I put logic and what is an acceptable amount of logic for each layer to contain.</p>
[ { "answer_id": 263852, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 3, "selected": true, "text": "<p>I'd probably implement the code to render that class attribute in a helper method. Either one specific to this view, or one slightly more generic. That way you have less code in your view and it could handle whether or not to even render the class attribute in the case there's nothing to render.</p>\n" }, { "answer_id": 263908, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 0, "selected": false, "text": "<p>Alright, so based on Phil's input this is what I have done. It works. Please add a comment if there is any useful feedback that anyone has.</p>\n\n<ol>\n<li><p>I created a HtmlHelper extension method called GenerateAttribute. </p>\n\n<pre><code>public static string GenerateAttribute(this HtmlHelper hh,\n string name,\n Func&lt;string&gt; valueFunc)\n{ \n string value = valueFunc().Trim();\n if (!string.IsNullOrEmpty(value))\n return string.Format(\"{0}=\\\"{1}\\\"\", name, value);\n return string.Empty;\n}\n</code></pre></li>\n<li><p>From my View I call Html.GenerateAttribute, passing it a lambda expression that generates the value. The GenerateAttribute method will then return the full attribute (name=\"val\") if the value is not string.Empty.</p>\n\n<pre><code>&lt;li &lt;%= Html.GenerateAttribute(\"class\", () =&gt; string.Format(\"{0} {1}\", td.Active ? \"youarehere\" : string.Empty, i == ViewData.Model.Count() - 1 ? \"last\" : string.Empty)) %&gt;&gt;\n</code></pre></li>\n</ol>\n" }, { "answer_id": 264082, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 1, "selected": false, "text": "<p>An additional thing for this code would be to move the calculation work to a either the controller or the code-behind.</p>\n\n<p>i.e. replace</p>\n\n<pre><code>&lt;li &lt;%= Html.GenerateAttribute(\"class\", \n () =&gt; string.Format(\"{0} {1}\", td.Active \n ? \"youarehere\" : string.Empty, \n i == ViewData.Model.Count() - 1 \n ? \"last\" : string.Empty)) %&gt;&gt;\n</code></pre>\n\n<p>with something like</p>\n\n<pre><code>&lt;%= Html.ListItem( ViewData.Model.Value, \n GetItemCssClass(i, ViewData.Model.Count()) ) %&gt;\n</code></pre>\n\n<p>and GetItemCssClass could be in code-behind.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3957/" ]
I have a model being populated by my data layer and then I have a partial view which is rendering an instance of that model. ``` <li class="<%= td.Active ? "youarehere" : string.Empty %> <%= i == ViewData.Model.Count() - 1 ? "last" : string.Empty %>"> ``` The problem is that `class=""` is invalid XHTML and I will need more complex logic to output the class attribute. What would be the proper way to go about this using ASP.NET MVC. Should the logic live in the view or the model? I'm just starting out with MVC and I guess I'm still struggling on where exactly to draw the lines as far as where I put logic and what is an acceptable amount of logic for each layer to contain.
I'd probably implement the code to render that class attribute in a helper method. Either one specific to this view, or one slightly more generic. That way you have less code in your view and it could handle whether or not to even render the class attribute in the case there's nothing to render.
263,816
<p>Alright. I have a query that looks like this:</p> <pre><code>SELECT SUM(`order_items`.`quantity`) as `count`, `menu_items`.`name` FROM `orders`, `menu_items`, `order_items` WHERE `orders`.`id` = `order_items`.`order_id` AND `menu_items`.`id` = `order_items`.`menu_item_id` AND `orders`.`date` &gt;= '2008-11-01' AND `orders`.`date` &lt;= '2008-11-30' GROUP BY `menu_items`.`id` </code></pre> <p>The purpose of this query is to show the amount of items sold in a given date range. Although this works, I now need it to show a <code>count</code> of <code>0</code> if a particular item has no sales in the date range. I tried using <code>COALESCE</code> around the <code>SUM</code> but that didn't do the trick, and I didn't really expect it to. Anyhow, does anyone know how I would go about accomplishing this? I'm having one of those moments where I feel like I should know this but I can't think of it.</p> <p>Cheers</p>
[ { "answer_id": 263917, "author": "Jamie Love", "author_id": 27308, "author_profile": "https://Stackoverflow.com/users/27308", "pm_score": 2, "selected": false, "text": "<p>Randy's answer is close, but the where statement removes any mention of those items not part of any orders in that date range.</p>\n\n<p>Note that \"left join\" is different to linking tables in the where clause in the manner you have done (i.e. inner joins). I suggest you read up on the different types of SQL joins (inner, outer, cross).</p>\n\n<p>In essense, you need to join the data you get from Randy's query against your source list of items. Using a subselect will do this:</p>\n\n<pre><code>SELECT\n name\n , nvl(count, 0) as count\nFROM \n menu_items items \n LEFT JOIN (\n SELECT\n menu_items.id\n , SUM(order_items.quantity) as count\n FROM \n menu_items\n LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id\n LEFT JOIN orders ON orders.id = order_items.order_id\n WHERE\n \"date\" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')\n GROUP BY\n menu_items.id\n ) counts on items.id = counts.id;\n</code></pre>\n\n<p>This is in Oracle 10g BTW. I doubt you're using Oracle, so you'll need to convert to your own database.</p>\n\n<p>Running a test shows the following:</p>\n\n<pre><code>SQL&gt; create table menu_items ( id number, name varchar2(10));\ncreate table order_items (order_id number, menu_item_id number, quantity number);\ncreate table orders (id number, \"date\" date);\n\nTable created.\n\nSQL&gt; \nTable created.\n\nSQL&gt; \nTable created.\n\nSQL&gt; \ninsert into menu_items values (1, 'bread');\ninsert into menu_items values (2, 'milk');\ninsert into menu_items values (3, 'honey');\ninsert into menu_items values (4, 'cheese');\nSQL&gt; \n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; \ninsert into orders values (1, to_date('2008-11-02', 'YYYY-MM-DD'));\ninsert into orders values (2, to_date('2008-11-03', 'YYYY-MM-DD'));\ninsert into orders values (3, to_date('2008-10-29', 'YYYY-MM-DD'));SQL&gt; \n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; \ninsert into order_items values (1, 1, 1);\ninsert into order_items values (1, 3, 1);\n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; \ninsert into order_items values (2, 1, 1);\ninsert into order_items values (2, 2, 1);\ninsert into order_items values (2, 3, 1);\n\ninsert into order_items values (3, 4, 10);\n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; \n1 row created.\n\nSQL&gt; SQL&gt; \n\n1 row created.\n\nSQL&gt; \nSELECT\n name\n , nvl(count, 0) as count\nFROM \n menu_items items \n LEFT JOIN (\n SELECT\n menu_items.id\n , SUM(order_items.quantity) as count\n FROM \n menu_items\n LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id\n LEFT JOIN orders ON orders.id = order_items.order_id\n WHERE\n \"date\" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')\n GROUP BY\n menu_iteSQL&gt; 2 3 4 5 6 7 ms.id\n ) counts on items.id = counts.id; 8 9 10 11 12 13 14 15 16 17 18 \n\nNAME COUNT\n---------- ----------\nbread 2\nmilk 1\nhoney 2\ncheese 0\n\nSQL&gt; \ndrop table menu_items;\ndrop table order_items;\ndrop table orders;SQL&gt; \nTable dropped.\n\nSQL&gt; \nTable dropped.\n\nSQL&gt; \n\nTable dropped.\n\nSQL&gt; \n</code></pre>\n\n<p>PS: It's bad practice to use 'date' as a column name as it is (in most cases) a type name and can cause problems to queries and parses.</p>\n" }, { "answer_id": 263991, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "<p>This can be done without any subqueries, if one puts the date conditions in the <code>JOIN</code> clause. </p>\n\n<p>Below is code I tested on MySQL 5.0.</p>\n\n<pre><code>SELECT m.name, COALESCE(SUM(oi.quantity), 0) AS count\nFROM menu_items AS m\n LEFT OUTER JOIN (\n order_items AS oi JOIN orders AS o\n ON (o.id = oi.order_id)\n ) ON (m.id = oi.menu_item_id\n AND o.`date` BETWEEN '2008-11-01' AND '2008-11-30')\nGROUP BY m.id;\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>+--------+-------+\n| name | count |\n+--------+-------+\n| bread | 2 | \n| milk | 1 | \n| honey | 2 | \n| cheese | 0 | \n+--------+-------+\n</code></pre>\n\n<p>Here's the DDL and setup code, in the MySQL flavor:</p>\n\n<pre><code>DROP TABLE IF EXISTS menu_items;\nCREATE TABLE menu_items (\n id INT PRIMARY KEY,\n name VARCHAR(10)\n) TYPE=InnoDB;\n\nDROP TABLE IF EXISTS orders;\nCREATE TABLE orders (\n id INT PRIMARY KEY,\n `date` DATE\n) TYPE=InnoDB;\n\nDROP TABLE IF EXISTS order_items;\nCREATE TABLE order_items (\n order_id INT,\n menu_item_id INT,\n quantity INT,\n PRIMARY KEY (order_id, menu_item_id),\n FOREIGN KEY (order_id) REFERENCES orders(id),\n FOREIGN KEY (menu_item_id) REFERENCES menu_items(id)\n) TYPE=InnoDB;\n\nINSERT INTO menu_items VALUES\n (1, 'bread'),\n (2, 'milk'),\n (3, 'honey'),\n (4, 'cheese');\n\nINSERT INTO orders VALUES\n (1, '2008-11-02'),\n (2, '2008-11-03'),\n (3, '2008-10-29');\n\nINSERT INTO order_items VALUES\n (1, 1, 1),\n (1, 3, 1),\n (2, 1, 1),\n (2, 2, 1),\n (2, 3, 1),\n (3, 4, 10);\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16417/" ]
Alright. I have a query that looks like this: ``` SELECT SUM(`order_items`.`quantity`) as `count`, `menu_items`.`name` FROM `orders`, `menu_items`, `order_items` WHERE `orders`.`id` = `order_items`.`order_id` AND `menu_items`.`id` = `order_items`.`menu_item_id` AND `orders`.`date` >= '2008-11-01' AND `orders`.`date` <= '2008-11-30' GROUP BY `menu_items`.`id` ``` The purpose of this query is to show the amount of items sold in a given date range. Although this works, I now need it to show a `count` of `0` if a particular item has no sales in the date range. I tried using `COALESCE` around the `SUM` but that didn't do the trick, and I didn't really expect it to. Anyhow, does anyone know how I would go about accomplishing this? I'm having one of those moments where I feel like I should know this but I can't think of it. Cheers
This can be done without any subqueries, if one puts the date conditions in the `JOIN` clause. Below is code I tested on MySQL 5.0. ``` SELECT m.name, COALESCE(SUM(oi.quantity), 0) AS count FROM menu_items AS m LEFT OUTER JOIN ( order_items AS oi JOIN orders AS o ON (o.id = oi.order_id) ) ON (m.id = oi.menu_item_id AND o.`date` BETWEEN '2008-11-01' AND '2008-11-30') GROUP BY m.id; ``` Output: ``` +--------+-------+ | name | count | +--------+-------+ | bread | 2 | | milk | 1 | | honey | 2 | | cheese | 0 | +--------+-------+ ``` Here's the DDL and setup code, in the MySQL flavor: ``` DROP TABLE IF EXISTS menu_items; CREATE TABLE menu_items ( id INT PRIMARY KEY, name VARCHAR(10) ) TYPE=InnoDB; DROP TABLE IF EXISTS orders; CREATE TABLE orders ( id INT PRIMARY KEY, `date` DATE ) TYPE=InnoDB; DROP TABLE IF EXISTS order_items; CREATE TABLE order_items ( order_id INT, menu_item_id INT, quantity INT, PRIMARY KEY (order_id, menu_item_id), FOREIGN KEY (order_id) REFERENCES orders(id), FOREIGN KEY (menu_item_id) REFERENCES menu_items(id) ) TYPE=InnoDB; INSERT INTO menu_items VALUES (1, 'bread'), (2, 'milk'), (3, 'honey'), (4, 'cheese'); INSERT INTO orders VALUES (1, '2008-11-02'), (2, '2008-11-03'), (3, '2008-10-29'); INSERT INTO order_items VALUES (1, 1, 1), (1, 3, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 4, 10); ```
263,820
<p>The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?</p> <p>As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes <code>devenv</code> without the necessary context.</p> <pre><code>os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86') os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt') </code></pre> <p>think of it as in i'm in bash, and i need to execute a command in a perl context, so i type <code>perl -c 'asdf'</code>. executing perl and asdf back to back won't work, i need to get the <code>devenv</code> inside of the perl context.</p>
[ { "answer_id": 263856, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You could append the devenv command onto the end of the original batch file like so:</p>\n\n<pre><code>'%comspec% /k \"...vcvarsall.bat\" x86 &amp;&amp; devenv asdf.sln /rebuild ...'\n</code></pre>\n\n<p>(obviously I have shortened the commands for simplicity's sake)</p>\n" }, { "answer_id": 263881, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": 3, "selected": true, "text": "<p>I these situations I use script that does it all. That way you can chain as much as you want. Sometimes I will generate the script on the fly.</p>\n\n<pre><code>compileit.cmd\n call C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\n devenv $1.sln /rebuild Debug /Out last-build.txt\n</code></pre>\n" }, { "answer_id": 288734, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 2, "selected": false, "text": "<p>I run my Python script from a batch file that sets the variables :-)</p>\n\n<pre><code>call ...\\vcvarsall.bat\nc:\\python26\\python.exe myscript.py\n</code></pre>\n\n<p>But Brett's solution sounds better.</p>\n" }, { "answer_id": 1237505, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 2, "selected": false, "text": "<p>I think that the proper way for achieving this would be running this command:</p>\n\n<pre><code>%comspec% /C \"%VCINSTALLDIR%\\vcvarsall.bat\" x86 &amp;&amp; vcbuild \"project.sln\"\n</code></pre>\n\n<p>Below you'll see the Python version of the same command:</p>\n\n<pre><code>os.system('%comspec% /C \"%VCINSTALLDIR%\\\\vcvarsall.bat\" x86 &amp;&amp; vcbuild \"project.sln\"')\n</code></pre>\n\n<p>This should work with any Visual Studio so it would be a good idea to edit the question to make it more generic.</p>\n\n<p>There is a small problem I found regarding the location of vcvarsall.bat - Because VCINSTALLDIR is not always set, you have to use the registry entries in order to detect the location where it is installer:</p>\n\n<pre><code>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0]\n\"InstallDir\"=\"c:\\\\Program Files\\\\Microsoft Visual Studio 9.0\\\\Common7\\\\IDE\\\\\"\n</code></pre>\n\n<p>Add <code>..\\..\\VC\\vcvarsall.bat</code> to this path. Also is a good idea to test for other versions of Visual Studio.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20003/" ]
The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python? As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes `devenv` without the necessary context. ``` os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86') os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt') ``` think of it as in i'm in bash, and i need to execute a command in a perl context, so i type `perl -c 'asdf'`. executing perl and asdf back to back won't work, i need to get the `devenv` inside of the perl context.
I these situations I use script that does it all. That way you can chain as much as you want. Sometimes I will generate the script on the fly. ``` compileit.cmd call C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat devenv $1.sln /rebuild Debug /Out last-build.txt ```
263,834
<p>I just lost 50% of my answer on a test because I wrote the code out instead of an algorithm on my midterm, bumping me from an A to a C. Is writing code out still considered an algorithmic representation?</p> <p><a href="http://en.wikipedia.org/wiki/Algorithm#Expressing_algorithms" rel="nofollow noreferrer">Wikipedia: Algorithm Representation</a> (since programming style is pretty much consensus-based)</p> <p>EDIT: Ok, so let me make a few points clear: </p> <ol> <li><p>The test asked for pseudo-code, which we never really "defined" in class; we just wrote out English for our algorithms.</p></li> <li><p>It's a Java class, and wrote out the entire solution in a Java method, along with comments. All of this was hand-written, and took longer to write out than pseudo-code. I thought it would be more clear.</p></li> <li><p>I normally wouldn't make an issue about such things, but it's the difference between an A and a C, and I have a scholarship riding on my exams.</p></li> <li><p>Finally, I'm making this post for two reasons:</p> <p>4.1 I want to show what the modern programming community thinks about pseudo-code and algorithmic representation.</p> <p>4.2 I want to know what's acceptable in the "real world"; I've been programming for some time, but I want to be able to contribute to open-source projects soon, and I don't want to step on anyone's toes. (Although I'm pretty sure that this topic has little chance of coming up in the real world).</p></li> </ol> <p>Again, thanks for any help/advice.</p>
[ { "answer_id": 263842, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>All I know is you shouldn't write any code until after you have an algorithim.</p>\n" }, { "answer_id": 263854, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "<p>You may want to give an example. If your code focuses too much on language specifics that are not part of the algorithm, then Understandably, it could be said you had non-algorithm mixed with your algorithm, resulting in an incorrect result. </p>\n\n<p>I Feel for the reasoning, the whole point of learning is to show you understand the concept, not to bend over and tick all the right boxes. </p>\n\n<p>A computer can be taught to pass university, but a computer cant be yet taught to actually think for itself and apply knowledge. </p>\n\n<p>Eat and regurgitate mentality is why I never graduated. </p>\n\n<hr>\n\n<p>With respect to your recent comment, its important to realise pseudocode is undefined. There are generally reused terms in it, but its not a strict language any more than english is ( otherwise it would <em>be</em> a programming language, which could be parsed and executed verbatim ) </p>\n\n<p>The <strong>importance</strong> of pseudocode is to flesh out the <em>logic</em> part of the system and not have to worry overly about the syntax beyond 'it makes sense' </p>\n\n<p>Often this can make the pseudocode both more <em>terse</em> <strong>and</strong> more understandable. </p>\n\n<p>Pseudocode also doesn't rely on the reader having an understanding of the 'magic syntax' in the language in order to process it, all they need to understand is the terms used.</p>\n\n<p>If you were to give the average person an algorithm in perl for example, most people would just die from horror because they don't see past the screeds of line noise. </p>\n\n<p>While: </p>\n\n<pre><code>sub foo { \n my @args = @_ ; \n my( $a, $b )=(@args[0],@args[1]); \n for( @{ $a } ){\n $b .= $_ ; \n s/id//g; \n }\n return [$b,$a];\n}\n</code></pre>\n\n<p>may make some coherent sence to somebody versed in perl, to the average code reader all they get is a \"what the hell did you just say\" response. Documenting it doesn't help a lot either. </p>\n\n<pre><code>| there is a subroute foo which can take a list of strings, and a default string, \n\\- which then iterates all items in that list, \n| \\- and for each item in that list \n| 1. appends the contents of that item to the end of the default string\n| 2. removes all instances of the string \"id\" in that item\n| \n \\ and returns a list, which contains \n 1. the concatentated default string \n 2. the modified input list \n</code></pre>\n\n<p>Suddenly it becomes less ambiguous and a greater percentage of peoples can understand it. </p>\n\n<p>So possibly, half the exercise with writing the algorithm is an exercise in \"Not only do you have to prove you understand it, you also have to prove you can explain your reasoning to others whom know nothing of the problem\" , which is a vital ability you need. If you can't communicate what you have done, nobody can use it. </p>\n\n<p><sub>there's also this nasty little problem with code, that doesn't exist in an algorithm, and that is the code may <em>look</em> right, but may not do what you <em>think</em> it does, and if it doesn't do it right, and you don't realise, people reading the code reverse engineering it will foul it up and copy a <em>broken</em> algorithm. not good. the algorithm in human form better translates 'this is what i want it do do' </sub></p>\n" }, { "answer_id": 263866, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 2, "selected": false, "text": "<p>In this case, you have to defer to the professor.</p>\n" }, { "answer_id": 263882, "author": "AticusFinch", "author_id": 34479, "author_profile": "https://Stackoverflow.com/users/34479", "pm_score": 0, "selected": false, "text": "<p>The problem with using code instead of pseudocode is that, theoretically speaking, one could assume that it was code, not pseudocode. Anyway, the teacher grades you for your response, not for your knowledge - you would be better off answering what you were asked for, in the terms the teacher likes. Yes, we all know, you know better. But it is never a bad exercise to try to reason another person's way, you know. And at least in my country the teacher has the right to evaluate you freely, so... get along with him!</p>\n" }, { "answer_id": 263915, "author": "Huntrods", "author_id": 33977, "author_profile": "https://Stackoverflow.com/users/33977", "pm_score": 2, "selected": false, "text": "<p>You need to supply more information. You were asked for an algorithm, but supplied code. Did you comment the code? How much? (I'd like to see the question and your answer, but perhaps that's requesting too much).</p>\n\n<p>So I'll answer based on my own experience. If I'm asking for an algorithm, then I want something that explains, in decent english, how to solve the problem and/or meet the requirements of the question. Diagrams are also good (sometimes better). Paragraph, point form, whatever - it just needs to be clear, concise and correct.</p>\n\n<p>If you supply me with code that does the above, then full marks. However, if you supply code that is pure \"language\" and rather cryptic, then marks will be lost - more or less depending on how cryptic the code actually is. Even with code, I'd like to see a diagram as well, just to show complete understanding of the concepts.</p>\n\n<p>One of the hardest things I face when teaching programming is in getting students to write MORE, not less. Sometimes I have had to remind them that an assignment (or exam) is not an entry in the \"most obfuscated code contest\". ;-)</p>\n\n<p>Cheers,</p>\n\n<p>-R</p>\n" }, { "answer_id": 264047, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": 0, "selected": false, "text": "<p>Just talk to your professor and ask him why you got the question wrong. Ask him what a right answer would be, and what the fundamental difference is between the two.</p>\n\n<p>Could it be that the algorithm you wrote wasn't correct?</p>\n" }, { "answer_id": 264114, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 0, "selected": false, "text": "<p>Code is an algorithm written so that a machine may execute it. There's nothing in that definition that says it's not also written for a human to understand. Did writing in Java obscure your algorithm? That would determine whether I agreed with your teacher.</p>\n" }, { "answer_id": 288086, "author": "Scott Wegner", "author_id": 33791, "author_profile": "https://Stackoverflow.com/users/33791", "pm_score": 2, "selected": false, "text": "<p>As a grader for an advanced algorithms course, I would <em>always</em> take off points if there is simply a coded solution.</p>\n\n<p>Some things simply cannot be expressed as eloquently in code as they can in English. Pseudo-code is an attempt to break free of strict compiler syntax and allow some expressiveness. It's a step in the right direction of understandability, but not always enough.</p>\n\n<p>Especially in an algorithms class, it's always important to provide a proof of correctness (whether it be by induction, contradiction, etc.), as well as a big-O notation for the space- and time- complexity of your algorithm.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10636/" ]
I just lost 50% of my answer on a test because I wrote the code out instead of an algorithm on my midterm, bumping me from an A to a C. Is writing code out still considered an algorithmic representation? [Wikipedia: Algorithm Representation](http://en.wikipedia.org/wiki/Algorithm#Expressing_algorithms) (since programming style is pretty much consensus-based) EDIT: Ok, so let me make a few points clear: 1. The test asked for pseudo-code, which we never really "defined" in class; we just wrote out English for our algorithms. 2. It's a Java class, and wrote out the entire solution in a Java method, along with comments. All of this was hand-written, and took longer to write out than pseudo-code. I thought it would be more clear. 3. I normally wouldn't make an issue about such things, but it's the difference between an A and a C, and I have a scholarship riding on my exams. 4. Finally, I'm making this post for two reasons: 4.1 I want to show what the modern programming community thinks about pseudo-code and algorithmic representation. 4.2 I want to know what's acceptable in the "real world"; I've been programming for some time, but I want to be able to contribute to open-source projects soon, and I don't want to step on anyone's toes. (Although I'm pretty sure that this topic has little chance of coming up in the real world). Again, thanks for any help/advice.
You may want to give an example. If your code focuses too much on language specifics that are not part of the algorithm, then Understandably, it could be said you had non-algorithm mixed with your algorithm, resulting in an incorrect result. I Feel for the reasoning, the whole point of learning is to show you understand the concept, not to bend over and tick all the right boxes. A computer can be taught to pass university, but a computer cant be yet taught to actually think for itself and apply knowledge. Eat and regurgitate mentality is why I never graduated. --- With respect to your recent comment, its important to realise pseudocode is undefined. There are generally reused terms in it, but its not a strict language any more than english is ( otherwise it would *be* a programming language, which could be parsed and executed verbatim ) The **importance** of pseudocode is to flesh out the *logic* part of the system and not have to worry overly about the syntax beyond 'it makes sense' Often this can make the pseudocode both more *terse* **and** more understandable. Pseudocode also doesn't rely on the reader having an understanding of the 'magic syntax' in the language in order to process it, all they need to understand is the terms used. If you were to give the average person an algorithm in perl for example, most people would just die from horror because they don't see past the screeds of line noise. While: ``` sub foo { my @args = @_ ; my( $a, $b )=(@args[0],@args[1]); for( @{ $a } ){ $b .= $_ ; s/id//g; } return [$b,$a]; } ``` may make some coherent sence to somebody versed in perl, to the average code reader all they get is a "what the hell did you just say" response. Documenting it doesn't help a lot either. ``` | there is a subroute foo which can take a list of strings, and a default string, \- which then iterates all items in that list, | \- and for each item in that list | 1. appends the contents of that item to the end of the default string | 2. removes all instances of the string "id" in that item | \ and returns a list, which contains 1. the concatentated default string 2. the modified input list ``` Suddenly it becomes less ambiguous and a greater percentage of peoples can understand it. So possibly, half the exercise with writing the algorithm is an exercise in "Not only do you have to prove you understand it, you also have to prove you can explain your reasoning to others whom know nothing of the problem" , which is a vital ability you need. If you can't communicate what you have done, nobody can use it. there's also this nasty little problem with code, that doesn't exist in an algorithm, and that is the code may *look* right, but may not do what you *think* it does, and if it doesn't do it right, and you don't realise, people reading the code reverse engineering it will foul it up and copy a *broken* algorithm. not good. the algorithm in human form better translates 'this is what i want it do do'
263,836
<p>We are using an Oracle 11 database and a java development environment (using Eclipse) and would like to migrate several xml schemas to SQL schemas.</p> <p>Have looked ax xsd but really need something that we can run from ant/ Eclipse without SQL Server installed.</p> <p>Regards,</p> <p>Andy</p>
[ { "answer_id": 263842, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>All I know is you shouldn't write any code until after you have an algorithim.</p>\n" }, { "answer_id": 263854, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": true, "text": "<p>You may want to give an example. If your code focuses too much on language specifics that are not part of the algorithm, then Understandably, it could be said you had non-algorithm mixed with your algorithm, resulting in an incorrect result. </p>\n\n<p>I Feel for the reasoning, the whole point of learning is to show you understand the concept, not to bend over and tick all the right boxes. </p>\n\n<p>A computer can be taught to pass university, but a computer cant be yet taught to actually think for itself and apply knowledge. </p>\n\n<p>Eat and regurgitate mentality is why I never graduated. </p>\n\n<hr>\n\n<p>With respect to your recent comment, its important to realise pseudocode is undefined. There are generally reused terms in it, but its not a strict language any more than english is ( otherwise it would <em>be</em> a programming language, which could be parsed and executed verbatim ) </p>\n\n<p>The <strong>importance</strong> of pseudocode is to flesh out the <em>logic</em> part of the system and not have to worry overly about the syntax beyond 'it makes sense' </p>\n\n<p>Often this can make the pseudocode both more <em>terse</em> <strong>and</strong> more understandable. </p>\n\n<p>Pseudocode also doesn't rely on the reader having an understanding of the 'magic syntax' in the language in order to process it, all they need to understand is the terms used.</p>\n\n<p>If you were to give the average person an algorithm in perl for example, most people would just die from horror because they don't see past the screeds of line noise. </p>\n\n<p>While: </p>\n\n<pre><code>sub foo { \n my @args = @_ ; \n my( $a, $b )=(@args[0],@args[1]); \n for( @{ $a } ){\n $b .= $_ ; \n s/id//g; \n }\n return [$b,$a];\n}\n</code></pre>\n\n<p>may make some coherent sence to somebody versed in perl, to the average code reader all they get is a \"what the hell did you just say\" response. Documenting it doesn't help a lot either. </p>\n\n<pre><code>| there is a subroute foo which can take a list of strings, and a default string, \n\\- which then iterates all items in that list, \n| \\- and for each item in that list \n| 1. appends the contents of that item to the end of the default string\n| 2. removes all instances of the string \"id\" in that item\n| \n \\ and returns a list, which contains \n 1. the concatentated default string \n 2. the modified input list \n</code></pre>\n\n<p>Suddenly it becomes less ambiguous and a greater percentage of peoples can understand it. </p>\n\n<p>So possibly, half the exercise with writing the algorithm is an exercise in \"Not only do you have to prove you understand it, you also have to prove you can explain your reasoning to others whom know nothing of the problem\" , which is a vital ability you need. If you can't communicate what you have done, nobody can use it. </p>\n\n<p><sub>there's also this nasty little problem with code, that doesn't exist in an algorithm, and that is the code may <em>look</em> right, but may not do what you <em>think</em> it does, and if it doesn't do it right, and you don't realise, people reading the code reverse engineering it will foul it up and copy a <em>broken</em> algorithm. not good. the algorithm in human form better translates 'this is what i want it do do' </sub></p>\n" }, { "answer_id": 263866, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 2, "selected": false, "text": "<p>In this case, you have to defer to the professor.</p>\n" }, { "answer_id": 263882, "author": "AticusFinch", "author_id": 34479, "author_profile": "https://Stackoverflow.com/users/34479", "pm_score": 0, "selected": false, "text": "<p>The problem with using code instead of pseudocode is that, theoretically speaking, one could assume that it was code, not pseudocode. Anyway, the teacher grades you for your response, not for your knowledge - you would be better off answering what you were asked for, in the terms the teacher likes. Yes, we all know, you know better. But it is never a bad exercise to try to reason another person's way, you know. And at least in my country the teacher has the right to evaluate you freely, so... get along with him!</p>\n" }, { "answer_id": 263915, "author": "Huntrods", "author_id": 33977, "author_profile": "https://Stackoverflow.com/users/33977", "pm_score": 2, "selected": false, "text": "<p>You need to supply more information. You were asked for an algorithm, but supplied code. Did you comment the code? How much? (I'd like to see the question and your answer, but perhaps that's requesting too much).</p>\n\n<p>So I'll answer based on my own experience. If I'm asking for an algorithm, then I want something that explains, in decent english, how to solve the problem and/or meet the requirements of the question. Diagrams are also good (sometimes better). Paragraph, point form, whatever - it just needs to be clear, concise and correct.</p>\n\n<p>If you supply me with code that does the above, then full marks. However, if you supply code that is pure \"language\" and rather cryptic, then marks will be lost - more or less depending on how cryptic the code actually is. Even with code, I'd like to see a diagram as well, just to show complete understanding of the concepts.</p>\n\n<p>One of the hardest things I face when teaching programming is in getting students to write MORE, not less. Sometimes I have had to remind them that an assignment (or exam) is not an entry in the \"most obfuscated code contest\". ;-)</p>\n\n<p>Cheers,</p>\n\n<p>-R</p>\n" }, { "answer_id": 264047, "author": "Cybis", "author_id": 32998, "author_profile": "https://Stackoverflow.com/users/32998", "pm_score": 0, "selected": false, "text": "<p>Just talk to your professor and ask him why you got the question wrong. Ask him what a right answer would be, and what the fundamental difference is between the two.</p>\n\n<p>Could it be that the algorithm you wrote wasn't correct?</p>\n" }, { "answer_id": 264114, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 0, "selected": false, "text": "<p>Code is an algorithm written so that a machine may execute it. There's nothing in that definition that says it's not also written for a human to understand. Did writing in Java obscure your algorithm? That would determine whether I agreed with your teacher.</p>\n" }, { "answer_id": 288086, "author": "Scott Wegner", "author_id": 33791, "author_profile": "https://Stackoverflow.com/users/33791", "pm_score": 2, "selected": false, "text": "<p>As a grader for an advanced algorithms course, I would <em>always</em> take off points if there is simply a coded solution.</p>\n\n<p>Some things simply cannot be expressed as eloquently in code as they can in English. Pseudo-code is an attempt to break free of strict compiler syntax and allow some expressiveness. It's a step in the right direction of understandability, but not always enough.</p>\n\n<p>Especially in an algorithms class, it's always important to provide a proof of correctness (whether it be by induction, contradiction, etc.), as well as a big-O notation for the space- and time- complexity of your algorithm.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34469/" ]
We are using an Oracle 11 database and a java development environment (using Eclipse) and would like to migrate several xml schemas to SQL schemas. Have looked ax xsd but really need something that we can run from ant/ Eclipse without SQL Server installed. Regards, Andy
You may want to give an example. If your code focuses too much on language specifics that are not part of the algorithm, then Understandably, it could be said you had non-algorithm mixed with your algorithm, resulting in an incorrect result. I Feel for the reasoning, the whole point of learning is to show you understand the concept, not to bend over and tick all the right boxes. A computer can be taught to pass university, but a computer cant be yet taught to actually think for itself and apply knowledge. Eat and regurgitate mentality is why I never graduated. --- With respect to your recent comment, its important to realise pseudocode is undefined. There are generally reused terms in it, but its not a strict language any more than english is ( otherwise it would *be* a programming language, which could be parsed and executed verbatim ) The **importance** of pseudocode is to flesh out the *logic* part of the system and not have to worry overly about the syntax beyond 'it makes sense' Often this can make the pseudocode both more *terse* **and** more understandable. Pseudocode also doesn't rely on the reader having an understanding of the 'magic syntax' in the language in order to process it, all they need to understand is the terms used. If you were to give the average person an algorithm in perl for example, most people would just die from horror because they don't see past the screeds of line noise. While: ``` sub foo { my @args = @_ ; my( $a, $b )=(@args[0],@args[1]); for( @{ $a } ){ $b .= $_ ; s/id//g; } return [$b,$a]; } ``` may make some coherent sence to somebody versed in perl, to the average code reader all they get is a "what the hell did you just say" response. Documenting it doesn't help a lot either. ``` | there is a subroute foo which can take a list of strings, and a default string, \- which then iterates all items in that list, | \- and for each item in that list | 1. appends the contents of that item to the end of the default string | 2. removes all instances of the string "id" in that item | \ and returns a list, which contains 1. the concatentated default string 2. the modified input list ``` Suddenly it becomes less ambiguous and a greater percentage of peoples can understand it. So possibly, half the exercise with writing the algorithm is an exercise in "Not only do you have to prove you understand it, you also have to prove you can explain your reasoning to others whom know nothing of the problem" , which is a vital ability you need. If you can't communicate what you have done, nobody can use it. there's also this nasty little problem with code, that doesn't exist in an algorithm, and that is the code may *look* right, but may not do what you *think* it does, and if it doesn't do it right, and you don't realise, people reading the code reverse engineering it will foul it up and copy a *broken* algorithm. not good. the algorithm in human form better translates 'this is what i want it do do'
263,838
<p>I usually type my map declarations but was doing some maint and found one without typing. This got me thinking (Oh No!). What is the default typing of a Map declaration. Consider the following:</p> <pre><code>Map map = new HashMap(); map.put("one", "1st"); map.put("two", new Integer(2)); map.put("three", "3rd"); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " -&gt; " + entry.getValue()); } </code></pre> <p>this errors with a incompatible types on Map.Entry. So if I type the declaration with:</p> <pre><code>Map&lt;Object, Object&gt; map = new HashMap(); </code></pre> <p>then all works well. So what is the default type that gets set in the declaration about? Or am I missing something else?</p>
[ { "answer_id": 263861, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 3, "selected": false, "text": "<p>There is no default type.</p>\n\n<p>The types in Java generics are only for compile-time checking. They are erased at runtime and essentially gone.</p>\n\n<p>Think of generics as a static helper to a) better document your code, and b) enable some limited compile-time checking for type safety.</p>\n" }, { "answer_id": 263864, "author": "WolfmanDragon", "author_id": 13491, "author_profile": "https://Stackoverflow.com/users/13491", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html\" rel=\"nofollow noreferrer\">HashMap</a> is a collection of objects, Think C++ containers. Each element of the map is a \"bucket\" to hold data.<br>\nYou are putting different types of data in the buckets, the hashmap needs to know that these are not all the same data type. If only one type of data was placed in the hashmap, you would get a warning but it would compile. </p>\n" }, { "answer_id": 263903, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 3, "selected": true, "text": "<p>The type is <em>java.lang.Object</em>.</p>\n\n<p>The <em>for</em> construct takes a type of <em>Iterable</em> and calls its <em>iterator</em> method. Since the <em>Set</em> isn't typed with generics, the iterator returns objects of type <em>Object</em>. These need to be explicitly cast to type <em>Map.Entry</em>.</p>\n\n<pre><code>Map map = new HashMap();\nmap.put(\"one\", \"1st\");\nmap.put(\"two\", new Integer(2));\nmap.put(\"three\", \"3rd\");\nfor (Object o : map.entrySet()) {\n Map.Entry entry = (Map.Entry) o;\n System.out.println(entry.getKey() + \" -&gt; \" + entry.getValue());\n}\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34475/" ]
I usually type my map declarations but was doing some maint and found one without typing. This got me thinking (Oh No!). What is the default typing of a Map declaration. Consider the following: ``` Map map = new HashMap(); map.put("one", "1st"); map.put("two", new Integer(2)); map.put("three", "3rd"); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } ``` this errors with a incompatible types on Map.Entry. So if I type the declaration with: ``` Map<Object, Object> map = new HashMap(); ``` then all works well. So what is the default type that gets set in the declaration about? Or am I missing something else?
The type is *java.lang.Object*. The *for* construct takes a type of *Iterable* and calls its *iterator* method. Since the *Set* isn't typed with generics, the iterator returns objects of type *Object*. These need to be explicitly cast to type *Map.Entry*. ``` Map map = new HashMap(); map.put("one", "1st"); map.put("two", new Integer(2)); map.put("three", "3rd"); for (Object o : map.entrySet()) { Map.Entry entry = (Map.Entry) o; System.out.println(entry.getKey() + " -> " + entry.getValue()); } ```
263,850
<p>Is there a way to create a Distinct query in HQL. Either by using the "distinct" keyword or some other method. I am not sure if distinct is a valid keywork for HQL, but I am looking for the HQL equivalent of the SQL keyword "distinct".</p>
[ { "answer_id": 263870, "author": "Feet", "author_id": 18340, "author_profile": "https://Stackoverflow.com/users/18340", "pm_score": 8, "selected": true, "text": "<p>Here's a snippet of hql that we use. (Names have been changed to protect identities)</p>\n\n<pre><code>String queryString = \"select distinct f from Foo f inner join foo.bars as b\" +\n \" where f.creationDate &gt;= ? and f.creationDate &lt; ? and b.bar = ?\";\n return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar});\n</code></pre>\n" }, { "answer_id": 313052, "author": "Daniel Alexiuc", "author_id": 34553, "author_profile": "https://Stackoverflow.com/users/34553", "pm_score": 6, "selected": false, "text": "<p>It's worth noting that the <code>distinct</code> keyword in HQL does not map directly to the <code>distinct</code> keyword in SQL. </p>\n\n<p>If you use the <code>distinct</code> keyword in HQL, then sometimes Hibernate will use the <code>distinct</code> SQL keyword, but in some situations it will use a result transformer to produce distinct results. For example when you are using an outer join like this:</p>\n\n<pre><code>select distinct o from Order o left join fetch o.lineItems\n</code></pre>\n\n<p>It is not possible to filter out duplicates at the SQL level in this case, so Hibernate uses a <code>ResultTransformer</code> to filter duplicates <strong>after</strong> the SQL query has been performed.</p>\n" }, { "answer_id": 920256, "author": "Tadeusz Kopec for Ukraine", "author_id": 113662, "author_profile": "https://Stackoverflow.com/users/113662", "pm_score": 2, "selected": false, "text": "<p>I had some problems with result transformers combined with HQL queries. When I tried </p>\n\n<pre><code>final ResultTransformer trans = new DistinctRootEntityResultTransformer();\nqry.setResultTransformer(trans);\n</code></pre>\n\n<p>it didn't work. I had to transform manually like this:</p>\n\n<pre><code>final List found = trans.transformList(qry.list());\n</code></pre>\n\n<p>With Criteria API transformers worked just fine.</p>\n" }, { "answer_id": 6065843, "author": "Michael", "author_id": 699058, "author_profile": "https://Stackoverflow.com/users/699058", "pm_score": 4, "selected": false, "text": "<p>do something like this next time </p>\n\n<pre><code> Criteria crit = (Criteria) session.\n createCriteria(SomeClass.class).\n setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\n List claz = crit.list();\n</code></pre>\n" }, { "answer_id": 15025242, "author": "San Lin Naing", "author_id": 2099561, "author_profile": "https://Stackoverflow.com/users/2099561", "pm_score": 1, "selected": false, "text": "<p>I have got a answer for Hibernate Query Language to use Distinct fields.\nYou can use *SELECT DISTINCT(TO_CITY) FROM FLIGHT_ROUTE*.\nIf you use <em>SQL</em> query, it return String List. You can't use it return value by Entity Class.\nSo the Answer to solve that type of Problem is use <em>HQL</em> with <em>SQL</em>.</p>\n\n<pre><code>FROM FLIGHT_ROUTE F WHERE F.ROUTE_ID IN (SELECT SF.ROUTE_ID FROM FLIGHT_ROUTE SF GROUP BY SF.TO_CITY);\n</code></pre>\n\n<p>From <em>SQL</em> query statement it got DISTINCT ROUTE_ID and input as a List.\nAnd IN query filter the distinct TO_CITY from IN (List).</p>\n\n<p>Return type is Entity Bean type.\nSo you can it in AJAX such as <em>AutoComplement</em>.</p>\n\n<p>May all be OK</p>\n" }, { "answer_id": 25310246, "author": "aadi53", "author_id": 3941677, "author_profile": "https://Stackoverflow.com/users/3941677", "pm_score": 3, "selected": false, "text": "<p>You can also use <code>Criteria.DISTINCT_ROOT_ENTITY</code> with Hibernate HQL query as well.</p>\n\n<p>Example:</p>\n\n<pre><code>Query query = getSession().createQuery(\"from java_pojo_name\");\nquery.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\nreturn query.list();\n</code></pre>\n" }, { "answer_id": 26720538, "author": "Nathan Mitchell", "author_id": 4211430, "author_profile": "https://Stackoverflow.com/users/4211430", "pm_score": 2, "selected": false, "text": "<p>My main query looked like this in the model:</p>\n\n<pre><code>@NamedQuery(name = \"getAllCentralFinancialAgencyAccountCd\", \n query = \"select distinct i from CentralFinancialAgencyAccountCd i\")\n</code></pre>\n\n<p>And I was still not getting what I considered \"distinct\" results. They were just distinct based on a primary key combination on the table.</p>\n\n<p>So in the <code>DaoImpl</code> I added an one line change and ended up getting the \"distinct\" return I wanted. An example would be instead of seeing 00 four times I now just see it once. Here is the code I added to the <code>DaoImpl</code>:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic List&lt;CacheModelBase&gt; getAllCodes() {\n\n Session session = (Session) entityManager.getDelegate();\n org.hibernate.Query q = session.getNamedQuery(\"getAllCentralFinancialAgencyAccountCd\");\n q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // This is the one line I had to add to make it do a more distinct query.\n List&lt;CacheModelBase&gt; codes;\n codes = q.list();\n return codes; \n}\n</code></pre>\n\n<p>I hope this helped! Once again, this might only work if you are following coding practices that implement the service, dao, and model type of project.</p>\n" }, { "answer_id": 30194486, "author": "chammu", "author_id": 1960964, "author_profile": "https://Stackoverflow.com/users/1960964", "pm_score": 2, "selected": false, "text": "<p>Suppose you have a Customer Entity mapped to CUSTOMER_INFORMATION table and you want to get list of distinct firstName of customer. You can use below snippet to get the same.</p>\n\n<pre><code>Query distinctFirstName = session.createQuery(\"select ci.firstName from Customer ci group by ci.firstName\");\nObject [] firstNamesRows = distinctFirstName.list();\n</code></pre>\n\n<p>I hope it helps. So here we are using group by instead of using distinct keyword. </p>\n\n<p>Also previously I found it difficult to use distinct keyword when I want to apply it to multiple columns. For example I want of get list of distinct firstName, lastName then group by would simply work. I had difficulty in using distinct in this case.</p>\n" }, { "answer_id": 51945678, "author": "Santosh Singh", "author_id": 2733355, "author_profile": "https://Stackoverflow.com/users/2733355", "pm_score": 2, "selected": false, "text": "<p>You can you the distinct keyword in you criteria builder like this.</p>\n\n<pre><code>CriteriaBuilder builder = session.getCriteriaBuilder();\nCriteriaQuery&lt;Orders&gt; query = builder.createQuery(Orders.class);\nRoot&lt;Orders&gt; root = query.from(Orders.class);\nquery.distinct(true).multiselect(root.get(\"cust_email\").as(String.class));\n</code></pre>\n\n<p>And create the field constructor in your model class.</p>\n" }, { "answer_id": 61722212, "author": "Manish Sharma", "author_id": 3994713, "author_profile": "https://Stackoverflow.com/users/3994713", "pm_score": 0, "selected": false, "text": "<p>If you need to use <strong>new</strong> keyword for a custom DTO in your select statement and need <strong>distinct elements</strong>, use new outside of new like as follows-</p>\n\n<pre><code>select distinct new com.org.AssetDTO(a.id, a.address, a.status) from Asset as a where ...\n</code></pre>\n" }, { "answer_id": 62042727, "author": "Rustem", "author_id": 9708287, "author_profile": "https://Stackoverflow.com/users/9708287", "pm_score": 0, "selected": false, "text": "<p>You can simply add GROUP BY instead of Distinct</p>\n\n<pre><code>@Query(value = \"from someTableEntity where entityCode in :entityCode\" +\n \" group by entityCode, entityName, entityType\")\nList&lt;someTableEntity &gt; findNameByCode(@Param(\"entityCode\") List&lt;String&gt; entityCode);\n</code></pre>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16404/" ]
Is there a way to create a Distinct query in HQL. Either by using the "distinct" keyword or some other method. I am not sure if distinct is a valid keywork for HQL, but I am looking for the HQL equivalent of the SQL keyword "distinct".
Here's a snippet of hql that we use. (Names have been changed to protect identities) ``` String queryString = "select distinct f from Foo f inner join foo.bars as b" + " where f.creationDate >= ? and f.creationDate < ? and b.bar = ?"; return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar}); ```
263,890
<p>As a simple example, I want to write a CLI script which can print <code>=</code> across the entire width of the terminal window.</p> <pre><code>#!/usr/bin/env php &lt;?php echo str_repeat('=', ???); </code></pre> <p>or</p> <pre><code>#!/usr/bin/env python print '=' * ??? </code></pre> <p>or</p> <pre><code>#!/usr/bin/env bash x=0 while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo </code></pre>
[ { "answer_id": 263900, "author": "TonyUser", "author_id": 22873, "author_profile": "https://Stackoverflow.com/users/22873", "pm_score": 10, "selected": true, "text": "<ul>\n<li><code>tput cols</code> tells you the number of columns.</li>\n<li><code>tput lines</code> tells you the number of rows.</li>\n</ul>\n" }, { "answer_id": 263919, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 4, "selected": false, "text": "<pre><code>yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\\n'\n</code></pre>\n" }, { "answer_id": 563592, "author": "David Dean", "author_id": 67829, "author_profile": "https://Stackoverflow.com/users/67829", "pm_score": 7, "selected": false, "text": "<p>In bash, the <code>$LINES</code> and <code>$COLUMNS</code> environmental variables should be able to do the trick. The will be set automatically upon any change in the terminal size. (i.e. the <a href=\"http://en.wikipedia.org/wiki/SIGWINCH\" rel=\"noreferrer\">SIGWINCH</a> signal)</p>\n" }, { "answer_id": 7575044, "author": "lyceus", "author_id": 967809, "author_profile": "https://Stackoverflow.com/users/967809", "pm_score": 4, "selected": false, "text": "<p>To do this in Windows CLI environment, the best way I can find is to use the mode command and parse the output.</p>\n\n<pre><code>function getTerminalSizeOnWindows() {\n $output = array();\n $size = array('width'=&gt;0,'height'=&gt;0);\n exec('mode',$output);\n foreach($output as $line) {\n $matches = array();\n $w = preg_match('/^\\s*columns\\:?\\s*(\\d+)\\s*$/i',$line,$matches);\n if($w) {\n $size['width'] = intval($matches[1]);\n } else {\n $h = preg_match('/^\\s*lines\\:?\\s*(\\d+)\\s*$/i',$line,$matches);\n if($h) {\n $size['height'] = intval($matches[1]);\n }\n }\n if($size['width'] AND $size['height']) {\n break;\n }\n }\n return $size;\n}\n</code></pre>\n\n<p>I hope it's useful!</p>\n\n<p><strong>NOTE</strong>: The height returned is the number of lines in the buffer, it is not the number of lines that are visible within the window. Any better options out there?</p>\n" }, { "answer_id": 10081642, "author": "LeoNerd", "author_id": 1069726, "author_profile": "https://Stackoverflow.com/users/1069726", "pm_score": 4, "selected": false, "text": "<p>On POSIX, ultimately you want to be invoking the <code>TIOCGWINSZ</code> (Get WINdow SiZe) <code>ioctl()</code> call. Most languages ought to have some sort of wrapper for that. E.g in Perl you can use <a href=\"http://search.cpan.org/perldoc?Term::Size\" rel=\"noreferrer\">Term::Size</a>:</p>\n\n<pre><code>use Term::Size qw( chars );\n\nmy ( $columns, $rows ) = chars \\*STDOUT;\n</code></pre>\n" }, { "answer_id": 21190143, "author": "Camilo Martin", "author_id": 124119, "author_profile": "https://Stackoverflow.com/users/124119", "pm_score": 2, "selected": false, "text": "<p>As I mentioned in lyceus answer, his code will fail on non-English locale Windows because then the output of <code>mode</code> may not contain the substrings \"columns\" or \"lines\":</p>\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src=\"https://i.stack.imgur.com/qwUgY.png\" alt=\"mode command output\"></p>\n\n<p>You can find the correct substring without looking for text:</p>\n\n<pre><code> preg_match('/---+(\\n[^|]+?){2}(?&lt;cols&gt;\\d+)/', `mode`, $matches);\n $cols = $matches['cols'];\n</code></pre>\n\n<p>Note that I'm not even bothering with lines because it's unreliable (and I actually don't care about them).</p>\n\n<p><strong>Edit:</strong> According to comments about Windows 8 (oh you...), I think this may be more reliable:</p>\n\n<pre><code> preg_match('/CON.*:(\\n[^|]+?){3}(?&lt;cols&gt;\\d+)/', `mode`, $matches);\n $cols = $matches['cols'];\n</code></pre>\n\n<p>Do test it out though, because I didn't test it.</p>\n" }, { "answer_id": 26855761, "author": "ryenus", "author_id": 537554, "author_profile": "https://Stackoverflow.com/users/537554", "pm_score": 7, "selected": false, "text": "<p>And there's <code>stty</code>, see <a href=\"https://www.gnu.org/software/coreutils/manual/html_node/stty-invocation.html\" rel=\"noreferrer\">stty: Print or change terminal characteristics</a>, more specifically <a href=\"https://www.gnu.org/software/coreutils/manual/html_node/Special.html\" rel=\"noreferrer\">Special settings</a></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ stty size\n60 120 # &lt;= sample output\n\n# To read into variables, in bash\n$ read -r rows cols &lt; &lt;(stty size)\n$ echo &quot;rows: $rows, cols: $cols&quot;\nrows: 60, cols: 120\n</code></pre>\n<p>It will print the number of rows and columns, or height and width, respectively.</p>\n<p>Or you can use either <code>cut</code> or <code>awk</code> to extract the part you want.</p>\n<p>That's <code>stty size | cut -d&quot; &quot; -f1</code> for the height/lines and <code>stty size | cut -d&quot; &quot; -f2</code> for the width/columns</p>\n" }, { "answer_id": 49876367, "author": "huoneusto", "author_id": 1814589, "author_profile": "https://Stackoverflow.com/users/1814589", "pm_score": 2, "selected": false, "text": "<p>Inspired by @pixelbeat's answer, here's a horizontal bar brought to existence by <code>tput</code>, slight misuse of <code>printf</code> padding/filling and <code>tr</code> </p>\n\n<pre><code>printf \"%0$(tput cols)d\" 0|tr '0' '='\n</code></pre>\n" }, { "answer_id": 54008767, "author": "pourhaus", "author_id": 3558322, "author_profile": "https://Stackoverflow.com/users/3558322", "pm_score": 1, "selected": false, "text": "<p>There are some cases where your rows/LINES and columns do not match the actual size of the \"terminal\" being used. Perhaps you may not have a \"tput\" or \"stty\" available.</p>\n\n<p>Here is a bash function you can use to visually check the size. This will work up to 140 columns x 80 rows. You can adjust the maximums as needed.</p>\n\n<pre><code>function term_size\n{\n local i=0 digits='' tens_fmt='' tens_args=()\n for i in {80..8}\n do\n echo $i $(( i - 2 ))\n done\n echo \"If columns below wrap, LINES is first number in highest line above,\"\n echo \"If truncated, LINES is second number.\"\n for i in {1..14}\n do\n digits=\"${digits}1234567890\"\n tens_fmt=\"${tens_fmt}%10d\"\n tens_args=(\"${tens_args[@]}\" $i)\n done\n printf \"$tens_fmt\\n\" \"${tens_args[@]}\"\n echo \"$digits\"\n}\n</code></pre>\n" }, { "answer_id": 68085512, "author": "Odin Kroeger", "author_id": 1523367, "author_profile": "https://Stackoverflow.com/users/1523367", "pm_score": 2, "selected": false, "text": "<h1>Getting the window width</h1>\n<p>This shell code makes a global variable <code>$TERM_SIZE</code> track the size of the terminal window:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>set_term_size() {\n TERM_SIZE=&quot;$(stty size 2&gt;/dev/null)&quot; &amp;&amp; [ &quot;$TERM_SIZE&quot; ] ||\n TERM_SIZE='25 80'\n}\ntrap set_term_size WINCH\nset_term_size\n</code></pre>\n<p>It tries <code>stty size</code> before falling back to assuming that the terminal is 25 lines high and 80 characters wide. POSIX does <em>not</em> mandate the <code>size</code> operand for <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/utilities/stty.html\" rel=\"nofollow noreferrer\"><code>stty</code></a>`, so the fallback is needed.</p>\n<p>You can then access the columsn argument by using the shell's limited string substitution capabilities:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>echo &quot;${TERM_SIZE% *}&quot; # Prints the terminal's height.\necho &quot;${TERM_SIZE#* }&quot; # Prints the terminal's width.\n</code></pre>\n<p>Of course, the scripting language you use likely offers a library that takes care of that for you -- and you should use it.</p>\n<h1>Printing a line</h1>\n<p>Once you know the width of the terminal, printing a horizontal line is easy, for example, by abusing <code>printf</code>'s string padding:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>printf '%*s\\n' &quot;${TERM_SIZE#* }&quot; '' | \ntr ' ' -\n</code></pre>\n<p>The first line tells <code>printf</code> to print as many spaces as there are columns (by abusing string paddin) to a pipe. Note, POSIX does <em>not</em> mention the <code>*</code> syntax, so this may not be as portable as the code above.</p>\n<p>The second line tells <code>tr</code> to read from that pipe and replace every space with a hypen.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28835/" ]
As a simple example, I want to write a CLI script which can print `=` across the entire width of the terminal window. ``` #!/usr/bin/env php <?php echo str_repeat('=', ???); ``` or ``` #!/usr/bin/env python print '=' * ??? ``` or ``` #!/usr/bin/env bash x=0 while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo ```
* `tput cols` tells you the number of columns. * `tput lines` tells you the number of rows.
263,892
<p>I'm using Gnome terminal and I want to change the background color or the profile through a command so I can group some commands in an alias to visually differentiate my windows when I run certain processes. I'm running Ubuntu, and bash is my shell. Are there commands in to do this?</p>
[ { "answer_id": 263928, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>I used to do this with command line arguments to xterm. I set up my .olvwm (am I dating myself) to execute 4 xterms with different background colours.</p>\n" }, { "answer_id": 263957, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>Assuming you know what profile you want before you open your terminal:</p>\n\n<p>Right-click on your Panel and \"Add to Panel\" and add a custom application launcher</p>\n\n<p>You can define position, size and profile (which takes care of colours, fonts, etc)</p>\n\n<pre><code>gnome-terminal --hide-menubar --geometry 115x40+0+0\ngnome-terminal --window-with-profile=logs --hide-menubar --geometry=144x15+0-55\n</code></pre>\n\n<p>\"man gnome-terminal\" has lots of useful information</p>\n" }, { "answer_id": 263971, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You want to use gconftool.</p>\n\n<p>Gnome holds its settings in a hierarchy similar to the Windows Registry. Once you know the path to the item you want to change you can set that item's value with gconftool from the command line.</p>\n\n<p>Use gconf-editor to browse through the Gnome settings.<br/>Use gconftool to set the value of an item in your script.</p>\n\n<p>In your case, you want to do the following:</p>\n\n<pre>\ngconftool --type string --set /desktop/gnome/background/primary_color \"#dadab0b08282\"\n</pre>\n\n<p>Obviously you'll want to replace that color value with whatever color you want.</p>\n" }, { "answer_id": 624812, "author": "Kai", "author_id": 75458, "author_profile": "https://Stackoverflow.com/users/75458", "pm_score": 1, "selected": false, "text": "<p>I looked into it and it turns out this is not possible. I filed bug:\n<a href=\"http://bugzilla.gnome.org/show_bug.cgi?id=569869\" rel=\"nofollow noreferrer\">http://bugzilla.gnome.org/show_bug.cgi?id=569869</a></p>\n\n<p>gconftool-2 can get/set profile properties, but there is no way to script an existing, open gnome-terminal.</p>\n" }, { "answer_id": 1936387, "author": "Zeograd", "author_id": 232849, "author_profile": "https://Stackoverflow.com/users/232849", "pm_score": 4, "selected": false, "text": "<p>you can use setterm like this</p>\n\n<pre><code>setterm -term linux -back blue -fore white -clear\n</code></pre>\n" }, { "answer_id": 7605564, "author": "serxyz", "author_id": 972339, "author_profile": "https://Stackoverflow.com/users/972339", "pm_score": 2, "selected": false, "text": "<p>1) Create a terminal profile with the color and settings you desire, and call it \"myGterm\"<br>\n2) Edit your <code>.bashrc</code> file.<br>\n3) Add the following line:<br></p>\n\n<pre><code>alias Gterm='gnome-terminal --window-with-profile=myGterm'\n</code></pre>\n\n<p>4) Save and close <code>.bashrc</code><br>\n5) Open a terminal and type:</p>\n\n<pre><code>$ Gterm\n</code></pre>\n\n<p>6) Voila!</p>\n" }, { "answer_id": 14059620, "author": "Jonathan Chad Faling", "author_id": 1894837, "author_profile": "https://Stackoverflow.com/users/1894837", "pm_score": 1, "selected": false, "text": "<p>To create 4 terminals with different backgrounds and titles you need to add the below lines to the .bashrc_profile file</p>\n\n<pre><code>$.bash_profile\n</code></pre>\n\n<p>add the below lines to file</p>\n\n<pre><code>alias term1='gnome-terminal –window-with-profile=term1'\nalias term2='gnome-terminal –window-with-profile=term2'\nalias term3='gnome-terminal –window-with-profile=term3'\nalias term4='gnome-terminal –window-with-profile=term4'\n</code></pre>\n\n<ol>\n<li>Now edit / create your 4 terminal profiles</li>\n<li>open > terminal > edit > profiles > new > profile name = term1</li>\n<li>colors tab > choose your font and background colors</li>\n<li>Title and Command tab > initial title = term1</li>\n<li>repeat the above commands for 3 remaining terminals.</li>\n</ol>\n\n<p>close any open terminals you may have then re-open a new terminal and type 'term1' hit enter and repeat for all 4 now you have 4 unique terminals open!</p>\n" }, { "answer_id": 18397919, "author": "wessexmario", "author_id": 2710224, "author_profile": "https://Stackoverflow.com/users/2710224", "pm_score": 2, "selected": false, "text": "<p>try the following command from a desktop launcher:</p>\n\n<pre><code>gnome-terminal --window-with-profile=site2 -x ssh site2\n</code></pre>\n\n<p>Using <code>-x ssh</code> means that the terminal will only be active on the remote site, so completely removing the possibility of typing a command on the wrong machine because you've exited from a terminal command line ssh.</p>\n" }, { "answer_id": 35316936, "author": "Joniale", "author_id": 5842403, "author_profile": "https://Stackoverflow.com/users/5842403", "pm_score": 0, "selected": false, "text": "<p>i have created some functions, based on github code from other threads. Sorry i don't remember.</p>\n\n<p>You can put these functions in your ~/.bashrc file</p>\n\n<p>As you can see, if you call \"create_random_profile\", </p>\n\n<p>First, it will check and delte any previous random profile you have created.</p>\n\n<p>Second, it will create a random name profile in gnome terminals.</p>\n\n<p>Third, it will set that name in an environment variable that you can use to change your color in predefined functions. See last function function setcolord().</p>\n\n<p>This should be useful, to have many terminals with different colors. Besides, with predefined functions you can change these colors on the fly.\nEnjoy it!</p>\n\n<pre><code> function create_random_profile() {\n #delete previous profiles in case there were something\n #delete_one_random_profile\n prof=\"`mktemp -u HACK_PROFILE_XXXXXXXXXX`\"\n gconftool-2 --type list --list-type string --set $prof_list \"`gconftool-2 --get $prof_list | sed \"s/]/,$prof]/\"`\"\n file=\"`mktemp`\"\n gconftool-2 --dump \"/apps/gnome-terminal/profiles/Default\" | sed \"s,profiles/$2,profiles/$prof,g\" &gt; \"$file\"\n gconftool-2 --load \"$file\"\n gconftool-2 --type string --set \"/apps/gnome-terminal/profiles/$prof/visible_name\" \"$prof\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$prof/use_theme_colors\" --type bool false\n rm -f -- \"$file\"\n export __TERM_PROF=$prof\n }\n\n function delete_one_random_profile() {\n regular=\"HACK_PROFILE_\"\n prof=$(gconftool-2 --get /apps/gnome-terminal/global/profile_list | sed -n \"s/.*\\(HACK_PROFILE_..........\\).*/\\1/p\") \n if [ ! -z \"$prof\"]; then\n echo \"size ${#prof}\"\n echo \"size of regular ${#regular}\"\n echo \"DO DELETE of $prof\"\n #if not empty\n gconftool-2 --type list --list-type string --set $prof_list \"`gconftool-2 --get $prof_list | sed \"s/$prof//;s/\\[,/[/;s/,,/,/;s/,]/]/\"`\"\n gconftool-2 --unset \"/apps/gnome-terminal/profiles/$prof\"\n else\n echo \"NOTHING TO DELETE\"\n fi\n }\n\n function setcolord() \n {\n echo \"Dont forget to change to Profile0 in the menu of your terminal-&gt;Change Profile-&gt;Profile_0\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/background_color\" --type string white\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/foreground_color\" --type string black\n }\n function setcolor_cyan() \n {\n echo \"Dont forget to change to $__TERM_PROF in the menu of your terminal-&gt;Change Profile-&gt;Profile_0\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/background_color\" --type string \"#8DCBCC\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/foreground_color\" --type string black\n }\n</code></pre>\n\n<p>By the way you can save time if you create the terminal using already the random. You can do that calling:</p>\n\n<pre><code>gnome-terminal --working-directory=$HOME --window-with-profile=\"$prof\" \n</code></pre>\n" }, { "answer_id": 52582839, "author": "Christopher M", "author_id": 10438003, "author_profile": "https://Stackoverflow.com/users/10438003", "pm_score": 1, "selected": false, "text": "<p>You don't have to do this via command you can go to Edit>>Preferences>>color to change it.</p>\n" }, { "answer_id": 58581072, "author": "Maurizio Omissoni", "author_id": 6396839, "author_profile": "https://Stackoverflow.com/users/6396839", "pm_score": -1, "selected": false, "text": "<p>well, xterm has direct methods to change colours, fonts and size:</p>\n\n<p>xterm -bg Blue1 -fg white -fa 'Monospace' -fs 9 </p>\n\n<p>why use gnome-terminal?</p>\n" }, { "answer_id": 58657948, "author": "Beginer", "author_id": 8691290, "author_profile": "https://Stackoverflow.com/users/8691290", "pm_score": -1, "selected": false, "text": "<pre><code>sudo apt-get install dconf-cli uuid-runtime\nbash -c \"$(wget -qO- https://git.io/vQgMr)\"\n</code></pre>\n\n<p>Select theme you want by enter the number <a href=\"http://mayccoll.github.io/Gogh/\" rel=\"nofollow noreferrer\">Gogh - Color Scheme</a></p>\n" }, { "answer_id": 69015595, "author": "Tschallacka", "author_id": 1356107, "author_profile": "https://Stackoverflow.com/users/1356107", "pm_score": 2, "selected": false, "text": "<p>In the gnome terminal on ubuntu 20lts you can run a command like:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>echo -e '\\e]11;rgb:aa/bb/cc\\a'\n</code></pre>\n<p>where <strong>aa</strong>, <strong>bb</strong>, <strong>cc</strong> are hexadecimal numbers from 0 to 255.</p>\n<p>If you wish to change the foreground color, use <code>\\e]10;</code> instead of <code>\\e]11;</code></p>\n<p>To get the correct color commands you can use the color pickers in the snippet below.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let bg = document.getElementById('bg');\nlet fg = document.getElementById('fg');\nlet binp = document.getElementById('numberbg');\nlet finp = document.getElementById('numberfg');\n\nbinp.addEventListener('input', (e) =&gt; {\n let val = spl(e);\n bg.innerText = \"echo -e '\\\\e]11;rgb:\"+val+\"\\\\a'\"; \n up(bg); up(fg);\n});\n\nfinp.addEventListener('input', (e) =&gt; {\n let val = spl(e);;\n fg.innerText = \"echo -e '\\\\e]10;rgb:\"+val+\"\\\\a'\";\n up(bg); up(fg);\n});\n\nfunction spl(e) { \n return e.target.value.substring(1).match(/.{1,2}/g).join('/');\n}\n\nfunction up(i) {\n i.style.backgroundColor = binp.value;\n i.style.color = finp.value;\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>code {\n margin: 20px;\n background: #ddd;\n border: 1px solid #333;\n padding:20px;\n clear:both;\n display: inline-block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;\n &lt;label for=\"numberbg\"&gt;set background: &lt;/label&gt;\n &lt;input id=\"numberbg\" type=\"color\" value=\"#000000\"&gt; &lt;BR&gt;\n &lt;code id=\"bg\"&gt;\n echo -e '\\e]11;rgb:00/00/00\\a'\n &lt;/code&gt;\n&lt;/div&gt;\n&lt;div&gt;\n &lt;label for=\"numberfg\"&gt;set foreground: &lt;/label&gt;\n &lt;input id=\"numberfg\" type=\"color\" value=\"#eeeeee\"&gt; &lt;BR&gt;\n &lt;code id=\"fg\"&gt;\n echo -e '\\e]10;rgb:ee/ee/ee\\a'\n &lt;/code&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using Gnome terminal and I want to change the background color or the profile through a command so I can group some commands in an alias to visually differentiate my windows when I run certain processes. I'm running Ubuntu, and bash is my shell. Are there commands in to do this?
you can use setterm like this ``` setterm -term linux -back blue -fore white -clear ```
263,899
<p>I have been searching for a way to allow one element of my FileHelpers mapping class to be an array of specific length.</p> <p>For instance, I have a class like this:</p> <pre><code>[DelimitedRecord(",")] public class Example { public string code; public int month; public int day; public double h1; public double h2; public double h3; public double h4; } </code></pre> <p>The values h1-h4 would really make more sense as an array simply called 'h'. It would make processing the file a little easier as well. I also know that the file I am reading will always have these, and only these, fields in it.</p> <p>Has anyone figured out a way to include arrays in your FileHelper mapping classes?</p>
[ { "answer_id": 264500, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>I don't know anything about the tool in question, but (assuming it isn't a limitation of the tool) I <em>really</em> doubt the wisdom of public fields. Properties would also give you the opportunity to shim the values:</p>\n\n<pre><code>[DelimitedRecord(\",\")]\npublic class Example\n{\n public string Code {get;set;}\n public int Month {get;set;}\n public int Day {get;set;}\n\n private readonly double[] h = new double[4];\n\n public double H1 {get {return h[0];} set {h[0] = value;}}\n public double H2 {get {return h[1];} set {h[1] = value;}}\n public double H3 {get {return h[2];} set {h[2] = value;}}\n public double H4 {get {return h[3];} set {h[3] = value;}}\n}\n</code></pre>\n\n<p>Again - I have no idea if the tool would support this, but it would be a viable way of implementing it. Of course, the \"h\" values would do just as well (actually, slightly more efficient - no array on the heap and no de-reference) as direct members:</p>\n\n<pre><code> public double H1 {get;set;}\n public double H2 {get;set;}\n public double H3 {get;set;}\n public double H4 {get;set;}\n</code></pre>\n" }, { "answer_id": 13187743, "author": "shamp00", "author_id": 1077279, "author_profile": "https://Stackoverflow.com/users/1077279", "pm_score": 1, "selected": false, "text": "<p>FileHelpers record classes require public fields. The record class should not be considered as a normal C# class that should follow best coding practices; rather it is just a syntax for describing an import file's structure. </p>\n\n<p>The recommended procedure with FileHelpers would be to loop through the resulting <code>Example[]</code> array and map the fields you need to a more normal class (with properties instead of public fields). At this point you can copy your H1-H4 values to an array property instead.</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23597/" ]
I have been searching for a way to allow one element of my FileHelpers mapping class to be an array of specific length. For instance, I have a class like this: ``` [DelimitedRecord(",")] public class Example { public string code; public int month; public int day; public double h1; public double h2; public double h3; public double h4; } ``` The values h1-h4 would really make more sense as an array simply called 'h'. It would make processing the file a little easier as well. I also know that the file I am reading will always have these, and only these, fields in it. Has anyone figured out a way to include arrays in your FileHelper mapping classes?
FileHelpers record classes require public fields. The record class should not be considered as a normal C# class that should follow best coding practices; rather it is just a syntax for describing an import file's structure. The recommended procedure with FileHelpers would be to loop through the resulting `Example[]` array and map the fields you need to a more normal class (with properties instead of public fields). At this point you can copy your H1-H4 values to an array property instead.
263,901
<p>I have a local MINICPAN repository, but I want to remove a specific version of a module, and inject an older version.</p> <p>This is the steps I've taken.</p> <pre><code>- create the MINICPAN, not filtering any modules - use mcpani --add for the module in question - use mcpani --inject </code></pre> <p>At this point, I can see in the MINICPAN that it has both the version I want, and the newer version, if I issue install in cpan, then the newer version of the module is install. How can I get rid of the newer version from my minicpan?</p>
[ { "answer_id": 264173, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "<p>Doesn't filtering out the module initially work?</p>\n" }, { "answer_id": 264393, "author": "brian d foy", "author_id": 2766176, "author_profile": "https://Stackoverflow.com/users/2766176", "pm_score": 4, "selected": true, "text": "<p>Filter the modules that you are going to inject. The <a href=\"http://search.cpan.org/dist/CPAN-Mini\" rel=\"nofollow noreferrer\">CPAN::Mini</a> has the documentation for filtering, and I think I had some examples in the resources I pointed you toward earlier. :)</p>\n\n<p>If you already have the minicpan, as you said in the comment to ysth, you can create <em>another</em> minicpan from that one. The \"remote\" CPAN in that case is the one that you have. I do that all the time: I have a canonical minicpan, but then for testing things, I filter from that to create new repositories just so I don't have to deal with the network.</p>\n" }, { "answer_id": 20340540, "author": "Jeffrey Ryan Thalhammer", "author_id": 1229730, "author_profile": "https://Stackoverflow.com/users/1229730", "pm_score": 0, "selected": false, "text": "<p>Another strategy would be to use <a href=\"https://metacpan.org/pod/Pinto\" rel=\"nofollow\">Pinto</a>. Unlike a minicpan, a Pinto repository contains <em>only</em> the distributions you want (and their dependencies), so there is no need for filtering. This results in a much smaller and more manageable pile of files, so you can easily do things like check it into your SCM. Pinto also has some neat tools for handling upgrades without accidentally breaking your application.</p>\n\n<p>Also, <a href=\"https://stratopan.com\" rel=\"nofollow\">Stratopan</a> hosts Pinto repositories in the cloud. You can manage the repository through your browser and install modules anywhere that has internet access. It doesn't yet support all the features Pinto has, but Stratopan really takes the hassle out of maintaining a local CPAN.</p>\n\n<p><em>Disclaimer: I operate Stratopan.</em> </p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
I have a local MINICPAN repository, but I want to remove a specific version of a module, and inject an older version. This is the steps I've taken. ``` - create the MINICPAN, not filtering any modules - use mcpani --add for the module in question - use mcpani --inject ``` At this point, I can see in the MINICPAN that it has both the version I want, and the newer version, if I issue install in cpan, then the newer version of the module is install. How can I get rid of the newer version from my minicpan?
Filter the modules that you are going to inject. The [CPAN::Mini](http://search.cpan.org/dist/CPAN-Mini) has the documentation for filtering, and I think I had some examples in the resources I pointed you toward earlier. :) If you already have the minicpan, as you said in the comment to ysth, you can create *another* minicpan from that one. The "remote" CPAN in that case is the one that you have. I do that all the time: I have a canonical minicpan, but then for testing things, I filter from that to create new repositories just so I don't have to deal with the network.
263,906
<pre><code>AlertEvent::AlertEvent(const std::string&amp; text) : IMEvent(kIMEventAlert, alertText.c_str()), alertText(text) { //inspection at time of crash shows alertText is a valid string } IMEvent::IMEvent(long eventID, const char* details) { //during construction, details==0xcccccccc } </code></pre> <p>on a related note, the monospace font looks really terrible in chrome, whats up with that?</p>
[ { "answer_id": 263911, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 2, "selected": false, "text": "<p>The IMEvent constructor is called before alertText's constructor is called. In particular therefore its argument <code>alertText.c_str()</code> is evaluated before alertText's constructor is called. This ain't good.</p>\n\n<p>Initializer expressions are called in the order that the things being initialized are declared (not necessarily the order the initializers are listed). So parent classes first, then members. Compilers sometime helpfully warn you if you don't list the initializers in the order they will actually be executed. So provided you get that right, the rule is \"don't use anything you haven't initialized\". This code uses alertText before it is initialized.</p>\n" }, { "answer_id": 263914, "author": "Adam Holmberg", "author_id": 20688, "author_profile": "https://Stackoverflow.com/users/20688", "pm_score": 3, "selected": true, "text": "<p>alertText may be shown as a string in a debugger, but it has not been constructed yet (and therefore alertText.c_str() will return an indeterminate pointer).</p>\n\n<p>To avoid this, one could initialize use text.c_str() as an argument to the IMEvent ctor.</p>\n\n<pre><code>AlertEvent::AlertEvent(const std::string&amp; text) :\n IMEvent(kIMEventAlert, text.c_str()),\n alertText(text)\n{\n //inspection at time of crash shows alertText is a valid string\n}\n\n\nIMEvent::IMEvent(long eventID, const char* details)\n{\n //during construction, details==0xcccccccc\n}\n</code></pre>\n" }, { "answer_id": 263918, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "<p><em>The IMEvent constructor is called before alertText's constructor is called.</em></p>\n\n<p>Almost. <code>alertText.c_str()</code> is called before alertText is constructed, that is the real problem. The easiest solution is replacing it with <code>text.c_str()</code></p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20003/" ]
``` AlertEvent::AlertEvent(const std::string& text) : IMEvent(kIMEventAlert, alertText.c_str()), alertText(text) { //inspection at time of crash shows alertText is a valid string } IMEvent::IMEvent(long eventID, const char* details) { //during construction, details==0xcccccccc } ``` on a related note, the monospace font looks really terrible in chrome, whats up with that?
alertText may be shown as a string in a debugger, but it has not been constructed yet (and therefore alertText.c\_str() will return an indeterminate pointer). To avoid this, one could initialize use text.c\_str() as an argument to the IMEvent ctor. ``` AlertEvent::AlertEvent(const std::string& text) : IMEvent(kIMEventAlert, text.c_str()), alertText(text) { //inspection at time of crash shows alertText is a valid string } IMEvent::IMEvent(long eventID, const char* details) { //during construction, details==0xcccccccc } ```
263,913
<p>I am trying to get the DataGridView to render the "insert new row" row as the first row in the grid instead of the last row. How do I go about doing that, is it even possible in the control?</p>
[ { "answer_id": 264014, "author": "jons911", "author_id": 34375, "author_profile": "https://Stackoverflow.com/users/34375", "pm_score": 4, "selected": true, "text": "<p>I don't think there is any way to move the \"new row\" row to the top of the data grid.</p>\n\n<p>But, what if you left the top row empty and as the data filled in move the row down as appropriate? In other words, make your own \"new row\" row, which is just first row in the grid and add new blank rows above when editing is over. </p>\n\n<pre><code> Dim myrow = existingDataTable.NewRow\n\n existingDataTable.Rows.Add(myrow)\n\n adp.Fill(existingDataTable)\n With DataGridView1\n .DataSource =existingDataTable\n End With \n</code></pre>\n" }, { "answer_id": 267433, "author": "Jeremy Bade", "author_id": 13284, "author_profile": "https://Stackoverflow.com/users/13284", "pm_score": 1, "selected": false, "text": "<p>Can you assign a temporary value to the new row's key that is less than all of the existing rows? Then sort a DataView by that key and bind the view to your grid.</p>\n\n<p>My team uses negative numbers as row ids until that row has been inserted into the database. I don't recall our new rows showing up at the top but we also don't have that as a requirement.</p>\n" }, { "answer_id": 275368, "author": "xyz", "author_id": 82, "author_profile": "https://Stackoverflow.com/users/82", "pm_score": 1, "selected": false, "text": "<p>And if all else fails the hacky way would be to put a separate one line DataGridView above the existing one, clone its columns, and wire up the row submission event to add the data to the lower one :)</p>\n" }, { "answer_id": 291685, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>If you are not using bound controls, dgvItems.Rows.Insert( ) will allow you to specify where the row is inserted.</p>\n\n<p>If you are using a bound datagridview, without a sort active, add the new row to the data source in the desired location:</p>\n\n<p>BoundTable.Rows.InsertAt(BoundTable.Rows.NewRow(), RowLocation);</p>\n\n<p>I have found an interesting relationship, if there are edits on the current row and the row has not been committed to the datasource (i.e. you just started entering the data), it seems to be necessary to move the active cell to another row to commit the changes before inserting rows.</p>\n" }, { "answer_id": 291697, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 1, "selected": false, "text": "<p>Are you consuming the RowDataBound event? If so, you could check to see if you are binding the column header row and then add the appropriate code to insert a row just below that. </p>\n\n<p>That way when your content rows are bound, there isn't any confusion with item indexes being involved, though I would recommend using some DataKeys or something just in case. In addition, using the RowDatabound event would allow you to have an \"insert row\" available when the user pages to a different block of rows in the GridView.</p>\n" }, { "answer_id": 6314710, "author": "While-E", "author_id": 671827, "author_profile": "https://Stackoverflow.com/users/671827", "pm_score": -1, "selected": false, "text": "<p>I'm assuming you mean that when you want to add a new row, you want the row to actually be inserted at the top of the table instead of the bottom of the table like default? Well if this is so, you don't have to deal with sorting or key values; simply do as such with the Insert method:</p>\n\n<blockquote>\n <p><strong>'Create a new row</strong></p>\n \n <p>Dim tmpRow = New DataGridViewRow</p>\n \n <p><strong>'Adjust the row in some way</strong></p>\n \n <p>tmpRow.Height = _cellRectSize</p>\n \n <p><strong>'Add the row to DataGridView(i.e dgvEditor) at the top(index = 0)</strong></p>\n \n <p>Me.dgvEditor.Rows.Insert(0, tmpRow)</p>\n</blockquote>\n\n<p>Works like a charm for me, hope it helps someone else!</p>\n" }, { "answer_id": 7918419, "author": "banifesto", "author_id": 1016811, "author_profile": "https://Stackoverflow.com/users/1016811", "pm_score": 1, "selected": false, "text": "<p>As While-E said, use <code>Insert</code> instead of <code>Add</code>. This way you can specify where you want to add the new record. To add a new record on top of the grid, just use <code>Insert(0)</code>.</p>\n\n<p><code>DataGridView1.Rows.Insert(0)</code> this will add a new record on top, always</p>\n\n<p><code>DataGridView1.Rows(0).Cells(n).Value = \"abc\"</code> this will set the value at n column</p>\n" } ]
2008/11/04
[ "https://Stackoverflow.com/questions/263913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32809/" ]
I am trying to get the DataGridView to render the "insert new row" row as the first row in the grid instead of the last row. How do I go about doing that, is it even possible in the control?
I don't think there is any way to move the "new row" row to the top of the data grid. But, what if you left the top row empty and as the data filled in move the row down as appropriate? In other words, make your own "new row" row, which is just first row in the grid and add new blank rows above when editing is over. ``` Dim myrow = existingDataTable.NewRow existingDataTable.Rows.Add(myrow) adp.Fill(existingDataTable) With DataGridView1 .DataSource =existingDataTable End With ```
263,938
<p>For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code:</p> <pre><code> &lt;form name="wikiedit" action="[[script_name]]" method="post"&gt; &lt;textarea name="content" rows="25" cols="90" wrap="virtual"&gt;[[content]]&lt;/textarea&gt; &lt;input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap"&gt; &amp;nbsp; &lt;input type="submit" value="Save"&gt; &lt;/form&gt; </code></pre> <p>It works with IE, but not with Firefox or Opera. How should I do this?</p>
[ { "answer_id": 264006, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "<p>According to <a href=\"http://www.w3.org/TR/html4/interact/forms.html#edef-TEXTAREA\" rel=\"nofollow noreferrer\">the HTML 4.01 spec</a>, <code>wrap</code> isn't a valid attribute for <code>&lt;textarea&gt;</code>s which would explain why it's so difficult and strange. It looks as though Firefox actually does use the <code>wrap</code> attribute, but it won't let you change it.</p>\n\n<p>I do have a solution though! It's pretty awful, but here it is. Completely replace the textarea with a new one.</p>\n\n<pre><code>// this is the onclick handler for your button\ndocument.getElementById(\"nowrapButton\").onclick = function() {\n var oldOne = this.form.content; // the old textarea\n var newOne = document.createElement('textarea'); // the new textarea\n var attrs = ['name', 'rows', 'cols']; // these are the attributes to keep\n for (var i = 0; i &lt; attrs.length; ++i) {\n // copy the attributes to the new one\n newOne.setAttribute(attrs[i], oldOne.getAttribute(attrs[i]));\n }\n\n // toggle the wrapping on and off\n if (oldOne.getAttribute('wrap') != 'off') {\n newOne.setAttribute('wrap', 'off');\n }\n\n // copy the text over\n newOne.value = oldOne.value;\n\n // add the new one\n oldOne.parentNode.insertBefore(newOne, oldOne);\n // get rid of the old one\n oldOne.parentNode.removeChild(oldOne);\n return false;\n};\n</code></pre>\n\n<p>Here's a working version of this you can play with: <a href=\"http://jsbin.com/ugepa\" rel=\"nofollow noreferrer\">http://jsbin.com/ugepa</a></p>\n\n<p>As usual, this'd be much nicer in jQuery. :)</p>\n" }, { "answer_id": 264094, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": true, "text": "<p>See bug 41464: <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=41464\" rel=\"nofollow noreferrer\">https://bugzilla.mozilla.org/show_bug.cgi?id=41464</a></p>\n\n<p>Nasty workaround for now is to replace the textarea with a clone of itself:</p>\n\n<pre><code>function setWrap(area, wrap) {\n if (area.wrap) {\n area.wrap= wrap;\n } else { // wrap attribute not supported - try Mozilla workaround\n area.setAttribute('wrap', wrap);\n var newarea= area.cloneNode(true);\n newarea.value= area.value;\n area.parentNode.replaceChild(newarea, area);\n }\n}\n</code></pre>\n\n<p>Unrelated: try to avoid accessing elements straight out of the document object, it is unreliable on some browsers and causes name clash problems. ‘document.forms.wikiedit’ is better, and moving to ‘id’ on the form instead of ‘name’ and then using ‘document.getElementById('wikiedit')’ better still.</p>\n\n<p>form.elements.content is also more reliable than form.content for similar reasons... or, indeed, you could give the textarea an ID and go straight to the textarea with getElementById without having to bother look at the form.</p>\n" }, { "answer_id": 264218, "author": "Jared Farrish", "author_id": 451969, "author_profile": "https://Stackoverflow.com/users/451969", "pm_score": 1, "selected": false, "text": "<p>Here is a primer on textarea wrap, including a CSS solution:</p>\n\n<p><a href=\"http://www.web-wise-wizard.com/html-tutorials/html-form-forms-textarea-wrap.html\" rel=\"nofollow noreferrer\">http://www.web-wise-wizard.com/html-tutorials/html-form-forms-textarea-wrap.html</a></p>\n\n<p>The CSS solution they cite is:</p>\n\n<pre><code>white-space: pre; overflow: auto;\n</code></pre>\n\n<p>Which would be:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nfunction setNoWrap(textarea) {\n textarea.style.whiteSpace = 'pre';\n textarea.style.overflow = 'auto';\n}\n&lt;/script&gt;\n&lt;form name=\"wikiedit\" action=\"[[script_name]]\" method=\"post\"&gt;\n &lt;textarea name=\"content\" rows=\"25\" cols=\"90\" wrap=\"virtual\"&gt;[[content]]&lt;/textarea&gt;\n &lt;input type=\"button\" onclick=\"setNoWrap(this);\" value=\"No Wrap\"&gt; \n &lt;input type=\"submit\" value=\"Save\"&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 514538, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Although, this is a old post, but as I getting help from this, I also what to show a easier method I found just now. And I think it's more correct.</p>\n\n<p>To replace the .cloneNode(), I think the best method is:</p>\n\n<p>child.setAttribute( 'wrap', wrap );\nparent.removeChild( child );\nparent.appendChild( child );</p>\n\n<p>using this way, you can not only save the attributes of itself, but also the attributes you added, for example, a script handle or something else.</p>\n" }, { "answer_id": 719660, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Try this jQuery extension: <a href=\"http://blog.5ubliminal.com/posts/peculiarities-of-textarea-wrap-attribute-jquery-countermeasures/\" rel=\"nofollow noreferrer\">Textarea Wrap Changer</a> .</p>\n" }, { "answer_id": 4702505, "author": "Jesse Merriman", "author_id": 105782, "author_profile": "https://Stackoverflow.com/users/105782", "pm_score": 0, "selected": false, "text": "<p>Here's a variant of <a href=\"https://stackoverflow.com/questions/263938/changing-textarea-wrapping-using-javascript/264094#264094\" title=\"bobince&#39;s answer\">bobince's answer</a> that doesn't require cloning the textarea:</p>\n\n<pre><code>function setWrap(area, wrap) {\n if (area.wrap) {\n area.wrap = wrap;\n } else { // wrap attribute not supported - try Mozilla workaround\n area.setAttribute(\"wrap\", wrap);\n area.style.overflow = \"hidden\";\n area.style.overflow = \"auto\";\n }\n}\n</code></pre>\n\n<p>This is similar to <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=41464#c23\" rel=\"nofollow noreferrer\" title=\"VK\">VK's</a> comment in the bug that bobince referenced, but setting display instead of overflow didn't work for me unless I put the second set in a setTimeout.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/263938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code: ``` <form name="wikiedit" action="[[script_name]]" method="post"> <textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea> <input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap"> &nbsp; <input type="submit" value="Save"> </form> ``` It works with IE, but not with Firefox or Opera. How should I do this?
See bug 41464: <https://bugzilla.mozilla.org/show_bug.cgi?id=41464> Nasty workaround for now is to replace the textarea with a clone of itself: ``` function setWrap(area, wrap) { if (area.wrap) { area.wrap= wrap; } else { // wrap attribute not supported - try Mozilla workaround area.setAttribute('wrap', wrap); var newarea= area.cloneNode(true); newarea.value= area.value; area.parentNode.replaceChild(newarea, area); } } ``` Unrelated: try to avoid accessing elements straight out of the document object, it is unreliable on some browsers and causes name clash problems. ‘document.forms.wikiedit’ is better, and moving to ‘id’ on the form instead of ‘name’ and then using ‘document.getElementById('wikiedit')’ better still. form.elements.content is also more reliable than form.content for similar reasons... or, indeed, you could give the textarea an ID and go straight to the textarea with getElementById without having to bother look at the form.
263,945
<p>In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?</p> <pre><code>map&lt;string, SerialdMsg::SerialFunction_t&gt;::iterator pm_it; for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++) { if (pm_it-&gt;second == delete_this_id) { port_map.erase(pm_it-&gt;first); } } </code></pre> <p>UPDATE: Of course, I then <a href="https://stackoverflow.com/questions/52714/stl-vector-vs-map-erase">read this question</a> which I didn't think would be related but answers my question.</p>
[ { "answer_id": 263958, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 9, "selected": true, "text": "<h2>C++11</h2>\n\n<p>This has been fixed in C++11 (or erase has been improved/made consistent across all container types).<br>\nThe erase method now returns the next iterator.</p>\n\n<pre><code>auto pm_it = port_map.begin();\nwhile(pm_it != port_map.end())\n{\n if (pm_it-&gt;second == delete_this_id)\n {\n pm_it = port_map.erase(pm_it);\n }\n else\n {\n ++pm_it;\n }\n}\n</code></pre>\n\n<h2>C++03</h2>\n\n<p>Erasing elements in a map does not invalidate any iterators.<br>\n(apart from iterators on the element that was deleted)</p>\n\n<p>Actually inserting or deleting does not invalidate any of the iterators:</p>\n\n<p>Also see this answer:<br>\n<a href=\"https://stackoverflow.com/a/180616/14065\">Mark Ransom Technique</a> </p>\n\n<p>But you do need to update your code:<br>\nIn your code you increment pm_it after calling erase. At this point it is too late and is already invalidated.</p>\n\n<pre><code>map&lt;string, SerialdMsg::SerialFunction_t&gt;::iterator pm_it = port_map.begin();\nwhile(pm_it != port_map.end())\n{\n if (pm_it-&gt;second == delete_this_id)\n {\n port_map.erase(pm_it++); // Use iterator.\n // Note the post increment.\n // Increments the iterator but returns the\n // original value for use by erase \n }\n else\n {\n ++pm_it; // Can use pre-increment in this case\n // To make sure you have the efficient version\n }\n}\n</code></pre>\n" }, { "answer_id": 263975, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 1, "selected": false, "text": "<p>This is how I would do it, approximately:</p>\n\n<pre><code>bool is_remove( pair&lt;string, SerialdMsg::SerialFunction_t&gt; val )\n{\n return val.second == delete_this_id;\n}\n\nmap&lt;string, SerialdMsg::SerialFunction_t&gt;::iterator new_end = \n remove_if (port_map.begin( ), port_map.end( ), is_remove );\n\nport_map.erase (new_end, port_map.end( ) );\n</code></pre>\n\n<p>There is something odd about </p>\n\n<pre><code>val.second == delete_this_id\n</code></pre>\n\n<p>but I just copied it from your example code.</p>\n" }, { "answer_id": 825058, "author": "AlaaShaker", "author_id": 63326, "author_profile": "https://Stackoverflow.com/users/63326", "pm_score": 4, "selected": false, "text": "<p>Here's how I do that ...</p>\n\n<pre><code>typedef map&lt;string, string&gt; StringsMap;\ntypedef StringsMap::iterator StrinsMapIterator;\n\nStringsMap m_TheMap; // Your map, fill it up with data \n\nbool IsTheOneToDelete(string str)\n{\n return true; // Add your deletion criteria logic here\n}\n\nvoid SelectiveDelete()\n{\n StringsMapIter itBegin = m_TheMap.begin();\n StringsMapIter itEnd = m_TheMap.end();\n StringsMapIter itTemp;\n\n while (itBegin != itEnd)\n {\n if (IsTheOneToDelete(itBegin-&gt;second)) // Criteria checking here\n {\n itTemp = itBegin; // Keep a reference to the iter\n ++itBegin; // Advance in the map\n m_TheMap.erase(itTemp); // Erase it !!!\n }\n else\n ++itBegin; // Just move on ...\n }\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/263945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20889/" ]
In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()? ``` map<string, SerialdMsg::SerialFunction_t>::iterator pm_it; for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++) { if (pm_it->second == delete_this_id) { port_map.erase(pm_it->first); } } ``` UPDATE: Of course, I then [read this question](https://stackoverflow.com/questions/52714/stl-vector-vs-map-erase) which I didn't think would be related but answers my question.
C++11 ----- This has been fixed in C++11 (or erase has been improved/made consistent across all container types). The erase method now returns the next iterator. ``` auto pm_it = port_map.begin(); while(pm_it != port_map.end()) { if (pm_it->second == delete_this_id) { pm_it = port_map.erase(pm_it); } else { ++pm_it; } } ``` C++03 ----- Erasing elements in a map does not invalidate any iterators. (apart from iterators on the element that was deleted) Actually inserting or deleting does not invalidate any of the iterators: Also see this answer: [Mark Ransom Technique](https://stackoverflow.com/a/180616/14065) But you do need to update your code: In your code you increment pm\_it after calling erase. At this point it is too late and is already invalidated. ``` map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin(); while(pm_it != port_map.end()) { if (pm_it->second == delete_this_id) { port_map.erase(pm_it++); // Use iterator. // Note the post increment. // Increments the iterator but returns the // original value for use by erase } else { ++pm_it; // Can use pre-increment in this case // To make sure you have the efficient version } } ```
263,962
<p>Is there a difference in passing parameters to <code>.load</code></p> <pre><code>$("#myDiv").load("myScript.php?var=x&amp;var2=y&amp;var3=z") </code></pre> <p>vs</p> <pre><code>$("#myDiv").load("myScript.php", {var1:x, var2:y, var3:z}) </code></pre> <p>Also, is there a size limit to how much <code>.load</code> can handle? Can <code>myScript.php</code> return a couple hundred rows of data without issue?</p>
[ { "answer_id": 263974, "author": "Davide Gualano", "author_id": 28582, "author_profile": "https://Stackoverflow.com/users/28582", "pm_score": 5, "selected": false, "text": "<p>In the first case, the data are passed to the script via GET, in the second via POST.</p>\n\n<p><a href=\"http://docs.jquery.com/Ajax/load#urldatacallback\" rel=\"noreferrer\">http://docs.jquery.com/Ajax/load#urldatacallback</a></p>\n\n<p>I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.</p>\n" }, { "answer_id": 21646214, "author": "Farshid Saberi", "author_id": 1790801, "author_profile": "https://Stackoverflow.com/users/1790801", "pm_score": 5, "selected": false, "text": "<p>As Davide Gualano has been told. \nThis one </p>\n\n<pre><code>$(\"#myDiv\").load(\"myScript.php?var=x&amp;var2=y&amp;var3=z\")\n</code></pre>\n\n<p>use GET method for sending the request, and this one </p>\n\n<pre><code>$(\"#myDiv\").load(\"myScript.php\", {var:x, var2:y, var3:z})\n</code></pre>\n\n<p>use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.</p>\n\n<p>For example: url length limits the amount of sending data in GET method.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/263962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a difference in passing parameters to `.load` ``` $("#myDiv").load("myScript.php?var=x&var2=y&var3=z") ``` vs ``` $("#myDiv").load("myScript.php", {var1:x, var2:y, var3:z}) ``` Also, is there a size limit to how much `.load` can handle? Can `myScript.php` return a couple hundred rows of data without issue?
In the first case, the data are passed to the script via GET, in the second via POST. <http://docs.jquery.com/Ajax/load#urldatacallback> I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
263,965
<p>Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?</p> <p>I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.</p> <p>The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.</p> <pre><code>var myValue = document.myForm.IS_TRUE.value; var isTrueSet = myValue == 'true'; </code></pre> <p>Is there a better way to accomplish this?</p>
[ { "answer_id": 264037, "author": "guinaps", "author_id": 27225, "author_profile": "https://Stackoverflow.com/users/27225", "pm_score": 13, "selected": true, "text": "<h1>Do:</h1>\n<pre><code>var isTrueSet = (myValue === 'true');\n</code></pre>\n<p>using the identity operator (<code>===</code>), which doesn't make any implicit type conversions when the compared variables have different types.</p>\n<p>This will set <code>isTrueSet</code> to a boolean <code>true</code> if the string is &quot;true&quot; and boolean <code>false</code> if it is string &quot;false&quot; or not set at all.</p>\n<hr />\n<h2>Don't:</h2>\n<p>You should probably <strong>be cautious about using these two methods</strong> for your specific needs:</p>\n<pre><code>var myBool = Boolean(&quot;false&quot;); // == true\n\nvar myBool = !!&quot;false&quot;; // == true\n</code></pre>\n<p>Any string which isn't the empty string will evaluate to <code>true</code> by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.</p>\n" }, { "answer_id": 264071, "author": "Jared Farrish", "author_id": 451969, "author_profile": "https://Stackoverflow.com/users/451969", "pm_score": 7, "selected": false, "text": "<p>Remember to match case:</p>\n\n<pre><code>var isTrueSet = (myValue.toLowerCase() === 'true');\n</code></pre>\n\n<p>Also, if it's a form element checkbox, you can also detect if the checkbox is checked:</p>\n\n<pre><code>var isTrueSet = document.myForm.IS_TRUE.checked;\n</code></pre>\n\n<p>Assuming that if it is checked, it is \"set\" equal to true. This evaluates as true/false.</p>\n" }, { "answer_id": 264097, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 5, "selected": false, "text": "<p>Your solution is fine.</p>\n\n<p>Using <code>===</code> would just be silly in this case, as the field's <code>value</code> will always be a <code>String</code>.</p>\n" }, { "answer_id": 264105, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 3, "selected": false, "text": "<p>You need to separate (in your thinking) the value of your selections and the representation of that value. </p>\n\n<p>Pick a point in the JavaScript logic where they need to transition from string sentinels to native type and do a comparison there, preferably where it only gets done once for each value that needs to be converted. Remember to address what needs to happen if the string sentinel is not one the script knows (i.e. do you default to true or to false?)</p>\n\n<p>In other words, yes, you need to depend on the string's value. :-)</p>\n" }, { "answer_id": 264109, "author": "JW.", "author_id": 4321, "author_profile": "https://Stackoverflow.com/users/4321", "pm_score": 2, "selected": false, "text": "<p>If there's some other code that's converting the boolean value to a string, you need to know exactly how that code stores true/false values. Either that or you need to have access to a function that reverses that conversion.</p>\n\n<p>There are infinitely many ways to represent boolean values in strings (\"true\", \"Y\", \"1\", etc.). So you shouldn't rely on some general-purpose string-to-boolean converter, like Boolean(myValue). You need to use a routine that reverses the original boolean-to-string conversion, whatever that is.</p>\n\n<p>If you know that it converts true booleans to \"true\" strings, then your sample code is fine. Except that you should use === instead of ==, so there's no automatic type conversion.</p>\n" }, { "answer_id": 264180, "author": "Shadow2531", "author_id": 1697, "author_profile": "https://Stackoverflow.com/users/1697", "pm_score": 7, "selected": false, "text": "<p>You can use regular expressions:</p>\n\n<pre><code>/*\n * Converts a string to a bool.\n *\n * This conversion will:\n *\n * - match 'true', 'on', or '1' as true.\n * - ignore all white-space padding\n * - ignore capitalization (case).\n *\n * ' tRue ','ON', and '1 ' will all evaluate as true.\n *\n */\nfunction strToBool(s)\n{\n // will match one and only one of the string 'true','1', or 'on' rerardless\n // of capitalization and regardless off surrounding white-space.\n //\n regex=/^\\s*(true|1|on)\\s*$/i\n\n return regex.test(s);\n}\n</code></pre>\n\n<p>If you like extending the String class you can do:</p>\n\n<pre><code>String.prototype.bool = function() {\n return strToBool(this);\n};\n\nalert(\"true\".bool());\n</code></pre>\n\n<p>For those (see the comments) that would like to extend the String object to get this but are worried about enumerability and are worried about clashing with other code that extends the String object:</p>\n\n<pre><code>Object.defineProperty(String.prototype, \"com_example_bool\", {\n get : function() {\n return (/^(true|1)$/i).test(this);\n }\n});\nalert(\"true\".com_example_bool);\n</code></pre>\n\n<p>(Won't work in older browsers of course and Firefox shows false while Opera, Chrome, Safari and IE show true. <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=720760\" rel=\"noreferrer\">Bug 720760</a>) </p>\n" }, { "answer_id": 323546, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<p>I think this is much universal:</p>\n<p><code>if (String(a).toLowerCase() == &quot;true&quot;)</code> ...</p>\n<p>It goes:</p>\n<pre><code>String(true) == &quot;true&quot; //returns true\nString(false) == &quot;true&quot; //returns false\nString(&quot;true&quot;) == &quot;true&quot; //returns true\nString(&quot;false&quot;) == &quot;true&quot; //returns false\n</code></pre>\n" }, { "answer_id": 920942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>if (String(a) == \"true\"){\n //true block\n} else {\n //false block\n}\n</code></pre>\n" }, { "answer_id": 1414175, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": false, "text": "<pre><code>const stringToBoolean = (stringValue) =&gt; {\n switch(stringValue?.toLowerCase()?.trim()){\n case &quot;true&quot;: \n case &quot;yes&quot;: \n case &quot;1&quot;: \n return true;\n\n case &quot;false&quot;: \n case &quot;no&quot;: \n case &quot;0&quot;: \n case null: \n case undefined:\n return false;\n\n default: \n return JSON.parse(stringValue);\n }\n}\n</code></pre>\n" }, { "answer_id": 2114055, "author": "PixelSlave", "author_id": 256308, "author_profile": "https://Stackoverflow.com/users/256308", "pm_score": -1, "selected": false, "text": "<p>Just do a:</p>\n\n<pre><code>var myBool = eval (yourString);\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>alert (eval (\"true\") == true); // TRUE\nalert (eval (\"true\") == false); // FALSE\nalert (eval (\"1\") == true); // TRUE\nalert (eval (\"1\") == false); // FALSE\nalert (eval (\"false\") == true); // FALSE;\nalert (eval (\"false\") == false); // TRUE\nalert (eval (\"0\") == true); // FALSE\nalert (eval (\"0\") == false); // TRUE\nalert (eval (\"\") == undefined); // TRUE\nalert (eval () == undefined); // TRUE\n</code></pre>\n\n<p>This method handles the empty string and undefined string naturally as if you declare a variable without assigning it a value.</p>\n" }, { "answer_id": 2114091, "author": "Thomas Eding", "author_id": 239916, "author_profile": "https://Stackoverflow.com/users/239916", "pm_score": 4, "selected": false, "text": "<pre><code>Boolean.parse = function (str) {\n switch (str.toLowerCase ()) {\n case \"true\":\n return true;\n case \"false\":\n return false;\n default:\n throw new Error (\"Boolean.parse: Cannot convert string to boolean.\");\n }\n};\n</code></pre>\n" }, { "answer_id": 3394176, "author": "cypher", "author_id": 381786, "author_profile": "https://Stackoverflow.com/users/381786", "pm_score": 0, "selected": false, "text": "<p>The following would be enough</p>\n\n<pre><code>String.prototype.boolean = function() {\n return \"true\" == this; \n};\n\n\"true\".boolean() // returns true \"false\".boolean() // returns false\n</code></pre>\n" }, { "answer_id": 4380804, "author": "thdoan", "author_id": 452587, "author_profile": "https://Stackoverflow.com/users/452587", "pm_score": 5, "selected": false, "text": "<p>The Boolean object doesn't have a 'parse' method. <code>Boolean('false')</code> returns true, so that won't work. <code>!!'false'</code> also returns <code>true</code>, so that won't work also.</p>\n<p>If you want string <code>'true'</code> to return boolean <code>true</code> and string <code>'false'</code> to return boolean <code>false</code>, then the simplest solution is to use <code>eval()</code>. <code>eval('true')</code> returns true and <code>eval('false')</code> returns false.</p>\n<p><strong>Keep in mind the performance and security implications when using <code>eval()</code> though</strong>.</p>\n" }, { "answer_id": 7516741, "author": "risingfish", "author_id": 959378, "author_profile": "https://Stackoverflow.com/users/959378", "pm_score": 3, "selected": false, "text": "<p>Hands down the easiest way (assuming you string will be 'true' or 'false') is:</p>\n\n<pre><code>var z = 'true';\nvar y = 'false';\nvar b = (z === 'true'); // will evaluate to true\nvar c = (y === 'true'); // will evaluate to false\n</code></pre>\n\n<p><em><strong>Always</em></strong> use the === operator instead of the == operator for these types of conversions!</p>\n" }, { "answer_id": 7573471, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 1, "selected": false, "text": "<pre><code>function returnBoolean(str){\n\n str=str.toString().toLowerCase();\n\n if(str=='true' || str=='1' || str=='yes' || str=='y' || str=='on' || str=='+'){\n return(true);\n }\n else if(str=='false' || str=='0' || str=='no' || str=='n' || str=='off' || str=='-'){\n return(false);\n }else{\n return(undefined);\n }\n}\n</code></pre>\n" }, { "answer_id": 7833897, "author": "Luke", "author_id": 451139, "author_profile": "https://Stackoverflow.com/users/451139", "pm_score": 10, "selected": false, "text": "<h1>Warning</h1>\n\n<p>This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY <code>\"true\"</code> or <code>\"false\"</code>.</p>\n\n<p>An invalid json string passed into these functions below <strong>WILL throw an exception</strong>.</p>\n\n<hr>\n\n<p><strong>Original answer:</strong></p>\n\n<p>How about?</p>\n\n<pre><code>JSON.parse(\"True\".toLowerCase());\n</code></pre>\n\n<p>or with jQuery</p>\n\n<pre><code>$.parseJSON(\"TRUE\".toLowerCase());\n</code></pre>\n" }, { "answer_id": 9709935, "author": "hajikelist", "author_id": 822354, "author_profile": "https://Stackoverflow.com/users/822354", "pm_score": 2, "selected": false, "text": "<p>I've found that using '1' and an empty value '' for boolean values works far more predictably than 'true' or 'false' string values... specifically with html forms since uninitialized/empty values in Dom elements will consistently evaluate to false whereas <em>any</em> value within them evaluates to true. </p>\n\n<p>For instance:</p>\n\n<pre><code>&lt;input type='button' onclick='this.value = tog(this.value);' /&gt;\n\n&lt;script type=\"text/javascript\"&gt;\n\n function tog(off) {\n if(off) {\n alert('true, toggle to false');\n return '';\n } else {\n alert('false, toggle to true');\n return '1';\n }\n } \n&lt;/script&gt;\n</code></pre>\n\n<p>Just seemed like an easier road, so far it's been very consistent/easy... perhaps someone can determine a way to break this?</p>\n" }, { "answer_id": 10033879, "author": "imjustmatthew", "author_id": 864300, "author_profile": "https://Stackoverflow.com/users/864300", "pm_score": 3, "selected": false, "text": "<p>Like @Shadow2531 said, you can't just convert it directly. I'd also suggest that you consider string inputs besides \"true\" and \"false\" that are 'truthy' and 'falsey' if your code is going to be reused/used by others. This is what I use:</p>\n\n<pre><code>function parseBoolean(string) {\n switch (String(string).toLowerCase()) {\n case \"true\":\n case \"1\":\n case \"yes\":\n case \"y\":\n return true;\n case \"false\":\n case \"0\":\n case \"no\":\n case \"n\":\n return false;\n default:\n //you could throw an error, but 'undefined' seems a more logical reply\n return undefined;\n }\n}\n</code></pre>\n" }, { "answer_id": 10727873, "author": "Scrimothy", "author_id": 1408356, "author_profile": "https://Stackoverflow.com/users/1408356", "pm_score": 2, "selected": false, "text": "<p>@guinaps> Any string which isn't the empty string will evaluate to true by using them.</p>\n\n<p>How about using the String.match() method</p>\n\n<pre><code>var str=\"true\";\nvar boolStr=Boolean(str.match(/^true$/i)); \n</code></pre>\n\n<p>this alone won't get the 1/0 or the yes/no, but it will catch the TRUE/true, as well, it will return false for any string that happens to have \"true\" as a substring.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Below is a function to handle true/false, 1/0, yes/no (case-insensitive)</p>\n\n<pre><code>​function stringToBool(str) {\n var bool;\n if (str.match(/^(true|1|yes)$/i) !== null) {\n bool = true;\n } else if (str.match(/^(false|0|no)*$/i) !== null) {\n bool = false;\n } else {\n bool = null;\n if (console) console.log('\"' + str + '\" is not a boolean value');\n }\n return bool;\n}\n\nstringToBool('1'); // true\nstringToBool('No'); // false\nstringToBool('falsey'); // null (\"falsey\" is not a boolean value.)\nstringToBool(''); // false\n</code></pre>\n" }, { "answer_id": 12037917, "author": "mbeasley", "author_id": 984239, "author_profile": "https://Stackoverflow.com/users/984239", "pm_score": 1, "selected": false, "text": "<p><code>Boolean.parse()</code> does exist in some browser implementations. It's definitely not universal, so if that's something that you need than you shouldn't use this method. But in Chrome, for example (I'm using v21) it works just fine and as one would expect. </p>\n" }, { "answer_id": 13030634, "author": "jerone", "author_id": 108448, "author_profile": "https://Stackoverflow.com/users/108448", "pm_score": 2, "selected": false, "text": "<p>I've been using this snippet to convert Numbers and Booleans:</p>\n\n<pre><code>var result = !isNaN(value) ? parseFloat(value) : /^\\s*(true|false)\\s*$/i.exec(value) ? RegExp.$1.toLowerCase() === \"true\" : value;\n</code></pre>\n" }, { "answer_id": 14462838, "author": "AndreasPizsa", "author_id": 199263, "author_profile": "https://Stackoverflow.com/users/199263", "pm_score": 4, "selected": false, "text": "<p>The expression you're looking for simply is</p>\n\n<pre><code>/^true$/i.test(myValue)\n</code></pre>\n\n<p>as in</p>\n\n<pre><code>var isTrueSet = /^true$/i.test(myValue);\n</code></pre>\n\n<p>This tests <code>myValue</code> against a regular expression , case-insensitive, and doesn't modify the prototype.</p>\n\n<p>Examples:</p>\n\n<pre><code>/^true$/i.test(\"true\"); // true\n/^true$/i.test(\"TRUE\"); // true\n/^true$/i.test(\"tRuE\"); // true\n/^true$/i.test(\" tRuE\"); // false (notice the space at the beginning)\n/^true$/i.test(\"untrue\"); // false (some other solutions here will incorrectly return true\n/^true$/i.test(\"false\");// returns false\n/^true$/i.test(\"xyz\"); // returns false\n</code></pre>\n" }, { "answer_id": 14542479, "author": "BishopZ", "author_id": 901379, "author_profile": "https://Stackoverflow.com/users/901379", "pm_score": 3, "selected": false, "text": "<p>My take on this question is that it aims to satisfy three objectives:</p>\n\n<ul>\n<li>Return true/false for truthy and falsey values, but also return true/false for multiple string values that would be truthy or falsey if they were Booleans instead of strings.</li>\n<li>Second, provide a resilient interface so that values other than those specified will not fail, but rather return a default value</li>\n<li>Third, do all this with as little code as possible.</li>\n</ul>\n\n<p>The problem with using JSON is that it fails by causing a Javascript error. This solution is not resilient (though it satisfies 1 and 3):</p>\n\n<pre><code>JSON.parse(\"FALSE\") // fails\n</code></pre>\n\n<p>This solution is not concise enough:</p>\n\n<pre><code>if(value === \"TRUE\" || value === \"yes\" || ...) { return true; }\n</code></pre>\n\n<p>I am working on solving this exact problem for <a href=\"http://typecastjs.org\" rel=\"noreferrer\">Typecast.js</a>. And the best solution to all three objectives is this one:</p>\n\n<pre><code>return /^true$/i.test(v);\n</code></pre>\n\n<p>It works for many cases, does not fail when values like {} are passed in, and is very concise. Also it returns false as the default value rather than undefined or throwing an Error, which is more useful in loosely-typed Javascript development. Bravo to the other answers that suggested it!</p>\n" }, { "answer_id": 15125270, "author": "jackvsworld", "author_id": 1097054, "author_profile": "https://Stackoverflow.com/users/1097054", "pm_score": 2, "selected": false, "text": "<p>Building on Steven's answer above, I wrote this function as a generic parser for string input:</p>\n\n<pre><code>parse:\n function (value) {\n switch (value &amp;&amp; value.toLowerCase()) {\n case null: return null;\n case \"true\": return true;\n case \"false\": return false;\n default: try { return parseFloat(value); } catch (e) { return value; }\n }\n }\n</code></pre>\n" }, { "answer_id": 16937888, "author": "purab", "author_id": 1057818, "author_profile": "https://Stackoverflow.com/users/1057818", "pm_score": 1, "selected": false, "text": "<p>You even do not need to convert the string to boolean. just use the following:\n<code>var yourstring = yourstringValue == 1 ? true : false;</code></p>\n" }, { "answer_id": 17258019, "author": "dalimian", "author_id": 1275064, "author_profile": "https://Stackoverflow.com/users/1275064", "pm_score": 2, "selected": false, "text": "<p>i wrote a helper function that handles your cases (and some more). Feel free to alter it to your specific needs</p>\n\n<pre><code>/**\n * @example\n * &lt;code&gt;\n * var pageRequestParams = {'enableFeatureX': 'true'};\n * toBool(pageRequestParams.enableFeatureX); // returns true\n *\n * toBool(pageRequestParams.enableFeatureY, true, options.enableFeatureY)\n * &lt;/code&gt;\n * @param {*}value\n * @param {Boolean}[mapEmptyStringToTrue=false]\n * @param {Boolean}[defaultVal=false] this is returned if value is undefined.\n *\n * @returns {Boolean}\n * @example\n * &lt;code&gt;\n * toBool({'enableFeatureX': '' }.enableFeatureX); // false\n * toBool({'enableFeatureX': '' }.enableFeatureX, true); // true\n * toBool({ }.enableFeatureX, true); // false\n * toBool({'enableFeatureX': 0 }.enableFeatureX); // false\n * toBool({'enableFeatureX': '0' }.enableFeatureX); // false\n * toBool({'enableFeatureX': '0 ' }.enableFeatureX); // false\n * toBool({'enableFeatureX': 'false' }.enableFeatureX); // false\n * toBool({'enableFeatureX': 'falsE ' }.enableFeatureX); // false\n * toBool({'enableFeatureX': 'no' }.enableFeatureX); // false\n *\n * toBool({'enableFeatureX': 1 }.enableFeatureX); // true\n * toBool({'enableFeatureX': '-2' }.enableFeatureX); // true\n * toBool({'enableFeatureX': 'true' }.enableFeatureX); // true\n * toBool({'enableFeatureX': 'false_' }.enableFeatureX); // true\n * toBool({'enableFeatureX': 'john doe'}.enableFeatureX); // true\n * &lt;/code&gt;\n *\n */\nvar toBool = function (value, mapEmptyStringToTrue, defaultVal) {\n if (value === undefined) {return Boolean(defaultVal); }\n mapEmptyStringToTrue = mapEmptyStringToTrue !== undefined ? mapEmptyStringToTrue : false; // default to false\n var strFalseValues = ['0', 'false', 'no'].concat(!mapEmptyStringToTrue ? [''] : []);\n if (typeof value === 'string') {\n return (strFalseValues.indexOf(value.toLowerCase().trim()) === -1);\n }\n // value is likely null, boolean, or number\n return Boolean(value);\n};\n</code></pre>\n" }, { "answer_id": 17264572, "author": "Andreas Dyballa", "author_id": 1636136, "author_profile": "https://Stackoverflow.com/users/1636136", "pm_score": 2, "selected": false, "text": "<pre><code> MyLib.Convert.bool = function(param) {\n var res = String(param).toLowerCase();\n return !(!Boolean(res) || res === \"false\" || res === \"0\");\n }; \n</code></pre>\n" }, { "answer_id": 17558318, "author": "user3638793", "author_id": 3638793, "author_profile": "https://Stackoverflow.com/users/3638793", "pm_score": 2, "selected": false, "text": "<p>Here is my 1 liner submission: I needed to evaluate a string and output, true if 'true', false if 'false' and a number if anything like '-12.35673'.</p>\n\n<pre><code>val = 'false';\n\nval = /^false$/i.test(val) ? false : ( /^true$/i.test(val) ? true : val*1 ? val*1 : val );\n</code></pre>\n" }, { "answer_id": 17961343, "author": "zobier", "author_id": 18469, "author_profile": "https://Stackoverflow.com/users/18469", "pm_score": 4, "selected": false, "text": "<p>I use the following:</p>\n\n<pre><code>function parseBool(b) {\n return !(/^(false|0)$/i).test(b) &amp;&amp; !!b;\n}\n</code></pre>\n\n<p>This function performs the usual Boolean coercion with the exception of the strings \"false\" (case insensitive) and \"0\".</p>\n" }, { "answer_id": 18355136, "author": "Dead.Rabit", "author_id": 424963, "author_profile": "https://Stackoverflow.com/users/424963", "pm_score": 3, "selected": false, "text": "<p>I'm a little late, but I have a little snippet to do this, it essentially maintains all of JScripts truthey/falsey/<em>filthy</em>-ness but includes <code>\"false\"</code> as an acceptible value for false.</p>\n\n<p>I prefer this method to the ones mentioned because it doesn't rely on a 3rd party to parse the code (i.e: eval/JSON.parse), which is overkill in my mind, it's short enough to not require a utility function and maintains other truthey/falsey conventions.</p>\n\n<pre><code>var value = \"false\";\nvar result = (value == \"false\") != Boolean(value);\n\n// value = \"true\" =&gt; result = true\n// value = \"false\" =&gt; result = false\n// value = true =&gt; result = true\n// value = false =&gt; result = false\n// value = null =&gt; result = false\n// value = [] =&gt; result = true\n// etc..\n</code></pre>\n" }, { "answer_id": 19394362, "author": "Cliff Mayson", "author_id": 1100126, "author_profile": "https://Stackoverflow.com/users/1100126", "pm_score": 3, "selected": false, "text": "<pre><code>function parseBool(value) {\n if (typeof value === \"boolean\") return value;\n\n if (typeof value === \"number\") {\n return value === 1 ? true : value === 0 ? false : undefined;\n }\n\n if (typeof value != \"string\") return undefined;\n\n return value.toLowerCase() === 'true' ? true : false;\n}\n</code></pre>\n" }, { "answer_id": 19882502, "author": "CMCDragonkai", "author_id": 582917, "author_profile": "https://Stackoverflow.com/users/582917", "pm_score": 3, "selected": false, "text": "<p>I wrote a function to match PHP's filter_var which does this nicely. Available in a gist: <a href=\"https://gist.github.com/CMCDragonkai/7389368\" rel=\"noreferrer\">https://gist.github.com/CMCDragonkai/7389368</a></p>\n\n<pre><code>/**\n * Parses mixed type values into booleans. This is the same function as filter_var in PHP using boolean validation\n * @param {Mixed} value \n * @param {Boolean} nullOnFailure = false\n * @return {Boolean|Null}\n */\nvar parseBooleanStyle = function(value, nullOnFailure = false){\n switch(value){\n case true:\n case 'true':\n case 1:\n case '1':\n case 'on':\n case 'yes':\n value = true;\n break;\n case false:\n case 'false':\n case 0:\n case '0':\n case 'off':\n case 'no':\n value = false;\n break;\n default:\n if(nullOnFailure){\n value = null;\n }else{\n value = false;\n }\n break;\n }\n return value;\n};\n</code></pre>\n" }, { "answer_id": 21285901, "author": "Jan Remunda", "author_id": 77154, "author_profile": "https://Stackoverflow.com/users/77154", "pm_score": 5, "selected": false, "text": "<p>Universal solution with JSON parse:</p>\n\n<pre><code>function getBool(val) {\n return !!JSON.parse(String(val).toLowerCase());\n}\n\ngetBool(\"1\"); //true\ngetBool(\"0\"); //false\ngetBool(\"true\"); //true\ngetBool(\"false\"); //false\ngetBool(\"TRUE\"); //true\ngetBool(\"FALSE\"); //false\n</code></pre>\n\n<p>UPDATE (without JSON):</p>\n\n<pre><code>function getBool(val){ \n var num = +val;\n return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');\n}\n</code></pre>\n\n<p>I also created fiddle to test it <a href=\"http://jsfiddle.net/remunda/2GRhG/\">http://jsfiddle.net/remunda/2GRhG/</a></p>\n" }, { "answer_id": 21824488, "author": "Kyle Falconer", "author_id": 940217, "author_profile": "https://Stackoverflow.com/users/940217", "pm_score": 2, "selected": false, "text": "<p>A lot of the existing answers are similar, but most ignore the fact that the given argument could also be an object.</p>\n\n<p>Here is something I just whipped up:</p>\n\n<pre><code>Utils.parseBoolean = function(val){\n if (typeof val === 'string' || val instanceof String){\n return /true/i.test(val);\n } else if (typeof val === 'boolean' || val instanceof Boolean){\n return new Boolean(val).valueOf();\n } else if (typeof val === 'number' || val instanceof Number){\n return new Number(val).valueOf() !== 0;\n }\n return false;\n};\n</code></pre>\n\n<p>...and the unit test for it</p>\n\n<pre><code>Utils.Tests = function(){\n window.console.log('running unit tests');\n\n var booleanTests = [\n ['true', true],\n ['false', false],\n ['True', true],\n ['False', false],\n [, false],\n [true, true],\n [false, false],\n ['gibberish', false],\n [0, false],\n [1, true]\n ];\n\n for (var i = 0; i &lt; booleanTests.length; i++){\n var lhs = Utils.parseBoolean(booleanTests[i][0]);\n var rhs = booleanTests[i][1];\n var result = lhs === rhs;\n\n if (result){\n console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\\t : \\tpass');\n } else {\n console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\\t : \\tfail');\n }\n }\n};\n</code></pre>\n" }, { "answer_id": 21976486, "author": "BrDaHa", "author_id": 1827734, "author_profile": "https://Stackoverflow.com/users/1827734", "pm_score": 6, "selected": false, "text": "<p>I thought that @Steven 's answer was the best one, and took care of a lot more cases than if the incoming value was just a string. I wanted to extend it a bit and offer the following:</p>\n\n<pre><code>function isTrue(value){\n if (typeof(value) === 'string'){\n value = value.trim().toLowerCase();\n }\n switch(value){\n case true:\n case \"true\":\n case 1:\n case \"1\":\n case \"on\":\n case \"yes\":\n return true;\n default: \n return false;\n }\n}\n</code></pre>\n\n<p>It's not necessary to cover all the <code>false</code> cases if you already know all of the <code>true</code> cases you'd have to account for. You can pass anything into this method that could pass for a <code>true</code> value (or add others, it's pretty straightforward), and everything else would be considered <code>false</code></p>\n" }, { "answer_id": 22236564, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 6, "selected": false, "text": "<p>Wood-eye be careful.\nAfter seeing the consequences after applying the top answer with 500+ upvotes, I feel obligated to post something that is actually useful:</p>\n<p>Let's start with the shortest, but very strict way:</p>\n<pre><code>var str = &quot;true&quot;;\nvar mybool = JSON.parse(str);\n</code></pre>\n<p>And end with a proper, more tolerant way:</p>\n<pre><code>var parseBool = function(str, strict) \n{\n // console.log(typeof str);\n // strict: JSON.parse(str)\n \n if (str == null)\n {\n if (strict)\n throw new Error(&quot;Parameter 'str' is null or undefined.&quot;);\n\n return false;\n }\n \n if (typeof str === 'boolean')\n {\n return (str === true);\n } \n \n if(typeof str === 'string')\n {\n if(str == &quot;&quot;)\n return false;\n \n str = str.replace(/^\\s+|\\s+$/g, '');\n if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')\n return true;\n \n str = str.replace(/,/g, '.');\n str = str.replace(/^\\s*\\-\\s*/g, '-');\n }\n \n // var isNum = string.match(/^[0-9]+$/) != null;\n // var isNum = /^\\d+$/.test(str);\n if(!isNaN(str))\n return (parseFloat(str) != 0);\n \n return false;\n}\n</code></pre>\n<p>Testing:</p>\n<pre><code>var array_1 = new Array(true, 1, &quot;1&quot;,-1, &quot;-1&quot;, &quot; - 1&quot;, &quot;true&quot;, &quot;TrUe&quot;, &quot; true &quot;, &quot; TrUe&quot;, 1/0, &quot;1.5&quot;, &quot;1,5&quot;, 1.5, 5, -3, -0.1, 0.1, &quot; - 0.1&quot;, Infinity, &quot;Infinity&quot;, -Infinity, &quot;-Infinity&quot;,&quot; - Infinity&quot;, &quot; yEs&quot;);\n\nvar array_2 = new Array(null, &quot;&quot;, false, &quot;false&quot;, &quot; false &quot;, &quot; f alse&quot;, &quot;FaLsE&quot;, 0, &quot;00&quot;, &quot;1/0&quot;, 0.0, &quot;0.0&quot;, &quot;0,0&quot;, &quot;100a&quot;, &quot;1 00&quot;, &quot; 0 &quot;, 0.0, &quot;0.0&quot;, -0.0, &quot;-0.0&quot;, &quot; -1a &quot;, &quot;abc&quot;);\n\n\nfor(var i =0; i &lt; array_1.length;++i){ console.log(&quot;array_1[&quot;+i+&quot;] (&quot;+array_1[i]+&quot;): &quot; + parseBool(array_1[i]));}\n\nfor(var i =0; i &lt; array_2.length;++i){ console.log(&quot;array_2[&quot;+i+&quot;] (&quot;+array_2[i]+&quot;): &quot; + parseBool(array_2[i]));}\n\nfor(var i =0; i &lt; array_1.length;++i){ console.log(parseBool(array_1[i]));}\nfor(var i =0; i &lt; array_2.length;++i){ console.log(parseBool(array_2[i]));}\n</code></pre>\n" }, { "answer_id": 22988422, "author": "user3310384", "author_id": 3310384, "author_profile": "https://Stackoverflow.com/users/3310384", "pm_score": 2, "selected": false, "text": "<p>A shorter way to write this, could be <code>var isTrueSet = (myValue === \"true\") ? true : false;</code> Presuming only \"true\" is true and other values are false. </p>\n" }, { "answer_id": 24414775, "author": "Mahes", "author_id": 301960, "author_profile": "https://Stackoverflow.com/users/301960", "pm_score": 2, "selected": false, "text": "<p>Simple solution i have been using it for a while</p>\n\n<pre><code>function asBoolean(value) {\n\n return (''+value) === 'true'; \n\n}\n\n\n// asBoolean(true) ==&gt; true\n// asBoolean(false) ==&gt; false\n// asBoolean('true') ==&gt; true\n// asBoolean('false') ==&gt; false\n</code></pre>\n" }, { "answer_id": 24744599, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 5, "selected": false, "text": "<pre><code>var falsy = /^(?:f(?:alse)?|no?|0+)$/i;\nBoolean.parse = function(val) { \n return !falsy.test(val) &amp;&amp; !!val;\n};\n</code></pre>\n\n<p>This returns <code>false</code> for every falsy value and <code>true</code> for every truthy value except for <code>'false'</code>, <code>'f'</code>, <code>'no'</code>, <code>'n'</code>, and <code>'0'</code> (case-insensitive).</p>\n\n<pre><code>// False\nBoolean.parse(false);\nBoolean.parse('false');\nBoolean.parse('False');\nBoolean.parse('FALSE');\nBoolean.parse('f');\nBoolean.parse('F');\nBoolean.parse('no');\nBoolean.parse('No');\nBoolean.parse('NO');\nBoolean.parse('n');\nBoolean.parse('N');\nBoolean.parse('0');\nBoolean.parse('');\nBoolean.parse(0);\nBoolean.parse(null);\nBoolean.parse(undefined);\nBoolean.parse(NaN);\nBoolean.parse();\n\n//True\nBoolean.parse(true);\nBoolean.parse('true');\nBoolean.parse('True');\nBoolean.parse('t');\nBoolean.parse('yes');\nBoolean.parse('YES');\nBoolean.parse('y');\nBoolean.parse('1');\nBoolean.parse('foo');\nBoolean.parse({});\nBoolean.parse(1);\nBoolean.parse(-1);\nBoolean.parse(new Date());\n</code></pre>\n" }, { "answer_id": 25899590, "author": "konsumer", "author_id": 656398, "author_profile": "https://Stackoverflow.com/users/656398", "pm_score": 2, "selected": false, "text": "<p>I do this, which will handle 1=TRUE=yes=YES=true, 0=FALSE=no=NO=false:</p>\n\n<pre><code>BOOL=false\nif (STRING)\n BOOL=JSON.parse(STRING.toLowerCase().replace('no','false').replace('yes','true'));\n</code></pre>\n\n<p>Replace STRING with the name of your string variable.</p>\n\n<p>If it's not null, a numerical value or one of these strings:\n\"true\", \"TRUE\", \"false\", \"FALSE\", \"yes\", \"YES\", \"no\", \"NO\"\nIt will throw an error (intentionally.)</p>\n" }, { "answer_id": 28152765, "author": "Timo Ernst", "author_id": 286149, "author_profile": "https://Stackoverflow.com/users/286149", "pm_score": 3, "selected": false, "text": "<p>I use an own method which includes a check if the object exists first and a more intuitive conversion to boolean:</p>\n\n<pre><code>function str2bool(strvalue){\n return (strvalue &amp;&amp; typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true' || strvalue == '1') : (strvalue == true);\n}\n</code></pre>\n\n<p>The results are:</p>\n\n<pre><code>var test; // false\nvar test2 = null; // false\nvar test3 = 'undefined'; // false\nvar test4 = 'true'; // true\nvar test5 = 'false'; // false\nvar test6 = true; // true\nvar test7 = false; // false\nvar test8 = 1; // true\nvar test9 = 0; // false\nvar test10 = '1'; // true\nvar test11 = '0'; // false\n</code></pre>\n\n<p>Fiddle:\n<a href=\"http://jsfiddle.net/av5xcj6s/\" rel=\"nofollow\">http://jsfiddle.net/av5xcj6s/</a></p>\n" }, { "answer_id": 28374239, "author": "Adam Pietrasiak", "author_id": 2446799, "author_profile": "https://Stackoverflow.com/users/2446799", "pm_score": 3, "selected": false, "text": "<p>I'm using this one</p>\n\n<pre><code>String.prototype.maybeBool = function(){\n\n if ( [\"yes\", \"true\", \"1\", \"on\"].indexOf( this.toLowerCase() ) !== -1 ) return true;\n if ( [\"no\", \"false\", \"0\", \"off\"].indexOf( this.toLowerCase() ) !== -1 ) return false;\n\n return this;\n\n}\n\n\"on\".maybeBool(); //returns true;\n\"off\".maybeBool(); //returns false;\n\"I like js\".maybeBool(); //returns \"I like js\"\n</code></pre>\n" }, { "answer_id": 28588344, "author": "sospedra", "author_id": 2824333, "author_profile": "https://Stackoverflow.com/users/2824333", "pm_score": 4, "selected": false, "text": "<p>There are a lot of answers and it's hard to pick one. In my case, I prioritise the performance when choosing, so I create <a href=\"https://jsperf.com/cast-booleans\" rel=\"noreferrer\">this jsPerf</a> that I hope can throw some light here.</p>\n\n<p>Brief of results (the higher the better):</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/264037/2824333\"><strong>Conditional statement</strong></a>: 2,826,922</li>\n<li><a href=\"https://stackoverflow.com/a/2114091/2824333\"><strong>Switch case on Bool object</strong></a>: 2,825,469</li>\n<li><a href=\"https://stackoverflow.com/a/7833897/2824333\"><strong>Casting to JSON</strong></a>: 1,867,774</li>\n<li><a href=\"https://stackoverflow.com/a/21285901/2824333\"><strong>!! conversions</strong></a>: 805,322</li>\n<li><a href=\"https://stackoverflow.com/a/264180/2824333\"><strong>Prototype of String</strong></a>: 713,637</li>\n</ol>\n\n<p>They are linked to the related answer where you can find more information (pros and cons) about each one; specially in the comments.</p>\n" }, { "answer_id": 28706707, "author": "Martin Malinda", "author_id": 3997622, "author_profile": "https://Stackoverflow.com/users/3997622", "pm_score": 2, "selected": false, "text": "<p>To evaluate both boolean and boolean-like strings like boolean I used this easy formula:</p>\n\n<pre><code>var trueOrStringTrue = (trueOrStringTrue === true) || (trueOrStringTrue === 'true');\n</code></pre>\n\n<p>As is apparent, it will return true for both true and 'true'. Everything else returns false.</p>\n" }, { "answer_id": 28987637, "author": "Fizer Khan", "author_id": 1154350, "author_profile": "https://Stackoverflow.com/users/1154350", "pm_score": 4, "selected": false, "text": "<p>To convert both string(\"true\", \"false\") and boolean to boolean</p>\n\n<pre><code>('' + flag) === \"true\"\n</code></pre>\n\n<p>Where <code>flag</code> can be </p>\n\n<pre><code> var flag = true\n var flag = \"true\"\n var flag = false\n var flag = \"false\"\n</code></pre>\n" }, { "answer_id": 29838350, "author": "null", "author_id": 1521606, "author_profile": "https://Stackoverflow.com/users/1521606", "pm_score": -1, "selected": false, "text": "<p>works perfectly and very simple: </p>\n\n<pre><code>var boolean = \"false\";\nboolean = (boolean === \"true\");\n\n//boolean = JSON.parse(boolean); //or this way.. \n</code></pre>\n\n<p>to test it: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var boolean = \"false\";\r\nboolean = (boolean === \"true\");\r\n\r\n//boolean = JSON.parse(boolean); //or this way.. \r\n\r\nif(boolean == true){\r\n alert(\"boolean = \"+boolean);\r\n}else{\r\n alert(\"boolean = \"+boolean);\r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 31767875, "author": "vbranden", "author_id": 4723237, "author_profile": "https://Stackoverflow.com/users/4723237", "pm_score": 3, "selected": false, "text": "<p>another solution. <a href=\"http://jsfiddle.net/r5p7qobn/\">jsFiddle</a></p>\n\n<pre><code>var toBoolean = function(value) {\n var strValue = String(value).toLowerCase();\n strValue = ((!isNaN(strValue) &amp;&amp; strValue !== '0') &amp;&amp;\n strValue !== '' &amp;&amp;\n strValue !== 'null' &amp;&amp;\n strValue !== 'undefined') ? '1' : strValue;\n return strValue === 'true' || strValue === '1' ? true : false\n};\n</code></pre>\n\n<p>test cases run in node</p>\n\n<pre><code>&gt; toBoolean(true)\ntrue\n&gt; toBoolean(false)\nfalse\n&gt; toBoolean(undefined)\nfalse\n&gt; toBoolean(null)\nfalse\n&gt; toBoolean('true')\ntrue\n&gt; toBoolean('True')\ntrue\n&gt; toBoolean('False')\nfalse\n&gt; toBoolean('false')\nfalse\n&gt; toBoolean('0')\nfalse\n&gt; toBoolean('1')\ntrue\n&gt; toBoolean('100')\ntrue\n&gt; \n</code></pre>\n" }, { "answer_id": 34296412, "author": "Eugene Tiurin", "author_id": 2676500, "author_profile": "https://Stackoverflow.com/users/2676500", "pm_score": 2, "selected": false, "text": "<h1>The fastest safe way to convert a string to a boolean in one line of code</h1>\n<p>One of features that help to fasten the code execution in Javascript is <em>Short-Circuit Evaluation</em>:</p>\n<blockquote>\n<p>As logical expressions are evaluated left to right, they are tested for possible &quot;short-circuit&quot; evaluation using the following rules:</p>\n<ul>\n<li>false &amp;&amp; (anything) is short-circuit evaluated to false.</li>\n<li>true || (anything) is short-circuit evaluated to true.</li>\n</ul>\n</blockquote>\n<p>So that if you want to test a string value for being <code>true</code> of <code>false</code> in <code>JSON.parse</code> way of test and keep the performance strong, you may use the <code>||</code> operator to exclude the slow code from execution in case the test value is of boolean type.</p>\n<pre><code>test === true || ['true','yes','1'].indexOf(test.toString().toLowerCase()) &gt; -1\n</code></pre>\n<p>As the <code>Array.prototype.indexOf()</code> method is a part of <em>ECMA-262</em> standard in the 5th edition, you may need a <strong>polyfill</strong> for the old browsers support.</p>\n<pre><code>// Production steps of ECMA-262, Edition 5, 15.4.4.14\n// Reference: http://es5.github.io/#x15.4.4.14\nif (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function(searchElement, fromIndex) {\n\n var k;\n\n // 1. Let O be the result of calling ToObject passing\n // the this value as the argument.\n if (this == null) {\n throw new TypeError('&quot;this&quot; is null or not defined');\n }\n\n var O = Object(this);\n\n // 2. Let lenValue be the result of calling the Get\n // internal method of O with the argument &quot;length&quot;.\n // 3. Let len be ToUint32(lenValue).\n var len = O.length &gt;&gt;&gt; 0;\n\n // 4. If len is 0, return -1.\n if (len === 0) {\n return -1;\n }\n\n // 5. If argument fromIndex was passed let n be\n // ToInteger(fromIndex); else let n be 0.\n var n = +fromIndex || 0;\n\n if (Math.abs(n) === Infinity) {\n n = 0;\n }\n\n // 6. If n &gt;= len, return -1.\n if (n &gt;= len) {\n return -1;\n }\n\n // 7. If n &gt;= 0, then Let k be n.\n // 8. Else, n&lt;0, Let k be len - abs(n).\n // If k is less than 0, then let k be 0.\n k = Math.max(n &gt;= 0 ? n : len - Math.abs(n), 0);\n\n // 9. Repeat, while k &lt; len\n while (k &lt; len) {\n // a. Let Pk be ToString(k).\n // This is implicit for LHS operands of the in operator\n // b. Let kPresent be the result of calling the\n // HasProperty internal method of O with argument Pk.\n // This step can be combined with c\n // c. If kPresent is true, then\n // i. Let elementK be the result of calling the Get\n // internal method of O with the argument ToString(k).\n // ii. Let same be the result of applying the\n // Strict Equality Comparison Algorithm to\n // searchElement and elementK.\n // iii. If same is true, return k.\n if (k in O &amp;&amp; O[k] === searchElement) {\n return k;\n }\n k++;\n }\n return -1;\n };\n}\n</code></pre>\n" }, { "answer_id": 35986765, "author": "Siten", "author_id": 785775, "author_profile": "https://Stackoverflow.com/users/785775", "pm_score": 1, "selected": false, "text": "<p>To Get Boolean values from string or number Here is good solution:</p>\n\n<pre><code>var boolValue = Boolean(Number('0'));\n\nvar boolValue = Boolean(Number('1'));\n</code></pre>\n\n<p>First will return <code>false</code> and second will return <code>true</code>.</p>\n" }, { "answer_id": 36173924, "author": "ecabuk", "author_id": 629760, "author_profile": "https://Stackoverflow.com/users/629760", "pm_score": 3, "selected": false, "text": "<pre><code>function isTrue(val) {\n try {\n return !!JSON.parse(val);\n } catch {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 36705508, "author": "jdnichollsc", "author_id": 1532821, "author_profile": "https://Stackoverflow.com/users/1532821", "pm_score": 2, "selected": false, "text": "<p>Take care, maybe in the future the code change and return boolean instead of one string at the moment.</p>\n\n<p>The solution would be:</p>\n\n<pre><code>//Currently\nvar isTrue = 'true';\n//In the future (Other developer change the code)\nvar isTrue = true;\n//The solution to both cases\n(isTrue).toString() == 'true'\n</code></pre>\n" }, { "answer_id": 36942239, "author": "benipsen", "author_id": 296073, "author_profile": "https://Stackoverflow.com/users/296073", "pm_score": 3, "selected": false, "text": "<p>Lots of fancy answers here. Really surprised no one has posted this solution:</p>\n\n<pre><code>var booleanVal = toCast &gt; '';\n</code></pre>\n\n<p>This resolves to true in most cases other than bool false, number zero and empty string (obviously). You can easily look for other falsey string values after the fact e.g.:</p>\n\n<pre><code>var booleanVal = toCast &gt; '' &amp;&amp; toCast != 'false' &amp;&amp; toCast != '0'; \n</code></pre>\n" }, { "answer_id": 37610883, "author": "Sandip Nirmal", "author_id": 1904377, "author_profile": "https://Stackoverflow.com/users/1904377", "pm_score": 4, "selected": false, "text": "<p>There are already so many answers available. But following can be useful in some scenarios.</p>\n\n<pre><code>// One can specify all values against which you consider truthy\nvar TRUTHY_VALUES = [true, 'true', 1];\n\nfunction getBoolean(a) {\n return TRUTHY_VALUES.some(function(t) {\n return t === a;\n });\n}\n</code></pre>\n\n<p>This can be useful where one examples with non-boolean values.</p>\n\n<pre><code>getBoolean('aa'); // false\ngetBoolean(false); //false\ngetBoolean('false'); //false\n\ngetBoolean('true'); // true\ngetBoolean(true); // true\ngetBoolean(1); // true\n</code></pre>\n" }, { "answer_id": 40801019, "author": "Hakan Fıstık", "author_id": 4390133, "author_profile": "https://Stackoverflow.com/users/4390133", "pm_score": 4, "selected": false, "text": "<p>This has been taken from the accepted answer, but really it has a very weak point, and I am shocked how it got that count of upvotes, the problem with it that you have to consider the case of the string because this is case sensitive</p>\n\n<pre><code>var isTrueSet = (myValue.toLowerCase() === 'true');\n</code></pre>\n" }, { "answer_id": 41508677, "author": "jose.serapicos", "author_id": 6645736, "author_profile": "https://Stackoverflow.com/users/6645736", "pm_score": 2, "selected": false, "text": "<p>I use this simple approach (using \"myVarToTest\"):</p>\n\n<pre><code>var trueValuesRange = ['1', 1, 'true', true];\n\nmyVarToTest = (trueValuesRange.indexOf(myVarToTest) &gt;= 0);\n</code></pre>\n" }, { "answer_id": 42136805, "author": "Rohman HM", "author_id": 5531595, "author_profile": "https://Stackoverflow.com/users/5531595", "pm_score": 2, "selected": false, "text": "<p>Take it easy using this lib.</p>\n\n<p><a href=\"https://github.com/rohmanhm/force-boolean\" rel=\"nofollow noreferrer\">https://github.com/rohmanhm/force-boolean</a></p>\n\n<p>you just need to write a single line</p>\n\n<pre><code>const ForceBoolean = require('force-boolean')\n\nconst YOUR_VAR = 'false'\nconsole.log(ForceBoolean(YOUR_VAR)) // it's return boolean false\n</code></pre>\n\n<p>It's also support for following</p>\n\n<pre><code> return false if value is number 0\n return false if value is string '0'\n return false if value is string 'false'\n return false if value is boolean false\n return true if value is number 1\n return true if value is string '1'\n return true if value is string 'true'\n return true if value is boolean true\n</code></pre>\n" }, { "answer_id": 42220613, "author": "Steve Mc", "author_id": 126540, "author_profile": "https://Stackoverflow.com/users/126540", "pm_score": 1, "selected": false, "text": "<pre><code>var trueVals = [\"y\", \"t\", \"yes\", \"true\", \"gimme\"];\nvar isTrueSet = (trueVals.indexOf(myValue) &gt; -1) ? true : false;\n</code></pre>\n\n<p>or even just</p>\n\n<pre><code>var trueVals = [\"y\", \"t\", \"yes\", \"true\", \"gimme\"];\nvar isTrueSet = (trueVals.indexOf(myValue) &gt; -1);\n</code></pre>\n\n<p>Similar to some of the switch statements but more compact. The value returned will only be true if the string is one of the trueVals strings. Everything else is false. Of course, you might want to normalise the input string to make it lower case and trim any spaces.</p>\n" }, { "answer_id": 43327897, "author": "Surya R Praveen", "author_id": 714707, "author_profile": "https://Stackoverflow.com/users/714707", "pm_score": 1, "selected": false, "text": "<p><strong>Convert String to Boolean</strong></p>\n\n<pre><code>var vIn = \"true\";\nvar vOut = vIn.toLowerCase()==\"true\"?1:0;\n</code></pre>\n\n<p><strong>Convert String to Number</strong></p>\n\n<pre><code>var vIn = 0;\nvar vOut = parseInt(vIn,10/*base*/);\n</code></pre>\n" }, { "answer_id": 43694886, "author": "Dayem Siddiqui", "author_id": 4400495, "author_profile": "https://Stackoverflow.com/users/4400495", "pm_score": 2, "selected": false, "text": "<p>Here is simple function that will do the trick,</p>\n\n<pre><code> function convertStringToBool(str){\n return ((str === \"True\") || (str === \"true\")) ? true:false;\n }\n</code></pre>\n\n<p>This will give the following result</p>\n\n<pre><code>convertStringToBool(\"false\") //returns false\nconvertStringToBool(\"true\") // returns true\nconvertStringToBool(\"False\") // returns false\nconvertStringToBool(\"True\") // returns true\n</code></pre>\n" }, { "answer_id": 43852081, "author": "Vitim.us", "author_id": 938822, "author_profile": "https://Stackoverflow.com/users/938822", "pm_score": 3, "selected": false, "text": "<h1>One Liner</h1>\n\n<p>We just need to account for the \"false\" string since any other string (including \"true\") is already <code>true</code>.</p>\n\n<pre><code>function b(v){ return v===\"false\" ? false : !!v; }\n</code></pre>\n\n<p><strong>Test</strong></p>\n\n<pre><code>b(true) //true\nb('true') //true\nb(false) //false\nb('false') //false\n</code></pre>\n\n<hr>\n\n<h3>A more exaustive version</h3>\n\n<pre><code>function bool(v){ return v===\"false\" || v===\"null\" || v===\"NaN\" || v===\"undefined\" || v===\"0\" ? false : !!v; }\n</code></pre>\n\n<p><strong>Test</strong></p>\n\n<pre><code>bool(true) //true\nbool(\"true\") //true\nbool(1) //true\nbool(\"1\") //true\nbool(\"hello\") //true\n\nbool(false) //false\nbool(\"false\") //false\nbool(0) //false\nbool(\"0\") //false\nbool(null) //false\nbool(\"null\") //false\nbool(NaN) //false\nbool(\"NaN\") //false\nbool(undefined) //false\nbool(\"undefined\") //false\nbool(\"\") //false\n\nbool([]) //true\nbool({}) //true\nbool(alert) //true\nbool(window) //true\n</code></pre>\n" }, { "answer_id": 43996304, "author": "Chanakya Vadla", "author_id": 919216, "author_profile": "https://Stackoverflow.com/users/919216", "pm_score": 3, "selected": false, "text": "<pre><code>String(true).toLowerCase() == 'true'; // true\nString(\"true\").toLowerCase() == 'true'; // true\nString(\"True\").toLowerCase() == 'true'; // true\nString(\"TRUE\").toLowerCase() == 'true'; // true\n\nString(false).toLowerCase() == 'true'; // false\n</code></pre>\n\n<p>If you are not sure of the input, the above works for boolean and as well any string.</p>\n" }, { "answer_id": 45181561, "author": "guest271314", "author_id": 2801559, "author_profile": "https://Stackoverflow.com/users/2801559", "pm_score": 0, "selected": false, "text": "<p>You can use <code>Function</code> to return a <code>Boolean</code> value from string <code>\"true\"</code> or <code>\"false\"</code></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const TRUE_OR_FALSE = str =&gt; new Function(`return ${str}`)();\r\n\r\nconst [TRUE, FALSE] = [\"true\", \"false\"];\r\n\r\nconst [T, F] = [TRUE_OR_FALSE(TRUE), TRUE_OR_FALSE(FALSE)];\r\n\r\nconsole.log(T, typeof T); // `true` `\"boolean\"`\r\n\r\nconsole.log(F, typeof F); // `false` `\"boolean\"`</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 45294201, "author": "Mohammad Farahani", "author_id": 4764069, "author_profile": "https://Stackoverflow.com/users/4764069", "pm_score": 4, "selected": false, "text": "<p>you can use <code>JSON.parse</code> as follows:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> \nvar trueOrFalse='True';\nresult =JSON.parse(trueOrFalse.toLowerCase());\nif(result==true)\n alert('this is true');\nelse \n alert('this is false');</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>in this case <code>.toLowerCase</code> is important</p>\n" }, { "answer_id": 45448872, "author": "danday74", "author_id": 1205871, "author_profile": "https://Stackoverflow.com/users/1205871", "pm_score": 0, "selected": false, "text": "<p>The `toBoolean' function returns false for null, undefined, '', 'false'. It returns true for any other string:</p>\n\n<pre><code>const toBoolean = (bool) =&gt; {\n if (bool === 'false') bool = false\n return !!bool\n}\n\ntoBoolean('false') // returns false\n</code></pre>\n" }, { "answer_id": 46944503, "author": "Kostanos", "author_id": 2215679, "author_profile": "https://Stackoverflow.com/users/2215679", "pm_score": 2, "selected": false, "text": "<p>I'm using this one when I get value from URL/Form or other source.</p>\n\n<p>It is pretty universal one line piece of code.</p>\n\n<p>Maybe not the best for performance, if you need to run it millions times let me know, we can check how to optimize it, otherwise is pretty good and customizable.</p>\n\n<pre><code>boolResult = !(['false', '0', '', 'undefined'].indexOf(String(myVar).toLowerCase().trim()) + 1);\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>myVar = true; // true\nmyVar = 'true'; // true\nmyVar = 'TRUE'; // true\nmyVar = '1'; // true\nmyVar = 'any other value not related to false'; // true\n\nmyVar = false; // false\nmyVar = 'false'; // false\nmyVar = 'FALSE'; // false\nmyVar = '0'; // false\n</code></pre>\n" }, { "answer_id": 47583302, "author": "OhkaBaka", "author_id": 39835, "author_profile": "https://Stackoverflow.com/users/39835", "pm_score": 3, "selected": false, "text": "<p>Holy god some of these answers are just wild. I love JS and its infinite number of ways to skin a bool.</p>\n\n<p>My preference, which I was shocked not to see already, is:</p>\n\n<pre><code>testVar = testVar.toString().match(/^(true|[1-9][0-9]*|[0-9]*[1-9]+|yes)$/i) ? true : false;\n</code></pre>\n" }, { "answer_id": 47817211, "author": "Yohan", "author_id": 7061173, "author_profile": "https://Stackoverflow.com/users/7061173", "pm_score": 3, "selected": false, "text": "<p>why don't you try something like this</p>\n\n<pre><code>Boolean(JSON.parse((yourString.toString()).toLowerCase()));\n</code></pre>\n\n<p>It will return an error when some other text is given rather than true or false regardless of the case and it will capture the numbers also as </p>\n\n<pre><code>// 0-&gt; false\n// any other number -&gt; true\n</code></pre>\n" }, { "answer_id": 48929869, "author": "pankaj sharma", "author_id": 6565872, "author_profile": "https://Stackoverflow.com/users/6565872", "pm_score": 4, "selected": false, "text": "<p>This function can handle string as well as Boolean true/false.</p>\n\n<pre><code>function stringToBoolean(val){\n var a = {\n 'true':true,\n 'false':false\n };\n return a[val];\n}\n</code></pre>\n\n<p>Demonstration below: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function stringToBoolean(val) {\r\n var a = {\r\n 'true': true,\r\n 'false': false\r\n };\r\n return a[val];\r\n}\r\n\r\nconsole.log(stringToBoolean(\"true\"));\r\n\r\nconsole.log(typeof(stringToBoolean(\"true\")));\r\n\r\nconsole.log(stringToBoolean(\"false\"));\r\n\r\nconsole.log(typeof(stringToBoolean(\"false\")));\r\n\r\nconsole.log(stringToBoolean(true));\r\n\r\nconsole.log(typeof(stringToBoolean(true)));\r\n\r\nconsole.log(stringToBoolean(false));\r\n\r\nconsole.log(typeof(stringToBoolean(false)));\r\n\r\nconsole.log(\"=============================================\");\r\n// what if value was undefined? \r\nconsole.log(\"undefined result: \" + stringToBoolean(undefined));\r\nconsole.log(\"type of undefined result: \" + typeof(stringToBoolean(undefined)));\r\nconsole.log(\"=============================================\");\r\n// what if value was an unrelated string?\r\nconsole.log(\"unrelated string result: \" + stringToBoolean(\"hello world\"));\r\nconsole.log(\"type of unrelated string result: \" + typeof(stringToBoolean(undefined)));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 54089613, "author": "Ratan Uday Kumar", "author_id": 6633337, "author_profile": "https://Stackoverflow.com/users/6633337", "pm_score": 2, "selected": false, "text": "<p>In nodejs by using <a href=\"https://www.npmjs.com/package/node-boolify\" rel=\"nofollow noreferrer\">node-boolify</a> it is possible</p>\n\n<p><strong>Boolean Conversion Results</strong></p>\n\n<pre><code>Boolify(true); //true\nBoolify('true'); //true\nBoolify('TRUE'); //null\nBoolify(1); //true\nBoolify(2); //null\nBoolify(false); //false\nBoolify('false'); //false\nBoolify('FALSE'); //null\nBoolify(0); //false\nBoolify(null); //null\nBoolify(undefined); //null\nBoolify(); //null\nBoolify(''); //null\n</code></pre>\n" }, { "answer_id": 55019413, "author": "Yuriy Litvin", "author_id": 2465869, "author_profile": "https://Stackoverflow.com/users/2465869", "pm_score": 2, "selected": false, "text": "<p>For TypeScript we can use the function:</p>\n\n<pre><code>export function stringToBoolean(s: string, valueDefault: boolean = false): boolean {\n switch(s.toLowerCase())\n {\n case \"true\":\n case \"1\":\n case \"on\":\n case \"yes\":\n case \"y\":\n return true;\n\n case \"false\":\n case \"0\":\n case \"off\":\n case \"no\":\n case \"n\":\n return false;\n }\n\n return valueDefault;\n}\n</code></pre>\n" }, { "answer_id": 55570048, "author": "Al Albers", "author_id": 931513, "author_profile": "https://Stackoverflow.com/users/931513", "pm_score": 3, "selected": false, "text": "<p>If you are certain that the test subject is always a string, then explicitly checking that it equals <code>true</code> is your best bet.</p>\n\n<p>You may want to consider including an extra bit of code just in case the subject could actually a boolean.</p>\n\n<pre><code>var isTrueSet =\n myValue === true ||\n myValue != null &amp;&amp;\n myValue.toString().toLowerCase() === 'true';\n</code></pre>\n\n<p>This could save you a bit of work in the future if the code gets improved/refactored to use actual boolean values instead of strings. </p>\n" }, { "answer_id": 56392251, "author": "panatoni", "author_id": 5731985, "author_profile": "https://Stackoverflow.com/users/5731985", "pm_score": 3, "selected": false, "text": "<p>The simplest way which I always use:</p>\n\n<pre><code>let value = 'true';\nlet output = value === 'true';\n</code></pre>\n" }, { "answer_id": 58470519, "author": "olegtaranenko", "author_id": 455491, "author_profile": "https://Stackoverflow.com/users/455491", "pm_score": 1, "selected": false, "text": "<p>I hope this is a most comprehensive use case</p>\n\n<pre><code>function parseBoolean(token) {\n if (typeof token === 'string') {\n switch (token.toLowerCase()) {\n case 'on':\n case 'yes':\n case 'ok':\n case 'ja':\n case 'да':\n // case '':\n // case '':\n token = true;\n break;\n default:\n token = false;\n }\n }\n let ret = false;\n try {\n ret = Boolean(JSON.parse(token));\n } catch (e) {\n // do nothing or make a notification\n }\n return ret;\n}\n</code></pre>\n" }, { "answer_id": 59824949, "author": "James Anderson Jr.", "author_id": 2690928, "author_profile": "https://Stackoverflow.com/users/2690928", "pm_score": 2, "selected": false, "text": "<p>Try this solution (it works like a charm!):</p>\n\n<pre><code>function convertStrToBool(str)\n {\n switch(String(str).toLowerCase())\n {\n case 'undefined': case 'null': case 'nan': case 'false': case 'no': case 'f': case 'n': case '0': case 'off': case '':\n return false;\n break;\n default:\n return true;\n };\n };\n</code></pre>\n" }, { "answer_id": 60324885, "author": "sçuçu", "author_id": 2605049, "author_profile": "https://Stackoverflow.com/users/2605049", "pm_score": 1, "selected": false, "text": "<p>In HTML the values of attributes eventually become strings. To mitigate that in undesired situations you can have a function to conditionally parse them into values they represent in the JavaScript or any other programming langauge of interest.</p>\n\n<p>Following is an explanation to do it for reviving boolean type from the string type, but it can be further expanded into other data types too, like numbers, arrays or objects.</p>\n\n<p>In addition to that JSON.parse has a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Examples\" rel=\"nofollow noreferrer\">revive parameter</a> which is a function. It also can be used to achieve the same.</p>\n\n<p>Let's call a string looking like a <em>boolean</em>, \"true\", a <em>boolean string</em> likewise we can call a string like a number, \"1\", a <em>number string</em>. Then we can determine if a string is a <em>boolean string</em>:</p>\n\n<pre><code>const isBooleanString = (string) =&gt; ['true', 'false'].some(item =&gt; item === string);\n</code></pre>\n\n<p>After that we need to parse the <em>boolean string</em> as JSON by <code>JSON.parse</code> method:</p>\n\n<pre><code>JSON.parse(aBooleanString);\n</code></pre>\n\n<p>However, any string that is not a <em>boolean string</em>, <em>number string</em>, or any stringified object or array (any invalid JSON) will cause the <code>JSON.parse</code> method to throw a <code>SyntaxError</code>.</p>\n\n<p>So, you will need to know with what to call it, i.e. if it is a <em>boolean string</em>. You can achieve this by writing a function that makes the above defiend <em>boolean string</em> check and call <code>JSON.parse</code>:</p>\n\n<pre><code>function parse(string){\n return isBooleanString(string) ? JSON.parse(string)\n : string;\n}\n</code></pre>\n\n<p>One can further generalize the <code>isBooleanString</code> utility to have a more broader perspective on what qualifies as a <em>boolean string</em> by further parametrizing it to accept an optional array of accepted <em>boolean</em> strings:</p>\n\n<pre><code>const isBooleanString = (string, spec = ['true', 'false', 'True', 'False']) =&gt; spec.some(item =&gt; item === string);\n</code></pre>\n" }, { "answer_id": 60430683, "author": "Faizan Khan", "author_id": 11884468, "author_profile": "https://Stackoverflow.com/users/11884468", "pm_score": 3, "selected": false, "text": "<p>The most simple way is </p>\n\n<pre><code>a = 'True';\na = !!a &amp;&amp; ['1', 'true', 1, true].indexOf(a.toLowerCase()) &gt; -1;\n</code></pre>\n" }, { "answer_id": 61674681, "author": "Mansi", "author_id": 6228036, "author_profile": "https://Stackoverflow.com/users/6228036", "pm_score": 1, "selected": false, "text": "<pre><code>const result: Boolean = strValue === \"true\" ? true : false\n</code></pre>\n" }, { "answer_id": 61681862, "author": "jacobq", "author_id": 1171509, "author_profile": "https://Stackoverflow.com/users/1171509", "pm_score": 2, "selected": false, "text": "<p>Many of the existing answers use an approach that is semantically similar to this,\nbut I think there is value in mentioning that the following \"one liner\" is often sufficient. For example, in addition to the OP's case (strings in a form) one often wants to read environment variables from <a href=\"https://nodejs.org/dist/latest-v14.x/docs/api/process.html#process_process_env\" rel=\"nofollow noreferrer\"><code>process.env</code></a> in <a href=\"https://nodejs.org/\" rel=\"nofollow noreferrer\">NodeJS</a> (whose values, to the best of my knowledge, are always strings) in order to enable or disable certain behaviors, and it is common for these to have the form <code>SOME_ENV_VAR=1</code>.</p>\n\n<pre><code>const toBooleanSimple = (input) =&gt; \n ['t', 'y', '1'].some(truePrefix =&gt; truePrefix === input[0].toLowerCase());\n</code></pre>\n\n<p>A slightly more robust and expressive implementation might look like this:</p>\n\n<pre><code>/**\n * Converts strings to booleans in a manner that is less surprising\n * to the non-JS world (e.g. returns true for \"1\", \"yes\", \"True\", etc.\n * and false for \"0\", \"No\", \"false\", etc.)\n * @param input\n * @returns {boolean}\n */\nfunction toBoolean(input) {\n if (typeof input !== 'string') {\n return Boolean(input);\n }\n const s = input.toLowerCase();\n return ['t', 'y', '1'].some(prefix =&gt; s.startsWith(prefix));\n}\n</code></pre>\n\n<p>A (jest) unit test for this might look like this:</p>\n\n<pre><code>describe(`toBoolean`, function() {\n const groups = [{\n inputs: ['y', 'Yes', 'true', '1', true, 1],\n expectedOutput: true\n }, {\n inputs: ['n', 'No', 'false', '0', false, 0],\n expectedOutput: false\n }]\n for (let group of groups) {\n for (let input of group.inputs) {\n it(`should return ${group.expectedOutput} for ${JSON.stringify(input)}`, function() {\n expect(toBoolean(input)).toEqual(group.expectedOutput);\n });\n } \n }\n});\n</code></pre>\n" }, { "answer_id": 62118423, "author": "Justin Liu", "author_id": 13363264, "author_profile": "https://Stackoverflow.com/users/13363264", "pm_score": 1, "selected": false, "text": "<h1>Use an <code>if</code> statment:</h1>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseBool(str) {\n if (str.toLowerCase() == 'true') {\n var val = true;\n } else if (str.toLowerCase() == 'false') {\n var val = false;\n } else {\n //If it is not true of false it returns undefined.//\n var val = undefined;\n }\n return val;\n}\nconsole.log(parseBool(''), typeof parseBool(''));\nconsole.log(parseBool('TrUe'), typeof parseBool('TrUe'));\nconsole.log(parseBool('false'), typeof parseBool('false'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 62175543, "author": "ritesh", "author_id": 3316084, "author_profile": "https://Stackoverflow.com/users/3316084", "pm_score": 2, "selected": false, "text": "<p><strong>WARNING:</strong> <em>Never</em> use this method for untrusted input, such as URL parameters.</p>\n<p>You can use the <code>eval()</code> function.\nDirectly pass your string to <code>eval()</code> function.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(eval('true'), typeof eval('true'))\nconsole.log(eval('false'), typeof eval('false'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 63042101, "author": "Neil Higgins", "author_id": 8876947, "author_profile": "https://Stackoverflow.com/users/8876947", "pm_score": 1, "selected": false, "text": "<p>You don't even need to use a variable, if you know that 'true' will always be lowercase you can use this which will return true or false:</p>\n<pre><code>(eval(yourBooleanString == 'true'))\n</code></pre>\n" }, { "answer_id": 63373352, "author": "Bhupender Keswani", "author_id": 4082735, "author_profile": "https://Stackoverflow.com/users/4082735", "pm_score": 1, "selected": false, "text": "<p>I think it can be done in 1 liner with a use arrow function</p>\n<pre><code>const convertStringToBoolean = (value) =&gt; value ? String(value).toLowerCase() === 'true' : false;\n</code></pre>\n<p>You guys can run and test various cases with following code snippet</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const convertStringToBoolean = (value) =&gt; value ? String(value).toLowerCase() === 'true' : false;\n\nconsole.log(convertStringToBoolean(\"a\"));\nconsole.log(convertStringToBoolean(null));\nconsole.log(convertStringToBoolean(undefined));\nconsole.log(convertStringToBoolean(\"undefined\"));\nconsole.log(convertStringToBoolean(true));\nconsole.log(convertStringToBoolean(false));\nconsole.log(convertStringToBoolean(0));\nconsole.log(convertStringToBoolean(1)); // only case which will not work</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 64123006, "author": "Abderrahmen", "author_id": 1207297, "author_profile": "https://Stackoverflow.com/users/1207297", "pm_score": -1, "selected": false, "text": "<p>The simplest way to convert a string to a boolean is the following:</p>\n<pre><code>Boolean(&lt;stringVariable&gt;)\n</code></pre>\n" }, { "answer_id": 64595627, "author": "Kal", "author_id": 3717114, "author_profile": "https://Stackoverflow.com/users/3717114", "pm_score": -1, "selected": false, "text": "<p>Simple one line operation if you need Boolean <code>false</code> and <code>true</code> from the string values:</p>\n<pre><code>storeBooleanHere = stringVariable==&quot;true&quot;?true:false;\n</code></pre>\n<ul>\n<li>storeBooleanHere - This variable will hold the boolean value</li>\n<li>stringVariable - Variable that has boolean stored as string</li>\n</ul>\n" }, { "answer_id": 64687942, "author": "Kev", "author_id": 2686471, "author_profile": "https://Stackoverflow.com/users/2686471", "pm_score": -1, "selected": false, "text": "<p><a href=\"https://i.stack.imgur.com/TnPaA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TnPaA.png\" alt=\"Possible ways to convert String to Boolean\" /></a>\nI recommend you to create a function like the third option in the image and place it in a helper class as export, and reuse this function when you need.</p>\n" }, { "answer_id": 64817203, "author": "cskwg", "author_id": 4386189, "author_profile": "https://Stackoverflow.com/users/4386189", "pm_score": 2, "selected": false, "text": "<pre><code>/// Convert something to boolean\nfunction toBoolean( o ) {\n if ( null !== o ) {\n let t = typeof o;\n if ( &quot;undefined&quot; !== typeof o ) {\n if ( &quot;string&quot; !== t ) return !!o;\n o = o.toLowerCase().trim();\n return &quot;true&quot; === o || &quot;1&quot; === o;\n }\n }\n return false;\n}\n\ntoBoolean(false) --&gt; false\ntoBoolean(true) --&gt; true\ntoBoolean(&quot;false&quot;) --&gt; false\ntoBoolean(&quot;true&quot;) --&gt; true\ntoBoolean(&quot;TRue&quot;) --&gt; true\ntoBoolean(&quot;1&quot;) --&gt; true\ntoBoolean(&quot;0&quot;) --&gt; false\ntoBoolean(1) --&gt; true\ntoBoolean(0) --&gt; false\ntoBoolean(123.456) --&gt; true\ntoBoolean(0.0) --&gt; false\ntoBoolean(&quot;&quot;) --&gt; false\ntoBoolean(null) --&gt; false\ntoBoolean() --&gt; false\n</code></pre>\n" }, { "answer_id": 65113429, "author": "Alexandre Annic", "author_id": 5735030, "author_profile": "https://Stackoverflow.com/users/5735030", "pm_score": 1, "selected": false, "text": "<p>The strongest way is the following because it also handle undefined case:</p>\n<pre><code> ({'true': true, 'false': false})[myValue];\n</code></pre>\n<pre><code> ({'true': true, 'false': false})[undefined] // =&gt; undefined\n ({'true': true, 'false': false})['true'] // =&gt; true\n ({'true': true, 'false': false})['false] // =&gt; false\n</code></pre>\n" }, { "answer_id": 65512532, "author": "Debasish Jena", "author_id": 4336123, "author_profile": "https://Stackoverflow.com/users/4336123", "pm_score": 1, "selected": false, "text": "<p>if you are sure the input is anything only within 'true' and 'false'\nwhy not :</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let x = 'true' ;\n//let x = 'false';\nlet y = x === 'true' ? true : false;\nconsole.log(typeof(y), y);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 66044687, "author": "OMANSAK", "author_id": 5230705, "author_profile": "https://Stackoverflow.com/users/5230705", "pm_score": 2, "selected": false, "text": "<pre><code>function convertBoolean(value): boolean {\n if (typeof value == 'string') {\n value = value.toLowerCase();\n }\n switch (value) {\n case true:\n case &quot;true&quot;:\n case &quot;evet&quot;: // Locale\n case &quot;t&quot;:\n case &quot;e&quot;: // Locale\n case &quot;1&quot;:\n case &quot;on&quot;:\n case &quot;yes&quot;:\n case 1:\n return true;\n case false:\n case &quot;false&quot;:\n case &quot;hayır&quot;: // Locale\n case &quot;f&quot;:\n case &quot;h&quot;: // Locale\n case &quot;0&quot;:\n case &quot;off&quot;:\n case &quot;no&quot;:\n case 0:\n return false;\n default:\n return null;\n }\n}\n</code></pre>\n" }, { "answer_id": 66378318, "author": "Felipe Chernicharo", "author_id": 13111779, "author_profile": "https://Stackoverflow.com/users/13111779", "pm_score": 4, "selected": false, "text": "<h1>Simplest solution </h1>\n<h2>with ES6+</h2>\n<p>use the <strong>logical NOT</strong> twice <strong>[ !! ]</strong> to get the string converted</p>\n<p>Just paste this expression...</p>\n<pre><code>const stringToBoolean = (string) =&gt; string === 'false' ? false : !!string\n</code></pre>\n<p>And pass your string to it!</p>\n<pre><code>stringToBoolean('') // false\nstringToBoolean('false') // false\nstringToBoolean('true') // true\nstringToBoolean('hello my friend!') // true\n</code></pre>\n Bonus! \n<pre><code>const betterStringToBoolean = (string) =&gt; \n string === 'false' || string === 'undefined' || string === 'null' || string === '0' ?\n false : !!string\n</code></pre>\n<p>You can include other strings at will to easily extend the usage of this expression...:</p>\n<pre><code>betterStringToBoolean('undefined') // false\nbetterStringToBoolean('null') // false\nbetterStringToBoolean('0') // false\nbetterStringToBoolean('false') // false\nbetterStringToBoolean('') // false\nbetterStringToBoolean('true') // true\nbetterStringToBoolean('anything else') // true\n</code></pre>\n" }, { "answer_id": 67347536, "author": "Force Bolt", "author_id": 15478252, "author_profile": "https://Stackoverflow.com/users/15478252", "pm_score": -1, "selected": false, "text": "<p>// Try this in two ways convert a string to boolean</p>\n<pre><code> const checkBoolean = Boolean(&quot;false&quot;); \n const checkBoolean1 = !!&quot;false&quot;; \n \n console.log({checkBoolean, checkBoolean1}); \n</code></pre>\n" }, { "answer_id": 67949024, "author": "ru4ert", "author_id": 11123801, "author_profile": "https://Stackoverflow.com/users/11123801", "pm_score": 1, "selected": false, "text": "<h1>ES6+</h1>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const string = \"false\"\nconst string2 = \"true\"\n\nconst test = (val) =&gt; (val === \"true\" || val === \"True\")\nconsole.log(test(string))\nconsole.log(test(string2))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 68562494, "author": "Sigit", "author_id": 6178696, "author_profile": "https://Stackoverflow.com/users/6178696", "pm_score": 3, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const boolTrue = JSON.parse(\"true\")\nconst boolFalse = JSON.parse(\"false\")\n\n\nconsole.log(boolTrue) // true\nconsole.log(boolFalse) // false</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>To convert string boolean like &quot;true&quot; to actually boolean value is just wrapping to <code>JSON.parse()</code>\nexample: <code>JSON.parse(&quot;true&quot;)</code></p>\n" }, { "answer_id": 68582722, "author": "Deepak paramesh", "author_id": 5707334, "author_profile": "https://Stackoverflow.com/users/5707334", "pm_score": 7, "selected": false, "text": "<p>This is the easiest way to do boolean conversion I came across recently. Thought of adding it.</p>\n<pre><code>JSON.parse('true');\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let trueResponse = JSON.parse('true');\n\nlet falseResponse = JSON.parse('false');\n\nconsole.log(trueResponse);\nconsole.log(falseResponse);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 68897258, "author": "cabbage dude", "author_id": 13224736, "author_profile": "https://Stackoverflow.com/users/13224736", "pm_score": 2, "selected": false, "text": "<p>The shorthand of Boolean(value) is !!value, this is because ! converts a value to the opposite of what it currently is, and then ! reverses it again back to original form.</p>\n" }, { "answer_id": 69397610, "author": "Richard Torcato", "author_id": 1213956, "author_profile": "https://Stackoverflow.com/users/1213956", "pm_score": 2, "selected": false, "text": "<p>It would be great if there was a function on the String object that did this for us, but we can easily add our own prototypes to extend the String object.</p>\n<p>Add this code somewhere in your project before you use it.</p>\n<pre><code>String.prototype.toBoolean = function() {\n return String(this.valueOf()).toLowerCase() === true.toString();\n};\n</code></pre>\n<p>Try it out like this:</p>\n<pre><code>var myValue = &quot;false&quot;\nconsole.log(&quot;Bool is &quot; + myValue.toBoolean())\nconsole.log(&quot;Bool is &quot; + &quot;False&quot;.toBoolean())\nconsole.log(&quot;Bool is &quot; + &quot;FALSE&quot;.toBoolean())\nconsole.log(&quot;Bool is &quot; + &quot;TRUE&quot;.toBoolean())\nconsole.log(&quot;Bool is &quot; + &quot;true&quot;.toBoolean())\nconsole.log(&quot;Bool is &quot; + &quot;True&quot;.toBoolean())\n</code></pre>\n<p>So the result of the original question would then be:</p>\n<pre><code>var myValue = document.myForm.IS_TRUE.value;\nvar isTrueSet = myValue.toBoolean();\n</code></pre>\n" }, { "answer_id": 69862548, "author": "Friedrich", "author_id": 11769765, "author_profile": "https://Stackoverflow.com/users/11769765", "pm_score": 4, "selected": false, "text": "<p>I'm suprised that <code>includes</code> was not suggested</p>\n<pre class=\"lang-js prettyprint-override\"><code>let bool = &quot;false&quot;\nbool = ![&quot;false&quot;, &quot;0&quot;, 0].includes(bool)\n</code></pre>\n<p>You can modify the check for truely or include more conditions (e.g. <code>null</code>, <code>''</code>).</p>\n" }, { "answer_id": 71759831, "author": "M. Sherbeeny", "author_id": 5966433, "author_profile": "https://Stackoverflow.com/users/5966433", "pm_score": -1, "selected": false, "text": "<p>I needed a code that converts any variable type into Boolean.\nHere's what I came up with:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const toBoolean = (x) =&gt; {\n if (typeof x === 'object') {\n for (var i in x) return true\n return false\n }\n return (x !== null) &amp;&amp; (x !== undefined) &amp;&amp; !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase())\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Let's test it!</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const toBoolean = (x) =&gt; {\n if (typeof x === 'object') {\n for (var i in x) return true\n return false\n }\n return (x !== null) &amp;&amp; (x !== undefined) &amp;&amp; !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase())\n }\n \n\n // Let's test it!\n let falseValues = [false, 'False', 0, '', 'off', 'no', [], {}, null, undefined]\n let trueValues = [ true, 'true', 'True', 1, -1, 'Any thing', ['filled array'], {'object with any key': null}]\n \n falseValues.forEach((value, index) =&gt; console.log(`False value ${index} of type ${typeof value}: ${value} -&gt; ${toBoolean(value)}`))\n trueValues.forEach((value, index) =&gt; console.log(`True value ${index} of type ${typeof value}: ${value} -&gt; ${toBoolean(value)}`))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You can remove words like &quot;off&quot; and &quot;no&quot; from the array if they don't match your case.</p>\n" }, { "answer_id": 73388511, "author": "Abba", "author_id": 6828976, "author_profile": "https://Stackoverflow.com/users/6828976", "pm_score": 1, "selected": false, "text": "<p>In typescript, a small function to handle if the value was passed as a string, number or a boolean e.g. 'true', 'false', true, false, 1, or 0.</p>\n<pre><code>const getAsBoolean = (value: string | boolean | number) =&gt; {\n if (typeof value === 'string') {\n return value === 'true';\n } else if (typeof value === 'boolean' || typeof value === 'number') {\n return Boolean(value);\n } else {\n return undefined;\n }\n};\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/263965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4599/" ]
Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript? I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string. The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation. ``` var myValue = document.myForm.IS_TRUE.value; var isTrueSet = myValue == 'true'; ``` Is there a better way to accomplish this?
Do: === ``` var isTrueSet = (myValue === 'true'); ``` using the identity operator (`===`), which doesn't make any implicit type conversions when the compared variables have different types. This will set `isTrueSet` to a boolean `true` if the string is "true" and boolean `false` if it is string "false" or not set at all. --- Don't: ------ You should probably **be cautious about using these two methods** for your specific needs: ``` var myBool = Boolean("false"); // == true var myBool = !!"false"; // == true ``` Any string which isn't the empty string will evaluate to `true` by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.
263,985
<p>I want to be replace any occurrence of more than one space with a single space, but take no action in text between quotes.</p> <p>Is there any way of doing this with a Java regex? If so, can you please attempt it or give me a hint?</p>
[ { "answer_id": 264025, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": 0, "selected": false, "text": "<p>text between quotes : Are the quotes within the same line or multiple lines ?</p>\n" }, { "answer_id": 264044, "author": "Jeff Hillman", "author_id": 3950, "author_profile": "https://Stackoverflow.com/users/3950", "pm_score": 2, "selected": false, "text": "<p>When trying to match something that can be contained within something else, it can be helpful to construct a regular expression that matches both, like this:</p>\n\n<pre><code>(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|( +)\n</code></pre>\n\n<p>This will match a quoted string or two or more spaces. Because the two expressions are combined, it will match a quoted string OR two or more spaces, but not spaces within quotes. Using this expression, you will need to examine each match to determine if it is a quoted string or two or more spaces and act accordingly:</p>\n\n<pre><code>Pattern spaceOrStringRegex = Pattern.compile( \"(\\\"[^\\\"\\\\\\\\]*(?:\\\\\\\\.[^\\\"\\\\\\\\]*)*\\\")|( +)\" );\n\nStringBuffer replacementBuffer = new StringBuffer();\n\nMatcher spaceOrStringMatcher = spaceOrStringRegex.matcher( text );\n\nwhile ( spaceOrStringMatcher.find() ) \n{\n // if the space group is the match\n if ( spaceOrStringMatcher.group( 2 ) != null ) \n {\n // replace with a single space\n spaceOrStringMatcher.appendReplacement( replacementBuffer, \" \" );\n }\n}\n\nspaceOrStringMatcher.appendTail( replacementBuffer );\n</code></pre>\n" }, { "answer_id": 264055, "author": "Niniki", "author_id": 4155, "author_profile": "https://Stackoverflow.com/users/4155", "pm_score": 0, "selected": false, "text": "<p>Tokenize it and emit a single space between tokens. A quick google for \"java tokenizer that handles quotes\" turned up:\n<a href=\"http://www.koders.com/java/fid8C21DD2469686C91A0A2E6F25C36DFB659D267DB.aspx?s=file:semap*.java\" rel=\"nofollow noreferrer\">this link</a></p>\n\n<p>YMMV</p>\n\n<p>edit: SO didn't like that link. Here's the google search link: <a href=\"http://www.google.com/search?rlz=1C1CHMP_enUS291&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=java+tokenizer+that+handles+quotes\" rel=\"nofollow noreferrer\">google</a>. It was the first result.</p>\n" }, { "answer_id": 264124, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 0, "selected": false, "text": "<p>Personally, I don't use Java, but this RegExp could do the trick:</p>\n\n<pre><code>([^\\\" ])*(\\\\\\\".*?\\\\\\\")*\n</code></pre>\n\n<p>Trying the expression with RegExBuddy, it generates this code, looks fine to me:</p>\n\n<pre><code>try {\n Pattern regex = Pattern.compile(\"([^\\\" ])*(\\\\\\\".*?\\\\\\\")*\", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);\n Matcher regexMatcher = regex.matcher(subjectString);\n while (regexMatcher.find()) {\n for (int i = 1; i &lt;= regexMatcher.groupCount(); i++) {\n // matched text: regexMatcher.group(i)\n // match start: regexMatcher.start(i)\n // match end: regexMatcher.end(i)\n\n // I suppose here you must use something like\n // sstr += regexMatcher.group(i) + \" \"\n }\n }\n} catch (PatternSyntaxException ex) {\n // Syntax error in the regular expression\n}\n</code></pre>\n\n<p>At least, it seems to work fine in Python:</p>\n\n<pre><code>import re\n\ntext = \"\"\"\neste es un texto de prueba \"para ver como se comporta \" la funcion sobre esto\n\"para ver como se comporta \" la funcion sobre esto \"o sobre otro\" lo q sea\n\"\"\"\n\nret = \"\"\nprint text \n\nreobj = re.compile(r'([^\\\" ])*(\\\".*?\\\")*', re.IGNORECASE)\n\nfor match in reobj.finditer(text):\n if match.group() &lt;&gt; \"\":\n ret = ret + match.group() + \"|\"\n\nprint ret\n</code></pre>\n" }, { "answer_id": 264387, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 0, "selected": false, "text": "<p>After you parse out the quoted content, run this on the rest, in bulk or piece by piece as necessary:</p>\n\n<pre><code>String text = \"ABC DEF GHI JKL\";\ntext = text.replaceAll(\"( )+\", \" \");\n// text: \"ABC DEF GHI JKL\"\n</code></pre>\n" }, { "answer_id": 264458, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 0, "selected": false, "text": "<p>Jeff, you're on the right track, but there are a few errors in your code, to wit: (1) You forgot to escape the quotation marks inside the negated character classes; (2) The parens inside the first capturing group should have been of the non-capturing variety; (3) If the second set of capturing parens doesn't participate in a match, <code>group(2)</code> returns null, and you're not testing for that; and (4) If you test for <strong>two or more</strong> spaces in the regex instead of <em>one or more</em>, you don't need to check the length of the match later on. Here's the revised code: </p>\n\n<pre><code>import java.util.regex.*;\n\npublic class Test\n{\n public static void main(String[] args) throws Exception\n {\n String text = \"blah blah \\\"boo boo boo\\\" blah blah\";\n Pattern p = Pattern.compile( \"(\\\"[^\\\"\\\\\\\\]*(?:\\\\\\\\.[^\\\"\\\\\\\\]*)*\\\")|( +)\" );\n StringBuffer sb = new StringBuffer();\n Matcher m = p.matcher( text );\n while ( m.find() ) \n {\n if ( m.group( 2 ) != null ) \n {\n m.appendReplacement( sb, \" \" );\n }\n }\n m.appendTail( sb );\n System.out.println( sb.toString() );\n }\n}\n</code></pre>\n" }, { "answer_id": 264491, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 3, "selected": true, "text": "<p>Here's another approach, that uses a lookahead to determine that all quotation marks after the current position come in matched pairs.</p>\n\n<pre><code>text = text.replaceAll(\" ++(?=(?:[^\\\"]*+\\\"[^\\\"]*+\\\")*+[^\\\"]*+$)\", \" \");\n</code></pre>\n\n<p>If needed, the lookahead can be adapted to handle escaped quotation marks inside the quoted sections.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/263985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27677/" ]
I want to be replace any occurrence of more than one space with a single space, but take no action in text between quotes. Is there any way of doing this with a Java regex? If so, can you please attempt it or give me a hint?
Here's another approach, that uses a lookahead to determine that all quotation marks after the current position come in matched pairs. ``` text = text.replaceAll(" ++(?=(?:[^\"]*+\"[^\"]*+\")*+[^\"]*+$)", " "); ``` If needed, the lookahead can be adapted to handle escaped quotation marks inside the quoted sections.
264,022
<p>I have a DTS job that is using the MSXML2.XMLHTTP3.0 object to generate a post request to an ASP.NET application. Under the covers, the ASP.NET application is using System.Reflection to acquire some assembly information and I receive the following exception:</p> <blockquote> <p>System.Web.HttpException Error Code: -2147467259 Message Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \ section in the application configuration.</p> </blockquote> <p>DTS Job Code:</p> <pre><code>Dim objSvHTTP Dim PostData Set objSvHTTP = CreateObject("Msxml2.XMLHTTP.3.0") objSvHTTP.open "POST", "http://www.mywebsite.com", false objSvHTTP.send If (objSvrHTTP.responseText = "") Then //do something Else //do somethiing else End If </code></pre> <p>ASP.NET Application Code:</p> <pre><code>string WebPath = "D:\mywebsite\bin\mywebsite.dll"; Assembly UI = Assembly.LoadFrom( @WebPath ); Type t = UI.GetType( "MyWebsite.BasePage" ); MethodInfo MyMethod = t.GetMethod( "MyMethod" ); object obj = Activator.CreateInstance(t); MyMethod.Invoke( obj, null); </code></pre> <p>Question is, do I need to provide vaild Active Directory credentials in the XMLHTTP request to the ASP.NET application to avoid the error message</p>
[ { "answer_id": 289647, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 0, "selected": false, "text": "<p>Judging by the exception message this does not look like an authentication problem to me.\nCould it be that the invoked method tries to access the ASP.NET Session? That would explain the exception.</p>\n" }, { "answer_id": 289664, "author": "Israr Khan", "author_id": 37280, "author_profile": "https://Stackoverflow.com/users/37280", "pm_score": 1, "selected": false, "text": "<p>Try this: \n<a href=\"http://support.instantasp.co.uk/Topic4710-31-1.aspx\" rel=\"nofollow noreferrer\">http://support.instantasp.co.uk/Topic4710-31-1.aspx</a></p>\n" }, { "answer_id": 290777, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 0, "selected": false, "text": "<p>@Israr Khan:</p>\n\n<p>We eventually found a workaround by not executing the reflection code when the DTS called the particular web page that was required for the process.</p>\n\n<p>This would explain why we were getting mixed results when we were trying to resolve this issue in our development and production environments. I did a comparison of the web.config files in each environment and noticed that the Session reference in the HttpModules section was in our production environment, but not in our development environment.</p>\n\n<p>The process worked in development and did not work in production. I have submitted this suggestion to my co-workers to see if they want to try this solution instead of the workaround.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
I have a DTS job that is using the MSXML2.XMLHTTP3.0 object to generate a post request to an ASP.NET application. Under the covers, the ASP.NET application is using System.Reflection to acquire some assembly information and I receive the following exception: > > System.Web.HttpException Error Code: > -2147467259 Message Session state can only be used when enableSessionState > is set to true, either in a > configuration file or in the Page > directive. Please also make sure that > System.Web.SessionStateModule or a > custom session state module is > included in the \ section in the > application configuration. > > > DTS Job Code: ``` Dim objSvHTTP Dim PostData Set objSvHTTP = CreateObject("Msxml2.XMLHTTP.3.0") objSvHTTP.open "POST", "http://www.mywebsite.com", false objSvHTTP.send If (objSvrHTTP.responseText = "") Then //do something Else //do somethiing else End If ``` ASP.NET Application Code: ``` string WebPath = "D:\mywebsite\bin\mywebsite.dll"; Assembly UI = Assembly.LoadFrom( @WebPath ); Type t = UI.GetType( "MyWebsite.BasePage" ); MethodInfo MyMethod = t.GetMethod( "MyMethod" ); object obj = Activator.CreateInstance(t); MyMethod.Invoke( obj, null); ``` Question is, do I need to provide vaild Active Directory credentials in the XMLHTTP request to the ASP.NET application to avoid the error message
Try this: <http://support.instantasp.co.uk/Topic4710-31-1.aspx>
264,057
<p>I have some old C code that I would like to combine with some C++ code.</p> <p>The C code used to have has the following includes:</p> <pre><code>#include &lt;windows.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &quot;mysql.h&quot; </code></pre> <p>Now I'm trying to make it use C++ with iostream like this:</p> <pre><code>#include &lt;windows.h&gt; #include &lt;stdio.h&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &quot;mysql.h&quot; </code></pre> <p>But I keep getting the following linker errors when I compile:</p> <blockquote> <p>[Linker error] undefined reference to `std::string::size() const'</p> <p>[Linker error] undefined reference to `std::string::operator[](unsigned int) const'</p> <p>[Linker error] undefined reference to `std::string::operator[](unsigned int) const'</p> <p>[Linker error] undefined reference to `std::string::operator[](unsigned int) const'</p> <p>[Linker error] undefined reference to `std::ios_base::Init::Init()'</p> <p>[Linker error] undefined reference to `std::ios_base::Init::~Init()'</p> <p>ld returned 1 exit status</p> </blockquote> <p>How do I resolve this?</p> <p>Edit: My compiler is Dev-C++ 4.9.9.2</p>
[ { "answer_id": 264081, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 2, "selected": false, "text": "<p>You need to link against your C++ runtime. It depends on your platform and compiler, but adding -lC to your linkline might do it. </p>\n\n<p>So might linking using your C++ compiler rather than ld.</p>\n\n<p>In any case, you probably have to link using the C++ compiler rather than ld if you want your C++ code to work correctly -- it's often required for exceptions and static initializers to work correctly...</p>\n" }, { "answer_id": 264084, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 6, "selected": true, "text": "<p>The C <code>string.h</code> header and the C++ <code>string</code> header are not interchangeable.</p>\n\n<p>Overall, though, your problem is that the file is getting properly compiled, but the wrong runtime library is getting linked in.</p>\n\n<p>Dev-C++ uses GCC. GCC can correctly determine the language in a file based on file extension, but won't link the right runtime library in unless you specifically ask it to (-lstdc++ at the command line). Calling GCC as \"g++\" (or, in your case, \"mingwin32-g++\") will also get the right language and will link the needed library.</p>\n" }, { "answer_id": 34130770, "author": "Amaresh Kumar", "author_id": 1343196, "author_profile": "https://Stackoverflow.com/users/1343196", "pm_score": 2, "selected": false, "text": "<p>I got the same exact error when i was trying to compile with Cygwin (g++). </p>\n\n<p>just add <code>-L/usr/local/bin -L/usr/lib</code> in the compilation rules and it should work. </p>\n\n<p>This may be specific to Cygwin but it might help solve your problem too. </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
I have some old C code that I would like to combine with some C++ code. The C code used to have has the following includes: ``` #include <windows.h> #include <stdio.h> #include <string.h> #include "mysql.h" ``` Now I'm trying to make it use C++ with iostream like this: ``` #include <windows.h> #include <stdio.h> #include <string> #include <iostream> #include "mysql.h" ``` But I keep getting the following linker errors when I compile: > > [Linker error] undefined reference to `std::string::size() const' > > > [Linker error] undefined reference to `std::string::operator[](unsigned int) const' > > > [Linker error] undefined reference to `std::string::operator[](unsigned int) const' > > > [Linker error] undefined reference to `std::string::operator[](unsigned int) const' > > > [Linker error] undefined reference to `std::ios\_base::Init::Init()' > > > [Linker error] undefined reference to `std::ios\_base::Init::~Init()' > > > ld returned 1 exit status > > > How do I resolve this? Edit: My compiler is Dev-C++ 4.9.9.2
The C `string.h` header and the C++ `string` header are not interchangeable. Overall, though, your problem is that the file is getting properly compiled, but the wrong runtime library is getting linked in. Dev-C++ uses GCC. GCC can correctly determine the language in a file based on file extension, but won't link the right runtime library in unless you specifically ask it to (-lstdc++ at the command line). Calling GCC as "g++" (or, in your case, "mingwin32-g++") will also get the right language and will link the needed library.
264,058
<p>I've got a VS 2008 C# Web project and whenever I make some changes to the files in it (not even to the project file itself) VS will remove some lines like this from the csproj file:</p> <pre><code>&lt;SubType&gt;ASPXCodeBehind&lt;/SubType&gt; </code></pre> <p>So something like this:</p> <pre><code>&lt;Compile Include="Default.aspx.cs"&gt; &lt;DependentUpon&gt;Default.aspx&lt;/DependentUpon&gt; &lt;SubType&gt;ASPXCodeBehind&lt;/SubType&gt; &lt;/Compile&gt; </code></pre> <p>will become</p> <pre><code>&lt;Compile Include="Default.aspx.cs"&gt; &lt;DependentUpon&gt;Default.aspx&lt;/DependentUpon&gt; &lt;/Compile&gt; </code></pre> <p><strong>BUT</strong> the next time I work on this project it will add those lines back! It keeps going back and forth like this, resulting in a lot of meaningless "changes" in our source control system. This never used to happen with VS 2005 and it doesn't seem to be happening for other developers who work on the same project file, only for me.</p> <p>Does anyone know why this is happening and how I can stop it from doing this?</p>
[ { "answer_id": 270356, "author": "Eren Aygunes", "author_id": 27980, "author_profile": "https://Stackoverflow.com/users/27980", "pm_score": 2, "selected": false, "text": "<p>Splitting the content of your file into multiple files - one file per class may help.</p>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=283434\" rel=\"nofollow noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=283434</a></p>\n\n<p>Up-to-date link:</p>\n\n<p><a href=\"https://developercommunity.visualstudio.com/content/problem/389773/vs-2017-keeps-removing-and-re-adding-aspxcodebehin.html\" rel=\"nofollow noreferrer\">https://developercommunity.visualstudio.com/content/problem/389773/vs-2017-keeps-removing-and-re-adding-aspxcodebehin.html</a></p>\n" }, { "answer_id": 7493545, "author": "Tom", "author_id": 3139, "author_profile": "https://Stackoverflow.com/users/3139", "pm_score": 4, "selected": false, "text": "<p>For me, the difference depends on whether or not the web project is open in Visual Studio.</p>\n\n<p>I find if I commit the project file to version control with the project open in Visual Studio the SubType elements are present. Closing the solution/project then removes the SubType elements from the project file. Now I always ensure my commits are performed with the project closed in VS to avoid unnecessary changes to the project file.</p>\n" }, { "answer_id": 13807628, "author": "Alex Denysenko", "author_id": 1892631, "author_profile": "https://Stackoverflow.com/users/1892631", "pm_score": 3, "selected": false, "text": "<p>Working on VS2010 and solved this issue by deleting solutionFileName.sln.DotSettings.user file and solutionFileName.suo. That helped me, give it a try.</p>\n" }, { "answer_id": 27444794, "author": "laylarenee", "author_id": 1016567, "author_profile": "https://Stackoverflow.com/users/1016567", "pm_score": 0, "selected": false, "text": "<p>These lines are also appearing in the project file in VS2012 when committing project changes in Tortoise SVN. This project used to be a website that I converted into a web application.</p>\n\n<p>I was able to bypass this issue using the following steps which <strong>do not</strong> require closing the project:</p>\n\n<ol>\n<li>Just prior to committing to SVN, clean the solution using \"BUILD > Clean Solution\".</li>\n<li>Click the \"Save All\" button to save the project file.</li>\n<li>Commit changes using Tortoise SVN.</li>\n<li>Continue working on project...</li>\n</ol>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20336/" ]
I've got a VS 2008 C# Web project and whenever I make some changes to the files in it (not even to the project file itself) VS will remove some lines like this from the csproj file: ``` <SubType>ASPXCodeBehind</SubType> ``` So something like this: ``` <Compile Include="Default.aspx.cs"> <DependentUpon>Default.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> </Compile> ``` will become ``` <Compile Include="Default.aspx.cs"> <DependentUpon>Default.aspx</DependentUpon> </Compile> ``` **BUT** the next time I work on this project it will add those lines back! It keeps going back and forth like this, resulting in a lot of meaningless "changes" in our source control system. This never used to happen with VS 2005 and it doesn't seem to be happening for other developers who work on the same project file, only for me. Does anyone know why this is happening and how I can stop it from doing this?
For me, the difference depends on whether or not the web project is open in Visual Studio. I find if I commit the project file to version control with the project open in Visual Studio the SubType elements are present. Closing the solution/project then removes the SubType elements from the project file. Now I always ensure my commits are performed with the project closed in VS to avoid unnecessary changes to the project file.
264,080
<p>What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.</p> <p>3.5 would return 4 for power of 2 and 1 for power of 10</p> <p>123 would return 128 for power of 2 and 100 for power of 10</p> <p>0.24 would return 0.25 for power of 2 and 0.1 for power of 10</p> <p>I'm just looking for the algorithm and don't mind the language.</p>
[ { "answer_id": 264093, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 6, "selected": true, "text": "<pre><code>n^round(log_n(x))\n</code></pre>\n\n<p>where log_n is the logarithm to base n. You may have to modify the round() depending on how you define \"closest\".</p>\n\n<p>Note that <code>log_n(x)</code> can be implemented as:</p>\n\n<pre><code>log_n(x) = log(x) / log(n)\n</code></pre>\n\n<p>where <code>log</code> is a logarithm to any convenient base.</p>\n" }, { "answer_id": 264099, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>I think that I might approach the problem, but using log base 2 and log base 10.</p>\n\n<p>log10 of (123) is 2.something.\ntake the floor of that\nthen raise 10 to that power, and that ought to get you close.</p>\n\n<p>the same thing ought to work with log base 2.</p>\n\n<p>log2 of (9) is 3.something\ntake the floor of that\nthen raise to to that power</p>\n\n<p>you might play with rounding of the log.</p>\n" }, { "answer_id": 264112, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 2, "selected": false, "text": "<p>For power of 2 and >= 1 you can see how many times you can bit shift right. For each time this is 1 extra power of 2 you are taking away. Once you get down to 0 you have your number.</p>\n" }, { "answer_id": 311972, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "<p>For power of 2 on integers, there is a smart trick that consist of copying the last bit over and over to the right. Then, you only have to increment your number and you have your power of 2.</p>\n\n<pre><code>int NextPowerOf2(int n)\n{\n n |= (n &gt;&gt; 16);\n n |= (n &gt;&gt; 8);\n n |= (n &gt;&gt; 4);\n n |= (n &gt;&gt; 2);\n n |= (n &gt;&gt; 1);\n ++n;\n return n;\n}\n</code></pre>\n" }, { "answer_id": 312087, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>You may have to modify the round() depending on how you define \"closest\".</p>\n</blockquote>\n\n<p>@Greg Hewgill's answer is correct except it rounds up too early for the examples you gave. For example, 10^round(log_10(3.5)) == 10, not 1. I'm assuming that's what he means by 'how you define \"closest\"'.</p>\n\n<p>Probably the simplest way to use Greg's formula and if it's too high (or too low for x &lt; 1), use the next lower power of two:</p>\n\n<pre><code>closest = n ^ round(log_n(x))\n\nif (closest &gt; x) {\n other = closest / n\n} else {\n other = closest * n\n}\n\nif (abs(other - x) &lt; abs(closest - x)) {\n return other\n} else {\n return closest\n}\n</code></pre>\n" }, { "answer_id": 72439913, "author": "ZXYNINE", "author_id": 4285191, "author_profile": "https://Stackoverflow.com/users/4285191", "pm_score": 0, "selected": false, "text": "<p>to play off of Vincent Roberts trick, I just worked out a way to get the bit hacks to round to the nearest power of two not just always round to the next power of two.</p>\n<pre><code>private static int ClosestPowerOfTwo(int v) {\n //gets value of bit to the right of leading bit and moves it to left by 1\n int r = (v &amp; (v&gt;&gt;1))&lt;&lt;1; \n //rs bit in same place as vs leading bit is 1 to round up or 0 to round down.\n v &gt;&gt;= 1;\n //replaces leading bit with a 1 if rounding up or leaves 0 if rounding down.\n v |= r; \n //Next power of 2 exclusive\n v |= v &gt;&gt; 1;\n v |= v &gt;&gt; 2;\n v |= v &gt;&gt; 4;\n v |= v &gt;&gt; 8;\n v |= v &gt;&gt; 16;\n v++;\n return v;\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5932/" ]
What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g. 3.5 would return 4 for power of 2 and 1 for power of 10 123 would return 128 for power of 2 and 100 for power of 10 0.24 would return 0.25 for power of 2 and 0.1 for power of 10 I'm just looking for the algorithm and don't mind the language.
``` n^round(log_n(x)) ``` where log\_n is the logarithm to base n. You may have to modify the round() depending on how you define "closest". Note that `log_n(x)` can be implemented as: ``` log_n(x) = log(x) / log(n) ``` where `log` is a logarithm to any convenient base.
264,090
<p>How can I make:</p> <p>DELETE FROM foo WHERE id=1 AND <strong>bar not contains id==1</strong></p> <p>To elaborate, how can I remove a row with <code>id = 1</code>, from table <code>foo</code>, only if there is not a row in table <code>bar</code> with <code>id = 1</code>.</p>
[ { "answer_id": 264103, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 5, "selected": true, "text": "<pre><code>DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1)\n</code></pre>\n\n<p>I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar.</p>\n" }, { "answer_id": 264517, "author": "nathan_jr", "author_id": 3769, "author_profile": "https://Stackoverflow.com/users/3769", "pm_score": 4, "selected": false, "text": "<p>using a join: </p>\n\n<pre><code>delete f\nfrom foo f\nleft\njoin bar b on\n f.id = b.id \nwhere f.id = 1 and\n b.id is null\n</code></pre>\n" }, { "answer_id": 271158, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Use the SQL \"Exists\" command.</p>\n\n<p><a href=\"http://www.techonthenet.com/sql/exists.php\" rel=\"nofollow noreferrer\">http://www.techonthenet.com/sql/exists.php</a></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26004/" ]
How can I make: DELETE FROM foo WHERE id=1 AND **bar not contains id==1** To elaborate, how can I remove a row with `id = 1`, from table `foo`, only if there is not a row in table `bar` with `id = 1`.
``` DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1) ``` I'm assuming you mean that foo and bar are tables, and you want to remove a record from foo if it doesn't exist in bar.
264,123
<p>Is there a way to have % in vim find the next ([{ or whatever, even if it is not on the same line?</p> <p>Example:</p> <pre><code>int main(int argc, char ** argv) { #Your cursor is somewhere in this comment, I want #it to get to the ( after printf printf("Hello there.\n"); } </code></pre>
[ { "answer_id": 264136, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 1, "selected": false, "text": "<p>That's puzzling... For me, % finds the matching close for any {[( no matter how many lines away the match is. I don't see anything in my .vimrc that would change this behaviour, offhand.</p>\n" }, { "answer_id": 264137, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 3, "selected": true, "text": "<p>If you want to find opening braces on subsequent lines, without plugins, just enter normal mode and type:</p>\n\n<pre><code>/{ [enter]\n</code></pre>\n\n<p>Where { is the type of brace your looking for.</p>\n\n<p>You can then browse them all with <kbd>n</kbd> and <kbd>N</kbd>.</p>\n\n<p>To map the <kbd>F12</kbd> key to turn search highlighting on and off <a href=\"http://ronny.haryan.to/archives/2005/03/03/tip-quick-no-highlight-search-matches-in-vim/\" rel=\"nofollow noreferrer\">use this trick.</a></p>\n" }, { "answer_id": 264148, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 2, "selected": false, "text": "<p>If I understand correctly, you're trying to to get it to find the <strong>opening</strong> brace even on the next line. If you're complaining that it doesn't find the closing brace unless the whole thing is one line, I don't know why that wouldn't be working.</p>\n\n<p>In any case, if you want % to have superpowers, the <a href=\"http://www.vim.org/scripts/script.php?script_id=39\" rel=\"nofollow noreferrer\">matchit plugin</a> is the place to start. It's included in the normal distribution, so you shouldn't have to download it. Just add</p>\n\n<pre><code>:runtime macros/matchit.vim\n</code></pre>\n\n<p>To your .vimrc, and % will also know lots of new tricks (how to match balaced XML tags if/then/end if statements in languages that do those with keywords), etc. It won't solve your request directly, since matchit uses the same limitations as normal % (it wasnts the match to start at or after the cursor, on the same line). But since it can use regex searches as match markers (instead of just characters), it should be possible to configure it so the open expression is .<em>\\n.</em>{ or some such that would meet that criteria, yet pick up a brace on a line further down.</p>\n" }, { "answer_id": 267240, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It looks like Jim Burger has it, but just in case you were actually asking how to search for any of those things:</p>\n\n<p>/[{[(] [Enter]</p>\n\n<p>This will find the next of any of those symbols.</p>\n\n<p>By the way: In this case, vim is smart enough to figure out what you want, but you'll often have to escape a square or round bracket with '\\'. For example, to search for the next closing bracket, you would type (Note the \\]):</p>\n\n<p>/[\\]})] [Enter] </p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way to have % in vim find the next ([{ or whatever, even if it is not on the same line? Example: ``` int main(int argc, char ** argv) { #Your cursor is somewhere in this comment, I want #it to get to the ( after printf printf("Hello there.\n"); } ```
If you want to find opening braces on subsequent lines, without plugins, just enter normal mode and type: ``` /{ [enter] ``` Where { is the type of brace your looking for. You can then browse them all with `n` and `N`. To map the `F12` key to turn search highlighting on and off [use this trick.](http://ronny.haryan.to/archives/2005/03/03/tip-quick-no-highlight-search-matches-in-vim/)
264,127
<p>I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form:</p> <pre><code>OtherForm newForm=new OtherForm(); newForm.Show(); </code></pre> <p>How can i communicate from the new winform with the form that opened it? So that I can add some items in it.</p>
[ { "answer_id": 264132, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 2, "selected": false, "text": "<p>The simplest way is to override the constructor, eg, <code>OtherForm newForm=new OtherForm(string title, int data);</code>. This also works for reference types (which would be a simple way to send the data back).</p>\n" }, { "answer_id": 264151, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 2, "selected": false, "text": "<p>In the constructor for the other form add a reference to your main form. Then make public/internal anything on the main form that you need to access.</p>\n\n<pre><code>Form m_mainForm;\npublic OtherForm(Form mainForm)\n{\n m_mainForm = mainForm;\n}\n</code></pre>\n\n<p>Edit:</p>\n\n<p>In response to your second post - You might also consider exposing the necessary values you need to create you item. For example, if you need a first name and last name to create a new \"person\" item, you could expose those as properties in the dialog. That would help to disconnect it a little and make it a little more general purpose.</p>\n\n<p>Of course, your solution works as well, and only you know what will work best in your design.</p>\n" }, { "answer_id": 264155, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 1, "selected": true, "text": "<p>I think I have found the answer here:\n<a href=\"http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx</a></p>\n\n<p>I have to use delegates. In the second form I define:</p>\n\n<pre><code>public delegate void AddItemDelegate(string item);\npublic AddItemDelegate AddItemCallback;\n</code></pre>\n\n<p>And from the form that opened it I write:</p>\n\n<pre><code>private void btnScenario2_Click(object sender, EventArgs e)\n{\n\n FrmDialog dlg = new FrmDialog();\n //Subscribe this form for callback\n dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn);\n dlg.ShowDialog();\n\n}\nprivate void AddItemCallbackFn(string item)\n{\n\n lstBx.Items.Add(item);\n\n}\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31791/" ]
I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form: ``` OtherForm newForm=new OtherForm(); newForm.Show(); ``` How can i communicate from the new winform with the form that opened it? So that I can add some items in it.
I think I have found the answer here: <http://www.c-sharpcorner.com/UploadFile/mosessaur/winformsdelegates09042006094826AM/winformsdelegates.aspx> I have to use delegates. In the second form I define: ``` public delegate void AddItemDelegate(string item); public AddItemDelegate AddItemCallback; ``` And from the form that opened it I write: ``` private void btnScenario2_Click(object sender, EventArgs e) { FrmDialog dlg = new FrmDialog(); //Subscribe this form for callback dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn); dlg.ShowDialog(); } private void AddItemCallbackFn(string item) { lstBx.Items.Add(item); } ```
264,128
<p>I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:</p> <p>I have a test Ruby XML-RPC server as follows:</p> <pre><code>require "xmlrpc/server" class ExampleBar def bar() return "hello world!" end end class ExampleFoo def foo() return ExampleBar.new end def test() return "test!" end end s = XMLRPC::Server.new( 9090 ) s.add_introspection s.add_handler( "example", ExampleFoo.new ) s.serve </code></pre> <p>And I have a test Python XML-RPC Client as follows:</p> <pre><code>import xmlrpclib s = xmlrpclib.Server( "http://127.0.0.1:9090/" ) print s.example.foo().bar() </code></pre> <p>I would expect the python client to print "hello world!" as it is the equivalent of the following ruby code:</p> <pre><code>example = ExampleFoo.new puts example.foo().bar() </code></pre> <p>However it generates an error: "xmlrpclib.ProtocolError: &lt;ProtocolError for 127.0.0.1:9090/: 500 Internal Server Error&gt;".</p> <p>print s.example.test() works fine.</p> <p>I dont expect the new ExampleBar object to go over the wire but I would expect it to be 'cached' server side and the subsequent call to bar() to be honoured.</p> <p>Can XML-RPC support this kind of usage or is it too basic?</p> <p>So I guess my question really is; how can I get this working, if not with XML-RPC what with?</p>
[ { "answer_id": 264165, "author": "jakber", "author_id": 29812, "author_profile": "https://Stackoverflow.com/users/29812", "pm_score": 4, "selected": true, "text": "<p>Your client (s in you Python code) is a ServerProxy object. It only accepts return values of type boolean, integers, floats, arrays, structures, dates or binary data.</p>\n\n<p>However, without you doing the wiring, there is no way for it to return another ServerProxy, which you would need for accessing another class. You could probably implement an object cache on the Ruby side, but it would involve keeping track of active session and deciding when to remove objects, how to handle missing objects, etc.</p>\n\n<p>Instead I would suggest exposing a thin wrapper on the ruby side that does atomic operations like:</p>\n\n<pre><code>def foobar()\n return ExampleFoo.new().foo().bar()\nend\n</code></pre>\n" }, { "answer_id": 264586, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 1, "selected": false, "text": "<p>XML-RPC can't pass objects. The set of parameter types is limited (as jakber says).</p>\n" }, { "answer_id": 1257360, "author": "Kevin Martin", "author_id": 79286, "author_profile": "https://Stackoverflow.com/users/79286", "pm_score": 1, "selected": false, "text": "<p>Returning a nil inside of a supported data structure will also cause an Internal Server Error message. The stdlib ruby xmlrpc server does not appear to support the xmlrpc extensions which allow nils, even though the python side does. xmlrpc4r supports nils but I haven't tried it yet.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14260/" ]
I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below: I have a test Ruby XML-RPC server as follows: ``` require "xmlrpc/server" class ExampleBar def bar() return "hello world!" end end class ExampleFoo def foo() return ExampleBar.new end def test() return "test!" end end s = XMLRPC::Server.new( 9090 ) s.add_introspection s.add_handler( "example", ExampleFoo.new ) s.serve ``` And I have a test Python XML-RPC Client as follows: ``` import xmlrpclib s = xmlrpclib.Server( "http://127.0.0.1:9090/" ) print s.example.foo().bar() ``` I would expect the python client to print "hello world!" as it is the equivalent of the following ruby code: ``` example = ExampleFoo.new puts example.foo().bar() ``` However it generates an error: "xmlrpclib.ProtocolError: <ProtocolError for 127.0.0.1:9090/: 500 Internal Server Error>". print s.example.test() works fine. I dont expect the new ExampleBar object to go over the wire but I would expect it to be 'cached' server side and the subsequent call to bar() to be honoured. Can XML-RPC support this kind of usage or is it too basic? So I guess my question really is; how can I get this working, if not with XML-RPC what with?
Your client (s in you Python code) is a ServerProxy object. It only accepts return values of type boolean, integers, floats, arrays, structures, dates or binary data. However, without you doing the wiring, there is no way for it to return another ServerProxy, which you would need for accessing another class. You could probably implement an object cache on the Ruby side, but it would involve keeping track of active session and deciding when to remove objects, how to handle missing objects, etc. Instead I would suggest exposing a thin wrapper on the ruby side that does atomic operations like: ``` def foobar() return ExampleFoo.new().foo().bar() end ```
264,140
<p>I've a web service running on server which return data either in XML format or JSON format. I wanted to request a JSON format but using HTTP Post method.</p>
[ { "answer_id": 264340, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 2, "selected": false, "text": "<p>Not really sure what your question is exactly. But google \"TouchJSON\" that should help you get started.</p>\n" }, { "answer_id": 264380, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 0, "selected": false, "text": "<p>Sorry for errors and memory leaks, but how about something like:</p>\n\n<pre><code>CFURLRef url = CFURLCreateWithString(NULL, CFSTR(\"http://example.com/post\"), NULL);\nCFHTTPMessageRef msg = CFHTTPMessageCreateRequest(\n NULL,\n CFSTR(\"POST\"),\n url,\n kCFHTTPVersion1_1);\n\nconst char *body = \"key=value&amp;id=30293\";\nCFDataRef bodyData = CFDataCreate(NULL, body, strlen(body));\nCFHTTPMessageSetBody(msg, bodyData);\n\nCFReadStreamRef myReadStream = CFReadStreamCreateForHTTPRequest(NULL, myRequest);\nCFReadStreamOpen(myReadStream);\nCFHTTPMessageRef myResponse = CFReadStreamCopyProperty(\n myReadStream,\n kCFStreamPropertyHTTPResponseHeader);\n\n//\n// Handle myResponse\n//\n\nCFReadStreamClose(myReadStream);\nCFRelease(myReadStream);\nCFRelease(bodyData);\nCFRelease(msg);\nCFRelease(url);\n</code></pre>\n" }, { "answer_id": 264553, "author": "Amit Vaghela", "author_id": 451867, "author_profile": "https://Stackoverflow.com/users/451867", "pm_score": 6, "selected": true, "text": "<p>This is the code which work for JSON post request,\nTouchJSON Framework is used for parsing the JSON, thanks 'schwa'.</p>\n\n<pre><code>NSArray *keys = [NSArray arrayWithObjects:@\"username\", @\"password\", @\"preference\", @\"uid\", nil];\nNSArray *objects = [NSArray arrayWithObjects:@\"accuser\", @\"accpass\", @\"abc_region\", @\"100\", nil];\nNSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];\n\nNSURL *theURL = [NSURL URLWithString:@\"http://url.com/request.php\"];\nNSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];\n[theRequest setHTTPMethod:@\"POST\"];\n\n[theRequest setValue:@\"application/json-rpc\" forHTTPHeaderField:@\"Content-Type\"];\nNSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];\nNSLog(@\"%@\", theBodyString);\nNSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];\n// NSLog(@\"%@\", theBodyData);\n[theRequest setHTTPBody:theBodyData];\n\nNSURLResponse *theResponse = NULL;\nNSError *theError = NULL;\nNSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&amp;theResponse error:&amp;theError];\nNSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];\nNSLog(theResponseString);\nNSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString];\nNSLog(@\"%@\", theResponseDictionary);\nNSString *theGreeting = [theResponseDictionary objectForKey:@\"greeting\"];\n[self setValue:theGreeting forKey:@\"greeting\"];\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/451867/" ]
I've a web service running on server which return data either in XML format or JSON format. I wanted to request a JSON format but using HTTP Post method.
This is the code which work for JSON post request, TouchJSON Framework is used for parsing the JSON, thanks 'schwa'. ``` NSArray *keys = [NSArray arrayWithObjects:@"username", @"password", @"preference", @"uid", nil]; NSArray *objects = [NSArray arrayWithObjects:@"accuser", @"accpass", @"abc_region", @"100", nil]; NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; NSURL *theURL = [NSURL URLWithString:@"http://url.com/request.php"]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f]; [theRequest setHTTPMethod:@"POST"]; [theRequest setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"]; NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary]; NSLog(@"%@", theBodyString); NSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding]; // NSLog(@"%@", theBodyData); [theRequest setHTTPBody:theBodyData]; NSURLResponse *theResponse = NULL; NSError *theError = NULL; NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError]; NSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease]; NSLog(theResponseString); NSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString]; NSLog(@"%@", theResponseDictionary); NSString *theGreeting = [theResponseDictionary objectForKey:@"greeting"]; [self setValue:theGreeting forKey:@"greeting"]; ```
264,163
<p>I have a somewhat complex WPF application which seems to be 'hanging' or getting stuck in a Wait call when trying to use the dispatcher to invoke a call on the UI thread.</p> <p>The general process is:</p> <ol> <li>Handle the click event on a button</li> <li>Create a new thread (STA) which: creates a new instance of the presenter and UI, then calls the method <strong>Disconnect</strong></li> <li>Disconnect then sets a property on the UI called <strong>Name</strong></li> <li>The setter for Name then uses the following code to set the property:</li> </ol> <pre><code> if(this.Dispatcher.Thread != Thread.CurrentThread) { this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{ this.Name = value; // Call same setter, but on the UI thread }); return; } SetValue(nameProperty, value); // I have also tried a member variable and setting the textbox.text property directly. </code></pre> <p>My problem is that when the dispatcher <strong>invoke</strong> method is called it seems to hang every single time, and the callstack indicates that its in a sleep, wait or join within the Invoke implementation.</p> <p>So, is there something I am doing wrong which I am missing, obvious or not, or is there a better way of calling across to the UI thread to set this property (and others)?</p> <p><strong>Edit:</strong> The solution was to call System.Windows.Threading.Dispatcher.Run() at the end of the thread delegate (e.g. where the work was being performed) - Thanks to all who helped.</p>
[ { "answer_id": 264444, "author": "Ana Betts", "author_id": 5728, "author_profile": "https://Stackoverflow.com/users/5728", "pm_score": 4, "selected": false, "text": "<p>Invoke is synchronous - you want Dispatcher.BeginInvoke. Also, I believe your code sample should move the \"SetValue\" inside an \"else\" statement.</p>\n" }, { "answer_id": 264477, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>This sounds like a deadlock; this would typically happen if the thread calling .Invoke already held a lock / mutex / etc which the UI thread needs to complete it's work. The simplest approach would be to use BeginInvoke instead: that way, the current thread can keep running, and will (presumably) release the lock shortly - allowing the UI to aquire it. Alternatively, if you can identify the offending lock, you could deliberately release it for a duration.</p>\n" }, { "answer_id": 278453, "author": "Keith", "author_id": 36146, "author_profile": "https://Stackoverflow.com/users/36146", "pm_score": 4, "selected": true, "text": "<p>You say you are creating a new STA thread, is the dispatcher on this new thread running?</p>\n\n<p>I'm getting from \"this.Dispatcher.Thread != Thread.CurrentThread\" that you expect it to be a different dispatcher. Make sure that its running otherwise it wont process its queue.</p>\n" }, { "answer_id": 5215784, "author": "Jeff", "author_id": 164438, "author_profile": "https://Stackoverflow.com/users/164438", "pm_score": 2, "selected": false, "text": "<p>I'm having a similar problem and while I'm still not sure what the answer is, I think your</p>\n\n<pre><code> if(this.Dispatcher.Thread != Thread.CurrentThread)\n{\n this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{\n this.Name = value; // Call same setter, but on the UI thread\n });\n return;\n}\n</code></pre>\n\n<p>should be replaced by</p>\n\n<pre><code> if(this.Dispatcher.CheckAccess())\n{\n this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{\n this.Name = value; // Call same setter, but on the UI thread\n });\n return;\n}\n</code></pre>\n\n<p>CheckAccess won't show up in Intellisense but it is there and meant for this purpose. Also, I agree that in general you want BeginInvoke here, however I've found that I don't get UI updates when I do this async. Unfortunately, when I do it synchronously I get a deadlock condition...</p>\n" }, { "answer_id": 5598029, "author": "Andrew", "author_id": 699017, "author_profile": "https://Stackoverflow.com/users/699017", "pm_score": 2, "selected": false, "text": "<p>I think you mean if (!this.Dispatcher.CheckAccess())</p>\n\n<p>I am also geting a hang with Invoke, or if I can BeginInvoke my delegate isn't being called - seem to be doing everything by the book :-(</p>\n" }, { "answer_id": 14254324, "author": "Martin Lottering", "author_id": 1308645, "author_profile": "https://Stackoverflow.com/users/1308645", "pm_score": 0, "selected": false, "text": "<p>I know this is an old thread, but here is another solution.</p>\n\n<p>I just fixed a similar problem. My dispatcher was running fine, so...</p>\n\n<p>I had to show the DEBUG -> THREAD WINDOW to identify all the threads that are executing my code anywhere.</p>\n\n<p>By checking each of the threads, I quickly saw which thread caused the deadlock. </p>\n\n<p>It was multiple threads combining a <code>lock (locker) { ... }</code> statement, and calls to Dispatcher.Invoke().</p>\n\n<p>In my case I could just change a specific <code>lock (locker) { ... }</code> statement, and replace it with an <code>Interlocked.Increment(ref lockCounter)</code>.</p>\n\n<p>That solved my problem because the deadlock was avoided.</p>\n\n<pre><code>void SynchronizedMethodExample() {\n\n /* synchronize access to this method */\n if (Interlocked.Increment(ref _lockCounter) != 1) { return; }\n\n try {\n ...\n }\n finally {\n _mandatoryCounter--;\n }\n}\n</code></pre>\n" }, { "answer_id": 22101974, "author": "Alexandru", "author_id": 982639, "author_profile": "https://Stackoverflow.com/users/982639", "pm_score": 3, "selected": false, "text": "<p>I think this is better shown with code. Consider this scenario:</p>\n\n<p>Thread A does this:</p>\n\n<pre><code>lock (someObject)\n{\n // Do one thing.\n someDispatcher.Invoke(() =&gt;\n {\n // Do something else.\n }\n}\n</code></pre>\n\n<p>Thread B does this:</p>\n\n<pre><code>someDispatcher.Invoke(() =&gt;\n{\n lock (someObject)\n {\n // Do something.\n }\n}\n</code></pre>\n\n<p>Everything might appear fine and dandy at first glance, but its not. This will produce a deadlock. Dispatchers are like queues for a thread, and when dealing with deadlocks like these its important to think of them that way: \"What previous dispatch could have jammed my queue?\". Thread A will come in...and dispatch under a lock. But, what if thread B comes in at the point in time at which Thread A is in the code marked \"Do one thing\"? Well...</p>\n\n<ul>\n<li>Thread A has the lock on someObject and is running some code.</li>\n<li>Thread B now dispatches, and the dispatcher will try to get the lock on someObject, jamming up your dispatcher since Thread A has that lock already.</li>\n<li>Thread A will then queue up another dispatch item. This item will never be fired, because your dispatcher will never finish processing your previous request; its already jammed up.</li>\n</ul>\n\n<p>You now have a beautiful deadlock.</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18434/" ]
I have a somewhat complex WPF application which seems to be 'hanging' or getting stuck in a Wait call when trying to use the dispatcher to invoke a call on the UI thread. The general process is: 1. Handle the click event on a button 2. Create a new thread (STA) which: creates a new instance of the presenter and UI, then calls the method **Disconnect** 3. Disconnect then sets a property on the UI called **Name** 4. The setter for Name then uses the following code to set the property: ``` if(this.Dispatcher.Thread != Thread.CurrentThread) { this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{ this.Name = value; // Call same setter, but on the UI thread }); return; } SetValue(nameProperty, value); // I have also tried a member variable and setting the textbox.text property directly. ``` My problem is that when the dispatcher **invoke** method is called it seems to hang every single time, and the callstack indicates that its in a sleep, wait or join within the Invoke implementation. So, is there something I am doing wrong which I am missing, obvious or not, or is there a better way of calling across to the UI thread to set this property (and others)? **Edit:** The solution was to call System.Windows.Threading.Dispatcher.Run() at the end of the thread delegate (e.g. where the work was being performed) - Thanks to all who helped.
You say you are creating a new STA thread, is the dispatcher on this new thread running? I'm getting from "this.Dispatcher.Thread != Thread.CurrentThread" that you expect it to be a different dispatcher. Make sure that its running otherwise it wont process its queue.
264,216
<p>I'm playing around with ASP.net MVC and JQuery at the moment. I've come across behavour which doesn't seem to make sense. </p> <p>I'm calling JQuery's <code>$.getJSON</code> function to populate some div's. The event is triggered on the <code>$(document).ready</code> event. This works perfectly.</p> <p>There is a small <code>AJAX.BeginForm</code> which adds another value to be used when populating the divs. It calls the remote function correctly and upon success calls the original javascript function to repopulate the divs.</p> <p>Here is the weird part: In FireFox and Chrome - Everything works. BUT In IE8 (Beta) this second call to the populate Div script (which calls the $.getJSON function) gets cached data and does not ask the server!</p> <p>Hope this question makes sense: In a nut shell - Why is <code>$.getJSON</code> getting cached data? And why is it only effecting IE8?</p>
[ { "answer_id": 264227, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<p>You may need to send a cache-breaker. </p>\n\n<p>I would recommend using $.ajax( { cache: no }) just in case ( adds a random suffix to the get request) </p>\n\n<p>( I tend to use $.ajax everywhere these days, more tuneable ) </p>\n" }, { "answer_id": 264351, "author": "Andrew Harry", "author_id": 30576, "author_profile": "https://Stackoverflow.com/users/30576", "pm_score": 4, "selected": false, "text": "<p>Thanks Kent for your answer.\nUsing $.ajax('{ cache: no }'); worked perfectly.\n[edit]</p>\n\n<p>Or at least I thought i did. Seems that the jquery $.getJSON isn't reading any changes made to the $.ajax object.</p>\n\n<p>The solution that ended up working was to add a new parameter manually</p>\n\n<pre><code>var noCache = Date();\n$.getJSON(\"/somepage/someaction\", { \"noCache\": noCache }, Callback);\n</code></pre>\n\n<p>the date resolution is only to the minute; which effectively means this solution still caches for upto one minute. This is acceptable for my purposes.</p>\n" }, { "answer_id": 264654, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 7, "selected": true, "text": "<p>Just to let you know, Firefox and Chrome consider all Ajax request as non-cachable. IE (all versions) treat Ajax call just as other web request. That's why you see this behavior.<br>\nHow to force IE to download data at each request:</p>\n\n<ul>\n<li>As you said, use 'cache' or 'nocache' option in JQuery</li>\n<li>Add a random parameter to the request (ugly, but works :))</li>\n<li>On server side, set cachability (for example using an attribute, see below)</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>public class NoCacheAttribute : ActionFilterAttribute\n{\n public override void OnActionExecuted(ActionExecutedContext context)\n {\n context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);\n }\n}\n</code></pre>\n" }, { "answer_id": 358083, "author": "Jitesh Patil", "author_id": 1150244, "author_profile": "https://Stackoverflow.com/users/1150244", "pm_score": 7, "selected": false, "text": "<p>This is how it worked for me...</p>\n\n<pre><code>$.ajaxSetup({ cache: false });\n$.getJSON(\"/MyQueryUrl\",function(data,item) {\n // do stuff with callback data\n $.ajaxSetup({ cache: true });\n });\n</code></pre>\n" }, { "answer_id": 849023, "author": "Josh", "author_id": 59143, "author_profile": "https://Stackoverflow.com/users/59143", "pm_score": 2, "selected": false, "text": "<p>If you're using ASP.net MVC, consider adding an extension method to easily implement no caching like so: </p>\n\n<pre><code> public static void NoCache(this HttpResponse Response)\n {\n Response.Cache.SetNoStore();\n Response.Cache.SetExpires(DateTime.MinValue);\n Response.Cache.SetCacheability(HttpCacheability.NoCache);\n Response.Cache.SetValidUntilExpires(false);\n\n Response.Expires = -1;\n Response.ExpiresAbsolute = DateTime.MinValue;\n Response.AddHeader(\"Cache-Control\", \"no-cache\");\n Response.AddHeader(\"Pragma\", \"no-cache\");\n }\n</code></pre>\n" }, { "answer_id": 1269939, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": 4, "selected": false, "text": "<p>I solved this same problem by placing the following attribute on the Action in the Controller:</p>\n\n<pre><code>[OutputCache(Duration = 0, VaryByParam = \"None\")]\n</code></pre>\n" }, { "answer_id": 10794994, "author": "stadja", "author_id": 1211640, "author_profile": "https://Stackoverflow.com/users/1211640", "pm_score": 2, "selected": false, "text": "<p>Ready for THE answer ?</p>\n\n<p><a href=\"http://lestopher.tumblr.com/post/21742012438/if-youre-using-ie8-and-getjson\" rel=\"nofollow\">http://lestopher.tumblr.com/post/21742012438/if-youre-using-ie8-and-getjson</a></p>\n\n<p>So, just add </p>\n\n<pre><code>jQuery.support.cors = true; \n</code></pre>\n\n<p>at the beginning of your script and BANG it works !</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30576/" ]
I'm playing around with ASP.net MVC and JQuery at the moment. I've come across behavour which doesn't seem to make sense. I'm calling JQuery's `$.getJSON` function to populate some div's. The event is triggered on the `$(document).ready` event. This works perfectly. There is a small `AJAX.BeginForm` which adds another value to be used when populating the divs. It calls the remote function correctly and upon success calls the original javascript function to repopulate the divs. Here is the weird part: In FireFox and Chrome - Everything works. BUT In IE8 (Beta) this second call to the populate Div script (which calls the $.getJSON function) gets cached data and does not ask the server! Hope this question makes sense: In a nut shell - Why is `$.getJSON` getting cached data? And why is it only effecting IE8?
Just to let you know, Firefox and Chrome consider all Ajax request as non-cachable. IE (all versions) treat Ajax call just as other web request. That's why you see this behavior. How to force IE to download data at each request: * As you said, use 'cache' or 'nocache' option in JQuery * Add a random parameter to the request (ugly, but works :)) * On server side, set cachability (for example using an attribute, see below) Code: ``` public class NoCacheAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext context) { context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache); } } ```
264,224
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p> <p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p> <p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p> <p>Has anyone else encountered this problem?</p> <p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
[ { "answer_id": 264297, "author": "Sean", "author_id": 4919, "author_profile": "https://Stackoverflow.com/users/4919", "pm_score": 0, "selected": false, "text": "<p>In lib/gzip.py, we find the method that builds the header, including the part that does indeed contain a timestamp. In Python 2.5, this begins on line 143:</p>\n\n<pre><code>def _write_gzip_header(self):\n self.fileobj.write('\\037\\213') # magic header\n self.fileobj.write('\\010') # compression method\n fname = self.filename[:-3]\n flags = 0\n if fname:\n flags = FNAME\n self.fileobj.write(chr(flags))\n write32u(self.fileobj, long(time.time())) # The current time!\n self.fileobj.write('\\002')\n self.fileobj.write('\\377')\n if fname:\n self.fileobj.write(fname + '\\000')\n</code></pre>\n\n<p>As you can see, it uses time.time() to fetch the current time. According to the online module docs, time.time will \"return the time as a floating point number expressed in seconds since the epoch, in UTC.\" So, if you change this to a floating-point constant of your choosing, you can always have the same headers written out. I can't see a better way to do this unless you want to hack the library some more to accept an optional time param that you use while defaulting to time.time() when it's not specified, in which case, I'm sure they'd love it if you submitted a patch!</p>\n" }, { "answer_id": 264303, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 3, "selected": false, "text": "<p>Yeah, you don't have any pretty options. The time is written with this line in _write_gzip_header:</p>\n\n<pre><code>write32u(self.fileobj, long(time.time()))\n</code></pre>\n\n<p>Since they don't give you a way to override the time, you can do one of these things:</p>\n\n<ol>\n<li>Derive a class from GzipFile, and copy the <code>_write_gzip_header</code> function into your derived class, but with a different value in this one line.</li>\n<li>After importing the gzip module, assign new code to its time member. You will essentially be providing a new definition of the name time in the gzip code, so you can change what time.time() means.</li>\n<li>Copy the entire gzip module, and name it my_stable_gzip, and change the line you need to.</li>\n<li>Pass a CStringIO object in as fileobj, and modify the bytestream after gzip is done.</li>\n<li>Write a fake file object that keeps track of the bytes written, and passes everything through to a real file, except for the bytes for the timestamp, which you write yourself.</li>\n</ol>\n\n<p>Here's an example of option #2 (untested):</p>\n\n<pre><code>class FakeTime:\n def time(self):\n return 1225856967.109\n\nimport gzip\ngzip.time = FakeTime()\n\n# Now call gzip, it will think time doesn't change!\n</code></pre>\n\n<p>Option #5 may be the cleanest in terms of not depending on the internals of the gzip module (untested):</p>\n\n<pre><code>class GzipTimeFixingFile:\n def __init__(self, realfile):\n self.realfile = realfile\n self.pos = 0\n\n def write(self, bytes):\n if self.pos == 4 and len(bytes) == 4:\n self.realfile.write(\"XYZY\") # Fake time goes here.\n else:\n self.realfile.write(bytes)\n self.pos += len(bytes)\n</code></pre>\n" }, { "answer_id": 264348, "author": "Tony Arkles", "author_id": 13868, "author_profile": "https://Stackoverflow.com/users/13868", "pm_score": 0, "selected": false, "text": "<p>It's not pretty, but you could monkeypatch time.time temporarily with something like this:</p>\n\n<pre><code>import time\n\ndef fake_time():\n return 100000000.0\n\ndef do_gzip(content):\n orig_time = time.time\n time.time = fake_time\n # result = do gzip stuff here\n time.time = orig_time\n return result\n</code></pre>\n\n<p>It's not pretty, but it would probably work.</p>\n" }, { "answer_id": 265445, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>Submit a <a href=\"http://www.python.org/dev/patches/\" rel=\"nofollow noreferrer\">patch</a> in which the computation of the time stamp is factored out. It would almost certainly be accepted.</p>\n" }, { "answer_id": 270315, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 1, "selected": false, "text": "<p>I've taken Mr. Coventry's advice and <a href=\"http://bugs.python.org/issue4272\" rel=\"nofollow noreferrer\">submitted a patch</a>. However, given the current state of the Python release schedule, with 3.0 just around the corner, I don't expect it to show up in a release anytime soon. Still, we'll see what happens!</p>\n\n<p>In the meantime, I like Mr. Batchelder's option 5 of piping the gzip stream through a small custom filter that sets the timestamp field correctly. It sounds like the cleanest approach. As he demonstrates, the code required is actually quite small, though his example does depend for some of its simplicity on the (currently valid) assumption that the <code>gzip</code> module implementation will choose to write the timestamp using exactly one four-byte call to <code>write()</code>. Still, I don't think it would be very difficult to come up with a fully general version if needed.</p>\n\n<p>The monkey-patching approach (a.k.a. option 2) is quite tempting for its simplicity but gives me pause because I'm writing a library that calls <code>gzip</code>, not just a standalone program, and it seems to me that somebody might try to call <code>gzip</code> from another thread before my module is ready to reverse its change to the <code>gzip</code> module's global state. This would be especially unfortunate if the other thread were trying to pull a similar monkey-patching stunt! I admit this potential problem doesn't sound very likely to come up in practice, but imagine how painful it would be to diagnose such a mess!</p>\n\n<p>I can vaguely imagine trying to do something tricky and complicated and perhaps not so future-proof to somehow import a private copy of the <code>gzip</code> module and monkey-patch <em>that</em>, but by that point a filter seems simpler and more direct.</p>\n" }, { "answer_id": 36034315, "author": "Dominic Bevacqua", "author_id": 527997, "author_profile": "https://Stackoverflow.com/users/527997", "pm_score": 4, "selected": true, "text": "<p>From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually.</p>\n\n<pre><code>import gzip\n\ncontent = b\"Some content\"\nf = open(\"/tmp/f.gz\", \"wb\")\ngz = gzip.GzipFile(fileobj=f,mode=\"wb\",filename=\"\",mtime=0)\ngz.write(content)\ngz.close()\nf.close()\n</code></pre>\n" }, { "answer_id": 44054997, "author": "storm_m2138", "author_id": 1236537, "author_profile": "https://Stackoverflow.com/users/1236537", "pm_score": 0, "selected": false, "text": "<p>Similar to the answer from dominic's above, but for an <strong>existing</strong> file:</p>\n\n<pre><code>with open('test_zip1', 'rb') as f_in, open('test_zip1.gz', 'wb') as f_out:\n with gzip.GzipFile(fileobj=f_out, mode='wb', filename=\"\", mtime=0) as gz_out:\n shutil.copyfileobj(f_in, gz_out)\n</code></pre>\n\n<p>Testing MD5 sums:</p>\n\n<pre><code>md5sum test_zip*\n7e544bc6827232f67ff5508c8d6c30b3 test_zip1\n75decc5768bdc3c98d6e598dea85e39b test_zip1.gz\n7e544bc6827232f67ff5508c8d6c30b3 test_zip2\n75decc5768bdc3c98d6e598dea85e39b test_zip2.gz\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13871/" ]
I'm interested in compressing data using Python's `gzip` module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed. Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad. In any case, there doesn't seem to be a way for the caller of Python's `gzip` module to supply the correct modification time of the underlying data. (The actual `gzip` program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the `gunzip` command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask? Has anyone else encountered this problem? What's the least terrible way to `gzip` some data with an arbitrary timestamp from Python?
From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually. ``` import gzip content = b"Some content" f = open("/tmp/f.gz", "wb") gz = gzip.GzipFile(fileobj=f,mode="wb",filename="",mtime=0) gz.write(content) gz.close() f.close() ```
264,236
<p>How do you determine what to put in .rhosts file in an VAX openvms system when trying to remotely access the server using a remote shell from Cygwin on windows XP ? .rlogin and rsh are the only methods that can be used to access the VAX server and it must be using Cygwin to remote in to the VAX server. SSH is not an option. When the VAX server is accessed from a Sun server it works fine. I have tried many combination's of possible things that Cygwin could be sending the VAX as far as a user name an address of origin. </p>
[ { "answer_id": 264297, "author": "Sean", "author_id": 4919, "author_profile": "https://Stackoverflow.com/users/4919", "pm_score": 0, "selected": false, "text": "<p>In lib/gzip.py, we find the method that builds the header, including the part that does indeed contain a timestamp. In Python 2.5, this begins on line 143:</p>\n\n<pre><code>def _write_gzip_header(self):\n self.fileobj.write('\\037\\213') # magic header\n self.fileobj.write('\\010') # compression method\n fname = self.filename[:-3]\n flags = 0\n if fname:\n flags = FNAME\n self.fileobj.write(chr(flags))\n write32u(self.fileobj, long(time.time())) # The current time!\n self.fileobj.write('\\002')\n self.fileobj.write('\\377')\n if fname:\n self.fileobj.write(fname + '\\000')\n</code></pre>\n\n<p>As you can see, it uses time.time() to fetch the current time. According to the online module docs, time.time will \"return the time as a floating point number expressed in seconds since the epoch, in UTC.\" So, if you change this to a floating-point constant of your choosing, you can always have the same headers written out. I can't see a better way to do this unless you want to hack the library some more to accept an optional time param that you use while defaulting to time.time() when it's not specified, in which case, I'm sure they'd love it if you submitted a patch!</p>\n" }, { "answer_id": 264303, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 3, "selected": false, "text": "<p>Yeah, you don't have any pretty options. The time is written with this line in _write_gzip_header:</p>\n\n<pre><code>write32u(self.fileobj, long(time.time()))\n</code></pre>\n\n<p>Since they don't give you a way to override the time, you can do one of these things:</p>\n\n<ol>\n<li>Derive a class from GzipFile, and copy the <code>_write_gzip_header</code> function into your derived class, but with a different value in this one line.</li>\n<li>After importing the gzip module, assign new code to its time member. You will essentially be providing a new definition of the name time in the gzip code, so you can change what time.time() means.</li>\n<li>Copy the entire gzip module, and name it my_stable_gzip, and change the line you need to.</li>\n<li>Pass a CStringIO object in as fileobj, and modify the bytestream after gzip is done.</li>\n<li>Write a fake file object that keeps track of the bytes written, and passes everything through to a real file, except for the bytes for the timestamp, which you write yourself.</li>\n</ol>\n\n<p>Here's an example of option #2 (untested):</p>\n\n<pre><code>class FakeTime:\n def time(self):\n return 1225856967.109\n\nimport gzip\ngzip.time = FakeTime()\n\n# Now call gzip, it will think time doesn't change!\n</code></pre>\n\n<p>Option #5 may be the cleanest in terms of not depending on the internals of the gzip module (untested):</p>\n\n<pre><code>class GzipTimeFixingFile:\n def __init__(self, realfile):\n self.realfile = realfile\n self.pos = 0\n\n def write(self, bytes):\n if self.pos == 4 and len(bytes) == 4:\n self.realfile.write(\"XYZY\") # Fake time goes here.\n else:\n self.realfile.write(bytes)\n self.pos += len(bytes)\n</code></pre>\n" }, { "answer_id": 264348, "author": "Tony Arkles", "author_id": 13868, "author_profile": "https://Stackoverflow.com/users/13868", "pm_score": 0, "selected": false, "text": "<p>It's not pretty, but you could monkeypatch time.time temporarily with something like this:</p>\n\n<pre><code>import time\n\ndef fake_time():\n return 100000000.0\n\ndef do_gzip(content):\n orig_time = time.time\n time.time = fake_time\n # result = do gzip stuff here\n time.time = orig_time\n return result\n</code></pre>\n\n<p>It's not pretty, but it would probably work.</p>\n" }, { "answer_id": 265445, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>Submit a <a href=\"http://www.python.org/dev/patches/\" rel=\"nofollow noreferrer\">patch</a> in which the computation of the time stamp is factored out. It would almost certainly be accepted.</p>\n" }, { "answer_id": 270315, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 1, "selected": false, "text": "<p>I've taken Mr. Coventry's advice and <a href=\"http://bugs.python.org/issue4272\" rel=\"nofollow noreferrer\">submitted a patch</a>. However, given the current state of the Python release schedule, with 3.0 just around the corner, I don't expect it to show up in a release anytime soon. Still, we'll see what happens!</p>\n\n<p>In the meantime, I like Mr. Batchelder's option 5 of piping the gzip stream through a small custom filter that sets the timestamp field correctly. It sounds like the cleanest approach. As he demonstrates, the code required is actually quite small, though his example does depend for some of its simplicity on the (currently valid) assumption that the <code>gzip</code> module implementation will choose to write the timestamp using exactly one four-byte call to <code>write()</code>. Still, I don't think it would be very difficult to come up with a fully general version if needed.</p>\n\n<p>The monkey-patching approach (a.k.a. option 2) is quite tempting for its simplicity but gives me pause because I'm writing a library that calls <code>gzip</code>, not just a standalone program, and it seems to me that somebody might try to call <code>gzip</code> from another thread before my module is ready to reverse its change to the <code>gzip</code> module's global state. This would be especially unfortunate if the other thread were trying to pull a similar monkey-patching stunt! I admit this potential problem doesn't sound very likely to come up in practice, but imagine how painful it would be to diagnose such a mess!</p>\n\n<p>I can vaguely imagine trying to do something tricky and complicated and perhaps not so future-proof to somehow import a private copy of the <code>gzip</code> module and monkey-patch <em>that</em>, but by that point a filter seems simpler and more direct.</p>\n" }, { "answer_id": 36034315, "author": "Dominic Bevacqua", "author_id": 527997, "author_profile": "https://Stackoverflow.com/users/527997", "pm_score": 4, "selected": true, "text": "<p>From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually.</p>\n\n<pre><code>import gzip\n\ncontent = b\"Some content\"\nf = open(\"/tmp/f.gz\", \"wb\")\ngz = gzip.GzipFile(fileobj=f,mode=\"wb\",filename=\"\",mtime=0)\ngz.write(content)\ngz.close()\nf.close()\n</code></pre>\n" }, { "answer_id": 44054997, "author": "storm_m2138", "author_id": 1236537, "author_profile": "https://Stackoverflow.com/users/1236537", "pm_score": 0, "selected": false, "text": "<p>Similar to the answer from dominic's above, but for an <strong>existing</strong> file:</p>\n\n<pre><code>with open('test_zip1', 'rb') as f_in, open('test_zip1.gz', 'wb') as f_out:\n with gzip.GzipFile(fileobj=f_out, mode='wb', filename=\"\", mtime=0) as gz_out:\n shutil.copyfileobj(f_in, gz_out)\n</code></pre>\n\n<p>Testing MD5 sums:</p>\n\n<pre><code>md5sum test_zip*\n7e544bc6827232f67ff5508c8d6c30b3 test_zip1\n75decc5768bdc3c98d6e598dea85e39b test_zip1.gz\n7e544bc6827232f67ff5508c8d6c30b3 test_zip2\n75decc5768bdc3c98d6e598dea85e39b test_zip2.gz\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34531/" ]
How do you determine what to put in .rhosts file in an VAX openvms system when trying to remotely access the server using a remote shell from Cygwin on windows XP ? .rlogin and rsh are the only methods that can be used to access the VAX server and it must be using Cygwin to remote in to the VAX server. SSH is not an option. When the VAX server is accessed from a Sun server it works fine. I have tried many combination's of possible things that Cygwin could be sending the VAX as far as a user name an address of origin.
From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually. ``` import gzip content = b"Some content" f = open("/tmp/f.gz", "wb") gz = gzip.GzipFile(fileobj=f,mode="wb",filename="",mtime=0) gz.write(content) gz.close() f.close() ```
264,243
<p>I'm working on a quick project to monitor/process data. Essentially that's just monitors, schedules and processors. The monitor checks for data (ftp, local, imap, pop, etc) using a schedule and sends new data to a processor. They all have interfaces.</p> <p>I'm trying to find a sane way to use config to configure what schedule/processor each monitor uses. That's pretty easy:</p> <pre><code>&lt;monitor type="any.class.implementing.monitor"&gt; &lt;schedule type="any.class.implementing.schedule"&gt; ... &lt;/schedule&gt; &lt;processor type="any.class.implementing.processor" /&gt; &lt;/monitor&gt; </code></pre> <p>What I'm struggling with is what's the best way to configure any old monitor/schedule/processor thrown into the mix. On one hand, one could implement constructor params or properties (give ot take any syntax):</p> <pre><code>&lt;monitor type="any.class.implementing.monitor"&gt; &lt;args&gt; &lt;arg value="..." /&gt; &lt;/args&gt; &lt;properties&gt; &lt;property name="..." value=..." /&gt; &lt;/properties&gt; &lt;schedule type="any.class.implementing.schedule"&gt; ... &lt;/schedule&gt; &lt;processor type="any.class.implementing.processor" /&gt; &lt;/monitor&gt; </code></pre> <p>Another solution is factory method in each interface that takes the custom config as a param:</p> <pre><code>public IMonitor Create(CustomConfigSection config); </code></pre> <p>I've seen people use both. What do you prefer? Any tricks of the trade when mapping config to constructors?</p> <p>I'm a little torn as to whether DI can fit into this mess. In the end, it would be a set of bindings per monitor instance, which seems pointless except for defaults, which config could cover.</p>
[ { "answer_id": 264297, "author": "Sean", "author_id": 4919, "author_profile": "https://Stackoverflow.com/users/4919", "pm_score": 0, "selected": false, "text": "<p>In lib/gzip.py, we find the method that builds the header, including the part that does indeed contain a timestamp. In Python 2.5, this begins on line 143:</p>\n\n<pre><code>def _write_gzip_header(self):\n self.fileobj.write('\\037\\213') # magic header\n self.fileobj.write('\\010') # compression method\n fname = self.filename[:-3]\n flags = 0\n if fname:\n flags = FNAME\n self.fileobj.write(chr(flags))\n write32u(self.fileobj, long(time.time())) # The current time!\n self.fileobj.write('\\002')\n self.fileobj.write('\\377')\n if fname:\n self.fileobj.write(fname + '\\000')\n</code></pre>\n\n<p>As you can see, it uses time.time() to fetch the current time. According to the online module docs, time.time will \"return the time as a floating point number expressed in seconds since the epoch, in UTC.\" So, if you change this to a floating-point constant of your choosing, you can always have the same headers written out. I can't see a better way to do this unless you want to hack the library some more to accept an optional time param that you use while defaulting to time.time() when it's not specified, in which case, I'm sure they'd love it if you submitted a patch!</p>\n" }, { "answer_id": 264303, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 3, "selected": false, "text": "<p>Yeah, you don't have any pretty options. The time is written with this line in _write_gzip_header:</p>\n\n<pre><code>write32u(self.fileobj, long(time.time()))\n</code></pre>\n\n<p>Since they don't give you a way to override the time, you can do one of these things:</p>\n\n<ol>\n<li>Derive a class from GzipFile, and copy the <code>_write_gzip_header</code> function into your derived class, but with a different value in this one line.</li>\n<li>After importing the gzip module, assign new code to its time member. You will essentially be providing a new definition of the name time in the gzip code, so you can change what time.time() means.</li>\n<li>Copy the entire gzip module, and name it my_stable_gzip, and change the line you need to.</li>\n<li>Pass a CStringIO object in as fileobj, and modify the bytestream after gzip is done.</li>\n<li>Write a fake file object that keeps track of the bytes written, and passes everything through to a real file, except for the bytes for the timestamp, which you write yourself.</li>\n</ol>\n\n<p>Here's an example of option #2 (untested):</p>\n\n<pre><code>class FakeTime:\n def time(self):\n return 1225856967.109\n\nimport gzip\ngzip.time = FakeTime()\n\n# Now call gzip, it will think time doesn't change!\n</code></pre>\n\n<p>Option #5 may be the cleanest in terms of not depending on the internals of the gzip module (untested):</p>\n\n<pre><code>class GzipTimeFixingFile:\n def __init__(self, realfile):\n self.realfile = realfile\n self.pos = 0\n\n def write(self, bytes):\n if self.pos == 4 and len(bytes) == 4:\n self.realfile.write(\"XYZY\") # Fake time goes here.\n else:\n self.realfile.write(bytes)\n self.pos += len(bytes)\n</code></pre>\n" }, { "answer_id": 264348, "author": "Tony Arkles", "author_id": 13868, "author_profile": "https://Stackoverflow.com/users/13868", "pm_score": 0, "selected": false, "text": "<p>It's not pretty, but you could monkeypatch time.time temporarily with something like this:</p>\n\n<pre><code>import time\n\ndef fake_time():\n return 100000000.0\n\ndef do_gzip(content):\n orig_time = time.time\n time.time = fake_time\n # result = do gzip stuff here\n time.time = orig_time\n return result\n</code></pre>\n\n<p>It's not pretty, but it would probably work.</p>\n" }, { "answer_id": 265445, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "<p>Submit a <a href=\"http://www.python.org/dev/patches/\" rel=\"nofollow noreferrer\">patch</a> in which the computation of the time stamp is factored out. It would almost certainly be accepted.</p>\n" }, { "answer_id": 270315, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 1, "selected": false, "text": "<p>I've taken Mr. Coventry's advice and <a href=\"http://bugs.python.org/issue4272\" rel=\"nofollow noreferrer\">submitted a patch</a>. However, given the current state of the Python release schedule, with 3.0 just around the corner, I don't expect it to show up in a release anytime soon. Still, we'll see what happens!</p>\n\n<p>In the meantime, I like Mr. Batchelder's option 5 of piping the gzip stream through a small custom filter that sets the timestamp field correctly. It sounds like the cleanest approach. As he demonstrates, the code required is actually quite small, though his example does depend for some of its simplicity on the (currently valid) assumption that the <code>gzip</code> module implementation will choose to write the timestamp using exactly one four-byte call to <code>write()</code>. Still, I don't think it would be very difficult to come up with a fully general version if needed.</p>\n\n<p>The monkey-patching approach (a.k.a. option 2) is quite tempting for its simplicity but gives me pause because I'm writing a library that calls <code>gzip</code>, not just a standalone program, and it seems to me that somebody might try to call <code>gzip</code> from another thread before my module is ready to reverse its change to the <code>gzip</code> module's global state. This would be especially unfortunate if the other thread were trying to pull a similar monkey-patching stunt! I admit this potential problem doesn't sound very likely to come up in practice, but imagine how painful it would be to diagnose such a mess!</p>\n\n<p>I can vaguely imagine trying to do something tricky and complicated and perhaps not so future-proof to somehow import a private copy of the <code>gzip</code> module and monkey-patch <em>that</em>, but by that point a filter seems simpler and more direct.</p>\n" }, { "answer_id": 36034315, "author": "Dominic Bevacqua", "author_id": 527997, "author_profile": "https://Stackoverflow.com/users/527997", "pm_score": 4, "selected": true, "text": "<p>From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually.</p>\n\n<pre><code>import gzip\n\ncontent = b\"Some content\"\nf = open(\"/tmp/f.gz\", \"wb\")\ngz = gzip.GzipFile(fileobj=f,mode=\"wb\",filename=\"\",mtime=0)\ngz.write(content)\ngz.close()\nf.close()\n</code></pre>\n" }, { "answer_id": 44054997, "author": "storm_m2138", "author_id": 1236537, "author_profile": "https://Stackoverflow.com/users/1236537", "pm_score": 0, "selected": false, "text": "<p>Similar to the answer from dominic's above, but for an <strong>existing</strong> file:</p>\n\n<pre><code>with open('test_zip1', 'rb') as f_in, open('test_zip1.gz', 'wb') as f_out:\n with gzip.GzipFile(fileobj=f_out, mode='wb', filename=\"\", mtime=0) as gz_out:\n shutil.copyfileobj(f_in, gz_out)\n</code></pre>\n\n<p>Testing MD5 sums:</p>\n\n<pre><code>md5sum test_zip*\n7e544bc6827232f67ff5508c8d6c30b3 test_zip1\n75decc5768bdc3c98d6e598dea85e39b test_zip1.gz\n7e544bc6827232f67ff5508c8d6c30b3 test_zip2\n75decc5768bdc3c98d6e598dea85e39b test_zip2.gz\n</code></pre>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91911/" ]
I'm working on a quick project to monitor/process data. Essentially that's just monitors, schedules and processors. The monitor checks for data (ftp, local, imap, pop, etc) using a schedule and sends new data to a processor. They all have interfaces. I'm trying to find a sane way to use config to configure what schedule/processor each monitor uses. That's pretty easy: ``` <monitor type="any.class.implementing.monitor"> <schedule type="any.class.implementing.schedule"> ... </schedule> <processor type="any.class.implementing.processor" /> </monitor> ``` What I'm struggling with is what's the best way to configure any old monitor/schedule/processor thrown into the mix. On one hand, one could implement constructor params or properties (give ot take any syntax): ``` <monitor type="any.class.implementing.monitor"> <args> <arg value="..." /> </args> <properties> <property name="..." value=..." /> </properties> <schedule type="any.class.implementing.schedule"> ... </schedule> <processor type="any.class.implementing.processor" /> </monitor> ``` Another solution is factory method in each interface that takes the custom config as a param: ``` public IMonitor Create(CustomConfigSection config); ``` I've seen people use both. What do you prefer? Any tricks of the trade when mapping config to constructors? I'm a little torn as to whether DI can fit into this mess. In the end, it would be a set of bindings per monitor instance, which seems pointless except for defaults, which config could cover.
From Python 2.7 onwards you can specify the time to be used in the gzip header. N.B. filename is also included in the header and can also be specified manually. ``` import gzip content = b"Some content" f = open("/tmp/f.gz", "wb") gz = gzip.GzipFile(fileobj=f,mode="wb",filename="",mtime=0) gz.write(content) gz.close() f.close() ```
264,248
<p>I'm looking into integrating jBPM with my current project, so far so good just including the jpdl jar in my ear and using the spring modules 0.8 jbpm module, however I've got to have a reasonable way of going from my changes to to the process definition in the designer to deployment in production.</p> <p>The path has to be repeatable in a number of environments (dev, many test, staging and then prod) and ideally should be done while the system itself is not running.</p> <p>I'd Ideally package the entire definition as an SQL script, however I haven't seen any tool to translate from processdefinition.xml to sql and assembling it all manually seems too fiddly and error prone.</p> <p>Has anyone else out there had any experiences here?</p> <p>The system is running on websphere 6.1 and it's my preference to avoid executing java code at migration time (running java code to generate artifacts that can then be used during migration is ok though)</p>
[ { "answer_id": 266157, "author": "shyam", "author_id": 7616, "author_profile": "https://Stackoverflow.com/users/7616", "pm_score": 0, "selected": false, "text": "<p>Why not use the ant task extensions provided by JBPM specifically <a href=\"http://docs.jboss.org/jbpm/v3/javadoc/org/jbpm/ant/DeployProcessTask.html\" rel=\"nofollow noreferrer\"><code>DeployProcessTask</code></a>. You can deploy to different environments having just a single <code>.par</code> file and the corresponding <code>jbpm-cfg.xml</code> for the various dev/test/staging/prod environments. The only change you might have to do is to configure your hibernate config to directly connect to the database instead of using the datasource.</p>\n" }, { "answer_id": 286822, "author": "Harry Lime", "author_id": 21590, "author_profile": "https://Stackoverflow.com/users/21590", "pm_score": 1, "selected": false, "text": "<p>If you want to avoid going down the <code>.par</code> route, it's easy to write some simple Java code to deploy a new process definition version to your database. Something like</p>\n\n<pre><code>JbpmConfiguration jbpmConfiguration = JbpmConfiguration.getInstance(\"jbpm.cfg.xml\"));\nProcessDefinition processDefinition = ProcessDefinition.parseXmlInputStream(newPdStream);\nJbpmContext context = jbpmConfiguration.createJbpmContext();\ncontext.getGraphSession().deployProcessDefinition(processDefinition);\n</code></pre>\n\n<p>You'll need to have the <code>hibernate.properties</code> or <code>hibernate.cfg.xml</code> for the relevant database on the classpath.</p>\n\n<p>What's great about this way is that all of the versioning stuff is done for you automatically. We used to use a hack where we modified the process definition (basically ignoring versioning), but it was a big huge mess for process instances which were active at the time.</p>\n" }, { "answer_id": 333354, "author": "Balint Pato", "author_id": 19621, "author_profile": "https://Stackoverflow.com/users/19621", "pm_score": 1, "selected": false, "text": "<p>Workaround suggestion:\ndeploy and intercept sql queries</p>\n\n<p>I haven't tried this but I would suggest to try use the deployment of the jBPM-console deploy servlet or </p>\n\n<pre><code>context.getGraphSession().deployProcessDefinition(processDefinition);\n</code></pre>\n\n<p>as suggested by shyamsundar</p>\n\n<p>AND </p>\n\n<p>log the sql updates with LogDriver: <a href=\"http://rkbloom.net/logdriver/logdriver.tar.gz\" rel=\"nofollow noreferrer\">http://rkbloom.net/logdriver/logdriver.tar.gz</a></p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking into integrating jBPM with my current project, so far so good just including the jpdl jar in my ear and using the spring modules 0.8 jbpm module, however I've got to have a reasonable way of going from my changes to to the process definition in the designer to deployment in production. The path has to be repeatable in a number of environments (dev, many test, staging and then prod) and ideally should be done while the system itself is not running. I'd Ideally package the entire definition as an SQL script, however I haven't seen any tool to translate from processdefinition.xml to sql and assembling it all manually seems too fiddly and error prone. Has anyone else out there had any experiences here? The system is running on websphere 6.1 and it's my preference to avoid executing java code at migration time (running java code to generate artifacts that can then be used during migration is ok though)
If you want to avoid going down the `.par` route, it's easy to write some simple Java code to deploy a new process definition version to your database. Something like ``` JbpmConfiguration jbpmConfiguration = JbpmConfiguration.getInstance("jbpm.cfg.xml")); ProcessDefinition processDefinition = ProcessDefinition.parseXmlInputStream(newPdStream); JbpmContext context = jbpmConfiguration.createJbpmContext(); context.getGraphSession().deployProcessDefinition(processDefinition); ``` You'll need to have the `hibernate.properties` or `hibernate.cfg.xml` for the relevant database on the classpath. What's great about this way is that all of the versioning stuff is done for you automatically. We used to use a hack where we modified the process definition (basically ignoring versioning), but it was a big huge mess for process instances which were active at the time.
264,249
<p>I've been beating my head against this wall for quite some time now, so I thought I'd ask some experts.</p> <p>I need to send an xml string from one computer to the next. I would like to format the xml something like this:</p> <pre><code>&lt;xml&gt; &lt;author&gt;Joe the Magnificent&lt;/author&gt; &lt;title&gt;Joe Goes Home&lt;/title&gt; &lt;/xml&gt; </code></pre> <p>Can anyone provide some assistance?</p> <p>Edit: More detail</p> <p>I control both the send and receive, and have successfully transfered a hard coded string one-way.</p> <p>Here is the receive side:</p> <pre><code> Dim author As String Dim title As String Dim xDoc As New XmlDocument Dim xAuthor As XmlElement Dim xTitle As XmlElement xDoc.LoadXml(xml) xAuthor = xDoc.FirstChild.Item("author") xTitle = xDoc.FirstChild.Item("title") author = xAuthor.FirstChild.Value title = xTitle.FirstChild.Value ShowMessage(author, title) </code></pre> <p>Mostly this is an exercise in learning how to do XML for me, so there's no real purpose to it other than my own knowledge. I was kind of looking for some opinions on the best way to do such things.</p>
[ { "answer_id": 264279, "author": "Jim Burger", "author_id": 20164, "author_profile": "https://Stackoverflow.com/users/20164", "pm_score": 2, "selected": false, "text": "<p>Using the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx\" rel=\"nofollow noreferrer\">XmlDocument.Load</a> method you have 4 options: From a Stream, TextReader, URL, or XmlReader.</p>\n\n<p>You could use the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.aspx\" rel=\"nofollow noreferrer\">NetworkStream</a> class to go over a network. You could post your XML up on a website and suck it down via the URL option. You might want to be more specific about the protocol in which you want the transfer to occur.</p>\n\n<p>For example, to write to a stream use the XmlWriter.Create overload for a stream. Use an XmlWriterSettings object to provide indentation.</p>\n\n<pre><code> Dim settings As XmlWriterSettings = New XmlWriterSettings()\n settings.Indent = true\n settings.IndentChars = (ControlChars.Tab)\n settings.OmitXmlDeclaration = true\n\n Dim myNetworkStream As New NetworkStream(mySocket) 'mySocket is a whole other code sample\n\n ' Create the XmlWriter object and write some content.\n writer = XmlWriter.Create(myNetworkStream, settings)\n XmlDocument.WriteTo(writer)\n</code></pre>\n\n<p>To construct xml documents [the old way] was quite cumbersome, and I'd suggest looking at VB9 XML literals. However here is an example of .NET 2 style XmlDocument manipulation:</p>\n\n<pre><code> Dim doc As New XmlDocument()\n Dim root As XmlElement = doc.CreateElement(\"xml\")\n Dim author As XmlElement = doc.CreateElement(\"author\")\n author.Value = \"Joe the magnificent\"\n Dim title As XmlElement = doc.CreateElement(\"title\")\n title.Value = \"Joe goes home\"\n\n root.AppendChild(author)\n root.AppendChild(title)\n doc.AppendChild(root)\n</code></pre>\n" }, { "answer_id": 264282, "author": "Nathan W", "author_id": 6335, "author_profile": "https://Stackoverflow.com/users/6335", "pm_score": 1, "selected": false, "text": "<p>Well I don't know if this is what you are looking for but if you are using the latest version of VB and .NET then you should be able to use xml literals and LINQ to parse your xml: Like so-></p>\n\n<pre><code>Sub Send()\n Dim myxml = &lt;xml&gt;\n &lt;author&gt;Joe the Magnificent&lt;/author&gt;\n &lt;title&gt;Joe Goes Home&lt;/title&gt;\n &lt;/xml&gt;\nReadxml(myxml)\nEnd Sub\n\nSub Readxml(myxml as XDocument)\nDim Data = From xml in myxml...&lt;xml&gt; _\n Select New With {.Author = xml.&lt;author&gt;.value, _\n .title = xml.&lt;title&gt;.value}\n\nFor each item in Data\n ShowMessage(item.Author,Item.Title)\nNext\nEnd Sub\n</code></pre>\n\n<p>Note the above is just air code so it may not run, not at my computer so I can't test it.</p>\n" }, { "answer_id": 283819, "author": "Krakerjak", "author_id": 34539, "author_profile": "https://Stackoverflow.com/users/34539", "pm_score": 3, "selected": true, "text": "<p>Here's what I ended up doing:</p>\n\n<pre><code>Public Function FormatMessage(ByVal author As String, ByVal title As String, ByVal genre As String) As String\nDim xDoc As New XmlDocument\n\n' Create outer XML\nDim xNode As XmlNode = xDoc.AppendChild(xDoc.CreateElement(\"xml\"))\n\n' Create Author Node\nDim xAuthor As XmlNode = xNode.AppendChild(xDoc.CreateElement(\"author\"))\nxAuthor.InnerText = author\n\n' Create Message Node\nDim xTitle As XmlNode = xNode.AppendChild(xDoc.CreateElement(\"message\"))\nxtitle.InnerText = title\n\n' Create Genre Node\nDim xGenre As XmlNode = xNode.AppendChild(xDoc.CreateElement(\"genre\"))\nxGenre.InnerText = genre\n\n' Create StringWriter to convert XMLDoc to string\nDim xWriter As New IO.StringWriter()\nDim xml_writer As New XmlTextWriter(xWriter)\nxDoc.WriteContentTo(xml_writer)\nReturn xWriter.ToString\n\nEnd Function\n</code></pre>\n\n<p>This function builds the xml string based on the input values, then to break the xml string back down into the original values, I used this:</p>\n\n<pre><code>Dim author As String\nDim title As String\nDim genre As String\n\nDim xDoc As New XmlDocument\nDim xAuthor As XmlElement\nDim xTitle As XmlElement\nDim xGenre as XmlElement\n\nxDoc.LoadXml(xml)\nIf xDoc.DocumentElement.Name = \"xml\" Then\n xAuthor = xDoc.FirstChild.Item(\"author\")\n xTitle = xDoc.FirstChild.Item(\"title\")\n\n author = xAuthor.FirstChild.Value\n title = xTitle.FirstChild.Value\n genre = xGenre.FirstChild.Value\nEnd If\n\nShowMessage(author, title, genre)\n</code></pre>\n\n<p>Thanks for the help!\nKJ</p>\n" }, { "answer_id": 53653627, "author": "Danny James", "author_id": 7709026, "author_profile": "https://Stackoverflow.com/users/7709026", "pm_score": 0, "selected": false, "text": "<p>Create a class like this:</p>\n\n<pre><code>Imports System.Data\n\nPublic Class STKReservedStock_insertrow\nInherits Request\nPublic Sub New(User As String, Company As String)\n MyBase.New(\"stkreservestockall\", User, Company)\nEnd Sub\n\n\n#Region \"Properties\"\n\nPublic Property _pdt As String\n Get\n Return DirectCast(Field(\"pdt\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"pdt\") = value\n End Set\nEnd Property\nPublic Property _whse As String\n Get\n Return DirectCast(Field(\"whse\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"whse\") = value\n End Set\nEnd Property\nPublic Property _traceNumber As Integer\n Get\n Return DirectCast(Field(\"traceNumber\"), Integer)\n End Get\n Set(ByVal value As Integer)\n Field(\"traceNumber\") = value\n End Set\nEnd Property\nPublic Property _bin As String\n Get\n Return DirectCast(Field(\"bin\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"bin\") = value\n End Set\nEnd Property\nPublic Property _lotref As String\n Get\n Return DirectCast(Field(\"lotref\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"lotref\") = value\n End Set\nEnd Property\nPublic Property _packUOM As String\n Get\n Return DirectCast(Field(\"packUOM\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"packUOM\") = value\n End Set\nEnd Property\nPublic Property _grade As String\n Get\n Return DirectCast(Field(\"grade\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"grade\") = value\n End Set\nEnd Property\nPublic Property _shpLabel As Integer\n Get\n Return DirectCast(Field(\"shpLabel\"), Integer)\n End Get\n Set(ByVal value As Integer)\n Field(\"shpLabel\") = value\n End Set\nEnd Property\nPublic Property _countLoc As String\n Get\n Return DirectCast(Field(\"countLoc\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"countLoc\") = value\n End Set\nEnd Property\nPublic Property _palletType As String\n Get\n Return DirectCast(Field(\"palletType\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"palletType\") = value\n End Set\nEnd Property\nPublic Property _subPdt As String\n Get\n Return DirectCast(Field(\"subPdt\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"subPdt\") = value\n End Set\nEnd Property\nPublic Property _subTn As Integer\n Get\n Return DirectCast(Field(\"subTn\"), Integer)\n End Get\n Set(ByVal value As Integer)\n Field(\"subTn\") = value\n End Set\nEnd Property\nPublic Property _origReserved As Decimal\n Get\n Return DirectCast(Field(\"origReserved\"), Integer)\n End Get\n Set(ByVal value As Decimal)\n Field(\"origReserved\") = value\n End Set\nEnd Property\nPublic Property _reserved As Decimal\n Get\n Return DirectCast(Field(\"reserved\"), Integer)\n End Get\n Set(ByVal value As Decimal)\n Field(\"reserved\") = value\n End Set\nEnd Property\nPublic Property _dateReserved As Date\n Get\n Return DirectCast(Field(\"dateReserved\"), Date)\n End Get\n Set(ByVal value As Date)\n Field(\"dateReserved\") = value\n End Set\nEnd Property\nPublic Property _reservedBy As String\n Get\n Return DirectCast(Field(\"reservedBy\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"reservedBy\") = value\n End Set\nEnd Property\nPublic Property _reason As String\n Get\n Return DirectCast(Field(\"reason\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"reason\") = value\n End Set\nEnd Property\nPublic Property _party As String\n Get\n Return DirectCast(Field(\"party\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"party\") = value\n End Set\nEnd Property\nPublic Property _Cancelled As String\n Get\n Return DirectCast(Field(\"Cancelled\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"Cancelled\") = value\n End Set\nEnd Property\nPublic Property _CancelledByUsr As String\n Get\n Return DirectCast(Field(\"CancelledByUsr\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"CancelledByUsr\") = value\n End Set\nEnd Property\nPublic Property _RsvQty As Decimal\n Get\n Return DirectCast(Field(\"RsvQty\"), Integer)\n End Get\n Set(ByVal value As Decimal)\n Field(\"RsvQty\") = value\n End Set\nEnd Property\n#End Region\n\nEnd Class\n</code></pre>\n\n<p>Then just send it like this:</p>\n\n<pre><code> Dim XMLRqst As New STKReservedStock_insertrow(User, Company)\n\n Rqst._pdt = If(IsDBNull(drStock.Item(\"pdt\")), \"\", drStock.Item(\"pdt\").ToString)\n Rqst._whse = If(IsDBNull(drStock.Item(\"whse\")), \"\", drStock.Item(\"whse\").ToString)\n Rqst._traceNumber = If(IsDBNull(drStock.Item(\"traceNumber\")), 0, CInt(drStock.Item(\"traceNumber\")))\n Rqst._bin = If(IsDBNull(drStock.Item(\"bin\")), \"\", drStock.Item(\"bin\").ToString)\n Rqst._lotref = If(IsDBNull(drStock.Item(\"lotref\")), \"\", drStock.Item(\"lotref\").ToString)\n Rqst._packUOM = If(IsDBNull(drStock.Item(\"packUOM\")), \"\", drStock.Item(\"packUOM\").ToString)\n Rqst._grade = If(IsDBNull(drStock.Item(\"grade\")), \"\", drStock.Item(\"grade\").ToString)\n Rqst._shpLabel = If(IsDBNull(drStock.Item(\"shpLabel\")), 0, CInt(drStock.Item(\"shpLabel\")))\n Rqst._countLoc = If(IsDBNull(drStock.Item(\"countLoc\")), \"\", drStock.Item(\"countLoc\").ToString)\n Rqst._palletType = If(IsDBNull(drStock.Item(\"palletType\")), \"\", drStock.Item(\"palletType\").ToString)\n Rqst._subPdt = If(IsDBNull(drStock.Item(\"subPdt\")), \"\", drStock.Item(\"subPdt\").ToString)\n Rqst._subTn = If(IsDBNull(drStock.Item(\"subTn\")), 0, CInt(drStock.Item(\"subTn\")))\n Rqst._origReserved = reservedqty\n Rqst._reserved = reservedqty\n Rqst._dateReserved = Now\n Rqst._reservedBy = User\n Rqst._reason = reason\n Rqst._party = party\n Rqst._Cancelled = \"f\"\n Rqst._CancelledByUsr = \"\"\n Rqst._RsvQty = reservedqty\n\nSend(XMLRqst.toxml)\n</code></pre>\n\n<p>Send would obviously be your send sub routine (wherever it is sending it)</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34539/" ]
I've been beating my head against this wall for quite some time now, so I thought I'd ask some experts. I need to send an xml string from one computer to the next. I would like to format the xml something like this: ``` <xml> <author>Joe the Magnificent</author> <title>Joe Goes Home</title> </xml> ``` Can anyone provide some assistance? Edit: More detail I control both the send and receive, and have successfully transfered a hard coded string one-way. Here is the receive side: ``` Dim author As String Dim title As String Dim xDoc As New XmlDocument Dim xAuthor As XmlElement Dim xTitle As XmlElement xDoc.LoadXml(xml) xAuthor = xDoc.FirstChild.Item("author") xTitle = xDoc.FirstChild.Item("title") author = xAuthor.FirstChild.Value title = xTitle.FirstChild.Value ShowMessage(author, title) ``` Mostly this is an exercise in learning how to do XML for me, so there's no real purpose to it other than my own knowledge. I was kind of looking for some opinions on the best way to do such things.
Here's what I ended up doing: ``` Public Function FormatMessage(ByVal author As String, ByVal title As String, ByVal genre As String) As String Dim xDoc As New XmlDocument ' Create outer XML Dim xNode As XmlNode = xDoc.AppendChild(xDoc.CreateElement("xml")) ' Create Author Node Dim xAuthor As XmlNode = xNode.AppendChild(xDoc.CreateElement("author")) xAuthor.InnerText = author ' Create Message Node Dim xTitle As XmlNode = xNode.AppendChild(xDoc.CreateElement("message")) xtitle.InnerText = title ' Create Genre Node Dim xGenre As XmlNode = xNode.AppendChild(xDoc.CreateElement("genre")) xGenre.InnerText = genre ' Create StringWriter to convert XMLDoc to string Dim xWriter As New IO.StringWriter() Dim xml_writer As New XmlTextWriter(xWriter) xDoc.WriteContentTo(xml_writer) Return xWriter.ToString End Function ``` This function builds the xml string based on the input values, then to break the xml string back down into the original values, I used this: ``` Dim author As String Dim title As String Dim genre As String Dim xDoc As New XmlDocument Dim xAuthor As XmlElement Dim xTitle As XmlElement Dim xGenre as XmlElement xDoc.LoadXml(xml) If xDoc.DocumentElement.Name = "xml" Then xAuthor = xDoc.FirstChild.Item("author") xTitle = xDoc.FirstChild.Item("title") author = xAuthor.FirstChild.Value title = xTitle.FirstChild.Value genre = xGenre.FirstChild.Value End If ShowMessage(author, title, genre) ``` Thanks for the help! KJ
264,269
<p>A basic definition and example and a few references for "<a href="http://en.wikipedia.org/wiki/C_preprocessor#X-Macros" rel="nofollow noreferrer">X-Macros</a>" is given in this <a href="http://en.wikipedia.org/wiki/C_preprocessor" rel="nofollow noreferrer">wikipedia entry on the C pre-processor</a>:</p> <blockquote> <p>An X-Macro is a header file (commonly using a ".def" extension instead of the traditional ".h") that contains a list of similar macro calls (which can be referred to as "component macros").</p> </blockquote> <p>What are some good sources of information on how to use this powerful technique? Are there well-known open source libraries using this method?</p>
[ { "answer_id": 265291, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 3, "selected": false, "text": "<p>Dr. Dobb's has an <a href=\"http://www.ddj.com/cpp/184401387\" rel=\"noreferrer\">article</a> on this.</p>\n" }, { "answer_id": 265560, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 6, "selected": true, "text": "<p>I use X Macros() in code a lot. The value comes from only adding new data only to the \"X list\" and not modifying any other code.</p>\n\n<p>The most common use of X Macros() is for associating error text with error codes. When new error codes are added, programmers must remember to add the code and the text, typically in separate places. The X Macro allows the new error data to be added in a single place and get automatically populated anywhere it is needed.</p>\n\n<p>Unfortunately, the mechanisms use a lot of pre-compiler magic that can make the code somewhat hard to read (e.g. string joining with <code>token1##token2</code>, string creation with <code>#token</code>). Because of this I typically explain what the X Macro is doing in the comments.</p>\n\n<p>Here is an example using the error/return values. All new data gets added to the \"<code>X_ERROR</code>\" list. None of the other code hast to be modified.</p>\n\n<pre><code>/* \n * X Macro() data list\n * Format: Enum, Value, Text\n */\n#define X_ERROR \\\n X(ERROR_NONE, 1, \"Success\") \\\n X(ERROR_SYNTAX, 5, \"Invalid syntax\") \\\n X(ERROR_RANGE, 8, \"Out of range\")\n\n/* \n * Build an array of error return values\n * e.g. {0,5,8}\n */\nstatic int ErrorVal[] =\n{\n #define X(Enum,Val,Text) Val,\n X_ERROR\n #undef X\n};\n\n/* \n * Build an array of error enum names\n * e.g. {\"ERROR_NONE\",\"ERROR_SYNTAX\",\"ERROR_RANGE\"}\n */\n\nstatic char * ErrorEnum[] = {\n #define X(Enum,Val,Text) #Enum,\n X_ERROR\n #undef X\n};\n\n/* \n * Build an array of error strings\n * e.g. {\"Success\",\"Invalid syntax\",\"Out of range\"}\n */\nstatic char * ErrorText[] = {\n #define X(Enum,Val,Text) Text,\n X_ERROR\n #undef X\n};\n\n/* \n * Create an enumerated list of error indexes\n * e.g. 0,1,2\n */\nenum {\n #define X(Enum,Val,Text) IDX_##Enum,\n X_ERROR\n #undef X\n IDX_MAX /* Array size */\n};\n\nvoid showErrorInfo(void)\n{\n int i;\n\n /* \n * Access the values\n */\n for (i=0; i&lt;IDX_MAX; i++)\n printf(\" %s == %d [%s]\\n\", ErrorEnum[i], ErrorVal[i], ErrorText[i]);\n\n}\n</code></pre>\n\n<p>You can also use X Macros() to generate code. For example to test if an error value is \"known\", the X Macro can generate cases in a switch statement:</p>\n\n<pre><code> /*\n * Test validity of an error value\n * case ERROR_SUCCESS:\n * case ERROR_SYNTAX:\n * case ERROR_RANGE:\n */\n\n switch(value)\n {\n\n #define X(Enum,Val,Text) case Val:\n X_ERROR\n #undef X\n printf(\"Error %d is ok\\n\",value);\n break;\n default:\n printf(\"Invalid error: %d\\n\",value);\n break;\n }\n</code></pre>\n" }, { "answer_id": 9384365, "author": "ACRL", "author_id": 519285, "author_profile": "https://Stackoverflow.com/users/519285", "pm_score": 4, "selected": false, "text": "<p>I discovered X-macros a couple of years ago when I started making use of function pointers in my code. I am an embedded programmer and I use state machines frequently. Often I would write code like this:</p>\n\n<pre><code>/* declare an enumeration of state codes */\nenum{ STATE0, STATE1, STATE2, ... , STATEX, NUM_STATES};\n\n/* declare a table of function pointers */\np_func_t jumptable[NUM_STATES] = {func0, func1, func2, ... , funcX};\n</code></pre>\n\n<p>The problem was that I considered it very error prone to have to maintain the ordering of my function pointer table such that it matched the ordering of my enumeration of states.</p>\n\n<p>A friend of mine introduced me to X-macros and it was like a light-bulb went off in my head. Seriously, where have you been all my life x-macros!</p>\n\n<p>So now I define the following table:</p>\n\n<pre><code>#define STATE_TABLE \\\n ENTRY(STATE0, func0) \\\n ENTRY(STATE1, func1) \\\n ENTRY(STATE2, func2) \\\n ...\n ENTRY(STATEX, funcX) \\\n</code></pre>\n\n<p>And I can use it as follows:</p>\n\n<pre><code>enum\n{\n#define ENTRY(a,b) a,\n STATE_TABLE\n#undef ENTRY\n NUM_STATES\n};\n</code></pre>\n\n<p>and</p>\n\n<pre><code>p_func_t jumptable[NUM_STATES] =\n{\n#define ENTRY(a,b) b,\n STATE_TABLE\n#undef ENTRY\n};\n</code></pre>\n\n<p>as a bonus, I can also have the pre-processor build my function prototypes as follows:</p>\n\n<pre><code>#define ENTRY(a,b) static void b(void);\n STATE_TABLE\n#undef ENTRY\n</code></pre>\n\n<p>Another usage is to declare and initialize registers</p>\n\n<pre><code>#define IO_ADDRESS_OFFSET (0x8000)\n#define REGISTER_TABLE\\\n ENTRY(reg0, IO_ADDRESS_OFFSET + 0, 0x11)\\\n ENTRY(reg1, IO_ADDRESS_OFFSET + 1, 0x55)\\\n ENTRY(reg2, IO_ADDRESS_OFFSET + 2, 0x1b)\\\n ...\n ENTRY(regX, IO_ADDRESS_OFFSET + X, 0x33)\\\n\n/* declare the registers (where _at_ is a compiler specific directive) */\n#define ENTRY(a, b, c) volatile uint8_t a _at_ b:\n REGISTER_TABLE\n#undef ENTRY\n\n/* initialize registers */\n#def ENTRY(a, b, c) a = c;\n REGISTER_TABLE\n#undef ENTRY\n</code></pre>\n\n<p>My favourite usage however is when it comes to communication handlers</p>\n\n<p>First I create a comms table, containing each command name and code:</p>\n\n<pre><code>#define COMMAND_TABLE \\\n ENTRY(RESERVED, reserved, 0x00) \\\n ENTRY(COMMAND1, command1, 0x01) \\\n ENTRY(COMMAND2, command2, 0x02) \\\n ...\n ENTRY(COMMANDX, commandX, 0x0X) \\\n</code></pre>\n\n<p>I have both the uppercase and lowercase names in the table, because the upper case will be used for enums and the lowercase for function names.</p>\n\n<p>Then I also define structs for each command to define what each command looks like:</p>\n\n<pre><code>typedef struct {...}command1_cmd_t;\ntypedef struct {...}command2_cmd_t;\n\netc.\n</code></pre>\n\n<p>Likewise I define structs for each command response:</p>\n\n<pre><code>typedef struct {...}response1_resp_t;\ntypedef struct {...}response2_resp_t;\n\netc.\n</code></pre>\n\n<p>Then I can define my command code enumeration:</p>\n\n<pre><code>enum\n{\n#define ENTRY(a,b,c) a##_CMD = c,\n COMMAND_TABLE\n#undef ENTRY\n};\n</code></pre>\n\n<p>I can define my command length enumeration:</p>\n\n<pre><code>enum\n{\n#define ENTRY(a,b,c) a##_CMD_LENGTH = sizeof(b##_cmd_t);\n COMMAND_TABLE\n#undef ENTRY\n};\n</code></pre>\n\n<p>I can define my response length enumeration:</p>\n\n<pre><code>enum\n{\n#define ENTRY(a,b,c) a##_RESP_LENGTH = sizeof(b##_resp_t);\n COMMAND_TABLE\n#undef ENTRY\n};\n</code></pre>\n\n<p>I can determine how many commands there are as follows:</p>\n\n<pre><code>typedef struct\n{\n#define ENTRY(a,b,c) uint8_t b;\n COMMAND_TABLE\n#undef ENTRY\n} offset_struct_t;\n\n#define NUMBER_OF_COMMANDS sizeof(offset_struct_t)\n</code></pre>\n\n<p>NOTE: I never actually instantiate the offset_struct_t, I just use it as a way for the compiler to generator for me my number of commands.</p>\n\n<p>Note then I can generate my table of function pointers as follows:</p>\n\n<pre><code>p_func_t jump_table[NUMBER_OF_COMMANDS] = \n{\n#define ENTRY(a,b,c) process_##b,\n COMMAND_TABLE\n#undef ENTRY\n}\n</code></pre>\n\n<p>And my function prototypes:</p>\n\n<pre><code>#define ENTRY(a,b,c) void process_##b(void);\n COMMAND_TABLE\n#undef ENTRY\n</code></pre>\n\n<p>Now lastly for the coolest use ever, I can have the compiler calculate how big my transmit buffer should be.</p>\n\n<pre><code>/* reminder the sizeof a union is the size of its largest member */\ntypedef union\n{\n#define ENTRY(a,b,c) uint8_t b##_buf[sizeof(b##_cmd_t)];\n COMMAND_TABLE\n#undef ENTRY\n}tx_buf_t\n</code></pre>\n\n<p>Again this union is like my offset struct, it is not instantiated, instead I can use the sizeof operator to declare my transmit buffer size.</p>\n\n<pre><code>uint8_t tx_buf[sizeof(tx_buf_t)];\n</code></pre>\n\n<p>Now my transmit buffer tx_buf is the optimal size and as I add commands to this comms handler, my buffer will always be the optimal size. Cool!</p>\n" } ]
2008/11/05
[ "https://Stackoverflow.com/questions/264269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30636/" ]
A basic definition and example and a few references for "[X-Macros](http://en.wikipedia.org/wiki/C_preprocessor#X-Macros)" is given in this [wikipedia entry on the C pre-processor](http://en.wikipedia.org/wiki/C_preprocessor): > > An X-Macro is a header file (commonly > using a ".def" extension instead of > the traditional ".h") that contains a > list of similar macro calls (which can > be referred to as "component macros"). > > > What are some good sources of information on how to use this powerful technique? Are there well-known open source libraries using this method?
I use X Macros() in code a lot. The value comes from only adding new data only to the "X list" and not modifying any other code. The most common use of X Macros() is for associating error text with error codes. When new error codes are added, programmers must remember to add the code and the text, typically in separate places. The X Macro allows the new error data to be added in a single place and get automatically populated anywhere it is needed. Unfortunately, the mechanisms use a lot of pre-compiler magic that can make the code somewhat hard to read (e.g. string joining with `token1##token2`, string creation with `#token`). Because of this I typically explain what the X Macro is doing in the comments. Here is an example using the error/return values. All new data gets added to the "`X_ERROR`" list. None of the other code hast to be modified. ``` /* * X Macro() data list * Format: Enum, Value, Text */ #define X_ERROR \ X(ERROR_NONE, 1, "Success") \ X(ERROR_SYNTAX, 5, "Invalid syntax") \ X(ERROR_RANGE, 8, "Out of range") /* * Build an array of error return values * e.g. {0,5,8} */ static int ErrorVal[] = { #define X(Enum,Val,Text) Val, X_ERROR #undef X }; /* * Build an array of error enum names * e.g. {"ERROR_NONE","ERROR_SYNTAX","ERROR_RANGE"} */ static char * ErrorEnum[] = { #define X(Enum,Val,Text) #Enum, X_ERROR #undef X }; /* * Build an array of error strings * e.g. {"Success","Invalid syntax","Out of range"} */ static char * ErrorText[] = { #define X(Enum,Val,Text) Text, X_ERROR #undef X }; /* * Create an enumerated list of error indexes * e.g. 0,1,2 */ enum { #define X(Enum,Val,Text) IDX_##Enum, X_ERROR #undef X IDX_MAX /* Array size */ }; void showErrorInfo(void) { int i; /* * Access the values */ for (i=0; i<IDX_MAX; i++) printf(" %s == %d [%s]\n", ErrorEnum[i], ErrorVal[i], ErrorText[i]); } ``` You can also use X Macros() to generate code. For example to test if an error value is "known", the X Macro can generate cases in a switch statement: ``` /* * Test validity of an error value * case ERROR_SUCCESS: * case ERROR_SYNTAX: * case ERROR_RANGE: */ switch(value) { #define X(Enum,Val,Text) case Val: X_ERROR #undef X printf("Error %d is ok\n",value); break; default: printf("Invalid error: %d\n",value); break; } ```