qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
353,485 | <p>I am trying to create a Data Source in SharePoint Designer that connects to a SharePoint List via XML Web Services. I have created the Data Source and connected to the list in question. I can view all the data using GetListItems, and I want to filter it using the query parameter.</p>
<p>The query parameter takes an XmlNode, and when I put this as the value I get an error:</p>
<pre><code><Query>
<Where>
<Eq>
<FieldRef Name="Title" />
<Value Type="Text">Foo</Value>
</Eq>
</Where>
</Query>
</code></pre>
<p>Of course, I have not entered any tabs or newlines, as I only have a one-line entry field in SharePoint Designer. I receive an error with this query:</p>
<blockquote>
<p>The server returned a non-specific
error when trying to get data from the
data source. Check the format and
content of your query and try again.
If the problem persists, contact the
server administrator.</p>
</blockquote>
<p>I simply want to filter the list items resultset to be those with the Title field of "Foo". Can this be done in SharePoint Designer?</p>
<hr>
<p>Update: escaping the < and > in this manner also fails:</p>
<pre><code>&lt;Query&gt;&lt;Where&gt;&lt;Eq&gt;&lt;FieldRef Name=&quot;Title&quot; /&gt;&lt;Value Type=&quot;Text&quot;&gt;Foo&lt;/Value&gt;&lt;/Eq&gt;&lt;/Where&gt;&lt;/Query&gt;
</code></pre>
<hr>
<p>Update: This appears to be a <a href="http://blogs.msdn.com/sharepointdesigner/archive/2008/06/20/data-source-issues-and-workarounds.aspx" rel="nofollow noreferrer">known issue</a> with SoapDataSource components and SOAP calls. Apparently, they are over-encoding the <'s and >'s before they get submitted. The workaround given is to save the data source without a query parameter, and then to add it to the page and create a filter in the Common Data View Tasks dialog. I was able to get this to work using the following filter string:</p>
<pre><code>[@ows_Title = 'Foo']
</code></pre>
<p>Unfortunately, this doesn't help me much as I am adding a Data View (showing the data) rather than a DataSource that I can use to point other controls to (like a drop-down list).</p>
<p>I'm still looking for a good solution on this that lets me place a datasource using SharePoint Designer.</p>
| [
{
"answer_id": 354027,
"author": "Peter Lillevold",
"author_id": 35245,
"author_profile": "https://Stackoverflow.com/users/35245",
"pm_score": 1,
"selected": false,
"text": "<Query><Where>\n <FieldRef Name="Title" />\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753/"
] |
353,486 | <p>I'm looking at using ASP.NET for a new SaaS service, but for the love of me I can't seem to figure out how to do account lookups based on subdomains like most SaaS applications (e.g. 37Signals) do.</p>
<p>For example, if I offer yourname.mysite.com, then how would I use ASP.NET (MVC specifically) to extract the subdomain so I can load the right template (displaying your company's name and the like)? Can it be done with regular routing?</p>
<p>This seems to be a common thing in SaaS so there has to be an easy way to do it in ASP.NET; I know there are plugins that do it for other frameworks like Ruby on Rails.</p>
| [
{
"answer_id": 368512,
"author": "Mark Brittingham",
"author_id": 15592,
"author_profile": "https://Stackoverflow.com/users/15592",
"pm_score": 3,
"selected": true,
"text": " //--------------------------------------------------------------------------------------------------------------------------\n public string GetSubDomain()\n {\n string SubDomain = \"\";\n\n if (Request.Url.HostNameType == UriHostNameType.Dns)\n SubDomain = Regex.Replace(Request.Url.Host, \"((.*)(\\\\..*){2})|(.*)\", \"$2\");\n if (SubDomain.Length == 0)\n SubDomain = \"www\";\n return SubDomain;\n }\n"
},
{
"answer_id": 414759,
"author": "holiveira",
"author_id": 49671,
"author_profile": "https://Stackoverflow.com/users/49671",
"pm_score": 1,
"selected": false,
"text": "* A 1.2.3.4\n string user = HttpContext.Request.ServerVariables[\"HTTP_HOST\"].Split(\".\")\n\n//use the user variable to query the database for specific data\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40667/"
] |
353,489 | <p>In my case, I have a number of column names coming from a form. I want to filter to make sure they're all true. Here's how I currently do it:</p>
<pre><code>for op in self.cleaned_data['options']:
cars = cars.filter((op, True))
</code></pre>
<p>Now it <em>works</em> but there are are a possible ~40 columns to be tested and it therefore doesn't appear very efficient to keep querying.</p>
<p>Is there a way I can condense this into one filter query?</p>
| [
{
"answer_id": 353602,
"author": "prairiedogg",
"author_id": 27462,
"author_profile": "https://Stackoverflow.com/users/27462",
"pm_score": 3,
"selected": false,
"text": "op_kwargs = {}\nfor op in self.cleaned_data['options']:\n op_kwargs[op] = True\ncars = CarModel.objects.filter(**op_kwargs)\n"
},
{
"answer_id": 354215,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 3,
"selected": true,
"text": "cars = CarModel.objects.all()\nfor op in self.cleaned_data['options']:\n cars = cars.filter((op, True))\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
353,491 | <p>Say I have a hierarchy of classes, let's use the classic <code>Shape</code> examples: </p>
<p><code>abstract class Shape</code><br>
<code>Circle : Shape</code><br>
<code>Square : Shape</code> </p>
<p>I have a second hierarchy of renderer classes that handle the rendering of shapes in different ways:</p>
<p><code>abstract class ShapeRenderer</code><br>
<code>HtmlShapeRenderer : ShapeRenderer</code><br>
<code>WindowsFormsShapeRenderer : ShapeRenderer</code> </p>
<p>Allowing these to vary independently would traditionally involve using the Bridge pattern. Allowing the rendering actions to be extended without modifying the <code>Shape</code> classes would traditionally involve the Visitor pattern.</p>
<p>However, both of these focus exclusively on extending the implementation side and not the abstraction side. Say I wanted to add a new <code>Shape</code>, say <code>Triangle</code> - I want to be able to support rendering the <code>Triangle</code> as well. Since both the Visitor and the Bridge pattern rely on "flattening" the abstraction hierarchy into a set of methods, e.g.:</p>
<pre><code>public abstract class ShapeRenderer
{
public abstract void RenderCircle(Circle c);
public abstract void RenderSquare(Square s);
}
</code></pre>
<p>The only way to extend the <code>Shape</code> hierarchy is to modify the code of the base <code>ShapeRenderer</code> class, which is a breaking change.</p>
<p>Jon, to clarify: Using the Bridge or Visitor allows clients to provide alternative rendering implementations, but requires them to know about all potential Shapes. What I'd like to be able to do is allow clients to <em>also</em> be able to extend the <code>Shape</code> class and <em>require</em> them to provide a rendering implementation for their new class. This way, existing code can work with any type of <code>Shape</code>, without worrying about the particulars of rendering them.</p>
<p>Is there a common solution to this sort of problem usable in C#?</p>
| [
{
"answer_id": 355034,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 2,
"selected": false,
"text": "class Triangle : public Shape\n{\n public:\n Triangle( const RenderEngine& whichRenderEngine );\n void render( void ) { renderStrategy->renderTriangle( *this );\n\n private:\n RenderEngine* renderStrategy;\n};\n\nclass TriangleRender : HTMLShapeRender\n{\n public:\n // if inheriting from concrete class, all other rendering functions \n // already exist... otherwise re-implement them here.\n\n void renderTriangle( const Triangle& t ) { /* impl */ }\n};\n\nHTMLRenderer r; // doesn't know about Triangles.\nCircle c( &r );\nc.render();\n\nSquare s( &r );\ns.render();\n\n// Now we add Triangle\nTriangleRenderer tr;\nTriangle t( &tr );\nt.render();\n\nSquare s2( &tr ); // tr still knows how to render squares... \ns2.render();\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
353,505 | <p>I'm trying to get a JEditorPane to highlight the full width of a displayed line. All the examples I've tried only highlight the textual content. For example if I have content such as this:</p>
<pre><code> ---------------------------------
|Here is some text |
|some more text |
---------------------------------
</code></pre>
<p>within a JEditorPane represented by the box above, then highlighting the first row highlights only the 'Here is some text' (represented between [ and ] below).</p>
<pre><code> ---------------------------------
[Here is some text] |
|some more text |
---------------------------------
</code></pre>
<p>I would like it to highlight the full width of the JEditorPane like the following:</p>
<pre><code> ---------------------------------
[Here is some text ]
|some more text |
---------------------------------
</code></pre>
<p>Is there a way to do this?</p>
| [
{
"answer_id": 354283,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "paint() textPane.setSelectionColor(new Color(1.0f, 1.0f, 1.0f, 0.0f));"
},
{
"answer_id": 359811,
"author": "Matthew Murdoch",
"author_id": 4023,
"author_profile": "https://Stackoverflow.com/users/4023",
"pm_score": 1,
"selected": false,
"text": "textPane.setSelectionColor(new Color(1.0f, 1.0f, 1.0f, 0.0f));\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4023/"
] |
353,520 | <p>Is it possible to post a description/comment variable to the facebook sharer url? It's only possible for url and title as far as I can figure out.</p>
| [
{
"answer_id": 529285,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "meta <link rel='image_src' href='http://www.yourwebsite/dir1/dir2/picture.jpg' />\n"
},
{
"answer_id": 936769,
"author": "Andrew Cox",
"author_id": 27907,
"author_profile": "https://Stackoverflow.com/users/27907",
"pm_score": 6,
"selected": true,
"text": "sharer.php url title meta <meta name=\"title\" \n content=\"Smith hails 'unique' Wable legacy\">\n<meta name=\"description\" \n content=\"John Smith claims beautiful football ...\" />\n<link rel=\"image_src\" \n href=\"http://www.onjd.com/design05/images/PH2/WableAFC205.jpg\" />\n"
},
{
"answer_id": 8537448,
"author": "grant",
"author_id": 1102381,
"author_profile": "https://Stackoverflow.com/users/1102381",
"pm_score": 1,
"selected": false,
"text": "<meta> <link>"
},
{
"answer_id": 10768486,
"author": "Rodney",
"author_id": 1381610,
"author_profile": "https://Stackoverflow.com/users/1381610",
"pm_score": 4,
"selected": false,
"text": "http://www.facebook.com/sharer.php?s=100&p[title]=titlehere&p[url]=http://www.yoururlhere.com&p[summary]=yoursummaryhere&p[images][0]=http://www.urltoyourimage.com\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18671/"
] |
353,526 | <p>On a SQL Server 2005 database, one of our remote developers just checked in a change to a stored procedure that changed a "select scope_identity" to "select @@identity". Do you know of any reasons why you'd use @@identity over scope_identity?</p>
| [
{
"answer_id": 353547,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 5,
"selected": true,
"text": "@@IDENTITY SCOPE_IDENTITY() @@IDENTITY INSERT"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] |
353,541 | <p>I am using Context.RewritePath() in ASP.NET 3.5 application running on IIS7.</p>
<p>I am doing it in application BeginRequest event and everything works file.</p>
<p>Requests for /sports are correctly rewritten to default.aspx?id=1, and so on.</p>
<p>The problem is that in my IIS log I see GET requests for /Default.aspx?id=1 and not for /sports.</p>
<p>This kind of code worked perfectly under IIS6.</p>
<p>Using Microsoft Rewrite module is not an option, due to some business logic which has to be implemented.</p>
<p>Thanks.</p>
<p>EDIT: </p>
<p>It seems my handler is too early in the pipeline, but if I move the logic to a later event, than the whole rewrite thing doesn't work (it's too late, StaticFileHandler picks up my request). </p>
<p>I googled and googled, asked around, can't believe that nobody has this problem?</p>
<p>EDIT:</p>
<p>Yikes! Here's what I found on the IIS forum:</p>
<p>"This is because in integrated mode, IIS and asp.net share a common pipeline and the RewritePath is now seen by IIS, while in IIS6, it was not even seen by IIS - you can workaround this by using classic mode which would behave like IIS6."</p>
<p><strong>Final update</strong>: Please take a look at <a href="https://stackoverflow.com/questions/353541/iis7-rewritepath-and-iis-log-files/579141#579141">my answer below</a>, I've updated it with results after more than a year in production environment.</p>
| [
{
"answer_id": 558076,
"author": "Daniel Richardson",
"author_id": 52049,
"author_profile": "https://Stackoverflow.com/users/52049",
"pm_score": 2,
"selected": false,
"text": "BeginRequest EndRequest public class RewriteModule : IHttpModule\n{\n public void Init(HttpApplication context)\n {\n context.BeginRequest += OnBeginRequest;\n context.EndRequest += OnEndRequest;\n }\n\n static void OnBeginRequest(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n app.Context.Items[\"OriginalPath\"] = app.Context.Request.Path;\n app.Context.RewritePath(\"Default.aspx?id=1\");\n }\n\n static void OnEndRequest(object sender, EventArgs e)\n {\n var app = (HttpApplication)sender;\n var originalPath = app.Context.Items[\"OriginalPath\"] as string;\n if (originalPath != null)\n {\n app.Context.RewritePath(originalPath);\n }\n }\n\n public void Dispose()\n {\n\n }\n}\n"
},
{
"answer_id": 14181017,
"author": "ingredient_15939",
"author_id": 471597,
"author_profile": "https://Stackoverflow.com/users/471597",
"pm_score": 0,
"selected": false,
"text": " <rule name=\"all\" patternSyntax=\"Wildcard\" stopProcessing=\"true\">\n <match url=\"*\"/>\n <action type=\"Rewrite\" url=\"/default.aspx\"/>\n </rule>\n Page_PreInit"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1269/"
] |
353,545 | <p>I have a C# program which uses a SQL Server database.I am already using it in a country that uses . as decimal separator.
Now I want to use it in another country that uses , as decimal separator.</p>
<p>in C# is there some application level setting that I can change or write some code so that I can use the same database and the same program ? or do I have to change my entire code to handle this new decimal separator?</p>
<p>I dont know how this works.Basically I think there would be problems in My Sql Queries.
example say one of my existing statements is
<br></p>
<pre><code>insert into tblproducts(productId,Price) values('A12',24.10)
</code></pre>
<p>now in new country it will become </p>
<pre><code>insert into tblproducts(productId,Price) values('A12',24,10)
</code></pre>
<p>this will raise an error</p>
<p>so do I have to change whole code to handle this situation ?</p>
<p>Thank you </p>
| [
{
"answer_id": 353618,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 0,
"selected": false,
"text": "Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(\"en-US\")\nThread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture\n (5000.25).ToString(CultureInfo.InvariantCulture) \n"
},
{
"answer_id": 353619,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 1,
"selected": false,
"text": " var query = \"insert into tblproducts(productId,Price) values('\" + article + \"','\"\n + price + ')';\n var query = \"insert into tblproducts(productId,Price) values(?,?)\"\n var cmd = new OleDbCommand(query, connection);\n cmd.Parameters.Add(\"@article\", OleDbType.VarChar).Value = article;\n cmd.Parameters.Add(\"@price\", OleDbType.Single).Value = price;\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
353,550 | <p>All the member variables and member functions in my class ClassA are static. </p>
<p>If a user is trying (by mistake) to create an object of this class, he receives a warning: "ClassA, local variable never referenced", because all the functions are static, so this object is never referenced. So, I want to prevent the user from trying to create an object of this class. </p>
<p>Would it be enough to create a private default (no variables) constructor? Or do I have to also create private copy constructor and private assignment operator (to prevent using the default constructors)? And if I do have to create them too, maybe it would be better just to create some dummy pure virtual function instead, and this will prevent the user from creating an object?</p>
<p>Thank you</p>
| [
{
"answer_id": 353580,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": false,
"text": "namespace::function() classname::function()"
},
{
"answer_id": 353640,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "class NonConstructible { \n NonConstructible();\n};\n\nclass SuperUtils: NonConstructible {\n static void foo();\n // ...\n static std::vector<int> globalIDs;\n // ...\n};\n namespace SuperUtils {\n void foo() {\n // ....\n }\n\n std::vector<int> globalIDs;\n};\n SuperUtils::foo(); SuperUtils:: void superFunction() {\n using namespace SuperUtils;\n foo();\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44673/"
] |
353,558 | <p>I have a classes like:</p>
<pre><code>[Serializable]
public class child {
public Parent parent;
}
[Serializable]
public class Parent {
public List<child> children;
}
</code></pre>
<p>When I deserialize Parent, I want each of each children to have a reference to it's parent. Question is, where in the deserialization process can I set the child's "parent" pointer? I can't seem to use a custom constructor for child, because deserialization always uses the default constructor. If I implement ISerializable, then it seems that the child objects have already been created by the time the parent is created. Is there another way to achieve this?</p>
| [
{
"answer_id": 353589,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 0,
"selected": false,
"text": " public class Connections: List<Connection>\n { public new void Add(Connection connection)\n {\n connection.ApplicationName = ApplicationName;\n base.Add(connection);\n }\n }\n"
},
{
"answer_id": 9742930,
"author": "Richard Deeming",
"author_id": 124386,
"author_profile": "https://Stackoverflow.com/users/124386",
"pm_score": 2,
"selected": false,
"text": "[Serializable]\nclass Parent : IDeserializationCallback \n{\n public List<child> children;\n\n void IDeserializationCallback.OnDeserialization(Object sender) \n {\n if (null != children)\n {\n children.ForEach(c => c.parent = this);\n }\n }\n}\n"
},
{
"answer_id": 9743483,
"author": "Luke Forder",
"author_id": 1239587,
"author_profile": "https://Stackoverflow.com/users/1239587",
"pm_score": 3,
"selected": false,
"text": "BinaryFormatter XmlSerializer DataContractSerializer BinaryFormatter using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n[Serializable]\npublic class Child\n{\n public Guid Id { get; set; }\n\n public Parent parent;\n}\n\n[Serializable]\npublic class Parent\n{\n public Guid Id;\n\n public List<Child> Children;\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Child c1 = new Child { Id = Guid.NewGuid() };\n Child c2 = new Child { Id = Guid.NewGuid() };\n\n Parent p = new Parent { Id = Guid.NewGuid(), Children = new List<Child> { c1, c2 } };\n\n c1.parent = p;\n c2.parent = p;\n\n using (var stream1 = new MemoryStream())\n {\n BinaryFormatter formatter = new BinaryFormatter();\n formatter.Serialize(stream1, p);\n stream1.Position = 0;\n\n var deserializedParent = formatter.Deserialize(stream1) as Parent;\n foreach (var child in deserializedParent.Children)\n {\n Console.WriteLine(\"Child Id: {0}, Parent Id: {1}\", child.Id, child.parent.Id);\n }\n }\n\n Console.ReadLine();\n }\n}\n XmlSerializer IXmlSerializable using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\nusing System.Text;\nusing System.Threading.Tasks;\nusing System.Xml;\nusing System.Xml.Linq;\nusing System.Xml.Serialization;\n\nnamespace XmlSerialization\n{\n\n [Serializable]\n public class Child\n {\n public Guid Id { get; set; }\n\n [XmlIgnore] // Don't serialize the reference to the parent\n public Parent parent;\n }\n\n [Serializable]\n public class Parent : IXmlSerializable\n {\n public List<Child> Children;\n\n public Guid Id;\n\n public System.Xml.Schema.XmlSchema GetSchema()\n {\n return null;\n }\n\n public void ReadXml(System.Xml.XmlReader reader)\n {\n XElement xml = XElement.ReadFrom(reader) as XElement;\n if (xml != null)\n {\n // Deserialize Children\n Children = \n xml.Descendants(\"Child\")\n .Select(x => new Child() { Id = Guid.Parse(x.Element(\"Id\").Value), parent = this })\n .ToList();\n\n // Deserialize Id\n Id = Guid.Parse(xml.Attribute(\"Id\").Value); \n }\n }\n\n public void WriteXml(System.Xml.XmlWriter writer)\n {\n // Serialize Id\n writer.WriteAttributeString(\"Id\", Id.ToString());\n\n // Serialize Children\n XmlSerializer childSerializer = new XmlSerializer(typeof(Child));\n foreach (Child child in Children)\n {\n childSerializer.Serialize(writer, child);\n }\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n Child c1 = new Child { Id = Guid.NewGuid() };\n Child c2 = new Child { Id = Guid.NewGuid() };\n\n Parent p = new Parent { Id = Guid.NewGuid(), Children = new List<Child> { c1, c2 } };\n\n c1.parent = p;\n c2.parent = p;\n\n using (var stream1 = new MemoryStream())\n {\n XmlSerializer formatter = new XmlSerializer(typeof(Parent), new Type[] { typeof(Child) }) ;\n formatter.Serialize(stream1, p);\n stream1.Position = 0;\n\n stream1.Position = 0;\n\n var deserializedParent = formatter.Deserialize(stream1) as Parent;\n foreach (var child in deserializedParent.Children)\n {\n Console.WriteLine(string.Format(\"Child Id: {0}, Parent Id: {1}\", child.Id, child.parent.Id ));\n }\n }\n\n Console.ReadLine();\n }\n\n }\n}\n DataContractSerializer DataContract using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\nusing System.Runtime.Serialization.Formatters.Binary;\n\n[DataContract(IsReference = true)]\npublic class Child\n{\n [DataMember]\n public Guid Id { get; set; }\n\n [DataMember]\n public Parent parent;\n}\n\n[DataContract(IsReference = true)]\npublic class Parent\n{\n [DataMember]\n public Guid Id;\n\n [DataMember]\n public List<Child> Children;\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Child c1 = new Child { Id = Guid.NewGuid() };\n Child c2 = new Child { Id = Guid.NewGuid() };\n\n Parent p = new Parent { Id = Guid.NewGuid(), Children = new List<Child> { c1, c2 } };\n\n c1.parent = p;\n c2.parent = p;\n\n using (var stream1 = new MemoryStream())\n {\n DataContractSerializer formatter = new DataContractSerializer(typeof(Parent));\n formatter.WriteObject(stream1, p);\n stream1.Position = 0;\n\n var deserializedParent = formatter.ReadObject(stream1) as Parent;\n foreach (var child in deserializedParent.Children)\n {\n Console.WriteLine(\"Child Id: {0}, Parent Id: {1}\", child.Id, child.parent.Id);\n }\n }\n\n Console.ReadLine();\n }\n\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
353,561 | <p>How can you create a C# Winforms control which goes out of the bounds of its region? Such as a drop down box. Kind of like if you had a DropDownBox in a Small Sized Panel.</p>
| [
{
"answer_id": 354326,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Drawing;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\npublic class MyListBox : ListBox {\n private Control mParent;\n private Point mPos;\n private bool mInitialized;\n\n public MyListBox(Control parent) {\n mParent = parent;\n mInitialized = true;\n this.SetTopLevel(true);\n parent.LocationChanged += new EventHandler(parent_LocationChanged);\n mPos = mParent.Location;\n }\n\n public new Point Location {\n get { return mParent.PointToClient(this.Location); }\n set { \n Point zero = mParent.PointToScreen(Point.Empty);\n base.Location = new Point(zero.X + value.X, zero.Y + value.Y);\n }\n }\n\n protected override Size DefaultSize {\n get {\n return mInitialized ? base.DefaultSize : Size.Empty;\n }\n }\n\n protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {\n if (this.mInitialized)\n base.SetBoundsCore(x, y, width, height, specified);\n }\n\n void parent_LocationChanged(object sender, EventArgs e) {\n base.Location = new Point(base.Left + mParent.Left - mPos.X, base.Top + mParent.Top - mPos.Y);\n mPos = mParent.Location;\n }\n\n protected override CreateParams CreateParams {\n get {\n CreateParams cp = base.CreateParams;\n if (mParent != null && !DesignMode) {\n cp.Style = (int)(((long)cp.Style & 0xffff) | 0x90200000);\n cp.Parent = mParent.Handle;\n Point pos = mParent.PointToScreen(Point.Empty);\n cp.X = pos.X;\n cp.Y = pos.Y;\n cp.Width = base.DefaultSize.Width;\n cp.Height = base.DefaultSize.Height;\n }\n return cp;\n }\n }\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28717/"
] |
353,569 | <p>Can any one explain why the output of this code is only 'hello' and what this code means?</p>
<pre><code>( 0, characterArray, 0, characterArray.Length );
</code></pre>
<p>The output is showing:</p>
<p><PRE>The character array is: hello</PRE></p>
<p>The code follows:</p>
<pre><code>string string1 = "hello there";
char[] characterArray = new char[ 5 ];
string1.CopyTo( 0, characterArray, 0, characterArray.Length );
Console.Write( "\nThe character array is: " );
for ( int i = 0; i < characterArray.Length; i++ )
Console.Write( characterArray[ i ] );
</code></pre>
| [
{
"answer_id": 353583,
"author": "AaronS",
"author_id": 26932,
"author_profile": "https://Stackoverflow.com/users/26932",
"pm_score": 4,
"selected": true,
"text": "public void CopyTo(\n int sourceIndex,\n char[] destination,\n int destinationIndex,\n int count\n)\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
353,571 | <p>I just got done working through the Django tutorials for the second time, and am understanding things much more clearly now. However, I'm still unclear how apps inside a site interact with one another.</p>
<p>For example, lets say I'm writing a blog application (a rather popular activity, apparently). Blog posts and comments tend to go together, and yet they are distinct enough that they should be built into separate apps, as is the general philosophy of Djano development.</p>
<p>Consider the following example. In reality I would not actually write the comment app myself, as good code for that already exists on the web, but this is for demonstration/practice purposes:</p>
<p><strong>mysite/blog/models.py</strong></p>
<pre><code>from django.db import models
class post(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
content = models.TextField()
</code></pre>
<p><strong>mysite/comments/models.py</strong></p>
<pre><code>from django.db import models
from mysite.blog.models import post
class comment(models.Model):
id = models.AutoField()
post = models.ForeignKey(post)
author = models.CharField(max_length=200)
text = models.TextField()
</code></pre>
<p>Is what I wrote above, importing a model from another app and setting it as a foreign key, how Django apps interact? Or is there a different/better method for the apps that comprise a site to interact?</p>
<p><strong>Update</strong><br>
Per the recommendation in one response, I'm reading the documentation for contrib.contenttypes. If I'm reading this correctly, I could rewrite my example comment app like this: </p>
<pre><code>from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contentypes import generic
class comment(models.Model):
id = models.AutoField()
author = models.CharField(max_length=200)
text = models.TextField()
content_type = models.ForeignKey(ContentType)
content_object = generic.GenericForeignKey(content_type, id)
</code></pre>
<p>Would this be correct?</p>
| [
{
"answer_id": 353615,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 2,
"selected": false,
"text": "django.contrib.admin"
},
{
"answer_id": 353667,
"author": "prairiedogg",
"author_id": 27462,
"author_profile": "https://Stackoverflow.com/users/27462",
"pm_score": 6,
"selected": true,
"text": "django.contrib.contenttypes Favorite from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\n\nclass Favorite(models.Model):\n user = models.ForeignKey(User)\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey('content_type', 'object_id')\n Favorite Favorite content_type object_id"
},
{
"answer_id": 353761,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 2,
"selected": false,
"text": "{% get_thread for arbitrary_object as thread %} from django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\n\nclass Thread( models.Model ):\n object_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n object = generic.GenericForeignKey('object_type', 'object_id')\n #inside the Thread class:\n def __unicode__(self):\n return unicode(self.object)\n def get_absolute_url(self):\n return self.object.get_absolute_url()\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33383/"
] |
353,596 | <p>I've copied a Dataset from one csproj to another, and the new project gets the following compile warning:
"The custom tool 'MSDataSetGenerator' failed while processing the file 'Client.xsd'."</p>
<p>In researching this warning I discovered that if I opened a VS cmd prompt and run XSD.exe on the xsd file directly I get more info. It says:
"Error: Can only generate one of classes or datasets."</p>
<p>The command line flag that fixes this is to run:
XSD /d {xsdfilename}</p>
<p>If I run that on the cmd line it generates the dataset code just fine. But I can't figure out how to make Visual Studio do that. Anyone know?</p>
| [
{
"answer_id": 67321806,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 2,
"selected": false,
"text": "Error: Can only generate one of classes or datasets.\n \"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.1 Tools\\xsd.exe\" /c myfile.cs\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29021/"
] |
353,601 | <p>I have a command-line process I would like to automate and capture in C#.</p>
<p>At the command line, I type:</p>
<pre><code>nslookup
</code></pre>
<p>This launches a shell which gives me a > prompt. At the prompt, I then type:</p>
<pre><code>ls -a mydomain.local
</code></pre>
<p>This returns a list of local CNAMEs from my primary DNS server and the physical machines they are attached to.</p>
<p>What I would like to do is automate this process from C#. If this were a simple command, I would just use Process.StartInfo.RedirectStandardOutput = true, but the requirement of a second step is tripping me up.</p>
| [
{
"answer_id": 353624,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 4,
"selected": true,
"text": "ProcessStartInfo si = new ProcessStartInfo(\"nslookup\");\nsi.RedirectStandardInput = true;\nsi.RedirectStandardOutput = true;\nProcess nslookup = new Process(si);\nnslookup.Start();\nnslookup.StandardInput.WriteLine(\"ls -a mydomain.local\");\nnslookup.StandardInput.Flush();\n// use nslookup.StandardOutput stream to read the result. \n"
},
{
"answer_id": 6597867,
"author": "XikiryoX",
"author_id": 828300,
"author_profile": "https://Stackoverflow.com/users/828300",
"pm_score": 1,
"selected": false,
"text": " private void button1_Click(object sender, EventArgs e)\n {\n IPAddress[] ips = NsLookup(computername, dnsserver);\n\n txtResult.Text = string.Empty;\n if (ips != null)\n {\n txtResult.Text = ips[0].ToString();\n txtResult.Text += Environment.NewLine;\n if (ips[1] != null)\n {\n txtResult.Text += ips[1].ToString();\n }\n else\n {\n\n }\n }\n else\n {\n txtResult.Text = \"No IP found\";\n }\n\n }\n\n\n\n public IPAddress[] NsLookup(string computername, string domaincontroller)\n {\n\n IPAddress[] ips = new IPAddress[2];\n\n try\n {\n // Creating streamreaders to read the output and the errors\n StreamReader outputReader = null;\n StreamReader errorReader = null;\n\n string nslookup = @\"C:\\Windows\\System32\\Nslookup.exe\";\n\n try\n {\n // Setting process startupinfo\n ProcessStartInfo processStartInfo = new ProcessStartInfo(nslookup, computername + \" \" + domaincontroller);\n processStartInfo.ErrorDialog = false;\n processStartInfo.UseShellExecute = false;\n processStartInfo.RedirectStandardError = true;\n processStartInfo.RedirectStandardInput = true;\n processStartInfo.RedirectStandardOutput = true;\n processStartInfo.WindowStyle = ProcessWindowStyle.Minimized;\n\n // Starting Process\n Process process = new Process();\n process.StartInfo = processStartInfo;\n bool processStarted = process.Start();\n\n if (processStarted)\n {\n // Catching the output streams\n outputReader = process.StandardOutput;\n errorReader = process.StandardError;\n\n string errorresult = errorReader.ReadLine();\n\n errorReader.Close();\n\n\n if (errorresult != null)\n {\n // Failure got thrown in NsLookup Streamreading, try build-in Method\n try\n {\n ips = Dns.GetHostAddresses(computername);\n return ips;\n }\n catch\n {\n return null;\n }\n }\n else\n {\n // Clearing out all the values before the addresses.\n outputReader.ReadLine();\n outputReader.ReadLine();\n outputReader.ReadLine();\n outputReader.ReadLine();\n\n // Reading and Verifying the first outputline (the address is found after \"Addresses: \") - 2 part of the array is taken (after second space)\n string outputline = outputReader.ReadLine();\n string[] outputlineaftersplit = outputline.Split(' ');\n string ipfortesting = outputlineaftersplit[2].Trim();\n\n if (verifyIP(ipfortesting) != null) // First entry is ipv4\n {\n ips[0] = verifyIP(ipfortesting);\n\n outputline = outputReader.ReadLine();\n ipfortesting = outputline.Trim();\n\n if (verifyIP(ipfortesting) != null) // First and second entry are ipv4\n {\n ips[1] = verifyIP(ipfortesting);\n return ips;\n }\n else\n {\n return ips;\n }\n }\n else\n {\n outputline = outputReader.ReadLine();\n ipfortesting = outputline.Trim();\n\n if (verifyIP(ipfortesting) != null)\n {\n ips[0] = verifyIP(ipfortesting);\n\n outputline = outputReader.ReadLine();\n ipfortesting = outputline.Trim();\n\n if (verifyIP(ipfortesting) != null)\n {\n ips[0] = verifyIP(ipfortesting);\n\n outputline = outputReader.ReadLine();\n ipfortesting = outputline.Trim();\n\n if (verifyIP(ipfortesting) != null)\n {\n ips[1] = verifyIP(ipfortesting);\n return ips;\n }\n else\n {\n return ips;\n }\n\n }\n else\n {\n return ips;\n }\n }\n else\n {\n outputline = outputReader.ReadLine();\n ipfortesting = outputline.Trim();\n\n if (verifyIP(ipfortesting) != null)\n {\n\n ips[0] = verifyIP(ipfortesting);\n\n outputline = outputReader.ReadToEnd();\n ipfortesting = outputline.Trim();\n\n if (verifyIP(ipfortesting) != null)\n {\n ips[1] = verifyIP(ipfortesting);\n return ips;\n }\n else\n {\n return ips;\n }\n\n }\n else\n {\n ips = null;\n return ips;\n }\n }\n }\n }\n }\n\n else\n {\n // Failure got thrown in NsLookup Streamreading, try build-in Method\n try\n {\n ips = Dns.GetHostAddresses(computername);\n return ips;\n }\n catch\n {\n return null;\n }\n }\n }\n catch\n {\n System.Windows.Forms.MessageBox.Show(\"ERROR 1\");\n // Failure got thrown in NsLookup Streamreading, try build-in Method\n try\n {\n ips = Dns.GetHostAddresses(computername);\n return ips;\n }\n catch\n {\n return null;\n }\n }\n finally\n {\n if (outputReader != null)\n {\n outputReader.Close();\n }\n }\n }\n catch\n {\n System.Windows.Forms.MessageBox.Show(\"ERROR 2\");\n // Failure got thrown in NsLookup Streamreading, try build-in Method\n try\n {\n ips = Dns.GetHostAddresses(computername);\n return ips;\n }\n catch\n {\n return null;\n }\n }\n\n }\n\n public IPAddress verifyIP(string ipfromreader)\n {\n IPAddress ipresult = null;\n bool isIP = IPAddress.TryParse(ipfromreader, out ipresult);\n\n if (isIP && (ipresult.AddressFamily != AddressFamily.InterNetworkV6))\n {\n return ipresult;\n }\n else\n {\n return null;\n }\n }\n\n\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287/"
] |
353,614 | <pre><code>int x;
printf("hello %n World\n", &x);
printf("%d\n", x);
</code></pre>
| [
{
"answer_id": 353674,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 2,
"selected": false,
"text": "int len;\nchar *thing = \"label of unknown length\";\nchar *value = \"value value value\"\nchar *value2=\"second line of value\";\nprintf (\"%s other stuff: %n\", thing, &len);\nprintf (\"%s\\n%*s, value, len, value2);\n label of unknown length other stuff: value value value\n second line of value\n"
},
{
"answer_id": 353676,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 5,
"selected": true,
"text": "printf() sscanf() fscanf() scanf() sscanf() char stringToParse[256];\n...\nchar *curPosInString = stringToParse; // start parsing at the beginning\nint bytesRead;\nwhile(needsParsing())\n{\n sscanf(curPosInString, \"(format string)%n\", ..., &bytesRead); // check the return value here\n curPosInString += bytesRead; // Advance read pointer\n ...\n}\n"
},
{
"answer_id": 353792,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 0,
"selected": false,
"text": "/* if %n is disabled, we skip an arg and print 'n' */\nif ( !_get_printf_count_output() )\n{\n _VALIDATE_RETURN((\"'n' format specifier disabled\", 0), EINVAL, -1);\n break;\n}\n printf (\"%s other stuff: %n\", thing, &len);\n"
},
{
"answer_id": 353893,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 1,
"selected": false,
"text": "#include <stdio.h>\nint main(int argc, char* argv[])\n{\n int col10 = (10 - 1);\n int col25 = (25 - 1);\n\n int pos1 = 0;\n int pos2 = 0;\n\n printf(\" 5 10 15 20 25 30\\n\");\n\n printf(\"%s%n%*s%n%*s\\n\", \"fried\", \n &pos1, col10 - pos1, \"green\", \n &pos2, col25 - pos2, \"tomatos\");\n\n\n printf(\" ^ ^ ^ ^ ^ ^\\n\");\n\n printf(\"%d %d\\n\", pos1, pos2);\n printf(\"%d %d\\n\", col10 - pos1, col25 - pos2);\n\n return 0;\n}\n"
},
{
"answer_id": 2721365,
"author": "yur",
"author_id": 326870,
"author_profile": "https://Stackoverflow.com/users/326870",
"pm_score": 0,
"selected": false,
"text": "int _get_printf_count_output();\n int _set_printf_count_output( int enable );\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734/"
] |
353,617 | <p>Let's say we have a solution with the following structure:</p>
<ul>
<li>Project.DAL - Data access layer,
depends on a lower-level library,
e.g. Oracle.DataAccess w/copy local
= true </li>
<li>Project.BLL - Business logic layer, references Project.DAL as
project </li>
<li>Project.UI - UI layer,
compiles to executable, references
Project.BLL, default project</li>
</ul>
<p>When Project.UI is compiled, VS is smart enough to copy Project.DAL.dll to the output directory, but it's not smart enough to figure out that I wanted Oracle.DataAccess to be copied to the output directory as well for distribution to clients.</p>
<p>Can anyone explain why this is so? Is it because it sees Oracle.DataAccess in the GAC and assumes that clients will have it in the GAC as well?</p>
<p>It's not that big of a deal, but it's kinda annoying that every time I add a new assembly reference, I have to remember to set it to copy local and add an item to copy it in my build script as well. </p>
| [
{
"answer_id": 2828191,
"author": "Shaun",
"author_id": 276874,
"author_profile": "https://Stackoverflow.com/users/276874",
"pm_score": 4,
"selected": false,
"text": "<ProjectReference Include=\"..\\SomeProject.csproj\">\n <Project>{11111111-1111-1111-1111-111111111111}</Project>\n <Name>Some Project Name</Name>\n <Private>True</Private>\n</ProjectReference>\n <Private>"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
353,632 | <p>Where I work, people mostly think that objects are best initialised using C++-style construction (with parentheses), whereas primitive types should be initialised with the = operator:</p>
<pre><code>std::string strFoo( "Foo" );
int nBar = 5;
</code></pre>
<p>Nobody seems to be able to explain why they prefer things this way, though. I can see that <code>std::string = "Foo";</code> would be inefficient because it would involve an extra copy, but what's wrong with just banishing the <code>=</code> operator altogether and using parentheses everywhere?</p>
<p>Is it a common convention? What's the thinking behind it?</p>
| [
{
"answer_id": 353649,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": false,
"text": "std::string strFooA(\"Foo\"); // Calls std::string(const char*) constructor\nstd::string strFoo = \"Foo\"; // Calls std::string(const char*) constructor\n // This is a valid (and standard) compiler optimization.\n\nstd::string strFoo; // Calls std::string() default constructor\nstrFoo = \"Foo\"; // Calls std::string::operator = (const char*)\n"
},
{
"answer_id": 353650,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "std::string strFoo = \"Foo\";\n"
},
{
"answer_id": 353659,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 3,
"selected": true,
"text": "std::string foo = \"Foo\";"
},
{
"answer_id": 353736,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "string str1 = \"foo\";\n string str1(string(\"foo\")); \n T t = u; // u of type U\n string str1(\"foo\");\n -fno-elide-constructors\n The C++ standard allows an implementation to omit creating a temporary which \n is only used to initialize another object of the same type. Specifying this \n option disables that optimization, and forces G++ to call the copy constructor \n in all cases.\n T a = u;\n T a(u);\n T u(v(a));\n u v a T u(v a);\n v a T u = v(a);\n T u((v(a)));\n"
},
{
"answer_id": 353784,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 1,
"selected": false,
"text": "foo::foo() \n ,anInt(0) \n ,aFloat(0.0) \n{ \n} \n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11575/"
] |
353,678 | <p>I have some data that has a detail table. I want the data to be presented in a ListView. I want the detail data to appear as a nested ListView when you select an item in the original list. I can't seem to figure out how to get the data binding to work.</p>
<p>Here's what I have so far, (the problem is the <code>{Binding Path=FK_History_HistoryItems}</code>):</p>
<pre><code><ListView Name="lstHistory" ItemsSource="{Binding Source={StaticResource History}}" SelectionChanged="lstHistory_SelectionChanged">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=Name}" Header="Name" Width="100" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Description}" Header="Description" Width="150" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Total, Converter={StaticResource moneyConvert}}" Header="Total" Width="100" />
<GridViewColumn DisplayMemberBinding="{Binding Converter={StaticResource categoryAggregate}}" Header="Categories" Width="100" />
</GridView>
</ListView.View>
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<Border>
<StackPanel>
<Border Name="presenter"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}">
<GridViewRowPresenter />
</Border>
<Border Name="details" Visibility="Collapsed" Margin="5"
BorderBrush="Black" BorderThickness="2">
<StackPanel Margin="5">
<ListView ItemsSource="{Binding Path=FK_History_HistoryItems}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=Ammount}" Header="Ammount" Width="100" />
<GridViewColumn DisplayMemberBinding="{Binding Path=Category}" Header="Category" Width="100" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Border>
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="details" Property="Visibility" Value="Visible" />
<Setter TargetName="presenter" Property="Background" Value="Navy"/>
<Setter TargetName="presenter" Property="TextElement.Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.Resources>
</ListView>
</code></pre>
| [
{
"answer_id": 353925,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 1,
"selected": false,
"text": "<ListView ItemsSource=\"{Binding ElementName=lstHistory, Path=SelectedItem}\">\n"
},
{
"answer_id": 497702,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<ListView ItemsSource=\"{Binding FK_History_HistoryItems}\">\n"
},
{
"answer_id": 32995505,
"author": "J Townsend",
"author_id": 5419043,
"author_profile": "https://Stackoverflow.com/users/5419043",
"pm_score": 0,
"selected": false,
"text": "<ControlTemplate TargetType=\"{x:Type ListViewItem}\">\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42911/"
] |
353,684 | <p>I'm writing a mapping application that I am writing in python and I need to get the lat/lon centroid of N points.
Say I have two locations</p>
<pre><code>a.lat = 101
a.lon = 230
b.lat = 146
b.lon = 200
</code></pre>
<p>Getting the center of two points is fairly easy using a euclidean formula. I would like
to be able to do it for more then two points.</p>
<p>Fundamentally I'm looking to do something like <a href="http://a.placebetween.us/" rel="noreferrer">http://a.placebetween.us/</a> where one can enter multiple addresses and find a the spot that is equidistant for everyone.</p>
| [
{
"answer_id": 353732,
"author": "pdemarest",
"author_id": 40332,
"author_profile": "https://Stackoverflow.com/users/40332",
"pm_score": 2,
"selected": false,
"text": "Is the center of (0,359) and (0, 1) at (0,0) or (0,180)?\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33966/"
] |
353,698 | <p>I need to be able to change a user's password from a cron task or from an ssh session. Is there an easy way to do that with a bash script? If not, what's the easiest way to do it in Cocoa?</p>
| [
{
"answer_id": 353704,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 2,
"selected": true,
"text": "passwd"
},
{
"answer_id": 44683538,
"author": "toma",
"author_id": 4797324,
"author_profile": "https://Stackoverflow.com/users/4797324",
"pm_score": 2,
"selected": false,
"text": "#import <Collaboration/Collaboration.h>\n\n AuthorizationRef authRef = NULL; // You have to initialize authRef\n\n CBIdentityAuthority *authority = [CBIdentityAuthority defaultIdentityAuthority];\n CSIdentityRef identity = [CBIdentity identityWithName:user authority:authority].CSIdentity;\n if (CSIdentityGetClass(identity) == kCSIdentityClassUser) {\n CSIdentitySetPassword(identity, (__bridge CFStringRef)newPassword);\n CSIdentityCommit(identity, authRef, NULL);\n }\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
353,706 | <p>Beyond the official documentation, are there any recommended resources for learning to build jQuery plugins. I'm particularly interested in building plugins for the UI libary. </p>
<p>I've been looking at the source for some of the official ones, but I've found they all look quite different from each other. Many are not well commented and it is difficult to tell what blocks of code are part of the essential structure and what is specific to a particular plugin.</p>
<p>If there aren't yet any good resources for this, can anyone clue me in on what basic structure I should be starting with when writing a plugin from scratch?</p>
| [
{
"answer_id": 354071,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 3,
"selected": true,
"text": " $(this).highlight({\n foreground: 'red'\n });\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
353,715 | <p>i have a frame that instantiates another frame but i don't want to use the close(x) button on the instantiated frame., so i created a button. how do i code that this button can be used to close the instantiated frame without quitting the JVM.</p>
| [
{
"answer_id": 430762,
"author": "Tom",
"author_id": 8969,
"author_profile": "https://Stackoverflow.com/users/8969",
"pm_score": 3,
"selected": false,
"text": "jFrame.setVisible(false);\n jFrame.dispose();\n jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n jFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);\n"
},
{
"answer_id": 1743011,
"author": "shenol",
"author_id": 185614,
"author_profile": "https://Stackoverflow.com/users/185614",
"pm_score": 0,
"selected": false,
"text": "jFrame.setUndecorated(true);\njFrame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);\n"
},
{
"answer_id": 17604999,
"author": "AidoP",
"author_id": 2574610,
"author_profile": "https://Stackoverflow.com/users/2574610",
"pm_score": -1,
"selected": false,
"text": "dispose() show()"
},
{
"answer_id": 19507262,
"author": "mkaminsky",
"author_id": 2897919,
"author_profile": "https://Stackoverflow.com/users/2897919",
"pm_score": 0,
"selected": false,
"text": "setVisible(false)"
},
{
"answer_id": 21482195,
"author": "Elian Kamal",
"author_id": 3245556,
"author_profile": "https://Stackoverflow.com/users/3245556",
"pm_score": 0,
"selected": false,
"text": "[framename].setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n EXIT_ON_CLOSE [framename].setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n package answers;\n\nimport javax.swing.JFrame;\n\npublic class Answers {\n\n public static void main(String[] args) {\n\n //frame 1\n JFrame frame1 = new JFrame(\"this is frame 1\");\n frame1.setSize(500, 500);\n frame1.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n\n frame1.setLocationRelativeTo(null); // ignore this its just to place frame 1 on the center\n\n //now this is the code for frame2\n //frame 2\n JFrame frame2 = new JFrame(\"this is frame 2\");\n frame2.setSize(500, 500);\n frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n\n frame1.setVisible(true);\n frame2.setVisible(true);\n\n }\n\n}\n"
},
{
"answer_id": 24240959,
"author": "davie2510",
"author_id": 3554332,
"author_profile": "https://Stackoverflow.com/users/3554332",
"pm_score": 0,
"selected": false,
"text": " public class Main {\n\n/**\n * @param args\n */\npublic static void main(String[] args) {\n // TODO Auto-generated method stub\n //new DemoTryCatch()\n new Frame1();\n}\n\n}\n import java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\n\n\npublic class Frame1 extends JFrame{\nJButton newFrame=new JButton(\"Frame 2\");\npublic Frame1() {\n // TODO Auto-generated constructor stub\n super(\"Frame 1\");\n add(newFrame);\n setVisible(true);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n setSize(300,300);\n newFrame.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent arg0) {\n // TODO Auto-generated method stub\n new Frame2();\\\\instantiating your new Frame\n }\n });\n}\n}\n import java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\n\n\npublic class Frame2 extends JFrame{\n\nJButton CloseFrame2=new JButton(\"CloseFrame2\");\npublic Frame2() {\n // TODO Auto-generated constructor stub\n super(\"Frame 1\");\n add(CloseFrame2);\n setVisible(true);\n setDefaultCloseOperation(DISPOSE_ON_CLOSE);\n setSize(300,300);\n CloseFrame2.addActionListener(new ActionListener() {\n\n @Override\n public void actionPerformed(ActionEvent e) {\n // TODO Auto-generated method stub\n setVisible(false);\\\\You could also use dispose()\n }\n });\n}\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
353,721 | <p>I have a WebApplication project, a business logic project, and a WebDeployment project for the web app. </p>
<p>When I build solution, the deployment "Release" bin contains 1 dll for each of the projects - so I get one for MyWeb.dll, MyWebBusiness.dll, and MyWebDeploy.dll. </p>
<p>When I try to run the site, it sees the same type in both MyWeb.dll and MyWebDeploy.dll and chokes.</p>
<p>Error message:
CS0433: The type 'AV' exists in both 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\53d45622\6c032bd2\assembly\dl3\33f3c6b2\abc9430a_285ac901\MyWeb.DLL' and 'c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\53d45622\6c032bd2\assembly\dl3\631e5302\0231160d_285ac901\MyWebDeploy.DLL'</p>
| [
{
"answer_id": 14181544,
"author": "Rohit Naik",
"author_id": 1952705,
"author_profile": "https://Stackoverflow.com/users/1952705",
"pm_score": 0,
"selected": false,
"text": "<compilation ... batch=\"false\"/>\n\n ...\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44698/"
] |
353,746 | <p>This question deals with concurrency issues, for suggestions on how to display a busy icon see this question: <a href="https://stackoverflow.com/questions/205631/javascript-loadingbusy-indicator-or-transparent-div-over-page-on-event-click">Javascript - loading/busy indicator or transparent div over page on event click</a></p>
<p>When a user initiates an AJAX request on a page it's useful to show some kind of "working" or busy icon or progress indicator. If there is only one long-running process this can be handled in a relatively straightforward way:</p>
<pre><code>function do_action() {
show_busy_icon();
long_running_asynchronous_process(function() {
// Callback function run when process finishes
hide_busy_icon();
});
}
</code></pre>
<p>However, if multiple asynchronous processes are running on the page, using on/off methods wouldn't work. The first process to finish switches off the icon even though there are additional processes running.</p>
<p>So, <strong>how do you handle displaying an indicator, on a web page, that is on when there are one or more processes running, and off when there are no processes running?</strong></p>
<p>I imagine it would be possible to maintain a count of the number of processes running. <code>hide_busy_icon()</code> only hides the icon if the process count is 0. That seems kinda prone to failure. Perhaps there's a better/simpler way that I'm not seeing.</p>
<p>Thanks for your ideas and suggestions!</p>
<p>Edit: After working with the solution in the marked answer for a while, I'm happy to say it works very well. The only issue I've run into are cases where my own scripts call functions of scripts I don't control. Unless those functions allow callbacks to be supplied there's no way to update the process-count when they begin and end.</p>
<p>An example of where this can occurs is adding a set of markers to a Google map. Once my script calls the Google maps function the busy icon disappears, while the markers are still being loaded.</p>
<p>I'm not sure of a good way to handle this. </p>
| [
{
"answer_id": 354143,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 1,
"selected": false,
"text": "Ajax.activeRequestCount"
},
{
"answer_id": 10206151,
"author": "Henrik",
"author_id": 1331076,
"author_profile": "https://Stackoverflow.com/users/1331076",
"pm_score": 0,
"selected": false,
"text": " var actionRegister = new Array();\n\n function register_action(actionId)\n {\n show_busy_icon(); \n if(blockedTile.indexOf(actionId) != -1)\n { // element already registered\n return;\n }\n actionRegister.push(actionId)\n}\n\n\nfunction unregister_action(actionId)\n{\n var idx = blockedTile.indexOf(actionId);\n if(idx != -1)\n { \n actionRegister.splice(idx,1);\n }\n\n if(actionRegister.length < 1)\n {\n hide_busy_icon();\n }\n}\n"
},
{
"answer_id": 14099718,
"author": "Rohan Bagchi",
"author_id": 1939344,
"author_profile": "https://Stackoverflow.com/users/1939344",
"pm_score": 0,
"selected": false,
"text": "<html>\n<body>\n <div id=\"content_1\">\n </div>\n <div id=\"content_2\">\n </div>\n</body>\n</html>\n $(\"content_1\").html(\"<img src='loading.gif'>\").load(\"http://samplesite.com/content_1.php\");\n\n$(\"content_2\").html(\"<img src='loading.gif'>\").load(\"http://samplesite.com/content_2.php\");\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
] |
353,757 | <p>I've recently gotten charged with designing and implementing a source code version control, testing, and deployment scheme at the company I work.</p>
<p>Personally I've worked with Subversion for a few years on my own projects. But I've never dealt with it at this big scale. Hence I thought I'd ask here if anyone has any comments or suggestions about the following setup I've deviced:</p>
<ul>
<li>Trunk is used as the main development tree, as it should be</li>
<li>Remote servers (testing and production) check out code from the SVN repo.
<ul>
<li>Testing servers check out trunk.</li>
<li>Production servers checkout the "production" branch.</li>
</ul></li>
<li>Once trunk is deemed ready for production, it's merged into two branches, "stable", and "production".</li>
<li>The stable branch is a stepping stone to the production branch. If bugs are found once the new code goes live on the production server, the stable branch is used for fixing the bugs, and also testing the bug fixes.</li>
<li>Once fixed, changes are merged into the production branch, and also back into trunk where development has kept on going like normal adding new features and whatever independently of any bug fixes that were needed.</li>
</ul>
<p>This way, development doesn't have to halt on trunk whenever there's a production release, as bug fixes aren't dependent on trunk. Also, there's always a "read-only" branch where the latest stable and most-bug free code is available, even in the middle of heavy bug fixing.</p>
<p>If anybody has any suggestions, comments, or otherwise, I'd greatly appreciate it :)</p>
| [
{
"answer_id": 354143,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 1,
"selected": false,
"text": "Ajax.activeRequestCount"
},
{
"answer_id": 10206151,
"author": "Henrik",
"author_id": 1331076,
"author_profile": "https://Stackoverflow.com/users/1331076",
"pm_score": 0,
"selected": false,
"text": " var actionRegister = new Array();\n\n function register_action(actionId)\n {\n show_busy_icon(); \n if(blockedTile.indexOf(actionId) != -1)\n { // element already registered\n return;\n }\n actionRegister.push(actionId)\n}\n\n\nfunction unregister_action(actionId)\n{\n var idx = blockedTile.indexOf(actionId);\n if(idx != -1)\n { \n actionRegister.splice(idx,1);\n }\n\n if(actionRegister.length < 1)\n {\n hide_busy_icon();\n }\n}\n"
},
{
"answer_id": 14099718,
"author": "Rohan Bagchi",
"author_id": 1939344,
"author_profile": "https://Stackoverflow.com/users/1939344",
"pm_score": 0,
"selected": false,
"text": "<html>\n<body>\n <div id=\"content_1\">\n </div>\n <div id=\"content_2\">\n </div>\n</body>\n</html>\n $(\"content_1\").html(\"<img src='loading.gif'>\").load(\"http://samplesite.com/content_1.php\");\n\n$(\"content_2\").html(\"<img src='loading.gif'>\").load(\"http://samplesite.com/content_2.php\");\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42146/"
] |
353,772 | <p>i have the following jquery code. </p>
<p>basically i will have several overlapped divs and a list of links on the right of all those overlapped divs. when hovering over a link, the link's assigned div will fade in.</p>
<p>I have the following code and it works (it uses the default windows' sample pictures), but if someone can think of a way to optimize it or make it generic, i'd appreciate it.</p>
<pre><code><html>
<head>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#trigger1").mouseover(function() {
$(".contentdiv").addClass("inactive");
$("#divsunset").removeClass("inactive");
$(".inactive").fadeOut(500);
$("#divsunset").fadeIn(500);
});
$("#trigger2").mouseover(function() {
$(".contentdiv").addClass("inactive");
$("#divwinter").removeClass("inactive");
$(".inactive").fadeOut(500);
$("#divwinter").fadeIn(500);
});
$("#trigger3").mouseover(function() {
$(".contentdiv").addClass("inactive");
$("#divbh").removeClass("inactive");
$(".inactive").fadeOut(500);
$("#divbh").fadeIn(500);
});
$("#trigger4").mouseover(function() {
$(".contentdiv").addClass("inactive");
$("#divwl").removeClass("inactive");
$(".inactive").fadeOut(500);
$("#divwl").fadeIn(500);
});
});
</script>
<style>
#divsunset
{
position: absolute;
top: 5px;
left: 5px;
}
#divwinter
{
position: absolute;
top: 5px;
left: 5px;
}
#divbh
{
position: absolute;
top: 5px;
left: 5px;
}
#divwl
{
position: absolute;
top: 5px;
left: 5px;
}
#links
{
position: absolute;
top: 800px;
left: 700px;
}
.inactive
{
}
</style>
</head>
<body>
<div id="divsunset" class="contentdiv">
<img src="Sunset.jpg" />
</div>
<div id="divwinter" class="contentdiv">
<img src="Winter.jpg" />
</div>
<div id="divbh" class="contentdiv">
<img src="bh.jpg" />
</div>
<div id="divwl" class="contentdiv">
<img src="wl.jpg" />
</div>
<br />
<div id="links">
<a href="#" id="trigger1">Show Sunset</a>
<a href="#" id="trigger2">Show Winter</a>
<a href="#" id="trigger3">Show Blue Hills</a>
<a href="#" id="trigger4">Show Waterlillies</a>
</div>
</body>
</html>
</code></pre>
<hr>
<p>Thank you Matt, TM and kRON, your responses really helped.</p>
<p>I dont feel I explained myself totally, but TM provided the answer I was looking for.</p>
<p>I wanted to follow DRY and the code TM provided helped me best this time since it did not require for me to alter my markup, just the jQuery code.</p>
<p>Again, thanks a lot. Its amazing how quickly I got the answer. Keep up the great work.</p>
| [
{
"answer_id": 353809,
"author": "TM.",
"author_id": 12983,
"author_profile": "https://Stackoverflow.com/users/12983",
"pm_score": 4,
"selected": true,
"text": "document.ready() $('#trigger1').data('target', '#divsunset');\n$('#trigger2').data('target', '#divwinter');\n$('#trigger3').data('target', '#divbh');\n$('#trigger4').data('target', '#divwl');\n$('#trigger1,#trigger2,#trigger3,#trigger4').mouseover(function() {\n var selector = $(this).data('target');\n $(\".contentdiv\").addClass(\"inactive\");\n $(selector).removeClass(\"inactive\");\n $(\".inactive\").fadeOut(500);\n $(selector).fadeIn(500);\n});\n $(element).data() $(document).ready() $(function() {\n //DOM ready\n};\n"
},
{
"answer_id": 353835,
"author": "Filip Dupanović",
"author_id": 44041,
"author_profile": "https://Stackoverflow.com/users/44041",
"pm_score": 0,
"selected": false,
"text": "\n $(document).ready(function() {\n\n $(\".trigger\").mouseover(function() {\n\n $(\".contentdiv\").addClass(\"inactive\");\n $(\"#wrapper .\" + $(this).attr('class')[1]).removeClass(\"inactive\");\n $(\".inactive\").fadeOut(500);\n $(\"#wrapper .\" + $(this).attr('class')[1]).fadeIn(500);\n });\n"
},
{
"answer_id": 353855,
"author": "Matt Goddard",
"author_id": 5185,
"author_profile": "https://Stackoverflow.com/users/5185",
"pm_score": 1,
"selected": false,
"text": "<Div class=\"name1 name2\"></div>\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34683/"
] |
353,773 | <p>How can I determine when the control key is held down during button click in a C# Windows program? I want one action to take place for Ctrl/Click and a different one for Click.</p>
| [
{
"answer_id": 353816,
"author": "lesscode",
"author_id": 18482,
"author_profile": "https://Stackoverflow.com/users/18482",
"pm_score": 3,
"selected": false,
"text": "private void button1_Click(object sender, EventArgs e) {\n MessageBox.Show(Control.ModifierKeys.ToString());\n}\n private void Button_Click(object sender, RoutedEventArgs e) {\n MessageBox.Show(Keyboard.Modifiers.ToString());\n}\n"
},
{
"answer_id": 353827,
"author": "Simon Wilson",
"author_id": 12875,
"author_profile": "https://Stackoverflow.com/users/12875",
"pm_score": 6,
"selected": true,
"text": "private void button1_Click ( object sender, EventArgs e )\n{ \n if( (ModifierKeys & Keys.Control) == Keys.Control )\n {\n ControlClickMethod(); \n }\n else\n {\n ClickMethod();\n }\n}\n\nprivate void ControlClickMethod()\n{\n MessageBox.Show( \"Control is pressed\" );\n}\n\nprivate void ClickMethod()\n{\n MessageBox.Show ( \"Control is not pressed\" );\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] |
353,786 | <p>I have this function in my head:</p>
<pre><code><head>
window.onload = function(){
var x = new Array(0,2,3,4,5,6,7,8);
var y = new Array(20,10,40,30,60,50,70,10);
drawGraph(y,x);
}
</head>
</code></pre>
<p>Can I declare the function drawGraph() somewhere in the body? Do I need to declare it before it is called?</p>
| [
{
"answer_id": 608288,
"author": "Dscoduc",
"author_id": 51949,
"author_profile": "https://Stackoverflow.com/users/51949",
"pm_score": 0,
"selected": false,
"text": "function addLoadEvent(func) {\n var oldonload = window.onload;\n if (typeof window.onload != 'function') {\n window.onload = func;\n } \n else {\n window.onload = function() {\n oldonload();\n\n var x = new Array(0,2,3,4,5,6,7,8);\n var y = new Array(20,10,40,30,60,50,70,10); \n drawGraph(y,x);\n }\n }\n}\n $(document).ready(function() {\n var x = new Array(0,2,3,4,5,6,7,8);\n var y = new Array(20,10,40,30,60,50,70,10); \n drawGraph(y,x); \n })\n"
},
{
"answer_id": 1494328,
"author": "bambams",
"author_id": 149184,
"author_profile": "https://Stackoverflow.com/users/149184",
"pm_score": 0,
"selected": false,
"text": "drawGraph <script> function identifier ( arglist ) { body } <script> <html>\n <head>\n <script type=\"text/javascript\">\n function check_existance()\n {\n if(!check_existance.i)\n check_existance.i = 0;\n\n document.write(\"<h5>Call : \" + ++check_existance.i + \"</h5>\" +\n \"func1 : \" + typeof func1 + \"<br />\" +\n \"func2 : \" + typeof func2 + \"<br />\" +\n \"func3 : \" + typeof func3 + \"<br />\" +\n \"func4 : \" + typeof func4 + \"<br />\");\n }\n </script>\n <script type=\"text/javascript\">\n check_existance();\n\n func1 = function()\n {\n alert(\"func1\");\n };\n\n check_existance();\n\n function func2()\n {\n alert(\"func2\");\n }\n </script>\n </head>\n <body>\n <script type=\"text/javascript\">\n check_existance();\n\n func3 = function()\n {\n alert(\"func3\");\n };\n\n check_existance();\n\n function func4()\n {\n alert(\"func4\");\n }\n </script>\n </body>\n</html>\n <script> </body>"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26004/"
] |
353,788 | <p>Is there an similar property like System.getProperty("java.home") that will return the JDK directory instead of the JRE directory? I've looked <a href="https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()" rel="nofollow noreferrer">https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#getProperties()</a> and there doesn't seem to be anything for the JDK.</p>
| [
{
"answer_id": 353860,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 2,
"selected": false,
"text": "java.home"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19026/"
] |
353,793 | <p>Can I use a query in MSSQL to get the .mdf and .ldf filename/location for a specific database?</p>
| [
{
"answer_id": 353807,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM sys.master_files\n"
},
{
"answer_id": 685068,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 3,
"selected": false,
"text": "exec sp_helpfile\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
353,800 | <p>I'm wondering if storing the data in viewstate is a good idea for this given problem.
He's a simplified example of what I am trying to achieve, firstly we have a Repeater control:</p>
<pre><code><asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<asp:TextBox id="Name" runat="server" />
<asp:TextBox id="Age" runat="server" />
</ItemTemplate>
</asp:Repeater>
<asp:TextBox id="NewPersonName" runat="server" />
<asp:TextBox id="NewPersonAge" runat="server" />
<asp:Buttin id="Button1" runat="server" Text="Add" OnClick"Button1_Click"/>
</code></pre>
<p>To keep things simple I'll forego the databinding code, as this is working it loads in the current list of people and ages and binds perfectly.</p>
<p>The problem is with the bottom 3 controls, what I want is for the user to be able to type in a new entry, click the add button and this would then be added to the Repeater, but not persisted to the database.</p>
<p>The user should be able to add multiple names to the list and then click a Save button to commit all the new names in one click rather than committing for each entry.</p>
| [
{
"answer_id": 353807,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM sys.master_files\n"
},
{
"answer_id": 685068,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 3,
"selected": false,
"text": "exec sp_helpfile\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44702/"
] |
353,803 | <p>How can I get a PHP function go to a specific website when it is done running?</p>
<p>For example:</p>
<pre><code><?php
//SOMETHING DONE
GOTO(http://example.com/thankyou.php);
?>
</code></pre>
<p>I would really like the following...</p>
<pre><code><?php
//SOMETHING DONE
GOTO($url);
?>
</code></pre>
<p>I want to do something like this:</p>
<pre><code><?php
//SOMETHING DONE THAT SETS $url
header('Location: $url');
?>
</code></pre>
| [
{
"answer_id": 353839,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 4,
"selected": false,
"text": "<?php\n // SOMETHING DONE\n\n header('Location: http://stackoverflow.com');\n?>\n"
},
{
"answer_id": 353840,
"author": "Aistina",
"author_id": 37472,
"author_profile": "https://Stackoverflow.com/users/37472",
"pm_score": 2,
"selected": false,
"text": "<?php\n\n// do something here\n\nheader(\"Location: http://example.com/thankyou.php\");\n?>\n"
},
{
"answer_id": 353851,
"author": "Patrick Hogan",
"author_id": 4065,
"author_profile": "https://Stackoverflow.com/users/4065",
"pm_score": 7,
"selected": true,
"text": "<?\nob_start(); // ensures anything dumped out will be caught\n\n// do stuff here\n$url = 'http://example.com/thankyou.php'; // this can be set based on whatever\n\n// clear out the output buffer\nwhile (ob_get_status()) \n{\n ob_end_clean();\n}\n\n// no redirect\nheader( \"Location: $url\" );\n?>\n"
},
{
"answer_id": 353962,
"author": "FryGuy",
"author_id": 28776,
"author_profile": "https://Stackoverflow.com/users/28776",
"pm_score": 3,
"selected": false,
"text": "header('Location: $url');\n header(\"Location: $url\");\n"
},
{
"answer_id": 355105,
"author": "user44856",
"author_id": 44856,
"author_profile": "https://Stackoverflow.com/users/44856",
"pm_score": 5,
"selected": false,
"text": "<?php\n\n echo $htmlHeader;\n while($stuff){\n echo $stuff;\n }\n echo \"<script>window.location = 'http://www.yourdomain.com'</script>\";\n?>\n"
},
{
"answer_id": 17046485,
"author": "as_bold_as_love",
"author_id": 1306440,
"author_profile": "https://Stackoverflow.com/users/1306440",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n// do something here\n\nheader(\"Location: http://example.com/thankyou.php\");\ndie();\n\n//code down here now wont get run\n\n?>\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33194/"
] |
353,804 | <p>I'm working on a database that tracks files and dependencies in projects. Briefly, I have two main tables; the PROJECTS table lists project names and other properties, the FILES table lists files. Every file entry points to a project as a foreign key set to CASCADE, so if I delete a project record from the database, all the file records disappear as well. So far, so good.</p>
<p>Now I have an additional DEPENDENCIES table. Each record in the dependency table is two files, specifying that the first file depends on the second. Again these are foreign keys, the first is set to CASCADE (so if I delete a file entry, this record is deleted), but the second is set to RESTRICT (so I am not allowed to delete a file entry if any other files depend on it). Again, everything seems good.</p>
<p>Unfortunately it seems I can no longer delete a project with a single SQL delete statement! The delete tries to cascade-delete the files, but if any of these appear in the DEPENDENCIES table, the RESTRICT foreign key prevents the delete (even though that record in the dependencies table will be removed because the other column is CASCADE). The only workaround I have is to calculate an exact order to delete the files so none of the dependency record constraints are violated, and remove the file records one at a time before attempting to remove the project.</p>
<p>Is there any way to set up my database schema so a single SQL delete from the projects table will correctly cascade the other deletes? I'm using Firebird 2.1, but I don't know if that makes any difference - it seems like there ought to be a way to make this work?</p>
| [
{
"answer_id": 353913,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "PROJECTS FILES DEPENDENCIES FILES BEFORE DELETE CREATE TRIGGER Del_Child_Files FOR PROJECTS\nBEFORE INSERT\nAS BEGIN\n FOR SELECT F.FILE_ID FROM FILES F JOIN DEPENDENCIES D \n ON F.FILE_ID = D.CHILD_ID\n WHERE F.PROJECT_ID = OLD.PROJECT_ID\n INTO :file_id\n DO\n DELETE FROM FILES WHERE FILE_ID = :file_id;\n DONE\nEND\n DEPENDENCIES"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8415/"
] |
353,808 | <p>How do I implement this method (see below)? I'm new to Objective-C and I'm just not getting it right.</p>
<p>From: <a href="http://lists.apple.com/archives/Webkitsdk-dev/2008/Apr/msg00027.html" rel="nofollow noreferrer">http://lists.apple.com/archives/Webkitsdk-dev/2008/Apr/msg00027.html</a></p>
<blockquote>
<p>By default databases have a quota of 0; this quota must be increased before any database will be stored on disk.</p>
<p><strong>WebKit clients should implement the WebUIDelegate method <code>- webView:frame:exceededDatabaseQuotaForSecurityOrigin:database:</code> and increase the quota as desired when that method is called.</strong> This method is defined in WebUIDelegatePrivate.h. It was added too late in the previous release cycle to make it into a non-private header. It would be worthwhile to file a bug about moving this call to WebUIDelegate.h so that it is part of the official API.</p>
</blockquote>
<p>John</p>
| [
{
"answer_id": 354258,
"author": "Jeff",
"author_id": 8597,
"author_profile": "https://Stackoverflow.com/users/8597",
"pm_score": 1,
"selected": false,
"text": "- (void)webView:(WebView *)sender frame:(WebFrame *)frame\nexceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin\ndatabase:(NSString *)databaseIdentifier;\n - (void)webView:(WebView *)sender frame:(WebFrame *)frame\nexceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin\ndatabase:(NSString *)databaseIdentifier\n{\n static const unsigned long long defaultQuota = 5 * 1024 * 1024;\n [origin setQuota:defaultQuota];\n}\n"
},
{
"answer_id": 354279,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 3,
"selected": true,
"text": "- (void)webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(WebSecurityOrigin *)origin database:(NSString *)databaseIdentifier {\n unsigned long long newQuotaBytes = 10 * 1024 * 1024;\n [origin setQuota:newQuotaBytes];\n\n // origin also responds to -usage method to return current size for all databases in this origin\n}\n"
},
{
"answer_id": 355207,
"author": "Jeff",
"author_id": 8597,
"author_profile": "https://Stackoverflow.com/users/8597",
"pm_score": 0,
"selected": false,
"text": "- (void)webView:(WebView *)sender frame:(WebFrame *)frame exceededDatabaseQuotaForSecurityOrigin:(id)origin database:(NSString *)databaseIdentifier\n{\n static const unsigned long long defaultQuota = 5 * 1024 * 1024;\n if ([origin respondsToSelector: @selector(setQuota:)]) {\n [origin setQuota: defaultQuota];\n } else { \n NSLog(@\"could not increase quota for %@\", defaultQuota); \n }\n} \n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8597/"
] |
353,817 | <p>Java and C# support the notion of classes that can't be used as base classes with the <code>final</code> and <code>sealed</code> keywords. In C++ however there is no good way to prevent a class from being derived from which leaves the class's author with a dilemma, should every class have a virtual destructor or not?</p>
<hr>
<p><strong>Edit:</strong> Since C++11 this is no longer true, you can specify that a class is <a href="http://en.cppreference.com/w/cpp/language/final" rel="noreferrer"><code>final</code></a>.</p>
<hr>
<p>On the one hand giving an object a virtual destructor means it will have a <code>vtable</code> and therefore consume 4 (or 8 on 64 bit machines) additional bytes per-object for the <code>vptr</code>.</p>
<p>On the other hand if someone later derives from this class and deletes a derived class via a pointer to the base class the program will be ill-defined (due to the absence of a virtual destructor), and frankly optimizing for a pointer per object is ridiculous. </p>
<p>On the <a href="http://en.wikipedia.org/wiki/Gripping_hand" rel="noreferrer">gripping hand </a> having a virtual destructor (arguably) advertises that this type is meant to be used polymorphically.</p>
<p>Some people think you need an explicit reason to not use a virtual destructor (as is the subtext of <a href="https://stackoverflow.com/questions/300986">this question</a>) and others say that you should use them only when you have reason to believe that your class is to be derived from, what do <em>you</em> think?</p>
| [
{
"answer_id": 353856,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": false,
"text": "virtual virtual protected virtual std::iterator"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
353,841 | <p>I'm new to the forum and very new to silverlight. Myself and my coworker are working on a custom application. We are building a menu system that will only display buttons if that useris in an assigned role. A new property was created to allow roles to be defined, and for testing purposes we are simply trying to assign that value, which is a string, to a textblock's text property. Some code is attached.</p>
<p>This is one of the items to be added to the collection. the allowedroles property is passing the string, this can be seen via the debugger. </p>
<pre><code><MenuButton:VerticalButtonCollection x:Key="VerticalButtonsDS" d:IsDataSource="True">
<MenuButton:VerticalButton AllowedRoles="test, test2">
<TextBlock Text="{Binding AllowedRoles}"></TextBlock>
</MenuButton:VerticalButton>
</MenuButton:VerticalButtonCollection>
Code for the allowed roles property
Public Shared ReadOnly AllowedRolesProperty As DependencyProperty = DependencyProperty.Register("AllowedRoles", GetType(String), GetType(mButton), New PropertyMetadata(New PropertyChangedCallback(AddressOf onAllowedRolesChanged)))
Public Shared Sub onAllowedRolesChanged(ByVal d As DependencyObject, ByVal args As DependencyPropertyChangedEventArgs)
Dim sender As mButton = CType(d, mButton)
sender.AllowedRoles = CStr(args.NewValue)
End Sub
</code></pre>
<p>The items are displayed in a list box, there are no errors, but binding does not work. I even attempted to do the binding in the listbox's data template. I appologize if this is confusing, I dont' know how to post something like this in easy to understand pieces.</p>
<p>Thanks</p>
| [
{
"answer_id": 353856,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": false,
"text": "virtual virtual protected virtual std::iterator"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44713/"
] |
353,842 | <p>In C#, I'm trying to build an extension method for StringBuilder called AppendCollection() that would let me do this:</p>
<pre><code>var sb1 = new StringBuilder();
var sb2 = new StringBuilder();
var people = new List<Person>() { ...init people here... };
var orders = new List<Orders>() { ...init orders here... };
sb1.AppendCollection(people, p => p.ToString());
sb2.AppendCollection(orders, o => o.ToString());
string stringPeople = sb1.ToString();
string stringOrders = sb2.ToString();
</code></pre>
<p>stringPeople would end up with a line for each person in the list. Each line would be the result of p.ToString(). Likewise for stringOrders. I'm not quite sure how to write the code to make the lambdas work with generics.</p>
| [
{
"answer_id": 353858,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "public static string Print<T>(this IEnumerable<T> col, Func<T,string> printer)\n{\n var sb = new StringBuilder();\n foreach (T t in col)\n {\n sb.AppendLine(printer(t));\n }\n return sb.ToString();\n}\n\nstring[] col = { \"Foo\" , \"Bar\" };\nstring lines = col.Print( s => s);\n public static void AppendCollection<T>(this StringBuilder sb, \n List<T> col, Func<T,string> printer)\n{\n col.ForEach( o => sb.AppendLine(printer(o)));\n}\n"
},
{
"answer_id": 353861,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 5,
"selected": true,
"text": "Func<T,string> public static void AppendCollection<T>(this StringBuilder sb, \n IEnumerable<T> collection, Func<T, string> method) {\n foreach(T x in collection) \n sb.AppendLine(method(x));\n}\n"
},
{
"answer_id": 353862,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": " public static void AppendCollection( this StringBuilder builder,\n ICollection collection )\n {\n foreach (var item in collection)\n {\n builder.AppendLine( Convert.ToString( item ) );\n }\n }\n List<Person> people = ...\n\n StringBuilder builder = new StringBuilder();\n builder.AppendCollection( people );\n var s = builder.ToString();\n"
},
{
"answer_id": 353865,
"author": "Jennifer",
"author_id": 22360,
"author_profile": "https://Stackoverflow.com/users/22360",
"pm_score": 2,
"selected": false,
"text": " public static void AppendCollection<TItem>(this StringBuilder builder, IEnumerable<TItem> items, Func<TItem, string> valueSelector)\n {\n foreach(TItem item in items)\n { \n builder.Append(valueSelector(item));\n }\n }\n public static void AppendCollection<TItem>(this StringBuilder builder, IEnumerable<TItem> items)\n {\n AppendCollection(builder, items, x=>x.ToString());\n }\n"
},
{
"answer_id": 353872,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "static class SBExtention\n{\n static string AppendCollection<T>(this StringBuilder sb, \n IEnumerable<T> coll, \n Func<T,string> action)\n {\n foreach(T t in coll)\n {\n sb.Append(action(t));\n sb.Append(\"\\n\");\n }\n return sb.ToString();\n\n }\n}\n static StringBuilder AppendCollection<T>(this StringBuilder sb, \n IEnumerable<T> coll, \n Func<T,string> action)\n {\n // same\n return sb;\n\n }\n public static StringBuilder AppendCollection<TItem>(\n this StringBuilder builder, \n IEnumerable<TItem> items)\n {\n return AppendCollection(builder, items, x=>x.ToString());\n }\n"
},
{
"answer_id": 353876,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 3,
"selected": false,
"text": " public static void AppendCollection<T>(this StringBuilder builder, IEnumerable<T> list, Func<T,string> func)\n {\n foreach (var item in list)\n {\n builder.AppendLine(func(item));\n }\n }\n"
},
{
"answer_id": 353931,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": " public static string AppendCollection<T>(this StringBuilder sb, IEnumerable<T> enumerable, Func<T, string> method)\n {\n List<T> l = new List<T>(enumerable);\n l.ForEach(item => sb.AppendLine(method(item)));\n return sb.ToString();\n }\n public static void AppendCollection<T>(this StringBuilder sb, IEnumerable<T> enumerable, Func<T, string> method)\n {\n List<T> l = new List<T>(enumerable);\n l.ForEach(item => sb.AppendLine(method(item)));\n }\n sb.AppendCollection(people, p => p.ToString());\n sb.AppendCollection(orders, o => o.ToString());\n Console.WriteLine(sb.ToString());\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/571/"
] |
353,843 | <p>I'm trying to search multiple attributes in XML :</p>
<pre><code><APIS>
<API Key="00001">
<field Username="username1" UserPassword="password1" FileName="Filename1.xml"/>
<field Username="username2" UserPassword="password2" FileName="Filename2.xml"/>
<field Username="username3" UserPassword="password3" FileName="Filename3.xml"/>
</API>
</APIS>
</code></pre>
<p>I need to check if in the "field" the Username AND UserPassword values are both what I am comparing with my Dataset values, is there a way where I can check multiple attributes (AND condition) without writing my own logic of using Flags and breaking out of loops. </p>
<p>Is there a built in function of XMLDoc that does it? Any help would be appreciated! </p>
| [
{
"answer_id": 353944,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": true,
"text": "/APIS/API/field[@Username='username1' and @UserPassword='password1']\n // make sure the following line is included in your class\nusing System.Xml;\n\nXmlDocument xmldoc = new XmlDocument();\nxmldoc.Load(\"your XML string or file\");\n\nstring xpath = \"/APIS/API/field[@Username='{0}' and @UserPassword='{1}']\";\nstring username = \"username1\";\nstring password = \"password1\";\n\nxpath = String.Format(xpath, username, password);\nXmlNode userNode = xmldoc.SelectSingleNode(xpath);\n\nif (userNode != null)\n{\n // found something with given user name and password\n}\nelse\n{\n // username or password incorrect\n}\n"
},
{
"answer_id": 354951,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 1,
"selected": false,
"text": "/*/*/field[@Username = your-ds-username and @UserPassword = your-ds-UserPassword] your-ds-username your-ds-UserPassword"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24958/"
] |
353,882 | <pre><code><asp:RadioButton GroupName="EndorsementType" runat="server" ID="rdoAddProperty" Text="Add Property to TIV" />
<asp:RadioButton GroupName="EndorsementType" runat="server" ID="rdoRemoveProperty" Text="Remove Property from TIV" />
<asp:RadioButton GroupName="EndorsementType" runat="server" ID="rdoChangeProperty" Text="Change Property Values" />
</code></pre>
<p>I was thinking about implementing a custom <code>validator</code>, and using a client <code>JavaScript</code> function to reference the RadioButton ID, (I'm using web forms, not mvc),</p>
<pre><code>something like..
if(document.getElementById(<%= rdoAddProperty.ClientId %>).checked == true) && ...
</code></pre>
<p>Anyone know of a way to do it without knowing the clientId?</p>
| [
{
"answer_id": 353917,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 3,
"selected": true,
"text": "<script type=\"text/javascript\" language=\"javascript\">\n function Validate()\n {\n var l_elemsRadios = document.getElementById(\"MyRadios\").getElementsByTagName(\"input\");\n\n if (l_elemsRadios == null)\n return;\n\n for (var i = 0; i < l_elemsRadios; i++)\n {\n // validate l_elemsRadios[i] through l_elemsRadios[n]\n }\n }\n</script>\n\n\n<div id=\"MyRadios\">\n <input type=\"radio\" name=\"EndorsementType\" value=\"Remove Property from TIV\" >Remove Property from TIV\n .\n .\n .\n</div>\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44595/"
] |
353,901 | <p>Is there a generic container implementing the 'set' behaviour in .NET?</p>
<p>I know I could just use a <code>Dictionary<T, Object></code> (and possibly add <code>nulls</code> as values), because its keys act as a set, but I was curious if there's something ready-made.</p>
| [
{
"answer_id": 353924,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 5,
"selected": true,
"text": "HashSet<T>"
},
{
"answer_id": 19141521,
"author": "Cristian Diaconescu",
"author_id": 11545,
"author_profile": "https://Stackoverflow.com/users/11545",
"pm_score": 2,
"selected": false,
"text": "HashSet<T> ISet<T> HashSet<T> SortedSet<T> internal class TreeSet<T>: SortedSet<T> System.Collections.Generic SortedDictionary<TKey, TValue>"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
] |
353,912 | <p>I need help getting my head around the difference between my current OOP notion of state, and the way it would be done in a functional language like Haskell or Clojure. </p>
<p>To use a hackneyed example, let's say we're dealing with simplified bank account objects/structs/whatever. In an OOP language, I'd have some class holding a reference to a BankAccount, which would have instance variables for things like interest rate, and methods like setInterestRate() which change the object's state and generally return nothing. In say Clojure, I'd have a bank-account struct (a glorified hashmap), and special functions that take a bank-account parameter and other info, and return a new struct. So instead of changing the state of the original object, I now have a new one being returned with the desired modifications. </p>
<p>So... what do I do with it? Overwrite whatever variable was referencing the old bank-account? If so, does that have advantages over the state-changing OOP approach? In the end, in both cases it seems one has a variable that references the object with the necessary changes. Retarded as I am, I have only a vague concept of what's going on. </p>
<p>I hope that made sense, thanks for any help!</p>
| [
{
"answer_id": 354017,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": " b__\n | \na -> [6|] -+-> [5|] -> [4|] -> [3|] -> [2|] -> [1|x]\n"
},
{
"answer_id": 355040,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 3,
"selected": false,
"text": "updatePortfolio :: Request -> Portfolio -> Portfolio\n readRequest :: IO Request -- an action that, when performed, reads a Request with side effects\n\nmain :: Portfolio -> IO () -- a completely useless program that updates a Portfolio in response to a stream of Requests\n\nmain portfolio = do req <- readRequest\n main (updatePortfolio req)\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38803/"
] |
353,926 | <p>Anyone know what the C# "M" syntax means?</p>
<pre><code>var1 = Math.Ceiling(hours / (40.00M * 4.3M));
</code></pre>
| [
{
"answer_id": 353939,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "decimal"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/300930/"
] |
353,948 | <p>Data table structure is:<br>
id1,id2,id3,id4,... (some other fields).<br>
I want to create summary query to find out how many times some ID value is used in every column.</p>
<p>Data<br>
1,2,3,4,2008<br>
2,3,5,1,2008<br>
1,3,2,5,2007<br>
1,2,3,6,2007<br>
3,1,2,5,2007<br></p>
<p>For value 1, the result should be<br>
1,0,0,1,2008<br>
2,1,0,0,2007<br></p>
<p>How to accomplish this with one query (in MySQL).</p>
| [
{
"answer_id": 353971,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "DECLARE @look_for AS int\nSET @look_for = 1\n\nSELECT SUM(CASE WHEN id1 = @look_for THEN 1 ELSE 0 END) AS id1_count\n ,SUM(CASE WHEN id2 = @look_for THEN 1 ELSE 0 END) AS id2_count\n ,SUM(CASE WHEN id3 = @look_for THEN 1 ELSE 0 END) AS id3_count\n ,SUM(CASE WHEN id4 = @look_for THEN 1 ELSE 0 END) AS id4_count\nFROM tbl\n"
},
{
"answer_id": 353972,
"author": "Dan Sydner",
"author_id": 43988,
"author_profile": "https://Stackoverflow.com/users/43988",
"pm_score": -1,
"selected": false,
"text": "select (select count(*) where id1 = X) as countid1 ... etc\n"
},
{
"answer_id": 354103,
"author": "Riho",
"author_id": 44715,
"author_profile": "https://Stackoverflow.com/users/44715",
"pm_score": 2,
"selected": true,
"text": "select years,\nsum(1*(1-abs(sign(id1-56)))) as id1,\nsum(1*(1-abs(sign(id2-56)))) as id2,\nsum(1*(1-abs(sign(id3-56)))) as id3,\nsum(1*(1-abs(sign(id4-56)))) as id4,\nfrom mytable\ngroup by years\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44715/"
] |
353,953 | <p>I am trying to create a new website on a remote server via msbuild (I like to call it "msdeploy"). I've downloaded and used the SDC tasks, the MSBuildExtension tasks and the MSBuildCommunity tasks but I simply can't get it right.</p>
<p>I figure that WebDirectorySetting (from MSBuild.Community.Tasks.IIS) is my best bet but I can't find the right SettingName to pass.</p>
<p>I'd like to use some sort of MSBuild task to accomplish this but maybe it just doesn't exist. Custom VBS or WMI are my last resort...</p>
<p>Thanks</p>
| [
{
"answer_id": 2886859,
"author": "Eduardo Xavier",
"author_id": 107452,
"author_profile": "https://Stackoverflow.com/users/107452",
"pm_score": 0,
"selected": false,
"text": "<WebDirectoryCreate\n ServerName=\"$(DeployServerName)\" \n VirtualDirectoryName=\"MyVirualSiteName\" />\n <InstallAspNet \n Path=\"W3SVC/1/Root/MyVirualSiteName\" \n Version=\"Version20\" />\n"
},
{
"answer_id": 3790568,
"author": "ocenteno",
"author_id": 145480,
"author_profile": "https://Stackoverflow.com/users/145480",
"pm_score": 2,
"selected": false,
"text": "<MSBuild.ExtensionPack.Web.Iis7AppPool TaskAction=\"Create\"\n Name=\"$(AppPool)\"\n IdentityType=\"SpecificUser\" \n PipelineMode=\"Integrated\"\n ManagedRuntimeVersion=\"v4.0\"\n PoolIdentity=\"$(UserName)\"\n IdentityPassword=\"$(UserPassword)\"\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44714/"
] |
353,982 | <p>because i read that one of the advantages of <a href="http://en.wikipedia.org/wiki/WS-Discovery" rel="nofollow noreferrer">WS-Discovery</a> that it
"Support both SOAP 1.1 and SOAP 1.2 Envelopes"
so what?</p>
| [
{
"answer_id": 2886859,
"author": "Eduardo Xavier",
"author_id": 107452,
"author_profile": "https://Stackoverflow.com/users/107452",
"pm_score": 0,
"selected": false,
"text": "<WebDirectoryCreate\n ServerName=\"$(DeployServerName)\" \n VirtualDirectoryName=\"MyVirualSiteName\" />\n <InstallAspNet \n Path=\"W3SVC/1/Root/MyVirualSiteName\" \n Version=\"Version20\" />\n"
},
{
"answer_id": 3790568,
"author": "ocenteno",
"author_id": 145480,
"author_profile": "https://Stackoverflow.com/users/145480",
"pm_score": 2,
"selected": false,
"text": "<MSBuild.ExtensionPack.Web.Iis7AppPool TaskAction=\"Create\"\n Name=\"$(AppPool)\"\n IdentityType=\"SpecificUser\" \n PipelineMode=\"Integrated\"\n ManagedRuntimeVersion=\"v4.0\"\n PoolIdentity=\"$(UserName)\"\n IdentityPassword=\"$(UserPassword)\"\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/353982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459737/"
] |
354,002 | <p>I have 2 tables (A and B) with the same primary keys. I want to select all row that are in A and not in B. The following works:</p>
<pre><code>select * from A where not exists (select * from B where A.pk=B.pk);
</code></pre>
<p>however it seems quite bad (~2 sec on only 100k rows in A and 3-10k less in B)</p>
<p>Is there a better way to run this? Perhaps as a left join?</p>
<pre><code>select * from A left join B on A.x=B.y where B.y is null;
</code></pre>
<p>On my data this seems to run slightly faster (~10%) but what about in general?</p>
| [
{
"answer_id": 354059,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 6,
"selected": false,
"text": "SELECT A.* \nfrom A left join B on \n A.x = B.y\n where B.y is null\n"
},
{
"answer_id": 34264638,
"author": "user3136147",
"author_id": 3136147,
"author_profile": "https://Stackoverflow.com/users/3136147",
"pm_score": -1,
"selected": false,
"text": "Joins SELECT tbl1.id FROM tbl1 t1\nLEFT OUTER JOIN tbl2 t2 ON t1.id = t2.id \nWHERE t1.id>=100 AND t2.id IS NULL ;\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
354,005 | <p><strong><code>oPanel = CType(Master.FindControl("panelSearch"), Panel)</code></strong></p>
<p>This code resides on my masterpage's back-end (<strong><code>theMaster.master.vb</code></strong>), but I get a "Cannot refer to an instance member from within a shared class or shared member initializer without an explicit instance of the class"</p>
<p>the function it resides in IS shared, I just can't remember for the life of me what I need to do to make this work.</p>
<p>thanks!</p>
| [
{
"answer_id": 354032,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 3,
"selected": true,
"text": "Shared"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
354,008 | <pre><code>SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value
FROM prodtree_element pe
LEFT JOIN prodtree_link pl
ON pe.prodtree_element_id = pl.to_prodtree_node_id
LEFT JOIN line li
ON pe.line_code = li.line_code
INNER JOIN attribute_values av
ON av.attribute_definition_id = #statusCode#
LEFT JOIN attribute_values av2
ON pe.prodtree_element_id = av.prodtree_element_id
WHERE pe.prodtree_element_func_type <> 'WIZARD'
AND pe.prodtree_element_topo_type = 'NODE'
</code></pre>
<p>"#statusCode#" is a static id that matches an id in the attribute definition table (let's say 22 for the sake of argument). The problem is, the query has some massive trouble finishing in any sane amount of time. The bigger problem is, I kinda need it to finish earlier, but the number of records is enormous that it has to draw back (around 30-50,000). I need data from multiple tables, which is where it starts to slow down. This is just a piece of what I need, I also need an entire other tables worth of data matching the current "prodtree_elment_id".</p>
<p>I'm using ColdFusion but even running the query directly in SQL Server 2005 creates the 15-30+ minute wait for this query (if it even finishes). Is there any conceivable way to speed up this query to take at most 5 minutes or less?</p>
| [
{
"answer_id": 354028,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 0,
"selected": false,
"text": " INNER JOIN attribute_values av\n ON av.attribute_definition_id = #statusCode# \n"
},
{
"answer_id": 354040,
"author": "Jennifer",
"author_id": 22360,
"author_profile": "https://Stackoverflow.com/users/22360",
"pm_score": 0,
"selected": false,
"text": "select * from [bigLongjoin to producttree_element]\nwhere prodtree_element_id\nin(\nselect prodtree_element_id from \n attribute_values where attribute_definition_id = #statusCode#)\n"
},
{
"answer_id": 354048,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 4,
"selected": true,
"text": "INNER JOIN attribute_values av\n ON av.attribute_definition_id = #statusCode# \nLEFT JOIN attribute_values av2\n ON pe.prodtree_element_id = av.prodtree_element_id\n SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value\nFROM prodtree_element pe\nLEFT JOIN prodtree_link pl\n ON pe.prodtree_element_id = pl.to_prodtree_node_id\nLEFT JOIN line li\n ON pe.line_code = li.line_code\n--replacement\nLEFT JOIN\nattribute_values av \n ON pe.prodtree_element_id = av.prodtree_element_id AND\n av.attribute_definition_id = #statusCode# \n--end replacement\nWHERE pe.prodtree_element_func_type <> 'WIZARD'\n AND pe.prodtree_element_topo_type = 'NODE'\n"
},
{
"answer_id": 354051,
"author": "Oscar Cabrero",
"author_id": 14440,
"author_profile": "https://Stackoverflow.com/users/14440",
"pm_score": 0,
"selected": false,
"text": "pe.prodtree_element_func_type <> 'WIZARD'\n AND pe.prodtree_element_topo_type = 'NODE'\n pe.prodtree_element_func_type_ID <> 1\n AND pe.prodtree_element_topo_type_ID = 2\n"
},
{
"answer_id": 354074,
"author": "Will Rickards",
"author_id": 290835,
"author_profile": "https://Stackoverflow.com/users/290835",
"pm_score": 0,
"selected": false,
"text": "SELECT pe.prodtree_element_id prodID, pe.prodtree_element_name_s, li.line_name, av2.value\n FROM prodtree_element pe\n LEFT JOIN prodtree_link pl\n ON (pe.prodtree_element_id = pl.to_prodtree_node_id)\n LEFT JOIN line li\n ON (pe.line_code = li.line_code)\n LEFT JOIN attribute_values av2\n ON (pe.prodtree_element_id IN (SELECT av.prodtree_element_id FROM attribute_values av WHERE av.attribute_definition_id = #statusCode#))\n WHERE pe.prodtree_element_func_type <> 'WIZARD'\n AND pe.prodtree_element_topo_type = 'NODE'\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16631/"
] |
354,010 | <p>Ok, so we have a bunch of tables that are named like this:</p>
<pre><code>training_data_001
training_data_002
training_data_003
training_data_004
training_data_005
</code></pre>
<p>And then to find those we look at a field in another table, let's just call it master.training_type.</p>
<p>Anyway, I was wondering if anyone knew of a way to do a weird table name based join with this kind of data. Something like this:</p>
<pre><code>SELECT foo FROM master WHERE id = ?
INNER JOIN training_data_${master.training_type}
ON foo.id = training_data_${master.training_type}.foo_id
</code></pre>
<p>I know that I can do this on the client side, but it would be nice to have the db do it.</p>
<p>Also note: it's SQL Server.</p>
<p><strong>Update</strong>: I decided to just do it on the client side. Thanks anyway everyone.</p>
<p>Thanks!</p>
<p>-fREW</p>
| [
{
"answer_id": 354013,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 2,
"selected": false,
"text": "EXEC (@stringvar)"
},
{
"answer_id": 354102,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 1,
"selected": false,
"text": "create view training_data_all as\nselect '001' as training_type, * from training_data_001\nunion all\nselect '002' as training_type, * from training_data_002\nunion all\nselect '003' as training_type, * from training_data_003\nunion all\nselect '004' as training_type, * from training_data_004\nunion all\nselect '005' as training_type, * from training_data_005\n SELECT foo FROM master WHERE id = ? \nINNER JOIN training_data_all\nON foo.id = training_data_all.foo_id\nWHERE training_data_all.training_type = ${master.training_type}\n"
},
{
"answer_id": 354165,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "SELECT\n foo\nFROM\n dbo.master m\nWHERE\n (training_type = '001' AND EXISTS (SELECT * FROM dbo.training_data_001 WHERE foo_id = m.id)) OR\n (training_type = '002' AND EXISTS (SELECT * FROM dbo.training_data_002 WHERE foo_id = m.id)) OR\n (training_type = '003' AND EXISTS (SELECT * FROM dbo.training_data_003 WHERE foo_id = m.id)) OR\n (training_type = '004' AND EXISTS (SELECT * FROM dbo.training_data_004 WHERE foo_id = m.id)) OR\n (training_type = '005' AND EXISTS (SELECT * FROM dbo.training_data_005 WHERE foo_id = m.id))\n SELECT\n m.id,\n COALESCE(t1.my_col, t2.my_col, t3.my_col, t4.my_col, t5.my_col) AS my_col\nFROM\n dbo.master m\nLEFT OUTER JOIN dbo.training_data_001 t1 ON m.training_type = '001' AND t1.foo_id = m.id\nLEFT OUTER JOIN dbo.training_data_002 t1 ON m.training_type = '002' AND t2.foo_id = m.id\nLEFT OUTER JOIN dbo.training_data_003 t1 ON m.training_type = '003' AND t3.foo_id = m.id\nLEFT OUTER JOIN dbo.training_data_004 t1 ON m.training_type = '004' AND t4.foo_id = m.id\nLEFT OUTER JOIN dbo.training_data_005 t1 ON m.training_type = '005' AND t5.foo_id = m.id\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12448/"
] |
354,019 | <p>I have a UI-dialog something like this: You must choose a book from a list. Optionally, you can either choose a publisher (another class) from a list or enter the publisher-name as as a string. </p>
<p>I think this gives me 3 types as the output from the dialog.</p>
<ol>
<li>book</li>
<li>book with publisher-class</li>
<li>book with publisher-string</li>
</ol>
<p>How would you model this in objects? It seems to me that the having a book base-class, and then two subclasses for publisher and publisher name is the correct choice. Are there any alternatives, perhaps favoring composition that would give a better model?</p>
<hr>
<p>I'll try to explain a bit more.
A book doesn't need to have a publisher.
The publisher object is not the same as a publisher-name entered as a string.</p>
<p>You must<br>
-choose a book from an existing list </p>
<p>You can one of the following<br>
-choose a publisher from an existing list or<br>
-you can enter a publisher name or<br>
-you can fill nothing about the publisher </p>
| [
{
"answer_id": 354220,
"author": "Eric",
"author_id": 42461,
"author_profile": "https://Stackoverflow.com/users/42461",
"pm_score": 0,
"selected": false,
"text": "Class Book\n{\n public string Name;\n public List<Publisher> publishers = new List<Publishers>;\n\n Book()\n {\n // Load publishers array with relevant instances of Publisher class...\n }\n}\n\nClass Books\n{\n private List<Book> books = new List<Book>;\n public Books()\n {\n // Load books array with all books...\n }\n\n public List<Book> GetBook (string publisher)\n {\n List<Book> retVal = new List<Book>;\n foreach (Book item in books)\n {\n if (item.Publisher.Name == publisher)\n {\n retVal.Add(item);\n }\n }\n }\n\n public List<Book> GetBook (Publisher publisher)\n {\n List<Book> retVal = new List<Book>;\n foreach (Book item in books)\n {\n if (item.Publisher.Name == publisher.Name)\n {\n retVal.Add(item);\n }\n }\n }\n}\n\nClass Publisher\n{\n public string Name;\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44726/"
] |
354,037 | <p>I am looking for a way to determine what the Name/IP Address of the domain controller is for a given domain that a client computer is connected to.</p>
<p>At our company we have a lot of small little networks that we use for testing and most of them have their own little domains. As an example, one of the domains is named "TESTLAB". I have an Windows XP workstation that is a member of the TESTLAB domain and I am trying to figure out the name of the domain controller so that I can go and look to see what users have been defined for the domain. In our lab there is a mix of Windows Server 2000 and Windows Server 2003 (and in reality probably a couple of NT 4 Servers) so it would be nice to find a solution that would work for both.</p>
<p>Looking on the Internet, it looks like there are various utilities, such as Windows Power Shell or nltest, but these all require that you download and install other utilities. I was hoping to find a way to find the domain controller without having to install anything additional.</p>
<p><strong>EDIT</strong> If I wanted to write a program to find the domain controller or the users in the current domain, how would I go about doing that?</p>
| [
{
"answer_id": 354128,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": false,
"text": "using (PrincipalContext context = new PrincipalContext(ContextType.Domain))\n{\n string controller = context.ConnectedServer;\n Console.WriteLine( \"Domain Controller:\" + controller );\n} \n using (PrincipalContext context = new PrincipalContext(ContextType.Domain))\n{\n using (UserPrincipal searchPrincipal = new UserPrincipal(context))\n {\n using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))\n {\n foreach (UserPrincipal principal in searcher.FindAll())\n {\n Console.WriteLine( principal.SamAccountName);\n }\n }\n }\n}\n"
},
{
"answer_id": 354210,
"author": "MZywitza",
"author_id": 44243,
"author_profile": "https://Stackoverflow.com/users/44243",
"pm_score": 9,
"selected": true,
"text": "echo %LOGONSERVER%\n"
},
{
"answer_id": 13361585,
"author": "Brett Veenstra",
"author_id": 307,
"author_profile": "https://Stackoverflow.com/users/307",
"pm_score": 1,
"selected": false,
"text": "DomainController DirectoryContext domainContext = new DirectoryContext(DirectoryContextType.Domain, \"targetDomainName\", \"validUserInDomain\", \"validUserPassword\");\n\n var domain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(domainContext);\n var controller = domain.FindDomainController();\n"
},
{
"answer_id": 14150396,
"author": "ErikE",
"author_id": 57611,
"author_profile": "https://Stackoverflow.com/users/57611",
"pm_score": 3,
"selected": false,
"text": "gpresult"
},
{
"answer_id": 32885029,
"author": "Lado Morela",
"author_id": 5396998,
"author_profile": "https://Stackoverflow.com/users/5396998",
"pm_score": 4,
"selected": false,
"text": "nltest /dclist:{domainname}\n"
},
{
"answer_id": 49127468,
"author": "Wim",
"author_id": 9450327,
"author_profile": "https://Stackoverflow.com/users/9450327",
"pm_score": 3,
"selected": false,
"text": "$env:logonserver"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34508/"
] |
354,038 | <p>How do I check if a string represents a numeric value in Python?</p>
<pre><code>def is_number(s):
try:
float(s)
return True
except ValueError:
return False
</code></pre>
<p>The above works, but it seems clunky.</p>
<hr />
<p><sub>If what you are testing comes from user input, it is <em>still</em> a string <em>even if it represents</em> an <code>int</code> or a <code>float</code>. See <a href="https://stackoverflow.com/questions/20449427/">How can I read inputs as numbers?</a> for converting the input, and <a href="https://stackoverflow.com/questions/23294658/">Asking the user for input until they give a valid response</a> for ensuring that the input represents an <code>int</code> or <code>float</code> (or other requirements) before proceeding.</sub></p>
| [
{
"answer_id": 354073,
"author": "Zoomulator",
"author_id": 44563,
"author_profile": "https://Stackoverflow.com/users/44563",
"pm_score": 11,
"selected": false,
"text": "isdigit() >>> a = \"03523\"\n>>> a.isdigit()\nTrue\n>>> b = \"963spam\"\n>>> b.isdigit()\nFalse\n isdigit() isnumeric()"
},
{
"answer_id": 1139186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "try:\n myvar.append( float(string_to_check) )\nexcept:\n continue\n"
},
{
"answer_id": 3335060,
"author": "Matthew Wilcoxson",
"author_id": 266375,
"author_profile": "https://Stackoverflow.com/users/266375",
"pm_score": 6,
"selected": false,
"text": "def is_number(s):\n try:\n complex(s) # for int, long, float and complex\n except ValueError:\n return False\n\n return True\n def is_number(s):\n try:\n float(s) # for int, long and float\n except ValueError:\n try:\n complex(s) # for complex\n except ValueError:\n return False\n\n return True\n"
},
{
"answer_id": 3618897,
"author": "W7GVR",
"author_id": 339667,
"author_profile": "https://Stackoverflow.com/users/339667",
"pm_score": 6,
"selected": false,
"text": ">>> float('NaN')\nnan\n"
},
{
"answer_id": 9337733,
"author": "Evan Plaice",
"author_id": 290340,
"author_profile": "https://Stackoverflow.com/users/290340",
"pm_score": 4,
"selected": false,
"text": "def parse(string):\n try:\n return float(string)\n except Exception:\n throw TypeError\n def try_parse(string, fail=None):\n try:\n return float(string)\n except Exception:\n return fail;\n def monkey_patch():\n if(!hasattr(float, 'parse')):\n float.parse = parse\n if(!hasattr(float, 'try_parse')):\n float.try_parse = try_parse\n float.parse('giggity') // throws TypeException\nfloat.parse('54.3') // returns the scalar value 54.3\nfloat.tryParse('twank') // returns None\nfloat.tryParse('32.2') // returns the scalar value 32.2\n"
},
{
"answer_id": 9842626,
"author": "a1an",
"author_id": 1006828,
"author_profile": "https://Stackoverflow.com/users/1006828",
"pm_score": 3,
"selected": false,
"text": "def is_number(s):\n try:\n n=str(float(s))\n if n == \"nan\" or n==\"inf\" or n==\"-inf\" : return False\n except ValueError:\n try:\n complex(s) # for complex\n except ValueError:\n return False\n return True\n"
},
{
"answer_id": 10762002,
"author": "haxwithaxe",
"author_id": 1137459,
"author_profile": "https://Stackoverflow.com/users/1137459",
"pm_score": 6,
"selected": false,
"text": "'3.14'.replace('.','',1).isdigit()\n '3.14.5'.replace('.','',1).isdigit()\n .replace(badstuff,'',maxnum_badstuff)"
},
{
"answer_id": 14352314,
"author": "Ron Reiter",
"author_id": 741628,
"author_profile": "https://Stackoverflow.com/users/741628",
"pm_score": 3,
"selected": false,
"text": "check_replace check_exception check_exception huge_number = float('1e+100')\n import time, re, random, string\n\nITERATIONS = 10000000\n\nclass Timer: \n def __enter__(self):\n self.start = time.clock()\n return self\n def __exit__(self, *args):\n self.end = time.clock()\n self.interval = self.end - self.start\n\ndef check_regexp(x):\n return re.compile(\"^\\d*\\.?\\d*$\").match(x) is not None\n\ndef check_replace(x):\n return x.replace('.','',1).isdigit()\n\ndef check_exception(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\nto_check = [check_regexp, check_replace, check_exception]\n\nprint('preparing data...')\ngood_numbers = [\n str(random.random() / random.random()) \n for x in range(ITERATIONS)]\n\nbad_numbers = ['.' + x for x in good_numbers]\n\nstrings = [\n ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randint(1,10)))\n for x in range(ITERATIONS)]\n\nprint('running test...')\nfor func in to_check:\n with Timer() as t:\n for x in good_numbers:\n res = func(x)\n print('%s with good floats: %s' % (func.__name__, t.interval))\n with Timer() as t:\n for x in bad_numbers:\n res = func(x)\n print('%s with bad floats: %s' % (func.__name__, t.interval))\n with Timer() as t:\n for x in strings:\n res = func(x)\n print('%s with strings: %s' % (func.__name__, t.interval))\n check_regexp with good floats: 12.688639\ncheck_regexp with bad floats: 11.624862\ncheck_regexp with strings: 11.349414\ncheck_replace with good floats: 4.419841\ncheck_replace with bad floats: 4.294909\ncheck_replace with strings: 4.086358\ncheck_exception with good floats: 3.276668\ncheck_exception with bad floats: 13.843092\ncheck_exception with strings: 15.786169\n check_regexp with good floats: 13.472906000000009\ncheck_regexp with bad floats: 12.977665000000016\ncheck_regexp with strings: 12.417542999999995\ncheck_replace with good floats: 6.011045999999993\ncheck_replace with bad floats: 4.849356\ncheck_replace with strings: 4.282754000000011\ncheck_exception with good floats: 6.039081999999979\ncheck_exception with bad floats: 9.322753000000006\ncheck_exception with strings: 9.952595000000002\n check_regexp with good floats: 2.693217\ncheck_regexp with bad floats: 2.744819\ncheck_regexp with strings: 2.532414\ncheck_replace with good floats: 0.604367\ncheck_replace with bad floats: 0.538169\ncheck_replace with strings: 0.598664\ncheck_exception with good floats: 1.944103\ncheck_exception with bad floats: 2.449182\ncheck_exception with strings: 2.200056\n"
},
{
"answer_id": 15205926,
"author": "Blackzafiro",
"author_id": 1998670,
"author_profile": "https://Stackoverflow.com/users/1998670",
"pm_score": 4,
"selected": false,
"text": ">>> s = u\"345\"\n>>> s.isnumeric()\nTrue\n >>> s = \"345\"\n>>> u = unicode(s)\n>>> u.isnumeric()\nTrue\n"
},
{
"answer_id": 16743970,
"author": "Thruston",
"author_id": 1274254,
"author_profile": "https://Stackoverflow.com/users/1274254",
"pm_score": 0,
"selected": false,
"text": "import sys\n\ndef fix_quotes(s):\n try:\n float(s)\n return s\n except ValueError:\n return '\"{0}\"'.format(s)\n\nfor line in sys.stdin:\n input = line.split()\n print input[0], '<- c(', ','.join(fix_quotes(c) for c in input[1:]), ')'\n"
},
{
"answer_id": 17926244,
"author": "philh",
"author_id": 2265468,
"author_profile": "https://Stackoverflow.com/users/2265468",
"pm_score": 2,
"selected": false,
"text": "x-1 == x 2.0**54 - 1 == 2.0**54"
},
{
"answer_id": 23639915,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "s.replace('.','',1).isdigit() def is_number_tryexcept(s):\n \"\"\" Returns True is string is a number. \"\"\"\n try:\n float(s)\n return True\n except ValueError:\n return False\n\nimport re \ndef is_number_regex(s):\n \"\"\" Returns True is string is a number. \"\"\"\n if re.match(\"^\\d+?\\.\\d+?$\", s) is None:\n return s.isdigit()\n return True\n\n\ndef is_number_repl_isdigit(s):\n \"\"\" Returns True is string is a number. \"\"\"\n return s.replace('.','',1).isdigit()\n funcs = [\n is_number_tryexcept, \n is_number_regex,\n is_number_repl_isdigit\n ]\n\na_float = '.1234'\n\nprint('Float notation \".1234\" is not supported by:')\nfor f in funcs:\n if not f(a_float):\n print('\\t -', f.__name__)\n scientific1 = '1.000000e+50'\nscientific2 = '1e50'\n\n\nprint('Scientific notation \"1.000000e+50\" is not supported by:')\nfor f in funcs:\n if not f(scientific1):\n print('\\t -', f.__name__)\n\n\n\n\nprint('Scientific notation \"1e50\" is not supported by:')\nfor f in funcs:\n if not f(scientific2):\n print('\\t -', f.__name__)\n import timeit\n\ntest_cases = ['1.12345', '1.12.345', 'abc12345', '12345']\ntimes_n = {f.__name__:[] for f in funcs}\n\nfor t in test_cases:\n for f in funcs:\n f = f.__name__\n times_n[f].append(min(timeit.Timer('%s(t)' %f, \n 'from __main__ import %s, t' %f)\n .repeat(repeat=3, number=1000000)))\n from re import match as re_match\nfrom re import compile as re_compile\n\ndef is_number_tryexcept(s):\n \"\"\" Returns True is string is a number. \"\"\"\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef is_number_regex(s):\n \"\"\" Returns True is string is a number. \"\"\"\n if re_match(\"^\\d+?\\.\\d+?$\", s) is None:\n return s.isdigit()\n return True\n\n\ncomp = re_compile(\"^\\d+?\\.\\d+?$\") \n\ndef compiled_regex(s):\n \"\"\" Returns True is string is a number. \"\"\"\n if comp.match(s) is None:\n return s.isdigit()\n return True\n\n\ndef is_number_repl_isdigit(s):\n \"\"\" Returns True is string is a number. \"\"\"\n return s.replace('.','',1).isdigit()\n"
},
{
"answer_id": 24559671,
"author": "astrodsg",
"author_id": 3802689,
"author_profile": "https://Stackoverflow.com/users/3802689",
"pm_score": 3,
"selected": false,
"text": "def str_to_type (s):\n \"\"\" Get possible cast type for a string\n\n Parameters\n ----------\n s : string\n\n Returns\n -------\n float,int,str,bool : type\n Depending on what it can be cast to\n\n \"\"\" \n try: \n f = float(s) \n if \".\" not in s:\n return int\n return float\n except ValueError:\n value = s.upper()\n if value == \"TRUE\" or value == \"FALSE\":\n return bool\n return type(s)\n str_to_type(\"true\") # bool\nstr_to_type(\"6.0\") # float\nstr_to_type(\"6\") # int\nstr_to_type(\"6abc\") # str\nstr_to_type(u\"6abc\") # unicode \n s = \"6.0\"\ntype_ = str_to_type(s) # float\nf = type_(s) \n"
},
{
"answer_id": 25299619,
"author": "SethMMorton",
"author_id": 1399279,
"author_profile": "https://Stackoverflow.com/users/1399279",
"pm_score": 4,
"selected": false,
"text": "try: except: from __future__ import print_function\nimport timeit\n\nprep_base = '''\\\nx = 'invalid'\ny = '5402'\nz = '4.754e3'\n'''\n\nprep_try_method = '''\\\ndef is_number_try(val):\n try:\n float(val)\n return True\n except ValueError:\n return False\n\n'''\n\nprep_re_method = '''\\\nimport re\nfloat_match = re.compile(r'[-+]?\\d*\\.?\\d+(?:[eE][-+]?\\d+)?$').match\ndef is_number_re(val):\n return bool(float_match(val))\n\n'''\n\nfn_method = '''\\\nfrom fastnumbers import isfloat\n\n'''\n\nprint('Try with non-number strings', timeit.timeit('is_number_try(x)',\n prep_base + prep_try_method), 'seconds')\nprint('Try with integer strings', timeit.timeit('is_number_try(y)',\n prep_base + prep_try_method), 'seconds')\nprint('Try with float strings', timeit.timeit('is_number_try(z)',\n prep_base + prep_try_method), 'seconds')\nprint()\nprint('Regex with non-number strings', timeit.timeit('is_number_re(x)',\n prep_base + prep_re_method), 'seconds')\nprint('Regex with integer strings', timeit.timeit('is_number_re(y)',\n prep_base + prep_re_method), 'seconds')\nprint('Regex with float strings', timeit.timeit('is_number_re(z)',\n prep_base + prep_re_method), 'seconds')\nprint()\nprint('fastnumbers with non-number strings', timeit.timeit('isfloat(x)',\n prep_base + 'from fastnumbers import isfloat'), 'seconds')\nprint('fastnumbers with integer strings', timeit.timeit('isfloat(y)',\n prep_base + 'from fastnumbers import isfloat'), 'seconds')\nprint('fastnumbers with float strings', timeit.timeit('isfloat(z)',\n prep_base + 'from fastnumbers import isfloat'), 'seconds')\nprint()\n Try with non-number strings 2.39108395576 seconds\nTry with integer strings 0.375686168671 seconds\nTry with float strings 0.369210958481 seconds\n\nRegex with non-number strings 0.748660802841 seconds\nRegex with integer strings 1.02021503448 seconds\nRegex with float strings 1.08564686775 seconds\n\nfastnumbers with non-number strings 0.174362897873 seconds\nfastnumbers with integer strings 0.179651021957 seconds\nfastnumbers with float strings 0.20222902298 seconds\n try: except: fastnumbers"
},
{
"answer_id": 26829047,
"author": "user1508746",
"author_id": 1508746,
"author_profile": "https://Stackoverflow.com/users/1508746",
"pm_score": 2,
"selected": false,
"text": "def string_or_number(s):\n try:\n z = int(s)\n return z\n except ValueError:\n try:\n z = float(s)\n return z\n except ValueError:\n return s\n"
},
{
"answer_id": 30549042,
"author": "TheRedstoneLemon",
"author_id": 4787422,
"author_profile": "https://Stackoverflow.com/users/4787422",
"pm_score": 0,
"selected": false,
"text": " def is_number(var):\n try:\n if var == int(var):\n return True\n except Exception:\n return False\n"
},
{
"answer_id": 32453110,
"author": "Sdwdaw",
"author_id": 5292245,
"author_profile": "https://Stackoverflow.com/users/5292245",
"pm_score": 5,
"selected": false,
"text": "int >>> \"1221323\".isdigit()\nTrue\n float >>> \"12.34\".isdigit()\nFalse\n>>> \"12.34\".replace('.','',1).isdigit()\nTrue\n>>> \"12.3.4\".replace('.','',1).isdigit()\nFalse\n lstrip() >>> '-12'.lstrip('-')\n'12'\n >>> '-12.34'.lstrip('-').replace('.','',1).isdigit()\nTrue\n>>> '.-234'.lstrip('-').replace('.','',1).isdigit()\nFalse\n"
},
{
"answer_id": 34615173,
"author": "Aruthawolf",
"author_id": 1523370,
"author_profile": "https://Stackoverflow.com/users/1523370",
"pm_score": 4,
"selected": false,
"text": "x.isdigit() x.replace('-','').isdigit() x.replace('.','').isdigit() x.replace(':','').isdigit() x.replace('/','',1).isdigit()"
},
{
"answer_id": 40064255,
"author": "mathfac",
"author_id": 1115384,
"author_profile": "https://Stackoverflow.com/users/1115384",
"pm_score": 1,
"selected": false,
"text": "def is_float(text):\n try:\n float(text)\n # check for nan/infinity etc.\n if text.isalpha():\n return False\n return True\n except ValueError:\n return False\n"
},
{
"answer_id": 42437198,
"author": "donald",
"author_id": 5869997,
"author_profile": "https://Stackoverflow.com/users/5869997",
"pm_score": -1,
"selected": false,
"text": "import re\na=re.match('((\\d+[\\.]\\d*$)|(\\.)\\d+$)' , '2.3') \na=re.match('((\\d+[\\.]\\d*$)|(\\.)\\d+$)' , '2.')\na=re.match('((\\d+[\\.]\\d*$)|(\\.)\\d+$)' , '.3')\na=re.match('((\\d+[\\.]\\d*$)|(\\.)\\d+$)' , '2.3sd')\na=re.match('((\\d+[\\.]\\d*$)|(\\.)\\d+$)' , '2.3')\n"
},
{
"answer_id": 48729739,
"author": "Moinuddin Quadri",
"author_id": 2063361,
"author_profile": "https://Stackoverflow.com/users/2063361",
"pm_score": 5,
"selected": false,
"text": "str.isdigit() # For digit\n>>> '1'.isdigit()\nTrue\n>>> '1'.isalpha()\nFalse\n str.isdigit() False # returns `False` for float\n>>> '123.3'.isdigit()\nFalse\n# returns `False` for negative number\n>>> '-123'.isdigit()\nFalse\n float def is_number(n):\n try:\n float(n) # Type-casting the string to `float`.\n # If string is not a valid `float`, \n # it'll raise `ValueError` exception\n except ValueError:\n return False\n return True\n >>> is_number('123') # positive integer number\nTrue\n\n>>> is_number('123.4') # positive float number\nTrue\n \n>>> is_number('-123') # negative integer number\nTrue\n\n>>> is_number('-123.4') # negative `float` number\nTrue\n\n>>> is_number('abc') # `False` for \"some random\" string\nFalse\n True >>> is_number('NaN')\nTrue\n math.isnan() >>> import math\n>>> nan_num = float('nan')\n\n>>> math.isnan(nan_num)\nTrue\n == False nan # `nan_num` variable is taken from above example\n>>> nan_num == nan_num\nFalse\n is_number False \"NaN\" def is_number(n):\n is_number = True\n try:\n num = float(n)\n # check for \"nan\" floats\n is_number = num == num # or use `math.isnan(num)`\n except ValueError:\n is_number = False\n return is_number\n >>> is_number('Nan') # not a number \"Nan\" string\nFalse\n\n>>> is_number('nan') # not a number string \"nan\" with all lower cased\nFalse\n\n>>> is_number('123') # positive integer\nTrue\n\n>>> is_number('-123') # negative integer\nTrue\n\n>>> is_number('-1.12') # negative `float`\nTrue\n\n>>> is_number('abc') # \"some random\" string\nFalse\n is_number"
},
{
"answer_id": 49343274,
"author": "Alex Pinto",
"author_id": 837562,
"author_profile": "https://Stackoverflow.com/users/837562",
"pm_score": -1,
"selected": false,
"text": "[ float(s) for s in list if isFloat(s)]\n def tryParseFloat(s):\n try:\n return(float(s), True)\n except:\n return(None, False)\n\ntupleList = [tryParseFloat(x) for x in list]\nfloats = [v for v,b in tupleList if b]\n"
},
{
"answer_id": 51652091,
"author": "xin.chen",
"author_id": 7603876,
"author_profile": "https://Stackoverflow.com/users/7603876",
"pm_score": 2,
"selected": false,
"text": "import re\ndef is_number(num):\n pattern = re.compile(r'^[-+]?[-0-9]\\d*\\.\\d*|[-+]?\\.?[0-9]\\d*$')\n result = pattern.match(num)\n if result:\n return True\n else:\n return False\n\n\n>>>: is_number('1')\nTrue\n\n>>>: is_number('111')\nTrue\n\n>>>: is_number('11.1')\nTrue\n\n>>>: is_number('-11.1')\nTrue\n\n>>>: is_number('inf')\nFalse\n\n>>>: is_number('-inf')\nFalse\n"
},
{
"answer_id": 52676692,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "a=\"50\" b=50 c=50.1 d=\"50.1\" import ast\nimport numbers \ndef is_numeric(obj):\n if isinstance(obj, numbers.Number):\n return True\n elif isinstance(obj, str):\n nodes = list(ast.walk(ast.parse(obj)))[1:]\n if not isinstance(nodes[0], ast.Expr):\n return False\n if not isinstance(nodes[-1], ast.Num):\n return False\n nodes = nodes[1:-1]\n for i in range(len(nodes)):\n #if used + or - in digit :\n if i % 2 == 0:\n if not isinstance(nodes[i], ast.UnaryOp):\n return False\n else:\n if not isinstance(nodes[i], (ast.USub, ast.UAdd)):\n return False\n return True\n else:\n return False\n >>> is_numeric(\"54\")\nTrue\n>>> is_numeric(\"54.545\")\nTrue\n>>> is_numeric(\"0x45\")\nTrue\n import ast\n\ndef is_float(obj):\n if isinstance(obj, float):\n return True\n if isinstance(obj, int):\n return False\n elif isinstance(obj, str):\n nodes = list(ast.walk(ast.parse(obj)))[1:]\n if not isinstance(nodes[0], ast.Expr):\n return False\n if not isinstance(nodes[-1], ast.Num):\n return False\n if not isinstance(nodes[-1].n, float):\n return False\n nodes = nodes[1:-1]\n for i in range(len(nodes)):\n if i % 2 == 0:\n if not isinstance(nodes[i], ast.UnaryOp):\n return False\n else:\n if not isinstance(nodes[i], (ast.USub, ast.UAdd)):\n return False\n return True\n else:\n return False\n >>> is_float(\"5.4\")\nTrue\n>>> is_float(\"5\")\nFalse\n>>> is_float(5)\nFalse\n>>> is_float(\"5\")\nFalse\n>>> is_float(\"+5.4\")\nTrue\n >>> a=454\n>>> a.isdigit()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'int' object has no attribute 'isdigit'\n>>> a=\"454\"\n>>> a.isdigit()\nTrue\n >>> isinstance(\"54\", int)\nFalse\n>>> isinstance(54, int)\nTrue\n>>> \n >>> isinstance(\"45.1\", float)\nFalse\n>>> isinstance(45.1, float)\nTrue\n"
},
{
"answer_id": 53800165,
"author": "ravi tanwar",
"author_id": 6481925,
"author_profile": "https://Stackoverflow.com/users/6481925",
"pm_score": 2,
"selected": false,
"text": "return True if str1.lstrip('-').replace('.','',1).isdigit() or float(str1) else False\n"
},
{
"answer_id": 56084922,
"author": "David Ljung Madison Stellar",
"author_id": 1795483,
"author_profile": "https://Stackoverflow.com/users/1795483",
"pm_score": 3,
"selected": false,
"text": "# Doesn't properly handle floats missing the integer part, such as \".7\"\nSIMPLE_FLOAT_REGEXP = re.compile(r'^[-+]?[0-9]+\\.?[0-9]+([eE][-+]?[0-9]+)?$')\n# Example \"-12.34E+56\" # sign (-)\n # integer (12)\n # mantissa (34)\n # exponent (E+56)\n\n# Should handle all floats\nFLOAT_REGEXP = re.compile(r'^[-+]?([0-9]+|[0-9]*\\.[0-9]+)([eE][-+]?[0-9]+)?$')\n# Example \"-12.34E+56\" # sign (-)\n # integer (12)\n # OR\n # int/mantissa (12.34)\n # exponent (E+56)\n\ndef is_float(str):\n return True if FLOAT_REGEXP.match(str) else False\n True <- +42\nTrue <- +42.42\nFalse <- +42.42.22\nTrue <- +42.42e22\nTrue <- +42.42E-22\nFalse <- +42.42e-22.8\nTrue <- .42\nFalse <- 42nope\n check_regexp with good floats: 18.001921\ncheck_regexp with bad floats: 17.861423\ncheck_regexp with strings: 17.558862\ncheck_correct_regexp with good floats: 11.04428\ncheck_correct_regexp with bad floats: 8.71211\ncheck_correct_regexp with strings: 8.144161\ncheck_replace with good floats: 6.020597\ncheck_replace with bad floats: 5.343049\ncheck_replace with strings: 5.091642\ncheck_exception with good floats: 5.201605\ncheck_exception with bad floats: 23.921864\ncheck_exception with strings: 23.755481\n"
},
{
"answer_id": 57516860,
"author": "Samantha Atkins",
"author_id": 423560,
"author_profile": "https://Stackoverflow.com/users/423560",
"pm_score": 1,
"selected": false,
"text": "def if_ok(fn, string):\n try:\n return fn(string)\n except Exception as e:\n return None\n if_ok(int, my_str) or if_ok(float, my_str) or if_ok(complex, my_str)\nis_number = lambda s: any([if_ok(fn, s) for fn in (int, float, complex)])\n"
},
{
"answer_id": 61014322,
"author": "Amir Saniyan",
"author_id": 309798,
"author_profile": "https://Stackoverflow.com/users/309798",
"pm_score": 1,
"selected": false,
"text": "def is_float(s):\n if s is None:\n return False\n\n if len(s) == 0:\n return False\n\n digits_count = 0\n dots_count = 0\n signs_count = 0\n\n for c in s:\n if '0' <= c <= '9':\n digits_count += 1\n elif c == '.':\n dots_count += 1\n elif c == '-' or c == '+':\n signs_count += 1\n else:\n return False\n\n if digits_count == 0:\n return False\n\n if dots_count > 1:\n return False\n\n if signs_count > 1:\n return False\n\n return True\n"
},
{
"answer_id": 61239204,
"author": "zardosht",
"author_id": 228965,
"author_profile": "https://Stackoverflow.com/users/228965",
"pm_score": 3,
"selected": false,
"text": "str.isnumeric() True False str.isdecimal() True False"
},
{
"answer_id": 65164407,
"author": "Siddharth Satpathy",
"author_id": 10626090,
"author_profile": "https://Stackoverflow.com/users/10626090",
"pm_score": 3,
"selected": false,
"text": "\"1.1\" word = \"1.1\"\n\n\"\".join(word.split(\".\")).isnumeric()\n>>> True\n word = \"1.1\"\n\n\"\".join(word.split(\".\")).isdigit()\n>>> True\n word = \"1.1\"\n\n\"\".join(word.split(\".\")).isdecimal()\n>>> True\n %timeit \"\".join(word.split(\".\")).isnumeric()\n>>> 257 ns ± 12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\n%timeit \"\".join(word.split(\".\")).isdigit()\n>>> 252 ns ± 11 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\n%timeit \"\".join(word.split(\".\")).isdecimal()\n>>> 244 ns ± 7.17 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n"
},
{
"answer_id": 66309594,
"author": "DJ Swarm",
"author_id": 12643931,
"author_profile": "https://Stackoverflow.com/users/12643931",
"pm_score": 0,
"selected": false,
"text": "# is_number() function - Uses re = regex library\n# Should handle all normal and complex numbers\n# Does not accept trailing spaces. \n# Note: accepts both engineering \"j\" and math \"i\" but only the imaginary part \"+bi\" of a complex number a+bi\n# Also accepts inf or NaN\n# Thanks to the earlier responders for most the regex fu\n\nimport re\n\nISNUM_REGEXP = re.compile(r'^[-+]?([0-9]+|[0-9]*\\.[0-9]+)([eE][-+]?[0-9]+)?[ij]?$')\n\ndef is_number(str):\n#change order if you have a lot of NaN or inf to parse\n if ISNUM_REGEXP.match(str) or str == \"NaN\" or str == \"inf\": \n return True \n else:\n return False\n# A couple test numbers\n# +42.42e-42j\n# -42.42E+42i\n\nprint('Is it a number?', is_number(input('Gimme any number: ')))\n"
},
{
"answer_id": 68410683,
"author": "Micka",
"author_id": 2199605,
"author_profile": "https://Stackoverflow.com/users/2199605",
"pm_score": 0,
"selected": false,
"text": "is this human written string with keyboard a number def isNumeric(string):\n result = True\n try:\n x = float(string)\n result = (x == x) and (x - 1 != x)\n except ValueError:\n result = False\n return result\n (+-)NaN (+-)inf"
},
{
"answer_id": 68780861,
"author": "Gru",
"author_id": 4779812,
"author_profile": "https://Stackoverflow.com/users/4779812",
"pm_score": 1,
"selected": false,
"text": "def get_number_from_string(value):\n try:\n int_value = int(value)\n return int_value\n\n except ValueError:\n return float(value)\n float int ValueError float"
},
{
"answer_id": 70597776,
"author": "Rafael Braga",
"author_id": 8616292,
"author_profile": "https://Stackoverflow.com/users/8616292",
"pm_score": 0,
"selected": false,
"text": "def is_number(value):\n return type(value) in [int, float]\n def isNumber (value):\n return True if type(value) in [int, float] else str(value).replace('.','',1).isdigit()\n >>> isNumber(1)\nTrue\n\n>>> isNumber(1/3)\nTrue\n\n>>> isNumber(1.3)\nTrue\n\n>>> isNumber('1.3')\nTrue\n\n>>> isNumber('s1.3')\nFalse\n"
},
{
"answer_id": 74580030,
"author": "Amit",
"author_id": 7480460,
"author_profile": "https://Stackoverflow.com/users/7480460",
"pm_score": 0,
"selected": false,
"text": "## Check whether it is not alpha rather than checking if it is digit\nprint(not \"-1.2345\".isalpha())\nprint(not \"-1.2345e-10\".isalpha())\n Valid_Numbers = [\"1\",\"-1\",\"+1\",\"0.0\",\".1\",\"1.2345\",\"-1.2345\",\"+1.2345\",\"1.2345e10\",\"1.2345e-10\",\"-1.2345e10\",\"-1.2345E10\",\"-inf\"]\nInvalid_Numbers = [\"1.1.1\",\"++1\",\"--1\",\"-1-1\",\"1.23e10e5\",\"--inf\"]\n\n################################ Condition 1: Valid number excludes 'inf' ####################################\n\nCase_1_Positive_Result = list(map(lambda x: not x.isalpha(),Valid_Numbers))\nprint(\"The below must all be True\")\nprint(Case_1_Positive_Result)\n\n## This check assumes a valid number. So it fails for the negative cases and wrongly detects string as number\nCase_1_Negative_Result = list(map(lambda x: not x.isalpha(),Invalid_Numbers))\nprint(\"The below must all be False\")\nprint(Case_1_Negative_Result)\n The below must all be True\n[True, True, True, True, True, True, True, True, True, True, True, True, True]\nThe below must all be False\n[True, True, True, True, True, True]\n ################################ Condition 2: Valid number includes 'inf' ###################################\nCase_2_Positive_Result = list(map(lambda x: x==\"inf\" or not x.isalpha(),Valid_Numbers+[\"inf\"]))\nprint(\"The below must all be True\")\nprint(Case_2_Positive_Result)\n\n## This check assumes a valid number. So it fails for the negative cases and wrongly detects string as number\nCase_2_Negative_Result = list(map(lambda x: x==\"inf\" or not x.isalpha(),Invalid_Numbers+[\"++inf\"]))\nprint(\"The below must all be False\")\nprint(Case_2_Negative_Result)\n The below must all be True\n[True, True, True, True, True, True, True, True, True, True, True, True, True, True]\nThe below must all be False\n[True, True, True, True, True, True, True]\n import re\nCompiledPattern = re.compile(r\"([+-]?(inf){1}$)|([+-]?[0-9]*\\.?[0-9]*$)|([+-]?[0-9]*\\.?[0-9]*[eE]{1}[+-]?[0-9]*$)\")\nCase_3_Positive_Result = list(map(lambda x: True if CompiledPattern.match(x) else False,Valid_Numbers+[\"inf\"]))\nprint(\"The below must all be True\")\nprint(Case_3_Positive_Result)\n\n## This check assumes a valid number. So it fails for the negative cases and wrongly detects string as number\nCase_3_Negative_Result = list(map(lambda x: True if CompiledPattern.match(x) else False,Invalid_Numbers+[\"++inf\"]))\nprint(\"The below must all be False\")\nprint(Case_3_Negative_Result)\n The below must all be True\n[True, True, True, True, True, True, True, True, True, True, True, True, True, True]\nThe below must all be False\n[False, False, False, False, False, False, False]\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40115/"
] |
354,044 | <p>A quick search for currency regex brings up <a href="https://regexlib.com/Search.aspx?k=currency&c=-1&m=-1&ps=20" rel="noreferrer">a lot of results</a>.</p>
<p>The problem I have in choosing one is that regex is difficult to verify without testing all the edge cases. Does anyone have a regex for U.S. currency that has been <em>thoroughly tested</em>?</p>
<p>My only requirement is that the matched string is U.S. currency and parses to <code>System.Decimal</code>:</p>
<pre>
[ws][sign][digits,]digits[.fractional-digits][ws]
Elements in square brackets ([ and ]) are optional.
The following table describes each element.
ELEMENT DESCRIPTION
ws Optional white space.
sign An optional sign.
digits A sequence of digits ranging from 0 to 9.
, A culture-specific thousands separator symbol.
. A culture-specific decimal point symbol.
fractional-digits A sequence of digits ranging from 0 to 9.
</pre>
| [
{
"answer_id": 354216,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 8,
"selected": true,
"text": "Match; JGsoft:\n^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*\\.[0-9]{2}$\n Match; JGsoft:\n^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\\.[0-9]{2})?$\n Match; JGsoft:\n^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{2})?|(?:,[0-9]{3})*(?:\\.[0-9]{2})?|(?:\\.[0-9]{3})*(?:,[0-9]{2})?)$\n"
},
{
"answer_id": 354276,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "\"^\\$?\\-?([1-9]{1}[0-9]{0,2}(\\,\\d{3})*(\\.\\d{0,2})?|[1-9]{1}\\d{0,}(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^\\-?\\$?([1-9]{1}\\d{0,2}(\\,\\d{3})*(\\.\\d{0,2})?|[1-9]{1}\\d{0,}(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))$|^\\(\\$?([1-9]{1}\\d{0,2}(\\,\\d{3})*(\\.\\d{0,2})?|[1-9]{1}\\d{0,}(\\.\\d{0,2})?|0(\\.\\d{0,2})?|(\\.\\d{1,2}))\\)$\"\n"
},
{
"answer_id": 354365,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 4,
"selected": false,
"text": "^-?(?:0|[1-9]\\d{0,2}(?:,?\\d{3})*)(?:\\.\\d+)?$\n 0\n1\n33\n555\n4,656\n4656\n99,785\n125,944\n7,994,169\n7994169\n0.00\n1.0\n33.78795\n555.12\n4,656.489\n99,785.01\n125,944.100\n-7,994,169\n-7994169.23 // Borderline...\n\nWrong:\n000\n01\n3,3\n5.\n555,\n,656\n99,78,5\n1,25,944\n--7,994,169\n0.0,0\n.10\n33.787,95\n4.656.489\n99.785,01\n1-125,944.1\n-7,994E169\n"
},
{
"answer_id": 7186237,
"author": "NoviceProgrammer",
"author_id": 582055,
"author_profile": "https://Stackoverflow.com/users/582055",
"pm_score": 1,
"selected": false,
"text": "CurrencyPositivePattern \nCurrencyGroupSeparator\nCurrencyDecimalSeparator\n NumberFormatInfo NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;\n // Assign needed property values to variables.\n string currencySymbol = nfi.CurrencySymbol;\n bool symbolPrecedesIfPositive = nfi.CurrencyPositivePattern % 2 == 0;\n string groupSeparator = nfi.CurrencyGroupSeparator;\n string decimalSeparator = nfi.CurrencyDecimalSeparator;\n\n // Form regular expression pattern.\n string pattern = Regex.Escape( symbolPrecedesIfPositive ? currencySymbol : \"\") + \n @\"\\s*[-+]?\" + \"([0-9]{0,3}(\" + groupSeparator + \"[0-9]{3})*(\" + \n Regex.Escape(decimalSeparator) + \"[0-9]+)?)\" + \n (! symbolPrecedesIfPositive ? currencySymbol : \"\"); \n"
},
{
"answer_id": 8311352,
"author": "eitanpo",
"author_id": 377973,
"author_profile": "https://Stackoverflow.com/users/377973",
"pm_score": 2,
"selected": false,
"text": "^-?0*(?:\\d+(?!,)(?:\\.\\d{1,2})?|(?:\\d{1,3}(?:,\\d{3})*(?:\\.\\d{1,2})?))$\n ^\\$?-?0*(?:\\d+(?!,)(?:\\.\\d{1,2})?|(?:\\d{1,3}(?:,\\d{3})*(?:\\.\\d{1,2})?))$\n \\( and \\)\n"
},
{
"answer_id": 13845407,
"author": "JoshMahowald",
"author_id": 252402,
"author_profile": "https://Stackoverflow.com/users/252402",
"pm_score": 1,
"selected": false,
"text": "case class CurrencyValue(dollars:Int,cents:Int)\ndef cents = \"\"\"[\\.\\,]\"\"\".r ~> \"\"\"\\d{0,2}\"\"\".r ^^ {\n _.toInt\n}\ndef dollarAmount: Parser[Int] = \"\"\"[1-9]{1}[0-9]{0,2}\"\"\".r ~ opt( \"\"\"[\\.\\,]\"\"\".r ~> \"\"\"\\d{3}\"\"\".r) ^^ {\n case x ~ Some(y) => x.toInt * 1000 + y.toInt\n case x ~ None => x.toInt\n}\ndef usCurrencyParser = \"\"\"(\\$\\s*)?\"\"\".r ~> dollarAmount ~ opt(cents) <~ opt( \"\"\"(?i)dollars?\"\"\".r) ^^ {\n case d ~ Some(change) => CurrencyValue(d, change)\n case d ~ None => CurrencyValue(d, 0)\n}\n"
},
{
"answer_id": 14174261,
"author": "jim",
"author_id": 914708,
"author_profile": "https://Stackoverflow.com/users/914708",
"pm_score": 2,
"selected": false,
"text": "\\$\\ ?[+-]?[0-9]{1,3}(?:,?[0-9])*(?:\\.[0-9]{1,2})?\n $46,48382\n$4,648,382\n$ 4,648,382\n$4,648,382.20\n$4,648,382.2\n$4,6483,82.20\n$46,48382 70.25PD\n$ 46,48382 70.25PD\n"
},
{
"answer_id": 27491430,
"author": "Leandro Bardelli",
"author_id": 888472,
"author_profile": "https://Stackoverflow.com/users/888472",
"pm_score": 2,
"selected": false,
"text": "\"^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{1})?|(?:,[0-9]{3})*(?:\\.[0-9]{1,2})?|(?:\\.[0-9]{3})*(?:,[0-9]{1,2})?)$\n"
},
{
"answer_id": 37770292,
"author": "Dan L",
"author_id": 667772,
"author_profile": "https://Stackoverflow.com/users/667772",
"pm_score": 2,
"selected": false,
"text": "jquery.inputmask autoNumeric"
},
{
"answer_id": 38255759,
"author": "MIkee",
"author_id": 615379,
"author_profile": "https://Stackoverflow.com/users/615379",
"pm_score": 1,
"selected": false,
"text": "^\\$\\d{1,3}\\.[0-9]{2}$|^\\$(\\d{1,3},)+\\d{3}\\.[0-9]{2}$\n ^[+-]?\\$\\d{1,3}\\.[0-9]{2}$|^[+-]?\\$(\\d{1,3},)+\\d{3}\\.[0-9]{2}$\n"
},
{
"answer_id": 51092882,
"author": "henrywright88404",
"author_id": 5275045,
"author_profile": "https://Stackoverflow.com/users/5275045",
"pm_score": 1,
"selected": false,
"text": "^(?:[$]|) ^(?:[$]|)[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{1})?|(?:,[0-9]{3})*(?:\\.[0-9]{1,2})?|(?:\\.[0-9]{3})*(?:,[0-9]{1,2})?)$\n 136,402.99\n25.27\n0.33\n$584.56\n1\n00.2\n3,254,546.00\n$3,254,546.00\n00.01\n-0.25\n+0.85\n+100,052.00\n 11124.52\n234223425.345\n234.\n.5234\na\na.23\n32.a\na.a\nz548,452.22\nu66.36\n"
},
{
"answer_id": 63249827,
"author": "Sal Coraccio IV",
"author_id": 6872967,
"author_profile": "https://Stackoverflow.com/users/6872967",
"pm_score": 2,
"selected": false,
"text": "/^[-]?[$]\\d{1,3}(?:,?\\d{3})*\\.\\d{2}$/ \\d [0-9]"
},
{
"answer_id": 70278278,
"author": "Fernando Gonzalez",
"author_id": 6387267,
"author_profile": "https://Stackoverflow.com/users/6387267",
"pm_score": 0,
"selected": false,
"text": "(?:\\,|\\.?\\d)*\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] |
354,045 | <p>I am considering writing two limited precision alternatives to BigDecimal, namely DecimalInt and DecimalLong. These would be capable of dealing with numbers within the real bounds of int and long with an arbitrary number of decimal places, creatable in both mutable and immutable form. My plan is to make DecimalInt support +/-999,999,999 to +/- 0.999999999 and DecimalLong the same, but with up to 18 digits.</p>
<p>This would be done by maintaining a decimal digit count value of 0-9 for DecimalInt and 0-18 for DecimalLong along side the actual value stored as a scaled int or long. The normal use would be for small numbers of decimals such as for money and stock prices, typically 2-4 decimal places.</p>
<p>The essential requirements are (a) lean footprint (2 classes, plus OverflowException), and (b) full support of all basic operations plus all of Math that makes sense.</p>
<p>Googling for results did not return any obvious hits - they all seemed to pertain to arbitrary decimals.</p>
<p>My questions are: Has this already been done? Are there hidden subtleties in this which is why it has not already been done? Has anyone heard rumors of Java supporting a decimal type like DotNet's.</p>
<p>EDIT: This is different from BigDecimal because it should be (a) a hell of a lot more efficient to not deal with an array of ints, and (b) it won't wrap BigInteger so it will be leaner on memory too, and (c) it will have a mutable option so it will be faster there as well. In summary - less overhead for the simple use cases like "I want to store a bank balance without the overhead of BigDecimal and the inaccuracy of double".</p>
<p>EDIT: I intend on doing all the math using int or long to avoid the classic problem of: 1586.60-708.75=877.8499999999999 instead of 877.85</p>
| [
{
"answer_id": 4261922,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 0,
"selected": false,
"text": "System.out.printf(\"%.2f%n\", 1586.60-708.75);\n 877.85\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8946/"
] |
354,050 | <p>I am trying to passing in 3 pointers to a DLL function. I have:</p>
<pre>
{
$code=1;
$len=100;
$str=" " x $len;
$function = new Win32::API(DLLNAME,'dllfunction','PPP','V');
$function->Call($code,$str,$len);
}
</pre>
<p>The DLL is defined as <code>void dllfunction(int* a, char* str, int* len);</code> The DLL will modify all the variables pointed by the three pointers.</p>
<p>However, I am segfaulting when I run this. The documentation for <a href="http://search.cpan.org/dist/Win32-API" rel="nofollow noreferrer">Win32::API</a> specified that I should use actual variable name instead of the Perl variable references. Can anyone tell me what I am missing? Thanks.</p>
<p>*more information:</p>
<p>I added <code>printf()</code> in the DLL to print out the address of the three pointers, and <code>printf</code> in Perl to print out the reference of the three variables. And I get the following</p>
<p>DLL : Code = 0x10107458 Error = 0x10046b50 str = 0x10107460</p>
<p>Perl : Code = 0x101311b8 Error = 0x101312a8 str = 0x10131230</p>
<p>Any idea why the DLL is getting the wrong addresses?</p>
<p>****More information</p>
<p>After much debugging, I found out that this is happening when returning from the DLL function. I added printf("done\n"); as the very last line of this DLL function, and this does output, then the program segfaults. I guess its happening in Win32::API? Has anyone experienced this?</p>
<p>Also, I am able to access the initial variables of all the three variables from the DLL. So the pointer is passed correctly, but for some reason it causes a segfault when returning from the DLL. Maybe it's segfaulting when trying to copy the new data into the Perl variable?</p>
| [
{
"answer_id": 354135,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 0,
"selected": false,
"text": "$function->Call(\\$code, \\$str, \\$len)\n"
},
{
"answer_id": 354248,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 0,
"selected": false,
"text": "$function->Call(code, $str, len)\n"
},
{
"answer_id": 354425,
"author": "mpeters",
"author_id": 12094,
"author_profile": "https://Stackoverflow.com/users/12094",
"pm_score": 0,
"selected": false,
"text": "$function->Call('code', 'str', 'len');\n $function->Call('$code', '$str', '$len');\n Win32::API"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44730/"
] |
354,057 | <p>I am begging to use jquery. I have the following call that works in IE7 but not FF 3.0.4. But if I change the <code>null</code> to <code>{}</code> it works fine. Is null not valid for this case and I just got lucky that it worked in IE or is this an error with jquery.</p>
<pre><code>$.post("complexitybar.ashx?a=init&vc=" + validationCode, null, loadInitialValues, "json");
</code></pre>
| [
{
"answer_id": 354079,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "null {} null null"
},
{
"answer_id": 354093,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 4,
"selected": true,
"text": "$.get() $.get('complexitybar.ashx?a=init&vc=...')\n $.post('complexitybar.ashx', 'a=init&vc=...')\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24500/"
] |
354,068 | <p>I have an application that is using Windows Authentication and a SqlRoleProvider for user authentication and role management respectively. It is working fine with my test users that I have added to the database as defaults. The application requires users to login (using Windows credentials) and then be able to use this internal application as a basic "user". If the user needs to be added to a high level role, an admin would be responsible for this after the first log in.</p>
<p>With that said, how would I add a user to the default role when they first log in? Logically, I know that I would need to call Roles.IsUserInRole() and then add them if they are not; however, where would I do this? I'm having trouble locating which event in the Global.asax to use.</p>
<p>Thanks</p>
<p><strong>EDIT:</strong>
To expand the scenario a bit, I'm not using a full membership provider system due to requirements on writing new providers to allow the connection string to be stored outside of the web.config. I am not using any form of registration or login page and letting the Windows Integrated Authentication in IIS handle the authentication aspects while my enhanced SqlRoleProvider manages the user roles. The system is working fine for users that I have setup roles via hard coded tests. I am just looking for a way to add new users (who would be authenticated by IIS) to be immediately added to a default "Users" role. I think I found it; however, am now examining ways to make it not fire upon every request for performance reasons.</p>
| [
{
"answer_id": 354105,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 0,
"selected": false,
"text": "user = Membership.GetUser()\nif (user != null)\n{\n // default role \n string[] defaultRoles = {\"MyRole\"};\n\n AddUsersToRoles(user, defaultRoles); \n\n}\n"
},
{
"answer_id": 354198,
"author": "JamesEggers",
"author_id": 28540,
"author_profile": "https://Stackoverflow.com/users/28540",
"pm_score": 2,
"selected": true,
"text": "protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)\n{\n if (!Roles.IsUserInRole(e.Identity.Name, \"Users\"))\n {\n Roles.AddUsersToRole(new string[] { e.Identity.Name }, \"Users\");\n }\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28540/"
] |
354,070 | <p>After reading it, this is <em>not</em> a duplicate of <a href="https://stackoverflow.com/questions/44917/explicit-vs-implicit-sql-joins">Explicit vs Implicit SQL Joins</a>.
The answer may be related (or even the same) but the <strong>question</strong> is different.</p>
<hr>
<p>What is the difference and what should go in each?</p>
<p>If I understand the theory correctly, the query optimizer should be able to use both interchangeably.</p>
| [
{
"answer_id": 354094,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 11,
"selected": true,
"text": "SELECT *\nFROM Orders\nLEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID\nWHERE Orders.ID = 12345\n SELECT *\nFROM Orders\nLEFT JOIN OrderLines ON OrderLines.OrderID=Orders.ID \n AND Orders.ID = 12345\n 12345 12345 INNER JOIN"
},
{
"answer_id": 354095,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 7,
"selected": false,
"text": "INNER JOIN OUTER JOIN"
},
{
"answer_id": 354214,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 6,
"selected": false,
"text": "ON INNER JOIN WHERE LEFT JOIN ON WHERE t2.idfield IS NULL"
},
{
"answer_id": 2711841,
"author": "Le Quang Chien",
"author_id": 325775,
"author_profile": "https://Stackoverflow.com/users/325775",
"pm_score": -1,
"selected": false,
"text": "SELECT song_ID,songs.fullname, singers.fullname\nFROM music JOIN songs ON songs.ID = music.song_ID \nJOIN singers ON singers.ID = music.singer_ID\nGROUP BY songs.fullname\n GROUP BY"
},
{
"answer_id": 20981676,
"author": "Sandeep Jindal",
"author_id": 231567,
"author_profile": "https://Stackoverflow.com/users/231567",
"pm_score": 9,
"selected": false,
"text": "WHERE ON WHERE SELECT documents.name, downloads.id\n FROM documents\n LEFT OUTER JOIN downloads\n ON documents.id = downloads.document_id\n WHERE username = 'sandeep'\n WHERE JOIN SELECT documents.name, downloads.id\n FROM documents\n LEFT OUTER JOIN downloads\n ON documents.id = downloads.document_id\n AND username = 'sandeep'\n documents NULL"
},
{
"answer_id": 21575269,
"author": "Sharon Fernando",
"author_id": 3205687,
"author_profile": "https://Stackoverflow.com/users/3205687",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM employee WHERE employee_id=101\n SELECT * FROM employee \nINNER JOIN employee_details \nON employee.employee_id = employee_details.employee_id\n"
},
{
"answer_id": 23705544,
"author": "Austin Barry",
"author_id": 3646355,
"author_profile": "https://Stackoverflow.com/users/3646355",
"pm_score": 2,
"selected": false,
"text": "WHERE ON ON update mytable\nset myscore=100\nwhere exists (\nselect 1 from table1\ninner join table2\non (table2.key = mytable.key)\ninner join table3\non (table3.key = table2.key and table3.key = table1.key)\n...\n)\n table1"
},
{
"answer_id": 23856232,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 5,
"selected": false,
"text": "post post_comment post | id | title |\n|----|-----------|\n| 1 | Java |\n| 2 | Hibernate |\n| 3 | JPA |\n post_comment | id | review | post_id |\n|----|-----------|---------|\n| 1 | Good | 1 |\n| 2 | Excellent | 1 |\n| 3 | Awesome | 2 |\n SELECT\n p.id AS \"p.id\",\n pc.id AS \"pc.id\"\nFROM post p\nINNER JOIN post_comment pc ON 1 = 1\n post post_comment | p.id | pc.id |\n|---------|------------|\n| 1 | 1 |\n| 1 | 2 |\n| 1 | 3 |\n| 2 | 1 |\n| 2 | 2 |\n| 2 | 3 |\n| 3 | 1 |\n| 3 | 2 |\n| 3 | 3 |\n SELECT\n p.id AS \"p.id\",\n pc.id AS \"pc.id\"\nFROM post p\nCROSS JOIN post_comment\nWHERE 1 = 1\nORDER BY p.id, pc.id\n SELECT\n p.id AS \"p.id\",\n pc.id AS \"pc.id\"\nFROM post p\nINNER JOIN post_comment pc ON 1 = 0\nORDER BY p.id, pc.id\n | p.id | pc.id |\n|---------|------------|\n SELECT\n p.id AS \"p.id\",\n pc.id AS \"pc.id\"\nFROM post p\nCROSS JOIN post_comment\nWHERE 1 = 0\nORDER BY p.id, pc.id\n SELECT\n p.id AS \"p.id\",\n pc.post_id AS \"pc.post_id\",\n pc.id AS \"pc.id\",\n p.title AS \"p.title\",\n pc.review AS \"pc.review\"\nFROM post p\nINNER JOIN post_comment pc ON pc.post_id = p.id\nORDER BY p.id, pc.id\n | p.id | pc.post_id | pc.id | p.title | pc.review |\n|---------|------------|------------|------------|-----------|\n| 1 | 1 | 1 | Java | Good |\n| 1 | 1 | 2 | Java | Excellent |\n| 2 | 2 | 3 | Hibernate | Awesome |\n post post_comment post post_comment SELECT\n p.id AS \"p.id\",\n pc.post_id AS \"pc.post_id\",\n pc.id AS \"pc.id\",\n p.title AS \"p.title\",\n pc.review AS \"pc.review\"\nFROM post p, post_comment pc\nWHERE pc.post_id = p.id\n"
},
{
"answer_id": 35967290,
"author": "Hrishikesh Mishra",
"author_id": 445058,
"author_profile": "https://Stackoverflow.com/users/445058",
"pm_score": 4,
"selected": false,
"text": "mysql> desc t1; \n+-------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-------------+------+-----+---------+-------+\n| id | int(11) | NO | | NULL | |\n| fid | int(11) | NO | | NULL | |\n| v | varchar(20) | NO | | NULL | |\n+-------+-------------+------+-----+---------+-------+\n mysql> desc t2;\n+-------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-------------+------+-----+---------+-------+\n| id | int(11) | NO | | NULL | |\n| v | varchar(10) | NO | | NULL | |\n+-------+-------------+------+-----+---------+-------+\n2 rows in set (0.00 sec)\n mysql> SELECT * FROM `t1` left join t2 on fid = t2.id AND t1.v = 'K' \n -> ;\n+----+-----+---+------+------+\n| id | fid | v | id | v |\n+----+-----+---+------+------+\n| 1 | 1 | H | NULL | NULL |\n| 2 | 1 | B | NULL | NULL |\n| 3 | 2 | H | NULL | NULL |\n| 4 | 7 | K | NULL | NULL |\n| 5 | 5 | L | NULL | NULL |\n+----+-----+---+------+------+\n5 rows in set (0.00 sec)\n mysql> SELECT * FROM `t1` left join t2 on fid = t2.id where t1.v = 'K';\n+----+-----+---+------+------+\n| id | fid | v | id | v |\n+----+-----+---+------+------+\n| 4 | 7 | K | NULL | NULL |\n+----+-----+---+------+------+\n1 row in set (0.00 sec)\n"
},
{
"answer_id": 55594225,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 2,
"selected": false,
"text": "FROM WHERE GROUP BY HAVING WINDOW SELECT DISTINCT UNION INTERSECT EXCEPT ORDER BY OFFSET FETCH FROM ON JOIN WHERE LEFT JOIN WHERE SELECT a.actor_id, a.first_name, a.last_name, count(fa.film_id)\nFROM actor a\nLEFT JOIN film_actor fa ON a.actor_id = fa.actor_id\nWHERE film_id < 10\nGROUP BY a.actor_id, a.first_name, a.last_name\nORDER BY count(fa.film_id) ASC;\n LEFT JOIN FILM_ID NULL WHERE ACTOR_ID FIRST_NAME LAST_NAME COUNT\n--------------------------------------\n194 MERYL ALLEN 1\n198 MARY KEITEL 1\n30 SANDRA PECK 1\n85 MINNIE ZELLWEGER 1\n123 JULIANNE DENCH 1\n ON SELECT a.actor_id, a.first_name, a.last_name, count(fa.film_id)\nFROM actor a\nLEFT JOIN film_actor fa ON a.actor_id = fa.actor_id\n AND film_id < 10\nGROUP BY a.actor_id, a.first_name, a.last_name\nORDER BY count(fa.film_id) ASC;\n FILM_ID < 10 ACTOR_ID FIRST_NAME LAST_NAME COUNT\n-----------------------------------------\n3 ED CHASE 0\n4 JENNIFER DAVIS 0\n5 JOHNNY LOLLOBRIGIDA 0\n6 BETTE NICHOLSON 0\n...\n1 PENELOPE GUINESS 1\n200 THORA TEMPLE 1\n2 NICK WAHLBERG 1\n198 MARY KEITEL 1\n"
},
{
"answer_id": 55649187,
"author": "Cid",
"author_id": 8398549,
"author_profile": "https://Stackoverflow.com/users/8398549",
"pm_score": 4,
"selected": false,
"text": "id | SomeData\n id | id_A | SomeOtherData\n id_A A SELECT *\nFROM A\nLEFT JOIN B\nON A.id = B.id_A;\n / : part of the result\n B\n +---------------------------------+\n A | |\n+---------------------+-------+ |\n|/////////////////////|///////| |\n|/////////////////////|///////| |\n|/////////////////////|///////| |\n|/////////////////////|///////| |\n|/////////////////////+-------+-------------------------+\n|/////////////////////////////|\n+-----------------------------+\n B.id_A / : part of the result\n* : part of the result with the specific B.id_A\n B\n +---------------------------------+\n A | |\n+---------------------+-------+ |\n|/////////////////////|///////| |\n|/////////////////////|///////| |\n|/////////////////////+---+///| |\n|/////////////////////|***|///| |\n|/////////////////////+---+---+-------------------------+\n|/////////////////////////////|\n+-----------------------------+\n SELECT *\nFROM A\nLEFT JOIN B\nON A.id = B.id_A\nAND B.id_A = SpecificPart;\n / : part of the result\n* : part of the result with the specific B.id_A\n B\n +---------------------------------+\n A | |\n+---------------------+-------+ |\n|/////////////////////| | |\n|/////////////////////| | |\n|/////////////////////+---+ | |\n|/////////////////////|***| | |\n|/////////////////////+---+---+-------------------------+\n|/////////////////////////////|\n+-----------------------------+\n B.id_A = SpecificPart SELECT *\nFROM A\nLEFT JOIN B\nON A.id = B.id_A\nWHERE B.id_A = SpecificPart;\n / : part of the result\n* : part of the result with the specific B.id_A\n B\n +---------------------------------+\n A | |\n+---------------------+-------+ |\n| | | |\n| | | |\n| +---+ | |\n| |***| | |\n| +---+---+-------------------------+\n| |\n+-----------------------------+\n B.id_A = SpecificPart B.id_A IS NULL"
},
{
"answer_id": 55911960,
"author": "matthew david",
"author_id": 6780195,
"author_profile": "https://Stackoverflow.com/users/6780195",
"pm_score": 3,
"selected": false,
"text": "¯\\_(ツ)_/¯"
},
{
"answer_id": 59842155,
"author": "Ezequiel",
"author_id": 6343065,
"author_profile": "https://Stackoverflow.com/users/6343065",
"pm_score": 1,
"selected": false,
"text": "select * from a inner join b on a.c = b.c\n select * from a inner join b where a.c = b.c\n"
},
{
"answer_id": 64836784,
"author": "blue_note",
"author_id": 3208297,
"author_profile": "https://Stackoverflow.com/users/3208297",
"pm_score": 2,
"selected": false,
"text": "join .. on where explain join join..on join ... on"
},
{
"answer_id": 67896429,
"author": "Edridge D'Souza",
"author_id": 15014819,
"author_profile": "https://Stackoverflow.com/users/15014819",
"pm_score": 1,
"selected": false,
"text": "JOIN ON ... WHERE JOIN ON ... AND SELECT *\nFROM Orders\nLEFT JOIN OrderLines ON Orders.ID = OrderLines.OrderID\n WHERE Orders.Username = OrderLines.Username\n SELECT *\nFROM Orders\nLEFT JOIN OrderLines ON Orders.ID = OrderLines.OrderID \n AND Orders.Username = OrderLines.Username\n ON ON ... AND Orders.Username Orders.ID JOIN ON ... WHERE ID Username JOIN ON ... AND Orders.ID Orders.Username"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
354,097 | <p>When I add a # in insert mode on an empty line in Vim while editing python files, vim moves the # to the beginning of the line, but I would like the # to be inserted at the tab level where I entered it.</p>
<p>For example, when writing this in vim</p>
<pre><code>for i in range(10):
#
</code></pre>
<p>the # does not stay there where I entered it.</p>
<p>It is moved like so, by vim.</p>
<pre><code>for i in range(10):
#
</code></pre>
<p>Does anyone know of a configuration item in vim that would change this?</p>
<p>If it helps, I am using Ubuntu 8.10.</p>
| [
{
"answer_id": 354422,
"author": "Paul D. Eden",
"author_id": 3045,
"author_profile": "https://Stackoverflow.com/users/3045",
"pm_score": 6,
"selected": true,
"text": "set smartindent\n set cindent\n"
},
{
"answer_id": 385388,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 2,
"selected": false,
"text": ":set smartindent"
},
{
"answer_id": 385724,
"author": "PolyThinker",
"author_id": 47707,
"author_profile": "https://Stackoverflow.com/users/47707",
"pm_score": 4,
"selected": false,
"text": "set smartindent\ninoremap # X^H#\nset autoindent\n"
},
{
"answer_id": 777385,
"author": "user94368",
"author_id": 94368,
"author_profile": "https://Stackoverflow.com/users/94368",
"pm_score": 4,
"selected": false,
"text": "filetype indent on set smartindent set autoindent set cindent cindent filetype indent on"
},
{
"answer_id": 23683246,
"author": "bearvarine",
"author_id": 1952060,
"author_profile": "https://Stackoverflow.com/users/1952060",
"pm_score": 2,
"selected": false,
"text": "\" cindent enable specific indenting for C code\n\" set cin nocin\nset cin\n\n\" cinkeys The default cinkeys causes leading # to unindent to column 0.\n\" To prevent this, remove the 0# from the definition.\n\" set cinkeys=0{,0},0),:,0#,!^F,o,O,e - default\nset cinkeys=0{,0},0),:,!^F,o,O,e\n"
},
{
"answer_id": 24045070,
"author": "wisbucky",
"author_id": 1081043,
"author_profile": "https://Stackoverflow.com/users/1081043",
"pm_score": 0,
"selected": false,
"text": "set smartindent ~/.vimrc :set smartindent? smartindent ~/.vimrc autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class\n ^^^^^^^^^^^\n"
},
{
"answer_id": 46313691,
"author": "piojo",
"author_id": 1682146,
"author_profile": "https://Stackoverflow.com/users/1682146",
"pm_score": 2,
"selected": false,
"text": "inoremap # X#<left><backspace><right>\n I#<esc>"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045/"
] |
354,110 | <p>Being fairly new to JavaScript, I'm unable to discern when to use each of these.</p>
<p>Can anyone help clarify this for me?</p>
| [
{
"answer_id": 354118,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": false,
"text": "indexOf search"
},
{
"answer_id": 354123,
"author": "ng.mangine",
"author_id": 37784,
"author_profile": "https://Stackoverflow.com/users/37784",
"pm_score": 9,
"selected": true,
"text": "search() indexOf()"
},
{
"answer_id": 34282912,
"author": "Zameer Ansari",
"author_id": 2404470,
"author_profile": "https://Stackoverflow.com/users/2404470",
"pm_score": -1,
"selected": false,
"text": "function FromSearch() {\n\n var str = document.getElementById(\"demo\").innerText;\n var n = str.search(\"difference\");\n document.getElementById(\"Location\").innerHTML = n;\n}\n\nfunction FromindexOf() {\n var str = document.getElementById(\"demo\").innerText;\n var n = str.indexOf(\"difference\");\n document.getElementById(\"Location\").innerHTML = n;\n} <p id=\"demo\">Without a <a href='http://www.w3schools.com/js/js_regexp.asp'>regex</a>, there is no practical difference between <a href='http://www.w3schools.com/jsref/jsref_indexof.asp'>indexOf</a> and <a href='http://www.w3schools.com/jsref/jsref_search.asp'>search</a>\n</p>\n\n<button onclick=\"FromSearch()\">From search</button>\n\n<button onclick=\"FromindexOf()\">From indexOf</button>\n\n<p>Location of difference in the above sentence is:</p>\n\n<mark id=\"Location\"></mark>"
},
{
"answer_id": 55794266,
"author": "K23raj",
"author_id": 10512264,
"author_profile": "https://Stackoverflow.com/users/10512264",
"pm_score": 4,
"selected": false,
"text": "let str='Book is booked for delivery'\nstr.indexOf('b') // returns position 8\nstr.search('b') // returns position 8 \n str.indexOf('k') // 3\nstr.indexOf('k',4) // 11 (it start search from 4th position) \n str.search('book') // 8\nstr.search(/book/i) // 0 ( /i =case-insensitive (Book == book)\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30433/"
] |
354,136 | <p>How do I create the default for a generic in VB? in C# I can call:</p>
<pre><code>T variable = default(T);
</code></pre>
<ol>
<li>How do I do this in VB?</li>
<li>If this just returns null (C#) or nothing (vb) then what happens to value types?</li>
<li>Is there a way to specify for a custom type what the default value is? For instance what if I want the default value to be the equivalent to calling a parameterless constructor on my class.</li>
</ol>
| [
{
"answer_id": 354142,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "Dim variable As T\n' or '\nDim variable As T = Nothing\n' or '\nDim variable As New T()\n Structure New T() default(T) null Nothing string \"\""
},
{
"answer_id": 354257,
"author": "Jon Norton",
"author_id": 4797,
"author_profile": "https://Stackoverflow.com/users/4797",
"pm_score": 0,
"selected": false,
"text": "default(T) Nothing Function ReturnSomething(Of T)() As T\n Return Nothing\nEnd Function\n\nFunction DoSomething(Of T)()\n Dim x as T = Nothing;\n If x = Nothing Then\n Console.WriteLine(\"x is default.\")\n Else\n Console.WriteLine(\"x has a value.\")\n End If\n default(T) T Nothing Nothing default(T) T ReturnSomething<T>()\n{\n return default(T);\n}\n\nvoid DoSomething<T>()\n{\n T x = default(T);\n if(x == default(T))\n Console.WriteLine(\"x is default.\");\n else\n Console.WriteLine(\"x has a value.\");\n}\n Function ReturnSomething(Of T)() As T\n Return Nothing\nEnd Function\n\nFunction DoSomething(Of T)()\n Dim x as T = Nothing;\n If x Is Nothing Then\n Console.WriteLine(\"x is default.\")\n Else\n Console.WriteLine(\"x has a value.\")\n End If\nEnd Function\n T ReturnSomething DoSomething T ReturnSomething DoSomething"
},
{
"answer_id": 1929159,
"author": "user234662",
"author_id": 234662,
"author_profile": "https://Stackoverflow.com/users/234662",
"pm_score": 3,
"selected": false,
"text": "null Nothing Dim tmpObj As T = CType(Nothing, T)\n CType(Nothing, T)"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17744/"
] |
354,139 | <p>When using Google Reader and browsing RSS entries in the "Expanded" view, entries will automatically be marked as 'read' once a certain percentage of the div is visible on the screen (difficult to tell what percentage has to be visible in the case of Google Reader). So, as I scroll down line-by-line, the javascript code can determine that a) the entry is being rendered in the visible window and b) a certain amount is visible and when those conditions are met, the state is toggled to read.</p>
<p>Does anyone have any idea how that feature is implemented? Specifically, does anyone here know how to tell if a div has scrolled into view an how much of the div is visible?</p>
<p>As an aside, I'm using jQuery, so if anyone has any jQuery-specific examples, they would be much appreciated.</p>
| [
{
"answer_id": 365937,
"author": "Yoni",
"author_id": 36071,
"author_profile": "https://Stackoverflow.com/users/36071",
"pm_score": 0,
"selected": false,
"text": "viewportOffset getOffsetParent scrollTo"
},
{
"answer_id": 46545607,
"author": "Jordan Stubblefield",
"author_id": 7768341,
"author_profile": "https://Stackoverflow.com/users/7768341",
"pm_score": 0,
"selected": false,
"text": "function isScrolledIntoView(element) {\n var elementTop = element.getBoundingRect().top;\n var elementBottom = element.getBoundingRect().bottom;\n\n var isVisible = (elementTop <= window.innerHeight) && (elementBottom >= 0);\n return isVisible;\n}\n function isRead(element) {\n var elementTop = element.getBoundingRect().top;\n var elementBottom = element.getBoundingRect().bottom;\n var elementHeight = elementBottom - elementTop;\n\n // if 75% of the document has been scrolled, we'll assume it's been read\n var readIfPercentage = 0.75;\n\n // an element has been read if the top has been scrolled up out of view\n // and at least 75% of the element is no longer visible\n var isRead = (elementTop < 0 && Math.abs(elementTop) / elementHeight >= readIfPercentage);\n return isRead;\n}\n isScrolledIntoView(document.getElementById('targetDiv');\n//or\nisRead(document.getElementById('targetDiv');\n function setScrollListener() {\n\n var scrollEventHandler = function() {\n if (isRead(document.getElementById('article'))) {\n // set article to 'read'\n }\n }\n\n // on scroll, fire the event handler\n $(document).scroll(scrollEventHandler);\n}\n function unbindScrollEventHandler() {\n $(document).unbind('scroll', scrollEventHandler);\n}\n"
},
{
"answer_id": 50572330,
"author": "Juk",
"author_id": 3660020,
"author_profile": "https://Stackoverflow.com/users/3660020",
"pm_score": 0,
"selected": false,
"text": "isRead(element) {\n let rect = element.getBoundingClientRect();\n const visibleRatio = 0.85;\n let elementRatio = (window.innerHeight - Math.abs(rect.top))/rect.height;\n let isRead = (rect.top >= 0) && (elementRatio >= visibleRatio);\n return isRead; \n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40123/"
] |
354,167 | <p>In its enthusiasm to <a href="http://www.postgresql.org/docs/current/interactive/textsearch-intro.html" rel="nofollow noreferrer">stemm tokens into lexemes</a>, PostgreSQL Full Text Search engine also reduce proper nouns. For instance:</p>
<pre><code>essais=> select to_tsquery('english', 'bortzmeyer');
to_tsquery
------------
'bortzmey'
essais=> select to_tsquery('english', 'balling');
to_tsquery
------------
'ball'
(1 row)
</code></pre>
<p>At least for the first one, I'm sure it is not in the english dictionary! What is the better way to avoid this spurious stemming?</p>
| [
{
"answer_id": 73913128,
"author": "Justin Tanner",
"author_id": 609,
"author_profile": "https://Stackoverflow.com/users/609",
"pm_score": 0,
"selected": false,
"text": "english SELECT to_tsquery('simple', 'bortzmeyer');\n to_tsquery \n------------\n'bortzmeyer'\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15625/"
] |
354,171 | <p>I am pretty new to both Struts and Spring. I need to know how to access a Spring Service in a Struts ActionForm. Even a pointer in the right direction would be appreciated.</p>
| [
{
"answer_id": 354205,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 1,
"selected": false,
"text": "<listener>\n <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n</listener>\n <constant name=\"struts.objectFactory\" value=\"spring\"/>\n class MyAction {\n @Autowired MyService service;\n ....\n}\n"
},
{
"answer_id": 354403,
"author": "Gareth Davis",
"author_id": 31480,
"author_profile": "https://Stackoverflow.com/users/31480",
"pm_score": 2,
"selected": false,
"text": "WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean(\"yourService\");\n"
},
{
"answer_id": 906843,
"author": "D. Wroblewski",
"author_id": 61530,
"author_profile": "https://Stackoverflow.com/users/61530",
"pm_score": 1,
"selected": false,
"text": " <action path=\"/faq\" type=\"org.springframework.web.struts.DelegatingActionProxy\" name=\"faqForm\" parameter=\"method\">\n <forward name=\"List\" path=\"faq.list\" />\n </action>\n <bean name=\"/faq\" class=\"com.mypackage.FAQAction\" autowire=\"byType\" />\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,182 | <p>Given Microsoft FORTRAN 5.1 and Microsoft C/C++ 14.0, along with the linker that comes with that version of FORTRAN (that must be used for other dependencies) how do I create a C function and call it from the FORTRAN application? </p>
| [
{
"answer_id": 594694,
"author": "KitsuneYMG",
"author_id": 86515,
"author_profile": "https://Stackoverflow.com/users/86515",
"pm_score": 2,
"selected": true,
"text": "program ftest\nuse iso_c_bindings\nimplicit none\ninterface\nfunction saythis(a) ! should be subroutine if saythis returns void\nimport :: c_ptr\ntype(c_ptr), value :: a\nend function saythis\nend interface\n\ncharacter(len=80), target :: str\ntype(c_ptr) cstr\ninteger :: r\n\nstr='Hello World From Fortran' // C_NULL_CHAR\ncstr=c_loc(str(1:1))\nr=saythis(cstr)\n #ifdef __cpluscplus\n#include <l;cstdio>\nusing namespace std;\n#else\n#inlcude <stdio.h>\n#endif\n\n#ifdef __GNUC__\n#define FORT(func) func ## _\n#else\n#define FORT(func) __stdcall func ## _\n#endif\n\n#ifdef __cpluscplus\nextern \"C\" {\n#endif\n__declspec(dllexport) int FORT(sayit)(char* c)\n{\nreturn printf(\"%s\\n\",c);\n}\n\n#ifdef __cpluscplus\n}\n#endif\n //This is for gcc toolchain\n//you'll have to find the symbol conversion yourself\n//I think that Visual Studio converts fortran names\n//to ALL CAPS so instead of func => _func you'll need func => FUNC\n program ftest\ninteger aa,bb,cc\ncommon/vari/aa,bb,cc\n\naa=7\nbb=11\ncc=0\ncall dosomething\ncall dosomethingelse(aa,bb,cc)\n #ifdef __cplusplus\nextern \"C\" {\n#endif\nint _dosomething();\nint _dosomethingelse(int*,int*,int*); //all fortran is pass by reference\nstruct { int aa,bb,cc; } vari;\n#ifdef __cplusplus\n}\n#endif\n\n//function def's go here\n//struct vari should be the same memory as common/vari block\n $>g++ -c ctest.c <br/>\n$>gfortran -c ftest.f90 <br/>\n$>gfortran *.o -lstdc++ -o test_prog <br/>\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070/"
] |
354,188 | <p>Unlike many of the ASP.NET documentation and examples, I'm doing a gridview list on one page, and it links to a 2nd page to do the edit/update view, sending the ID for the record in the GET string.</p>
<p>On my edit/update view, I'm using an ASP:DetailsView for viewing, editing and inserting records. All of this works fine. </p>
<p>On the <code>detailsView</code> page, I have it autogenerating a <code>new record</code> link that uses postback to show the blank insert form to be filled out.</p>
<p>The only problem is, I have no idea how to link to the <code>insert</code> view of the <code>DetailsView</code> from an external page. Am I missing something?</p>
| [
{
"answer_id": 355319,
"author": "Dhaust",
"author_id": 242,
"author_profile": "https://Stackoverflow.com/users/242",
"pm_score": 3,
"selected": true,
"text": "If Not idValue Is Nothing Then \n yourDetailsViewName.ChangeMode(DetailsViewMode.Insert)\nEnd If\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22452/"
] |
354,194 | <p>After upgrading a few gems via terminal on my mac, I have created a new rails project backed up by a mysql database. Upon starting the app, the regular welcome aboard page appears. </p>
<p>Here's the problem - I tried clicking the link entitled "About your application's environment", I receive the following output in my browser:</p>
<pre><code>MissingSourceFile in Rails/infoController#properties
no such file to load -- mysql
</code></pre>
<p>I also receive this output in the terminal</p>
<pre><code>The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
Processing Rails::InfoController#properties (for 127.0.0.1 at 2008-12-09 20:41:41) [GET]
Processing Rails::InfoController#properties (for 127.0.0.1 at 2008-12-09 20:41:41) [GET]
MissingSourceFile (no such file to load -- mysql):
...
</code></pre>
<p>As it says, I tried issuing "gem install mysql" after stopping the application, only to be greeted by this chunk of jargon which I am unable to comprehend:</p>
<pre><code>WARNING: Installing to ~/.gem since /Library/Ruby/Gems/1.8 and
/usr/bin aren't both writable.
WARNING: You don't have /Users/mymac/.gem/ruby/1.8/bin in your PATH,
gem executables will not run.
Building native extensions. This could take a while...
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb install mysql
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... no
checking for mysql_query() in -lmysqlclient... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
--with-mysql-config
--without-mysql-config
--with-mysql-dir
--without-mysql-dir
--with-mysql-include
--without-mysql-include=${mysql-dir}/include
--with-mysql-lib
--without-mysql-lib=${mysql-dir}/lib
--with-mysqlclientlib
--without-mysqlclientlib
--with-mlib
--without-mlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-zlib
--without-zlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-socketlib
--without-socketlib
--with-mysqlclientlib
--without-mysqlclientlib
--with-nsllib
--without-nsllib
--with-mysqlclientlib
--without-mysqlclientlib
Gem files will remain installed in /Users/mymac/.gem/ruby/1.8/gems/mysql-2.7 for inspection.
Results logged to /Users/mymac/.gem/ruby/1.8/gems/mysql-2.7/gem_make.out
</code></pre>
<p>Clearly there is something wrong with my mysql installation, as I have also tried running the rake command to create the database, which prompted me with the following.</p>
<pre><code>!!! The bundled mysql.rb driver has been removed from Rails 2.2. Please install the mysql gem and try again: gem install mysql.
rake aborted!
no such file to load -- mysql
(See full trace by running task with --trace)
</code></pre>
<p>However, when I run "mysql --version" at the command line, mysql is installed!</p>
<pre><code>mysql Ver 14.12 Distrib 5.0.67, for apple-darwin9.4.0 (i686) using readline 5.1
</code></pre>
<p>I also tried issuing "sudo gem install mysql", however that was also to no avail:</p>
<pre><code>sudo gem install mysql
Password:
Building native extensions. This could take a while...
ERROR: Error installing mysql:
ERROR: Failed to build gem native extension.
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb install mysql
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lm... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lz... yes
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lsocket... no
checking for mysql_query() in -lmysqlclient... no
checking for main() in -lnsl... no
checking for mysql_query() in -lmysqlclient... no
Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/mysql-2.7 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/mysql-2.7/gem_make.out
</code></pre>
<p>I also tried issuing "sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config" as instructed by bradheintz, which seemed to have installed ok, but after trying to view the application environment again, no ajaxy dropdown occurs and the rails app stops completely! The following output is printed just before the application decides to die on me lol.</p>
<pre><code>dyld: lazy symbol binding failed: Symbol not found: _mysql_init
Referenced from: /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle
Expected in: dynamic lookup
dyld: Symbol not found: _mysql_init
Referenced from: /Library/Ruby/Gems/1.8/gems/mysql-2.7/lib/mysql.bundle
Expected in: dynamic lookup
Trace/BPT trap
</code></pre>
<p>If anyone can understand what's going on here, and how to go about resolving this problem, I'd be very grateful :)</p>
| [
{
"answer_id": 354197,
"author": "bradheintz",
"author_id": 40093,
"author_profile": "https://Stackoverflow.com/users/40093",
"pm_score": 3,
"selected": false,
"text": "sudo gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config gem install sudo gem install mysql"
},
{
"answer_id": 355133,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 0,
"selected": false,
"text": "-V sudo env ARCHFLAGS=\"-arch i386\" gem install -V mysql -- --with-mysql-config=/usr/local/sql32/bin/mysql_config\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2294/"
] |
354,195 | <p>I'm finding that hitting the "Refresh" button on my browser will temporarily screw up the ViewState for controls inside an UpdatePanel.</p>
<p>Here's my situation : I made a custom WebControl that stores values in the ViewState. I put this control inside an UpdatePanel. When I hit the "refresh" button on my browser, it will temporarily wipe out the values in ViewState. However, on the next postback, the values that were in the ViewState before I hit "refresh" magically reappear. </p>
<p>This behavior screws up my webcontrol. After I hit "refresh," the control is returned to its initial state, since the ViewState is empty and IsPostBack is set to false. However, when I click on one of the postback controls within my WebControl, the WebControl will reload with the same values that were in ViewState before I hit "refresh." </p>
<p>Strangely, this only happens when I'm using AJAX. When my control is outside of an UpdatePanel, Firefox gives me it's standard message, "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier (Resend) (Cancel)." This is fine, because at least the behavior is consistent. However, I absolutely must use AJAX for this project.</p>
<p>So this is what I would like to do - I want to make the "refresh" behavior consistent. It would be best if hitting "refresh" didn't affect the ViewState at all. But if it has to wipe out the ViewState, that's fine, as long as the ViewState STAYS wiped out. None of this stuff with values disappearing and reappearing.</p>
<p>Oh yeah, and here's my example code :</p>
<pre><code>using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace TestControls
{
public class TestControl : WebControl
{
int _clickCount;
bool _mustUpdate;
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
_clickCount = ((int)ViewState["clickCount"]);
_mustUpdate = ((bool)ViewState["mustUpdate"]);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Controls.Clear();
ControlCreator();
}
private void ControlCreator()
{
Label tempLabel = new Label();
LiteralControl tempLiteral = new LiteralControl("<br/><br/>");
LinkButton tempLink = new LinkButton();
tempLink.ID = "testLink";
tempLink.Text = "Click me!";
tempLink.Click += new EventHandler(tempLink_Click);
tempLabel.ID = "testLabel";
tempLabel.Text = _clickCount.ToString();
Controls.Add(tempLabel);
Controls.Add(tempLiteral);
Controls.Add(tempLink);
}
void tempLink_Click(object sender, EventArgs e)
{
_clickCount++;
_mustUpdate = true;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (_mustUpdate)
{
Controls.Clear();
ControlCreator();
_mustUpdate = false;
}
}
protected override object SaveViewState()
{
ViewState["clickCount"] = _clickCount;
ViewState["mustUpdate"] = _mustUpdate;
return base.SaveViewState();
}
}
}
</code></pre>
| [
{
"answer_id": 354608,
"author": "BlackMael",
"author_id": 19377,
"author_profile": "https://Stackoverflow.com/users/19377",
"pm_score": 1,
"selected": false,
"text": " protected override void LoadViewState(object savedState)\n {\n if (savedState != null)\n {\n object[] myState = (object[])savedState;\n\n if (myState[0] != null) base.LoadViewState(myState[0]);\n if (myState[1] != null) _clickCount = ((int)myState[1]);\n if (myState[2] != null) _mustUpdate = ((bool)myState[2]);\n }\n }\n\n protected override object SaveViewState()\n {\n object[] allStates = new object[3];\n\n allStates[0] = base.SaveViewState();\n allStates[1] = _clickCount;\n allStates[2] = _mustUpdate;\n\n return allStates;\n }\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44701/"
] |
354,201 | <p>That's the question... Do you think ASP.Net is a technology suitable for high-load sites? Do you know any populer sites -apart from stackoverflow, of course- built with this technology?
Thanks.</p>
| [
{
"answer_id": 354206,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 6,
"selected": true,
"text": "HttpHandler"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2166249/"
] |
354,221 | <p>What is the most efficient algorithm for grouping identical items together in an array, given the following:</p>
<ol>
<li>Almost all items are duplicated several times.</li>
<li>The items are not necessarily integers or anything else that's similarly simple. The range of the keys is not even well-defined, let alone small. In fact, the keys can be arbitrary structs. This rules out the most simple forms of counting sort.</li>
<li>We care about both asymptotic and non-asymptotic properties, and n may be small sometimes. However, when n is small, performance is still important because this function may be called several million times in a loop on millions of small datasets. This rules out any expensive hash function or using a complex data structure that needs to perform lots of memory allocations.</li>
<li>The data may be sorted in arbitrary order as long as all identical items are grouped together.</li>
</ol>
<p>If this is confusing, here's an example, assuming such a function is named groupIdentical:</p>
<pre><code>uint[] foo = [1,2,3,2,1,5,4,5];
uint[] bar = groupIdentical(foo);
// One possibile correct value for bar:
// bar == [2,2,1,1,3,4,5,5].
// Another possible correct answer:
// bar == [1,1,2,2,5,5,4,3].
</code></pre>
<p>However, as a reminder, we cannot assume that the data is composed as integers.</p>
<p>Edit: Thank you for the answers. My main problem with hashing was that hash tables perform memory allocations to frequently. What I ended up doing was writing my own hash table that uses a region allocator that I had around to get around this problem. Works well.</p>
| [
{
"answer_id": 354265,
"author": "recursive",
"author_id": 44743,
"author_profile": "https://Stackoverflow.com/users/44743",
"pm_score": 0,
"selected": false,
"text": "uint[] bucket = new int[10];\nforeach(uint val in foo) {\n ++bucket[val];\n}\n\nuint bar_i = 0;\nuint[] bar = new int[foo.length];\nforeach(int val = 0; val < 10; val++) {\n uint occurrences = bucket[val];\n for(int i=0; i < occurrences; i++) {\n bar[bar_i++] = val;\n }\n}\n"
},
{
"answer_id": 354450,
"author": "Charlie Martin",
"author_id": 35092,
"author_profile": "https://Stackoverflow.com/users/35092",
"pm_score": 2,
"selected": false,
"text": "insert()"
},
{
"answer_id": 355326,
"author": "lakshmanaraj",
"author_id": 44541,
"author_profile": "https://Stackoverflow.com/users/44541",
"pm_score": 0,
"selected": false,
"text": "function groupIdentical(Input) \n{\n k=1;\n for i=1 to n \n {\n Visited[i]=false ;\n }\n\n for i=1 to n\n {\n if( !Visited(i) )\n { \n Result[k++]=Input[i];\n for j= (i+1) to n\n {\n if( Equals(i,j) )\n {\n Result[k++]=Input[j];\n Visited[j]=true;\n } \n }\n }\n }\n return Result;\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23903/"
] |
354,224 | <p>Using Firebird, I want to combine the results of two queries using UNION ALL, then sort the resulting output on a given column.</p>
<pre><code>(select C1, C2, C3 from T1)
union all
(select C1, C2, C3 from T2)
order by C3
</code></pre>
<p>The parentheses came from valid syntax for other databases, and are needed to make sure the arguments to UNION ALL (an operation that's defined to work on tables - i.e. an <em>unordered</em> set of records) don't try to be ordered individually. However I couldn't get this syntax to work in Firebird--how can it be done?</p>
| [
{
"answer_id": 354242,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 6,
"selected": true,
"text": "SELECT C1, C2, C3\nFROM (\n select C1, C2, C3 from T1\n union all \n select C1, C2, C3 from T2\n)\norder by C3\n"
},
{
"answer_id": 354451,
"author": "Douglas Tosi",
"author_id": 626,
"author_profile": "https://Stackoverflow.com/users/626",
"pm_score": 4,
"selected": false,
"text": "(select C1, C2, C3 from T1)\nunion all \n(select C7, C8, C9 from T2)\norder by 3 \n"
},
{
"answer_id": 507350,
"author": "Tiago Moraes",
"author_id": 61959,
"author_profile": "https://Stackoverflow.com/users/61959",
"pm_score": 2,
"selected": false,
"text": "create view V1 (C1, C2, C3) as\n select C1, C2, C3 from T1\n union all \n select C1, C2, C3 from T2\n select C1, C2, C3 from V1 order by C3\n"
},
{
"answer_id": 31006757,
"author": "KCM",
"author_id": 5040974,
"author_profile": "https://Stackoverflow.com/users/5040974",
"pm_score": 3,
"selected": false,
"text": "select C1, C2, C3 from T1\nunion all \nselect C1, C2, C3 from T2\norder by 2\n"
},
{
"answer_id": 43460306,
"author": "kai3341",
"author_id": 2651046,
"author_profile": "https://Stackoverflow.com/users/2651046",
"pm_score": 0,
"selected": false,
"text": "order by select * from (\n select first 1\n C1\n from T1\n order by id desc\n)\nunion all\nselect * from (\n select first 1\n C1\n from T2\n order by id desc\n)"
},
{
"answer_id": 74645533,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 0,
"selected": false,
"text": "NATURAL FULL JOIN UNION ALL select c1, c2, c3 \nfrom (select 't1' as x, t1.* from t1) as t1\nnatural full join (select 't2' as x, t2.* from t2) as t2\norder by c3\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8415/"
] |
354,226 | <p>I want to be able to run my SqlDataProvider against an oracle stored procedure. I can use Microsoft's Oracle Provider but that wouldn't allow me to call a stored procedure. has anyone been able to get this to work? I particularly want to be able to use declarative data binding. I have been able to programatically create a DataTable but I want to do this declaratively in the .aspx. </p>
| [
{
"answer_id": 366442,
"author": "user46119",
"author_id": 46119,
"author_profile": "https://Stackoverflow.com/users/46119",
"pm_score": 2,
"selected": false,
"text": "using (OracleConnection conn = new OracleConnection(\"connection string here\"))\n{\n conn.Open();\n\n OracleCommand command = conn.CreateCommand();\n command.CommandType = CommandType.StoredProcedure;\n\n command.CommandText = \"DATABASE_NAME_HERE.SPROC_NAME_HERE\";\n // Call command.Parameters.Add to add your parameters.\n\n using (OracleReader reader = command.ExecuteReader())\n {\n while(reader.Read())\n {\n // Process each row\n }\n }\n\n}\n <add name=\"OracleConnectionString\"\n connectionString=\"Data Source=YourServer;Persist \n Security Info=True;Password=\"******\";User ID=User1\"\n providerName=\"System.Data.OracleClient\" />\n <asp:SqlDataSource ID=\"SqlDataSource1\" runat=\"server\" ConnectionString=\"<%$ ConnectionStrings:OracleConnectionString %>\"\n ProviderName=\"<%$ ConnectionStrings:OracleConnectionString.ProviderName %>\" SelectCommand='TEST_ONE' SelectCommandType=\"StoredProcedure\" ></asp:SqlDataSource>\n"
},
{
"answer_id": 15300446,
"author": "Israel Margulies",
"author_id": 1346806,
"author_profile": "https://Stackoverflow.com/users/1346806",
"pm_score": 0,
"selected": false,
"text": "<asp:Parameter Name=\"io_cursor\" Direction=\"Output\" />\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
354,254 | <p><s><a href="https://stackoverflow.com/questions/354160/what-do-you-do-while-your-codes-compiling#354176">An answer</a></s> <strong>(see below)</strong> to one of the questions right here on Stack Overflow gave me an idea for a great little piece of software that could be invaluable to coders everywhere.</p>
<p>I'm imagining RAM drive software, but with one crucial difference - it would mirror a real folder on my hard drive. More specifically - the folder which contains the project I'm currently working on. This way any builds would be nearly instantaneous (or at least a couple orders of magnitude faster). The RAM drive would synchronize its contents with the hard disk drive in background using only idle resources.</p>
<p>A quick Google search revealed nothing, but perhaps I just don't know how to Google. Perhaps someone knows of such a software? Preferably free, but reasonable fees might be OK too.</p>
<p><b>Added:</b> Some solutions have been suggested which I discarded in the very beginning. They would be (in no particular order):</p>
<ul>
<li><b>Buy a faster hard disk drive (<a href="http://en.wikipedia.org/wiki/Solid-state_drive" rel="noreferrer">SSD</a> maybe or 10K RPM).</b> I don't want a hardware solution. Not only software has the potential to be cheaper (freeware, anyone?), but it can also be used in environments where hardware modifications would be unwelcome if not impossible - say, at the office.</li>
<li><b>Let OS/HDD do the caching - it knows better how to use your free RAM.</b> The OS/HDD have generic cache algorithms that cache everything and try to predict which data will be most needed in the future. They have no idea that for me the priority is my project folder. And as we all know quite well - they don't really cache it much anyway. ;)</li>
<li><b>There are plenty of RAM drives around; use one of those.</b> Sorry, that would be reckless. I need my data to be synchronized back to the HDD whenever there is a bit of free time. In the case of a power failure I could bear losing the last five minutes of work, but not everything since my last checkin.</li>
</ul>
<p><b>Added 2:</b> An idea that came up - use a normal RAM drive plus a background folder synchronizer (but I do mean <b>background</b>). Is there any such thing?</p>
<p><b>Added 3:</b> Interesting. I just tried out a simple RAM drive at work. The rebuild time drops from ~14 secs to ~7 secs (not bad), but incremental build is still at ~5 secs - just like on the HDD. Any ideas why? It uses <code>aspnet_compiler</code> and <code>aspnet_merge</code>. Perhaps they do something with other temp files elsewhere?</p>
<p><b>Added 4:</b> Oh, nice new set of answers! :) OK, I've got a bit more info for all you naysayers. :)</p>
<p>One of the main reasons for this idea is not the above-mentioned software (14 secs build time), but another one that I didn't have access at the time. This other application has a 100 MB code base, and its full build takes about 5 minutes. Ah yes, it's in <a href="http://en.wikipedia.org/wiki/Embarcadero_Delphi" rel="noreferrer">Delphi 5</a>, so the compiler isn't too advanced. :) Putting the source on a RAM drive resulted in a BIG difference. I got it below a minute, I think. I haven't measured. So for all those who say that the OS can cache stuff better - I'd beg to differ.</p>
<p><strong>Related Question:</strong> </p>
<blockquote>
<p><a href="https://stackoverflow.com/questions/501718/ram-disk-for-speed-up-ide">RAM disk for speed up IDE</a></p>
</blockquote>
<p><strong>Note on first link:</strong>
The question to which it links has been deleted because it was a duplicate. It asked:</p>
<blockquote>
<p>What do you do while your code’s compiling?</p>
</blockquote>
<p>And the answer by <a href="https://stackoverflow.com/users/9476/dmitri-nesteruk">Dmitri Nesteruk</a> to which I linked was:</p>
<blockquote>
<p>I compile almost instantly. Partly due to my projects being small, partly due to the use of RAM disks.</p>
</blockquote>
| [
{
"answer_id": 354553,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 4,
"selected": false,
"text": "~/code ~/code-real ~/code ~/code-real ~/code ~/code-real"
},
{
"answer_id": 354733,
"author": "composer",
"author_id": 44811,
"author_profile": "https://Stackoverflow.com/users/44811",
"pm_score": 3,
"selected": false,
"text": "git push"
},
{
"answer_id": 688567,
"author": "Adam Hawes",
"author_id": 54415,
"author_profile": "https://Stackoverflow.com/users/54415",
"pm_score": 1,
"selected": false,
"text": "-j[n] [n]"
},
{
"answer_id": 688636,
"author": "snemarch",
"author_id": 430360,
"author_profile": "https://Stackoverflow.com/users/430360",
"pm_score": 0,
"selected": false,
"text": "%temp% %TEMP%"
},
{
"answer_id": 688659,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 1,
"selected": false,
"text": "# setup locations\n$ramdrive = /Volumes/ramspace\n$project = $HOME/code/someproject\n\n# ..create ram drive..\n\n# sync project directory to RAM drive\nrsync -av $project $ramdrive\n\n# build\ncd $ramdrive\nmake\n\n#optional, copy the built data to the project directory:\nrsync $ramdrive/build $project/build\n"
},
{
"answer_id": 7575979,
"author": "IanNorton",
"author_id": 148415,
"author_profile": "https://Stackoverflow.com/users/148415",
"pm_score": 0,
"selected": false,
"text": ".o"
},
{
"answer_id": 7896860,
"author": "Joe McGrath",
"author_id": 897924,
"author_profile": "https://Stackoverflow.com/users/897924",
"pm_score": 2,
"selected": false,
"text": "uramdir tar --update #!/bin/bash\n\n# May need some error checking for bad input.\n\n# Convert relative path to absolute\n# /bin/pwd gets real path without symbolic link on my system and pwd\n# keeps symbolic link. You may need to change it to suit your needs.\nsomedir=`cd $1; /bin/pwd`;\nsomedirparent=`dirname $somedir`\n\n# Backup directory\n/bin/tar cf $somedir.tar $somedir\n\n# Copy, tried move like https://wiki.archlinux.org/index.php/Ramdisk\n# suggests, but I got an error.\nmkdir -p /mnt/ramdisk$somedir\n/bin/cp -r $somedir /mnt/ramdisk$somedirparent\n\n# Remove directory\n/bin/rm -r $somedir\n\n# Create symbolic link. It needs to be in parent of given folder.\n/bin/ln -s /mnt/ramdisk$somedir $somedirparent\n\n#Run updater\n~/bin/rdbackupd \"/bin/tar -uf $somedir.tar $somedir\" &\n #!/bin/bash\n\n#Convert relative path to absolute\n#somepath would probably make more sense\n# pwd and not /bin/pwd so we get a symbolic path.\nsomedir=`cd $1; pwd`;\n\n# Remove symbolic link\nrm $somedir\n\n# Copy dir back\n/bin/cp -r /mnt/ramdisk$somedir $somedir\n\n# Remove from ramdisk\n/bin/rm -r /mnt/ramdisk$somedir\n\n# Stop\nkillall rdbackupd\n #include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <signal.h>\n#include <sys/time.h>\n\nstruct itimerval it;\nchar* command;\n\nvoid update_archive(int sig)\n{\n system(command);\n}\n\nint main(int argc, char**argv)\n{\n it.it_value.tv_sec = 1; // Start right now\n it.it_value.tv_usec = 0;\n it.it_interval.tv_sec = 60; // Run every 60 seconds\n it.it_interval.tv_usec = 0;\n\n if (argc < 2)\n {\n printf(\"rdbackupd: Need command to run\\n\");\n return 1;\n }\n command = argv[1];\n\n signal(SIGALRM, update_archive);\n setitimer(ITIMER_REAL, &it, NULL); // Start\n\n while(true);\n\n return 0;\n}\n"
},
{
"answer_id": 45457818,
"author": "nex",
"author_id": 6385946,
"author_profile": "https://Stackoverflow.com/users/6385946",
"pm_score": 1,
"selected": false,
"text": "sudo vmtouch -d -L ./\n alias cacheThis = 'sudo vmtouch -d -L ./'\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41360/"
] |
354,263 | <p>Is there a CPAN module that can read a string like this:</p>
<pre><code>"[[<asdf>, <foo>], (abc, def, ghi), ({'jkl'})]"
</code></pre>
<p>...and parse it into some sort of tree structure that's easy to walk and pretty-print?</p>
| [
{
"answer_id": 354388,
"author": "codelogic",
"author_id": 43427,
"author_profile": "https://Stackoverflow.com/users/43427",
"pm_score": 0,
"selected": false,
"text": "eval"
},
{
"answer_id": 354821,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 2,
"selected": false,
"text": "(?PARNO) (?-PARNO) (?+PARNO) (?R) (?0)"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91385/"
] |
354,264 | <p>So regular expressions seem to match on the longest possible match. For instance:</p>
<pre><code>public static void main(String[] args) {
String s = "ClarkRalphKentGuyGreenGardnerClarkSupermanKent";
Pattern p = Pattern.compile("Clark.*Kent", Pattern.CASE_INSENSITIVE);
Matcher myMatcher = p.matcher(s);
int i = 1;
while (myMatcher.find()) {
System.out.println(i++ + ". " + myMatcher.group());
}
}
</code></pre>
<p>generates output</p>
<ol>
<li>ClarkRalphKentGuyGreenGardnerClarkSupermanKent</li>
</ol>
<p>I would like this output</p>
<ol>
<li>ClarkRalphKent</li>
<li>ClarkSupermanKent</li>
</ol>
<p>I have been trying Patterns like: </p>
<pre><code> Pattern p = Pattern.compile("Clark[^((Kent)*)]Kent", Pattern.CASE_INSENSITIVE);
</code></pre>
<p>that don't work, but you see what I'm trying to say. I want the string from Clark to Kent that doesn't contain any occurrences of Kent.</p>
<p>This string:</p>
<p>ClarkRalphKentGuyGreenGardnerBruceBatmanKent</p>
<p>should generate output </p>
<ol>
<li>ClarkRalphKent</li>
</ol>
| [
{
"answer_id": 354289,
"author": "Gareth Davis",
"author_id": 31480,
"author_profile": "https://Stackoverflow.com/users/31480",
"pm_score": 4,
"selected": true,
"text": "Clark.+?Kent"
},
{
"answer_id": 354291,
"author": "Adrian Pronk",
"author_id": 41861,
"author_profile": "https://Stackoverflow.com/users/41861",
"pm_score": 2,
"selected": false,
"text": "? Clark.*?Kent ? * + ?"
},
{
"answer_id": 354319,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": false,
"text": "\"Clark[^((Kent)*)]Kent\" \"Clark((?!Kent).)*Kent\" (, K, e, n, t, ), *"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34410/"
] |
354,288 | <p>I'm having a problem using CSS's <code>display:inline</code> property with the <code>list-style-image:</code> property on <code><li></code> tags. Basically, I want to output the following:</p>
<pre><code>* Link 1 * Link 2
</code></pre>
<p>where <code>*</code> represents an image.</p>
<p>I'm doing this with the following bit of HTML:</p>
<pre><code><ol class="widgets">
<li class="l1">Link 1</li>
<li class="l2">Link 2</li>
</ol>
</code></pre>
<p>which is styled with the following bit of CSS:</p>
<pre><code>ol.widgets { list-style-type:none; }
ol.widgets li { display:inline;
margin-left:10px; }
ol.widgets li.l1 { list-style-image:url(image1.gif); }
ol.widgets li.l2 { list-style-image:url(image2.gif); }
</code></pre>
<p>The problem is that when the list items are displayed inline, the images associated with the list items do not appear. They <em>do</em> appear if I take out the <code>display:inline</code> property on the <code><li></code> tag.</p>
<p>Is there a way to make the images appear even when the list items are displayed inline, or is that just impossible?</p>
| [
{
"answer_id": 354297,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 6,
"selected": true,
"text": "float: left right display: inline"
},
{
"answer_id": 354304,
"author": "flamingLogos",
"author_id": 8161,
"author_profile": "https://Stackoverflow.com/users/8161",
"pm_score": 3,
"selected": false,
"text": "ol.widgets li { \n float: left;\n margin-left: 10px;\n}\n"
},
{
"answer_id": 354337,
"author": "Liwen",
"author_id": 33449,
"author_profile": "https://Stackoverflow.com/users/33449",
"pm_score": 1,
"selected": false,
"text": "list-style-image ol.widgets,\nol.widgets li { list-style: none; }\nol.widgets li { padding-left: 20px; backgroud: transparent (\"image\") no-repeat x y; }\n"
},
{
"answer_id": 11343642,
"author": "CSS Guy",
"author_id": 1388604,
"author_profile": "https://Stackoverflow.com/users/1388604",
"pm_score": 2,
"selected": false,
"text": "ol.widgets ul\n{\nlist-style-image:url('some-img.gif');\n}\nol.widgets ul li\n{\nfloat:left;\n}\n"
},
{
"answer_id": 17574139,
"author": "Angelo Berçacola",
"author_id": 961688,
"author_profile": "https://Stackoverflow.com/users/961688",
"pm_score": 2,
"selected": false,
"text": ".widgets li:before{\n content:\"• \";\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28804/"
] |
354,309 | <p>I am trying to do some simple formatting stuff with 'sed' in linux, and i need to use a regex to trim a string after the 15th character, and append a '...' to the end. Something like this:</p>
<pre><code>before: this is a long string that needs to be shortened
after: this is a long ...
</code></pre>
<p>Can anyone please show me how i could write this as a regex, and if possible explain how it works so that i might learn regex a little better?</p>
| [
{
"answer_id": 354318,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "echo \"This is a test with more than 15 characters\" | sed \"s/\\(.\\{15\\}\\).\\+$/\\1…/\"\n . {15} .+$ \\1 sed"
},
{
"answer_id": 354321,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 2,
"selected": false,
"text": "$ echo 'this is a long string that needs to be shortened' \\\n| perl -pe 's/^(.{15}).+/$1.../'\nthis is a long ...\n ^\n / ^ ^.\n . ^.{15}\n * + {15} {...} * {0,} + {1,} ^(.{15})\n ( ) $1 \\1 $2 ^(.{15}).+\n * $ echo 'this is a long ' \\\n| perl -pe 's/^(.{15}).*/$1.../'\nthis is a long ...\n + $1...\n $1 ."
},
{
"answer_id": 354334,
"author": "Adrian Pronk",
"author_id": 41861,
"author_profile": "https://Stackoverflow.com/users/41861",
"pm_score": 0,
"selected": false,
"text": "s/(.{15}).*/$1.../ s/\\(...............\\).*/\\1.../ ( \\( \\)"
},
{
"answer_id": 354345,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 3,
"selected": false,
"text": " sed \"s/\\(.\\{15\\}\\).+$/\\1…/\"\n\n\\( \n .\n \\{15\\}\n \\)\n .+\n $\n \\1\n ...\n"
},
{
"answer_id": 355052,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 0,
"selected": false,
"text": "s/^\\(.\\{12\\}\\).\\{3\\}.\\+$/\\1.../\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
354,312 | <p>When you run <code>git branch -r</code> why the blazes does it list <code>origin/HEAD</code>? For example, there's a remote repo on GitHub, say, with two branches: master and awesome-feature. If I do <code>git clone</code> to grab it and then go into my new directory and list the branches, I see this:</p>
<pre><code>$ git branch -r
origin/HEAD
origin/master
origin/awesome-feature
</code></pre>
<p>Or whatever order it would be in (alpha? I'm faking this example to keep the identity of an innocent repo secret). So what's the <code>HEAD</code> business? Is it what the last person to <code>push</code> had their <code>HEAD</code> pointed at when they pushed? Won't that always be whatever it was they <code>push</code>ed? <code>HEAD</code>s move around... why do I care what someone's <code>HEAD</code> pointed at on another machine?</p>
<p>I'm just getting a handle on remote tracking and such, so this is one lingering confusion. Thanks!</p>
<p>EDIT: I was under the impression that dedicated remote repos (like GitHub where no one will ssh in and work on that code, but only pull or push, etc) didn't and shouldn't have a HEAD because there was, basically, no working copy. Not so?</p>
| [
{
"answer_id": 354617,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": -1,
"selected": false,
"text": "git push origin HEAD\n"
},
{
"answer_id": 357062,
"author": "Paul",
"author_id": 23356,
"author_profile": "https://Stackoverflow.com/users/23356",
"pm_score": 4,
"selected": false,
"text": "pull fetch HEAD\n\nA symref (see glossary) to the refs/heads/ namespace describing the currently active \nbranch. It does not mean much if the repository is not associated with any working tree \n(i.e. a bare repository), but a valid git repository must have the HEAD file; some \nporcelains may use it to guess the designated \"default\" branch of the repository \n(usually master). It is legal if the named branch name does not (yet) exist.\n"
},
{
"answer_id": 1205692,
"author": "boblu",
"author_id": 147715,
"author_profile": "https://Stackoverflow.com/users/147715",
"pm_score": 5,
"selected": false,
"text": "git branch -d -r origin/HEAD\n git remote set-head <name> -d\n git remote rename origin <new_name>\n"
},
{
"answer_id": 6838756,
"author": "cdunn2001",
"author_id": 263998,
"author_profile": "https://Stackoverflow.com/users/263998",
"pm_score": 8,
"selected": true,
"text": "origin/HEAD git remote set-head origin trunk\n git remote set-head origin -d\n trunk origin/HEAD trunk"
},
{
"answer_id": 10490224,
"author": "Walker Hale IV",
"author_id": 642372,
"author_profile": "https://Stackoverflow.com/users/642372",
"pm_score": 3,
"selected": false,
"text": "$ git remote show\norigin\n$ git remote show origin\n* remote origin\n Fetch URL: git@github.com:walkerh/pipe-o-matic.git\n Push URL: git@github.com:walkerh/pipe-o-matic.git\n HEAD branch: master\n Remote branch:\n master tracked\n Local branch configured for 'git pull':\n master merges with remote master\n Local ref configured for 'git push':\n master pushes to master (fast-forwardable)\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9619/"
] |
354,313 | <p>How can I force the input's onchange script to run <em>before</em> the RangeValidator's script? </p>
<p>I want to prevent a failed validation when the user enters a dollar sign or comma.</p>
<pre><code>function cleanUp(str) {
re = /^\$|,/g;
return str.replace(re, ""); // remove "$" and ","
}
<input type="text" id="salary" runat="server"
onchange="this.value=cleanUp(this.value)" />
<asp:RangeValidator ID="salaryValidator"
runat="server" ErrorMessage="Invalid Number"
ControlToValidate="salary" Type="Double" />
</code></pre>
<p><strong>UPDATE:</strong> <br />
I decided to use a CustomValidator that checks the range and uses a currency RegEx. Thanks Michael Kniskern.</p>
<pre><code>function IsCurrency(sender, args) {
var input = args.Value;
// Check for currency formatting.
// Expression is from http://regexlib.com/REDetails.aspx?regexp_id=70
re = /^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$/;
isCurrency = input.match(re);
if (isCurrency) {
// Convert the string to a number.
var number = parseFloat(CleanUp(input));
if (number != NaN) {
// Check the range.
var min = 0;
var max = 1000000;
if (min <= number && max >= number) {
// Input is valid.
args.IsValid = true;
return;
}
}
}
// Input is not valid if we reach this point.
args.IsValid = false;
return;
}
function CleanUp(number) {
re = /^\$|,/g;
return number.replace(re, ""); // remove "$" and ","
}
<input type="text" id="salary" runat="server" />
<asp:CustomValidator ID="saleryValidator" ControlToValidate="salary" runat="server"
ErrorMessage="Invalid Number" ClientValidationFunction="IsCurrency" />
</code></pre>
| [
{
"answer_id": 1752683,
"author": "Giablo",
"author_id": 213361,
"author_profile": "https://Stackoverflow.com/users/213361",
"pm_score": 0,
"selected": false,
"text": "\\. /^\\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(\\.[0-9][0-9])?$/\n"
},
{
"answer_id": 5188190,
"author": "Eric Eggers",
"author_id": 528733,
"author_profile": "https://Stackoverflow.com/users/528733",
"pm_score": 2,
"selected": false,
"text": "^\\$?([0-9]{1,3},?([0-9]{3},?)*[0-9]{3}|[0-9]+)(\\.[0-9]{0,2})?$\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23566/"
] |
354,329 | <p>I'm trying to set an invalid value to -1.. But I don't like magic numbers.. Anyone know where to find a set of common constants. I'm working in VS6 (ish). </p>
<p>I'm trying to read a file from across a network, and I need a bad value for the total file size,so I know if I got valid info on it.. 0 is a valid size so I can't use that. </p>
<p>Harper Shelby HIT THE NAIL ON THE HEAD.. Just a little thumb.
He mentioned the win32 constants.. which is exactly what I was thinking about.. Now to find a link :)</p>
| [
{
"answer_id": 354343,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 3,
"selected": true,
"text": "#define BAD_VALUE -1\n"
},
{
"answer_id": 354347,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 2,
"selected": false,
"text": "const int INVALID_FOO = -1\n #define INVALID_FOO -1\n"
},
{
"answer_id": 354348,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": " const int INVALID_VALUE = -1;\n"
},
{
"answer_id": 354648,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "char *myMessage = INVALID_HANDLE;\n"
},
{
"answer_id": 354659,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": -1,
"selected": false,
"text": "If bytes_read < 0\n // error\nEndIf\n"
},
{
"answer_id": 354716,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 1,
"selected": false,
"text": "#include <windows.h>\nvoid main(void) {}\n"
},
{
"answer_id": 355076,
"author": "Lodle",
"author_id": 23339,
"author_profile": "https://Stackoverflow.com/users/23339",
"pm_score": 1,
"selected": false,
"text": "const unsigned int INVALID_FILESIZE = 0xFFFFFFFF;\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354329",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31325/"
] |
354,330 | <p>I'm concerned that this might be working on an NP-Complete problem. I'm hoping someone can give me an answer as to whether it is or not. And I'm looking for more of an answer than just yes or no. I'd like to know why. If you can say,"This is basically this problem 'x' which is/is not NP-Complete. (wikipedia link)"</p>
<p>(No this is not homework)</p>
<p>Is there a way to determine if two points are connected on an arbitrary non-directed graph. e.g., the following</p>
<pre><code>Well
|
|
A
|
+--B--+--C--+--D--+
| | | |
| | | |
E F G H
| | | |
| | | |
+--J--+--K--+--L--+
|
|
M
|
|
House
</code></pre>
<p>Points A though M (no 'I') are control points (like a valve in a natural gas pipe) that can be either open or closed. The '+'s are nodes (like pipe T's), and I guess the Well and the House are also nodes as well.</p>
<p>I'd like to know if I shut an arbitrary control point (e.g., C) whether the Well and House are still connected (other control points may also be closed). E.g., if B, K and D are closed, we still have a path through A-E-J-F-C-G-L-M, and closing C will disconnect the Well and the House. Of course; if just D was closed, closing only C does not disconnect the House.</p>
<p>Another way of putting this, is C a bridge/cut edge/isthmus?</p>
<p>I could treat each control point as a weight on the graph (either 0 for open or 1 for closed); and then find the shortest path between Well and House (a result >= 1 would indicate that they were disconnected. There's various ways I can short circuit the algorithm for finding the shortest path too (e.g., discard a path once it reaches 1, stop searching once we have ANY path that connects the Well and the House, etc.). And of course, I can also put in some artificial limit on how many hops to check before giving up.</p>
<p>Someone must have classified this kind of problem before, I'm just missing the name.</p>
| [
{
"answer_id": 354366,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 5,
"selected": false,
"text": "Create two sets of nodes: toDoSet and doneSet\nAdd the source node to the toDoSet \nwhile (toDoSet is not empty) {\n Remove the first element from toDoSet\n Add it to doneSet\n foreach (node reachable from the removed node) {\n if (the node equals the destination node) {\n return success\n }\n if (the node is not in doneSet) {\n add it to toDoSet \n }\n }\n}\n\nreturn failure.\n"
},
{
"answer_id": 354465,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 2,
"selected": false,
"text": "bool[,] adj = new bool[n, n];\n public bool pathExists(int[,] adj, int start, int end)\n{\n List<int> visited = new List<int>();\n List<int> inprocess = new List<int>();\n inprocess.Add(start);\n\n while(inprocess.Count > 0)\n {\n int cur = inprocess[0];\n inprocess.RemoveAt(0);\n if(cur == end)\n return true;\n if(visited.Contains(cur))\n continue;\n visited.Add(cur);\n for(int i = 0; i < adj.Length; i++)\n if(adj[cur, i] && !visited.Contains(i) && !inprocess.Contains(i))\n inprocess.Add(i);\n }\n return false;\n}\n def connected? from, to, edges\n return true if from == to\n return true if edges.include?([from, to])\n return true if edges.include?([to, from])\n\n adjacent = edges.find_all { |e| e.include? from }\n .flatten\n .reject { |e| e == from }\n\n return adjacent.map do |a|\n connected? a, to, edges.reject { |e| e.include? from }\n end.any?\nend\n"
},
{
"answer_id": 8542302,
"author": "Adrian",
"author_id": 1007845,
"author_profile": "https://Stackoverflow.com/users/1007845",
"pm_score": 1,
"selected": false,
"text": "o o1 o o o o o o2\n \\ / \\ / \\ / \\ /\n o o o o o o o o\n \\ / \\ /\n o o o o o o o o \n \\ /\n o o1 o o o o o o2\n o-o1-o-o-o2\n | |\n o o\n |\n o\n"
},
{
"answer_id": 40583090,
"author": "cristianoms",
"author_id": 770557,
"author_profile": "https://Stackoverflow.com/users/770557",
"pm_score": -1,
"selected": false,
"text": "public void loadGraph() {\n // first we create a new undirected graph of Integers\n UndirectedGraph<Integer, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);\n\n // then we add some nodes\n graph.addVertex(1);\n graph.addVertex(2);\n graph.addVertex(3);\n graph.addVertex(4);\n graph.addVertex(5);\n graph.addVertex(6);\n graph.addVertex(7);\n graph.addVertex(8);\n graph.addVertex(9);\n graph.addVertex(10);\n graph.addVertex(11);\n graph.addVertex(12);\n graph.addVertex(13);\n graph.addVertex(14);\n graph.addVertex(15);\n graph.addVertex(16);\n\n // then we connect the nodes\n graph.addEdge(1, 2);\n graph.addEdge(2, 3);\n graph.addEdge(3, 4);\n graph.addEdge(3, 5);\n graph.addEdge(5, 6);\n graph.addEdge(6, 7);\n graph.addEdge(7, 8);\n graph.addEdge(8, 9);\n graph.addEdge(9, 10);\n graph.addEdge(10, 11);\n graph.addEdge(11, 12);\n graph.addEdge(13, 14);\n graph.addEdge(14, 15);\n graph.addEdge(15, 16);\n\n // finally we use ConnectivityInspector to check nodes connectivity\n ConnectivityInspector<Integer, DefaultEdge> inspector = new ConnectivityInspector<>(graph);\n\n debug(inspector, 1, 2);\n debug(inspector, 1, 4);\n debug(inspector, 1, 3);\n debug(inspector, 1, 12);\n debug(inspector, 16, 5);\n}\n\nprivate void debug(ConnectivityInspector<Integer, DefaultEdge> inspector, Integer n1, Integer n2) {\n System.out.println(String.format(\"are [%s] and [%s] connected? [%s]\", n1, n2, inspector.pathExists(n1, n2)));\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] |
354,349 | <p>Is it possible to change the auto-increment offset on a pre-existing table with JavaDB? </p>
<p>I'm having a problem where inserting new records usually (but not always) fails with an error complaining about using an existing key (my auto-increment column). To populate this database, I took a dump from another database (MySQL) and used a JavaDB stored procedure to insert them all into the corresponding JavaDB table. My theory is that inserting these records copied the existing IDs from the MySQL table. Now the auto-increment functionality is dishing out existing IDs. I figure explicitly setting the offset to some high number will allow the auto-increment to work again.</p>
| [
{
"answer_id": 354517,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 1,
"selected": true,
"text": "ALTER TABLE tbl ALTER COLUMN col SET INCREMENT BY x\n"
},
{
"answer_id": 4225357,
"author": "cweiske",
"author_id": 282601,
"author_profile": "https://Stackoverflow.com/users/282601",
"pm_score": 1,
"selected": false,
"text": "ALTER TABLE my_little_table AUTO_INCREMENT =2000\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471/"
] |
354,354 | <p>I'm using StructureMap in my project and when the application finishes running I need to call the Dispose() method on all of the Singleton instances inside the ObjectFactory that implement IDisposable.</p>
<p>I cannot find anyway to do it via the StructureMap API.</p>
<p>Another thought I had was to get a reference to every instance and call it myself, but I cannot figure out how to loop through all of the instances.</p>
| [
{
"answer_id": 354517,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 1,
"selected": true,
"text": "ALTER TABLE tbl ALTER COLUMN col SET INCREMENT BY x\n"
},
{
"answer_id": 4225357,
"author": "cweiske",
"author_id": 282601,
"author_profile": "https://Stackoverflow.com/users/282601",
"pm_score": 1,
"selected": false,
"text": "ALTER TABLE my_little_table AUTO_INCREMENT =2000\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8739/"
] |
354,369 | <p>In C# how do I still show the headers of a gridview, even with the data source is empty. </p>
<p>I am not auto generating the columns as they are all predefined. </p>
<p>Currently what I am doing is the following.</p>
<p>Get a DataTable back from a stored procedure, then set the DataSource of the gridview, and then call DataBind().</p>
<p>This works fine when I have data, but when no rows are returned then I just get a blank spot where the grid should be.</p>
<p><strong>Edit: Thanks all for the .NET 4+ property. I asked this back in the .NET 3.5 days. This is much easier now. :)</strong></p>
| [
{
"answer_id": 354391,
"author": "Joshua Hudson",
"author_id": 6232,
"author_profile": "https://Stackoverflow.com/users/6232",
"pm_score": 5,
"selected": false,
"text": "//Check to see if we get rows back, if we do just bind.\n\nif (dtFunding.Rows.Count != 0)\n{\n grdFunding.DataSource = dtFunding;\n grdFunding.DataBind();\n}\nelse\n{\n //Other wise add a emtpy \"New Row\" to the datatable and then hide it after binding.\n\n dtFunding.Rows.Add(dtFunding.NewRow());\n grdFunding.DataSource = dtFunding;\n grdFunding.DataBind();\n grdFunding.Rows[0].Visible = false;\n}\n"
},
{
"answer_id": 354497,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<asp:GridView ID=\"gvResults\" AutoGenerateColumns=\"False\" HeaderStyle-CssClass=\"tableheader\" runat=\"server\">\n <EmptyDataTemplate>\n <asp:Label ID=\"lblEmptySearch\" runat=\"server\">No Results Found</asp:Label>\n </EmptyDataTemplate>\n <Columns>\n <asp:BoundField DataField=\"ItemId\" HeaderText=\"ID\" />\n <asp:BoundField DataField=\"Description\" HeaderText=\"Description\" />\n ...\n </Columns>\n</asp:GridView>\n"
},
{
"answer_id": 1128033,
"author": "StriplingWarrior",
"author_id": 120955,
"author_profile": "https://Stackoverflow.com/users/120955",
"pm_score": 3,
"selected": false,
"text": "EmptyDataTemplate GridView ObjectDataSource DataSet DataTable CreateChildControls GridView"
},
{
"answer_id": 5033451,
"author": "zacharydl",
"author_id": 610832,
"author_profile": "https://Stackoverflow.com/users/610832",
"pm_score": 8,
"selected": true,
"text": "ShowHeaderWhenEmpty <asp:GridView runat=\"server\" ID=\"GridView1\" ShowHeaderWhenEmpty=\"true\" AutoGenerateColumns=\"false\">\n <Columns>\n <asp:BoundField HeaderText=\"First Name\" DataField=\"FirstName\" />\n <asp:BoundField HeaderText=\"Last Name\" DataField=\"LastName\" />\n </Columns>\n</asp:GridView>\n GridView1.DataSource = New List(Of String)\nGridView1.DataBind()\n"
},
{
"answer_id": 11020564,
"author": "anegin",
"author_id": 1454395,
"author_profile": "https://Stackoverflow.com/users/1454395",
"pm_score": 1,
"selected": false,
"text": " <Columns>\n <asp:TemplateField HeaderStyle-HorizontalAlign=\"Left\">\n <HeaderTemplate>\n\n <asp:Label ID=\"lbl0\" etc.> </asp:Label>\n <asp:Label ID=\"lbl1\" etc.> </asp:Label>\n\n </HeaderTemplate>\n </asp:TemplateField>\n </Columns>\n <div style=\"overflow: auto; height: 29.5em; width: 100%\">\n <asp:GridView ID=\"Rollup\" runat=\"server\" ShowHeader=\"false\" DataSourceID=\"ObjectDataSource\">\n <Columns>\n <asp:TemplateField HeaderStyle-HorizontalAlign=\"Left\">\n <ItemTemplate>\n\n <asp:Label ID=\"lbl0\" etc.> </asp:Label>\n <asp:Label ID=\"lbl1\" etc.> </asp:Label>\n\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n </asp:GridView>\n</div>\n"
},
{
"answer_id": 11416741,
"author": "Hammad Khan",
"author_id": 777982,
"author_profile": "https://Stackoverflow.com/users/777982",
"pm_score": 2,
"selected": false,
"text": "if not exists (select RepId, startdate,enddate from RepTable where RepID= 10)\n select null RepID,null StartDate,null EndDate\nelse\n select RepId, startdate,enddate from RepTable where RepID= 10\n if not exists (query part)"
},
{
"answer_id": 12535465,
"author": "Dmitriy Pichugin",
"author_id": 1689489,
"author_profile": "https://Stackoverflow.com/users/1689489",
"pm_score": -1,
"selected": false,
"text": "EmptyDataText <asp:GridView ID=\"_gridView\" RunAt=\"server\" AutoGenerateColumns=\"false\"\n EmptyDataText=\"No entries found.\">\n"
},
{
"answer_id": 13971072,
"author": "vikram Jangra",
"author_id": 1918608,
"author_profile": "https://Stackoverflow.com/users/1918608",
"pm_score": 2,
"selected": false,
"text": "\"<asp:GridView AutoGenerateColumns=\"false\" ShowHeaderWhenEmpty=\"true\"\" showheaderwhenEmpty"
},
{
"answer_id": 18653303,
"author": "user2753577",
"author_id": 2753577,
"author_profile": "https://Stackoverflow.com/users/2753577",
"pm_score": 1,
"selected": false,
"text": "<asp:GridView ID=\"grdGroup\" EmptyDataText=\"No Records Found\" ShowHeaderWhenEmpty=\"True\" runat=\"server\">\n"
},
{
"answer_id": 31287658,
"author": "Sureshkumar T",
"author_id": 4799535,
"author_profile": "https://Stackoverflow.com/users/4799535",
"pm_score": -1,
"selected": false,
"text": "<asp:GridView ID=\"gvEmployee\" runat=\"server\" \n AutoGenerateColumns=\"False\" ShowHeaderWhenEmpty=”True”> \n <Columns> \n <asp:BoundField DataField=\"Id\" HeaderText=\"Id\" /> \n <asp:BoundField DataField=\"Name\" HeaderText=\"Name\" /> \n <asp:BoundField DataField=\"Designation\" HeaderText=\"Designation\" /> \n <asp:BoundField DataField=\"Salary\" HeaderText=\"Salary\" /> \n </Columns> \n <EmptyDataTemplate>No Record Available</EmptyDataTemplate> \n </asp:GridView> \n\n\nin CS Page\n\ngvEmployee.DataSource = dt; \ngvEmployee.DataBind(); \n"
},
{
"answer_id": 31287726,
"author": "Suresh klt",
"author_id": 1805784,
"author_profile": "https://Stackoverflow.com/users/1805784",
"pm_score": -1,
"selected": false,
"text": " <asp:GridView ID=\"gvEmployee\" runat=\"server\" \n AutoGenerateColumns=\"False\" ShowHeaderWhenEmpty=”True”> \n <Columns> \n <asp:BoundField DataField=\"Id\" HeaderText=\"Id\" /> \n <asp:BoundField DataField=\"Name\" HeaderText=\"Name\" /> \n <asp:BoundField DataField=\"Designation\" HeaderText=\"Designation\" /> \n <asp:BoundField DataField=\"Salary\" HeaderText=\"Salary\" /> \n </Columns> \n <EmptyDataTemplate>No Record Available</EmptyDataTemplate> \n </asp:GridView> \n\n\n in CS Page\n\n gvEmployee.DataSource = dt; \n gvEmployee.DataBind(); \n\nHelp.. see that link:\nhttp://www.c-sharpcorner.com/UploadFile/d0e913/how-to-display-the-empty-gridview-in-case-of-no-records-in-d/\n"
},
{
"answer_id": 38096858,
"author": "kez",
"author_id": 4172460,
"author_profile": "https://Stackoverflow.com/users/4172460",
"pm_score": 2,
"selected": false,
"text": "<asp:GridView ID=\"RadGrid2\" runat=\"server\" > \n<MasterTableView ShowHeadersWhenNoRecords=\"true\" > \n if (GridView1.DataSource == null) \n { \n GridView1.DataSource = new string[] { }; \n } \n GridView1.DataBind();\n"
},
{
"answer_id": 48428451,
"author": "Md Toufiqul Islam",
"author_id": 1550436,
"author_profile": "https://Stackoverflow.com/users/1550436",
"pm_score": 0,
"selected": false,
"text": "<asp:SqlDataSource ID=\"SqlData1\" runat=\"server\" ConnectionString=\"\" SelectCommand=\"myStoredProcedure\" SelectCommandType=\"StoredProcedure\" CancelSelectOnNullParameter=\"False\"> </asp:SqlDataSource>"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6232/"
] |
354,374 | <p>I have a project that uses a class library for the business layer functionality (database access, etc.). A web application sits on top of this. I have a web service that I would like to call in the class library. Every time I add a 'service reference' (I am using VS2008) to the class library, everything seems to work OK. The name of the web service is 'EmployeeService'. However, when I try to access it from code, intellisense gives me options like: </p>
<p>'EmployeeServiceSoap'</p>
<p>'EmployeeServiceSoapChannel'</p>
<p>'EmployeeServiceSoapClient'</p>
<p>and lots of
'...Request'</p>
<p>'...RequestBody'</p>
<p>'...RequestResponse' types. </p>
<p>I can't access my EmployeeService class even if I write it anyway the compiler will complain. Any ideas? Thanks for any help...</p>
| [
{
"answer_id": 354424,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "EmployeeServiceSoapClient"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,385 | <p>I would like to create a view similar to the "Now Playing" page on the iPhone and have 3 lines of text in the Navigation bar.</p>
<p>The only way I could find to do this was:</p>
<pre><code>UINavigationBar *bar = [self.navigationController navigationBar];
label = [[UILabel alloc] initWithFrame:CGRectMake(60, 2, 200, 14)];
label.tag = SONG_TAG;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:14];
label.adjustsFontSizeToFitWidth = NO;
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.highlightedTextColor = [UIColor blackColor];
[bar addSubview:label];
[label release];
//Create album label
label = [[UILabel alloc] initWithFrame:CGRectMake(60, 17, 200, 12)];
label.tag = ALBUM_TAG;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont systemFontOfSize:12];
label.adjustsFontSizeToFitWidth = NO;
label.textAlignment = UITextAlignmentCenter;
label.highlightedTextColor = [UIColor blackColor];
label.textColor = HEXCOLOR(0xA5A5A5ff);
[bar addSubview:label];
[label release];
//Create artist label
label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.tag = ARTIST_TAG;
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont systemFontOfSize:12];
label.adjustsFontSizeToFitWidth = NO;
label.textAlignment = UITextAlignmentCenter;
label.highlightedTextColor = [UIColor blackColor];
label.textColor = HEXCOLOR(0xA5A5A5ff);
[bar addSubview:label];
[label release];
</code></pre>
<p>The problem with this is I have to remove them when the view changes. So, in -viewWillDisappear I have:</p>
<pre><code>UILabel *label;
label = (UILabel *)[self.navigationController.navigationBar viewWithTag:SONG_TAG];
[label removeFromSuperview];
label = (UILabel *)[self.navigationController.navigationBar viewWithTag:ALBUM_TAG];
[label removeFromSuperview];
label = (UILabel *)[self.navigationController.navigationBar viewWithTag:ARTIST_TAG];
[label removeFromSuperview];
</code></pre>
<p>I think the way to do this is make a custom view that has the 3 labels in it, and add this to the title view. (here's the catch - you can only add 1 label or view to the title view spot on the nav bar)</p>
<pre><code>self.navigationItem.titleView = newViewIMadeWithThreeLabels
</code></pre>
| [
{
"answer_id": 369966,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];\nbtn.frame = CGRectMake(0, 0, 320, 60);\n\nUILabel *label;\nlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 200, 16)];\nlabel.tag = SONG_TAG;\nlabel.backgroundColor = [UIColor clearColor];\nlabel.font = [UIFont boldSystemFontOfSize:16];\nlabel.adjustsFontSizeToFitWidth = NO;\nlabel.textAlignment = UITextAlignmentCenter;\nlabel.textColor = [UIColor blackColor];\nlabel.text = @\"first line\";\nlabel.highlightedTextColor = [UIColor blackColor];\n[btn addSubview:label];\n[label release];\n\nlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 200, 16)];\nlabel.tag = SONG_TAG;\nlabel.backgroundColor = [UIColor clearColor];\nlabel.font = [UIFont boldSystemFontOfSize:16];\nlabel.adjustsFontSizeToFitWidth = NO;\nlabel.textAlignment = UITextAlignmentCenter;\nlabel.textColor = [UIColor blackColor];\nlabel.text = @\"second line\";\nlabel.highlightedTextColor = [UIColor blackColor];\n[btn addSubview:label];\n[label release];\n\nself.navigationItem.titleView = btn;\n"
},
{
"answer_id": 1937153,
"author": "Nik Burns",
"author_id": 235647,
"author_profile": "https://Stackoverflow.com/users/235647",
"pm_score": 2,
"selected": false,
"text": "UIView *btn = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 60)];\n\nUILabel *label;\nlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 200, 16)];\nlabel.tag = 1;\nlabel.backgroundColor = [UIColor clearColor];\nlabel.font = [UIFont boldSystemFontOfSize:16];\nlabel.adjustsFontSizeToFitWidth = NO;\nlabel.textAlignment = UITextAlignmentCenter;\nlabel.textColor = [UIColor blackColor];\nlabel.text = @\"first line\";\nlabel.highlightedTextColor = [UIColor blackColor];\n[btn addSubview:label];\n[label release];\n\nlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 200, 16)];\nlabel.tag = 2;\nlabel.backgroundColor = [UIColor clearColor];\nlabel.font = [UIFont boldSystemFontOfSize:16];\nlabel.adjustsFontSizeToFitWidth = NO;\nlabel.textAlignment = UITextAlignmentCenter;\nlabel.textColor = [UIColor blackColor];\nlabel.text = @\"second line\";\nlabel.highlightedTextColor = [UIColor blackColor];\n[btn addSubview:label];\n[label release];\n\nself.navigationItem.titleView = btn;\n"
},
{
"answer_id": 2833975,
"author": "Stephen",
"author_id": 341212,
"author_profile": "https://Stackoverflow.com/users/341212",
"pm_score": 1,
"selected": false,
"text": "UINavigationBar *bar = [self.navigationController navigationBar];\nCGFloat navBarHeight = 70.0f; \nCGRect frame = CGRectMake(0.0f, 0.0f, 320.0f, navBarHeight);\n[bar setFrame:frame];\nUILabel *label;\nlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320, 10)];\nlabel.tag = 1;\nlabel.backgroundColor = [UIColor clearColor];\nlabel.font = [UIFont boldSystemFontOfSize:12];\nlabel.adjustsFontSizeToFitWidth = NO;\nlabel.textAlignment = UITextAlignmentCenter;\nlabel.textColor = [UIColor blackColor];\nlabel.text = @\"Set the details for this event.\";\nlabel.highlightedTextColor = [UIColor blackColor];\n[bar addSubview:label];\n[label release];\n[bar release];\n"
},
{
"answer_id": 3794912,
"author": "Viccaso",
"author_id": 458294,
"author_profile": "https://Stackoverflow.com/users/458294",
"pm_score": 0,
"selected": false,
"text": "enum enum {\n SONG_TAG,\n ALBUM_TAG,\n ARTIST_TAG\n};\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
354,386 | <p>I have a Windows Mobile application using the compact framework (NETCF) that I would like to respond to someone pressing the send key and have the phone dial the number selected in my application. Is there a way using the compact framework to trap the send key? I have looked at several articles on capturing keys, but I have not found one that includes the "Send" key.</p>
<p><strong>Update</strong>:</p>
<p>I found an article describing SetWindowsHookEx as an undocumented API on Windows Mobile. If this is the case then I really don't want to use it.</p>
<p><a href="http://blogs.msdn.com/raffael/archive/2008/05/12/setwindowshookex-on-windows-mobile.aspx" rel="nofollow noreferrer">SetWindowsHookEx on Windows Mobile</a></p>
<p>After doing more searching I found out that the "Send" key is called the "Talk" key in Windows Mobile lingo. I then found a blog post about using the SHCMBM_OVERRIDEKEY message to signal the OS to send my app a WM_HOTKEY message when the user presses the Talk key.</p>
<p><a href="http://blogs.msdn.com/windowsmobile/archive/2005/09/02/460327.aspx" rel="nofollow noreferrer">Jason Fuller Blog post about using the Talk button</a></p>
<p>The blog post and the documentation it points to seem like exactly what I'm looking for. I'm unable to find a working example, and I find a lot of people unable to make it work. It also looks like VK_TTALK is not supported in SmartPhones. I would love to hear from someone that actually has this working on both Smartphones and PocketPC phones.</p>
| [
{
"answer_id": 554375,
"author": "Shane Powell",
"author_id": 23235,
"author_profile": "https://Stackoverflow.com/users/23235",
"pm_score": 3,
"selected": true,
"text": "SendMessage(SHFindMenuBar(window_hwnd), \n SHCMBM_OVERRIDEKEY, \n VK_TTALK, \n MAKELPARAM((SHMBOF_NODEFAULT|SHMBOF_NOTIFY), (SHMBOF_NODEFAULT|SHMBOF_NOTIFY));\n SendMessage(SHFindMenuBar(window_hwnd), \n SHCMBM_OVERRIDEKEY, \n VK_TTALK, \n MAKELPARAM(0, (SHMBOF_NODEFAULT|SHMBOF_NOTIFY));\n case WM_HOTKEY:\n switch(HIWORD(lParam))\n {\n case VK_TTALK:\n // make ph call\n break;\n }\n return TRUE;\n #include <phone.h>\n\nvoid MakePhoneCall(const wchar_t* number)\n{\n PHONEMAKECALLINFO call;\n memset(&call, 0x0, sizeof(PHONEMAKECALLINFO));\n call.cbSize = sizeof(PHONEMAKECALLINFO);\n call.dwFlags = PMCF_DEFAULT;\n call.pszDestAddress = number;\n PhoneMakeCall(&call);\n}\n #include <snapi.h>\n RegistryNotifyWindow(SN_PHONEACTIVECALLCOUNT_ROOT, SN_PHONEACTIVECALLCOUNT_PATH, SN_PHONEACTIVECALLCOUNT_VALUE, window_hwnd, callback_window_msg_number /*e.g. WM_APP */, 0, NULL, &phone_call_notify_handle);\n RegistryCloseNotification(phone_call_notify_handle);\n #define WM_CPROG_SEND_VKEY_DTMF (WM_APP+3) // Sends the DTMF tone(s) through to the current call (converting from VKEY to DTMF chars)\n\n BOOL PhoneSendDTMF(UINT uvKey)\n {\n BOOL bRet = FALSE;\n static HWND s_hwndCProg = NULL;\n TCHAR chDTMF = MapVKeyToChar(uvKey);\n\n // Attempt to find the cprog window (MSCprog).\n // Try to keep this window handle cached.\n if(NULL == s_hwndCProg || !IsWindow(s_hwndCProg))\n {\n s_hwndCProg = FindWindow(TEXT(\"MSCprog\"), NULL);\n }\n\n // Send WM_CPROG_SEND_VKEY_DTMF to the CProg window.\n if(NULL != s_hwndCProg)\n {\n bRet = BOOLIFY(PostMessage(s_hwndCProg,\n WM_CPROG_SEND_VKEY_DTMF, (WPARAM)chDTMF, 0));\n }\n\n return bRet;\n }\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/791/"
] |
354,393 | <p>** Dup: <a href="https://stackoverflow.com/questions/226002/whats-the-difference-between-x-x-vs-x">What's the difference between X = X++; vs X++;?</a> **</p>
<p>So, even though I know you would never actually do this in code, I'm still curious:</p>
<pre><code>public static void main(String[] args) {
int index = 0;
System.out.println(index); // 0
index++;
System.out.println(index); // 1
index = index++;
System.out.println(index); // 1
System.out.println(index++); // 1
System.out.println(index); // 2
}
</code></pre>
<p>Note that the 3rd <code>sysout</code> is still <code>1</code>. In my mind the line <code>index = index++;</code> means "set index to index, then increment index by 1" in the same way <code>System.out.println(index++);</code> means "pass index to the println method then increment index by 1".</p>
<p>This is not the case however. Can anyone explain what's going on?</p>
| [
{
"answer_id": 354398,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": true,
"text": "a = function() {\n var old_value = a;\n a++;\n return old_value;\n}\n"
},
{
"answer_id": 354404,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "value++; int firtValue = 9;\nint secondValue = firstValue++;\n int firtValue = 9;\nint secondValue = ++firstValue;\n"
},
{
"answer_id": 354410,
"author": "Jeff Mc",
"author_id": 25521,
"author_profile": "https://Stackoverflow.com/users/25521",
"pm_score": 1,
"selected": false,
"text": "index++ int i = 5;\nSystem.out.println(i++);\n ++index"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] |
354,407 | <p>I totally understand the MVP pattern now, but I still struggle to see where views and presenters are instantiated. I have seen some examples where the presenter is newed up in the view, but is this correct. After reading a blog post of Jeremy Miller about communicating between View and Presenter he had a function on the Presenter to attach the presenter to the view.</p>
<p>My question is then this: Where should views and presenters be created? Also where in winforms and webforms.</p>
| [
{
"answer_id": 354485,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 2,
"selected": false,
"text": "main"
},
{
"answer_id": 14389890,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 1,
"selected": false,
"text": "public class SomePresenter\n{\n public ShowContactView(IContactView view)\n {\n IContact model = new Contact();\n new ContactPresenter(model, view);\n view.Show();\n }\n} \n\npublic class AnotherPresenter\n{\n public ShowContactView(IContactView view)\n {\n IContact model = new Contact();\n new ContactPresenter(model, view);\n view.Show();\n }\n} \n\npublic class YetAnotherPresenter\n{\n public ShowContactView(IContactView view)\n {\n IContact model = new Contact();\n new ContactPresenter(model, view);\n view.Show();\n }\n} \n\npublic partial class ContactView : Form, IContactView\n{ \n public ContactView()\n {\n InitializeComponent();\n }\n}\n public class SomePresenter\n{\n public ShowContactView(IContactView view)\n {\n view.Show();\n }\n} \n\npublic class AnotherPresenter\n{\n public ShowContactView(IContactView view)\n {\n view.Show();\n }\n} \n\npublic class YetAnotherPresenter\n{\n public ShowContactView(IContactView view)\n {\n view.Show();\n }\n} \n\npublic partial class ContactView : Form, IContactView\n{ \n public ContactView()\n {\n InitializeComponent();\n\n new ContactPresenter(new Contact(), this);\n }\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12230/"
] |
354,408 | <p>It seems like when you have a WinForms .NET application, and a ComboBox (set to the "DropDown" style), and that ComboBox has multiple items in it that are identical, weird things happen. Specifically, the index of the selected item can change <em>without</em> firing the SelectedIndexChanged event. </p>
<p>Of course, this causes mass confusion and weird, obscure errors, which is what I've been pulling my hair out over lately.</p>
<p>Here's a simple example you can use to see what I'm talking about:</p>
<ul>
<li>Make a new .NET WinForms project (I use VB.NET, but feel free to translate - it's simple enough).</li>
<li>Drop a ComboBox, a button, and a TextBox (set MultiLine=True) onto the form.</li>
<li>Use the following code to load the ComboBox with 3 identical items and to print some status messages when the SelectedIndexChanged event fires, and to see what the currently selected index is (via a button):</li>
</ul>
<pre><code>Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = TextBox1.Text & vbNewLine & "ComboBox SelectedIndexChanged event fired." & vbNewLine & _
"SelectedIndex is: " & ComboBox1.SelectedIndex
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
ComboBox1.Items.Add("John Doe")
ComboBox1.Items.Add("John Doe")
ComboBox1.Items.Add("John Doe")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = TextBox1.Text & vbNewLine & _
"Button clicked." & vbNewLine & _
"SelectedIndex is: " & ComboBox1.SelectedIndex
End Sub</code></pre>
<p>Run the project and select an item from the ComboBox (say, the middle one). Then, click the ComboBox's drop-down arrow, but DON'T SELECT ANYTHING. Click the Button (Button1 by default) and see what it says.</p>
<p>Unless I've lost my mind, here's what you should see:</p>
<pre>ComboBox SelectedIndexChanged event fired.
SelectedIndex is: 1
Button clicked.
SelectedIndex is: 0</pre>
<p>In other words, the SELECTED INDEX HAS CHANGED but without the SelectedIndexChanged event firing!</p>
<p>This only happens when the items in the ComboBox are identical. If they're different, this doesn't happen. (It also doesn't happen if the ComboBox's "DropDown" style is set to "DropDownList.")</p>
<p>I suspect this may be a bug in the .NET framework itself and not something I can fix, but on the off chance that anyone else has any ideas on what to do here (or what I might be doing wrong!), please chime in! I'm at a loss to explain this behavior or work around it (I expect the SelectedIndex to stay the same unless, y'know, you actually CHANGE it by selecting something else!)</p>
| [
{
"answer_id": 355012,
"author": "Eric Rosenberger",
"author_id": 41624,
"author_profile": "https://Stackoverflow.com/users/41624",
"pm_score": 5,
"selected": true,
"text": "CBN_SELCHANGE CBN_SELCHANGE CBN_SELCHANGE"
},
{
"answer_id": 923031,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "C:\\\nC:\\A\nC:\\A\\B\nC:\\A\\B\\A\n C:\\\n A\n B\n A\n using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace ComboBoxTest\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n if (DesignMode)\n return;\n\n BindingList<CBItem> items = new BindingList<CBItem>();\n items.Add(new CBItem(\"A\", @\"C:\\A\"));\n items.Add(new CBItem(\"B\", @\"C:\\A\\B\"));\n items.Add(new CBItem(\"A\", @\"C:\\A\\B\\A\"));\n\n comboBox.DisplayMember = \"DisplayValue\";\n comboBox.ValueMember = \"RealValue\";\n comboBox.DataSource = items;\n\n comboBox.SelectedValue = @\"C:\\A\\B\\A\";\n }\n }\n\n class CBItem\n {\n public CBItem(string displayValue, string realValue)\n {\n _displayValue = displayValue;\n _realValue = realValue;\n }\n\n private readonly string _displayValue, _realValue;\n\n public string DisplayValue { get { return _displayValue; } }\n public string RealValue { get { return _realValue; } }\n }\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5956/"
] |
354,414 | <p>Can anybody help me to build an XSD file to validate XMLs like these:</p>
<pre><code>[test]
[a/]
[b/]
[a/]
[b/]
[/test]
[test]
[a/]
[a/]
[b/]
[/test]
</code></pre>
<p>Basically, I can have any number of <code><a></code> and/or <code><b></code> nodes without any other rule (can't use <code><xs:sequence></code>).</p>
| [
{
"answer_id": 354908,
"author": "MotoWilliams",
"author_id": 2730,
"author_profile": "https://Stackoverflow.com/users/2730",
"pm_score": 2,
"selected": true,
"text": "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:element name=\"test\">\n <xs:complexType>\n <xs:sequence>\n <xs:choice maxOccurs=\"unbounded\">\n <xs:element name=\"a\"/>\n <xs:element name=\"b\"/>\n </xs:choice>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44769/"
] |
354,415 | <p>I'm using VS2008 Team Suite, ASP.NET MVC Beta, with TestDriven.Net installed. When I created my project from the template, it created a "Tests" project as well and put some controller tests for the AccountController in a folder inside this project. I've added other controllers and associated tests. Howerver, when I right-click on a method in a controller and use the "Create Unit Tests" dialog it fails to create the unit test stub in my existing test class in the project. It creates a new test class file with the same name at the root of the test project, but doesn't insert the test stub. If I move the controller tests up one level from the controllers folder in the test project it works fine.</p>
<p>Does anyone else see this behavior or is it something related to my particular set up? I wouldn't have noticed, but the project segregated the tests in a separate folder, which I thought was a good idea. Now that I'm trying to use it, I either have to create new tests by hand or undo the segregation. If it's just me, any ideas on where to adjust the behavior to fix it?</p>
<p>I have <code>Visual C# test project</code> selected as default in options, with <code>Unit Test</code> as the only file included.</p>
| [
{
"answer_id": 354908,
"author": "MotoWilliams",
"author_id": 2730,
"author_profile": "https://Stackoverflow.com/users/2730",
"pm_score": 2,
"selected": true,
"text": "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:element name=\"test\">\n <xs:complexType>\n <xs:sequence>\n <xs:choice maxOccurs=\"unbounded\">\n <xs:element name=\"a\"/>\n <xs:element name=\"b\"/>\n </xs:choice>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12950/"
] |
354,419 | <p>I'm migrating to Nhibernate 2.0 GA but have some trouble with setting cache expirations in memcached provider.</p>
<p>I see in the NHibernate.Caches.MemCache sources that there is a property for expiration and a default value for 300 seconds. </p>
<p>There are also properties for cache regions but the config section handler does not seem to map them.</p>
<p>Is there some other way cache expiration times are set that is not provider specific --</p>
<p>Here is functional web config section (without an expiration settings obviously).</p>
<pre><code><memcache>
<memcached host="127.0.0.1" port="11211"/>
<!-- or multiples -->
</memcache>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="show_sql">true</property>
<property name="connection.provider" >NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<!-- <property name="hibernate.cache.provider_class" value="NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache" /> -->
<property name="connection.connection_string">Data Source=stage2.ripple6.com;Initial Catalog=r6stage;User Id=sa;Password=mworld7650;Application Name=Hibernate;</property>
<property name="connection.isolation">ReadCommitted</property>
<property name="cache.use_second_level_cache">true</property>
<property name="cache.provider_class">NHibernate.Caches.MemCache.MemCacheProvider,NHibernate.Caches.MemCache</property>
<property name="default_schema" >r6stage.dbo</property>
</session-factory>
</hibernate-configuration>
</code></pre>
| [
{
"answer_id": 444445,
"author": "jozefsevcik",
"author_id": 11472,
"author_profile": "https://Stackoverflow.com/users/11472",
"pm_score": -1,
"selected": true,
"text": "<property name=\"expiration\" >YOUR_INTERVAL_IN_SECONDS</property>\n NHibernate.Caches.MemCache.MemCacheClient: 20:57:55,762 DEBUG MemCacheClient:0 - using expiration of YOUR_INTERVAL_IN_SECONDS seconds\n"
},
{
"answer_id": 5933302,
"author": "golamrabbi",
"author_id": 330662,
"author_profile": "https://Stackoverflow.com/users/330662",
"pm_score": 1,
"selected": false,
"text": "<property name=\"default_expiration\" >YOUR_INTERVAL_IN_SECONDS</property>\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43853/"
] |
354,421 | <p>I'm wondering where I find the source to show how the operator ** is implemented in Python. Can someone point me in the right direction? </p>
| [
{
"answer_id": 354626,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 6,
"selected": true,
"text": "PyObject *\nPyNumber_Power(PyObject *v, PyObject *w, PyObject *z)\n{\n return ternary_op(v, w, z, NB_SLOT(nb_power), \"** or pow()\");\n}\n if (Py_SIZE(b) <= FIVEARY_CUTOFF) {\n /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */\n /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */\n for (i = Py_SIZE(b) - 1; i >= 0; --i) {\n digit bi = b->ob_digit[i];\n\n for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {\n MULT(z, z, z)\n if (bi & j)\n MULT(z, a, z)\n }\n }\n}\nelse {\n /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */\n Py_INCREF(z); /* still holds 1L */\n table[0] = z;\n for (i = 1; i < 32; ++i)\n MULT(table[i-1], a, table[i])\n\n for (i = Py_SIZE(b) - 1; i >= 0; --i) {\n const digit bi = b->ob_digit[i];\n\n for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {\n const int index = (bi >> j) & 0x1f;\n for (k = 0; k < 5; ++k)\n MULT(z, z, z)\n if (index)\n MULT(z, table[index], z)\n }\n }\n}\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41718/"
] |
354,442 | <p>Before I write my own I will ask all y'all.</p>
<p>I'm looking for a C++ class that is almost exactly like a STL vector but stores data into an array on the stack. Some kind of STL allocator class would work also, but I am trying to avoid any kind of heap, even static allocated per-thread heaps (although one of those is my second choice). The stack is just more efficient.</p>
<p>It needs to be almost a drop in replacement for current code that uses a vector.</p>
<p>For what I was about to write myself I was thinking of something like this:</p>
<pre><code>char buffer[4096];
stack_vector<match_item> matches(buffer, sizeof(buffer));
</code></pre>
<p>Or the class could have buffer space allocated internally. Then it would look like:</p>
<pre><code>stack_vector<match_item, 256> matches;
</code></pre>
<p>I was thinking it would throw std::bad_alloc if it runs out of space, although that should not ever happen.</p>
<p><strong>Update</strong></p>
<p>Using Chromium's stack_container.h works great! </p>
<p>The reason I hadn't thought of doing it this way myself is that I have always overlooked the allocator object parameter to the STL collection constructors. I have used the template parameter a few times to do static pools but I'd never seen code or written any that actually used the object parameter. I learned something new. Very cool!</p>
<p>The code is a bit messy and for some reason GCC forced me to declare the allocator as an actual item instead of constructing it into vector's allocator parameter. It went from something like this:</p>
<pre><code>typedef std::pair< const char *, const char * > comp_list_item;
typedef std::vector< comp_list_item > comp_list_type;
comp_list_type match_list;
match_list.reserve(32);
</code></pre>
<p>To this:</p>
<pre><code>static const size_t comp_list_alloc_size = 128;
typedef std::pair< const char *, const char * > comp_list_item;
typedef StackAllocator< comp_list_item, comp_list_alloc_size > comp_list_alloc_type;
typedef std::vector< comp_list_item, comp_list_alloc_type > comp_list_type;
comp_list_alloc_type::Source match_list_buffer;
comp_list_alloc_type match_list_alloc( &match_list_buffer );
comp_list_type match_list( match_list_alloc );
match_list.reserve( comp_list_alloc_size );
</code></pre>
<p>And I have to repeat that whenever I declare a new one. But it works just like I wanted.</p>
<p>I noticed that stack_container.h has a StackVector defined and I tried using it. But it doesn't inherit from vector or define the same methods so it wasn't a drop-in replacement. I didn't want to rewrite all the code using the vector so I gave up on it.</p>
| [
{
"answer_id": 354481,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": true,
"text": "std::vector container.reserve(buffer_size); std::allocator StackVector<int, 128> s;\ns->push_back(42); // overloaded operator->\ns->push_back(43);\n\n// to get the real std::vector. \nStackVector<int, 128>::ContainerType & v = s.container();\nstd::cout << v[0] << \" \" << v[1] << std::endl;\n"
},
{
"answer_id": 354818,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "auto_buffer alloca() boost::array vector begin() end() size()"
},
{
"answer_id": 1199521,
"author": "denis",
"author_id": 86643,
"author_profile": "https://Stackoverflow.com/users/86643",
"pm_score": 3,
"selected": false,
"text": "<vector> <stlsoft/containers/pod_vector.hpp> #include <stlsoft/containers/pod_vector.hpp>\n#include <stdio.h>\nusing namespace std;\n\nint main( int argc, char* argv[] )\n{\n // times for 2 push, v[0] v[1], 2 pop, mac g4 ppc gcc-4.2 -O3 --\n // Vecint10 v; // stack int[10]: 4 ns\n vector<int> v; // 40 ns\n // stlsoft::pod_vector<int> v; // 1300 ns\n // stlsoft::pod_vector<int, std::allocator<int>, 64> v;\n\n int n = (argv[1] ? atoi( argv[1] ) : 10) * 1000000;\n int sum = 0;\n\n while( --n >= 0 ){\n v.push_back( n );\n v.push_back( n );\n sum += v[0] + v[1];\n v.pop_back();\n v.pop_back();\n }\n printf( \"sum: %d\\n\", sum );\n\n}\n"
},
{
"answer_id": 23640505,
"author": "Sebastian Graf",
"author_id": 388010,
"author_profile": "https://Stackoverflow.com/users/388010",
"pm_score": 2,
"selected": false,
"text": "QVarLengthArray std::vector std::array"
},
{
"answer_id": 49153114,
"author": "MathuSum Mut",
"author_id": 5007383,
"author_profile": "https://Stackoverflow.com/users/5007383",
"pm_score": 1,
"selected": false,
"text": "new_stack_vector(Type, name, size)\n Type name size size new_stack_vector(int, vec, 100); //like vector<int> vec; vec.reserve(100); but on the stack :)\nvec.push_back(10); //added \"10\" as the first item in the vector\n int var[9999999] new_stack_vector(int, vec, 9999999)"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13422/"
] |
354,445 | <p>Is there an easy method to restore a minimized form to its previous state, either Normal or Maximized? I'm expecting the same functionality as clicking the taskbar (or right-clicking and choosing restore).</p>
<p>So far, I have this, but if the form was previously maximized, it still comes back as a normal window.</p>
<pre><code>if (docView.WindowState == FormWindowState.Minimized)
docView.WindowState = FormWindowState.Normal;
</code></pre>
<p>Do I have to handle the state change in the form to remember the previous state?</p>
| [
{
"answer_id": 354493,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 3,
"selected": false,
"text": "SendMessage(docView.Handle, WM_SYSCOMMAND, SC_RESTORE, 0);\n"
},
{
"answer_id": 1398956,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "CxImports.ManagedWindowPlacement placement = new CxImports.ManagedWindowPlacement();\nCxImports.GetWindowPlacement(Convert.ToUInt32(Handle.ToInt64()), placement);\n\nif (placement.flags == CxImports.WPF_RESTORETOMAXIMIZED)\n WindowState = FormWindowState.Maximized;\nelse\n WindowState = FormWindowState.Normal;\n"
},
{
"answer_id": 2725234,
"author": "Mesmo",
"author_id": 327292,
"author_profile": "https://Stackoverflow.com/users/327292",
"pm_score": 7,
"selected": true,
"text": "using System.Runtime.InteropServices;\n\nnamespace System.Windows.Forms\n{\n public static class Extensions\n {\n [DllImport( \"user32.dll\" )]\n private static extern int ShowWindow( IntPtr hWnd, uint Msg );\n\n private const uint SW_RESTORE = 0x09;\n\n public static void Restore( this Form form )\n {\n if (form.WindowState == FormWindowState.Minimized)\n {\n ShowWindow(form.Handle, SW_RESTORE);\n }\n }\n }\n}\n form.Restore()"
},
{
"answer_id": 28697026,
"author": "Ashraf Sada",
"author_id": 2459714,
"author_profile": "https://Stackoverflow.com/users/2459714",
"pm_score": 4,
"selected": false,
"text": "if (MyForm.WindowState == FormWindowState.Minimized)\n{\n MyForm.WindowState = FormWindowState.Normal;\n}\n"
},
{
"answer_id": 51219043,
"author": "J. Doe",
"author_id": 9922804,
"author_profile": "https://Stackoverflow.com/users/9922804",
"pm_score": 2,
"selected": false,
"text": " public void UnMinimize(IntPtr handle)\n {\n WINDOWPLACEMENT WinPlacement = new WINDOWPLACEMENT();\n GetWindowPlacement(handle, out WinPlacement);\n if(WinPlacement.flags.HasFlag(WINDOWPLACEMENT.Flags.WPF_RESTORETOMAXIMIZED))\n {\n ShowWindow(handle, (int)SW_MAXIMIZE);\n }\n else\n {\n ShowWindow(handle, (int)SW_RESTORE);\n }\n }\n [StructLayout(LayoutKind.Sequential)]\npublic struct RECT\n{\n public Int32 Left;\n public Int32 Top;\n public Int32 Right;\n public Int32 Bottom;\n}\n\npublic struct POINT\n{\n public int x;\n public int y;\n}\n\npublic struct WINDOWPLACEMENT\n{\n\n [Flags]\n public enum Flags : uint\n {\n WPF_ASYNCWINDOWPLACEMENT = 0x0004,\n WPF_RESTORETOMAXIMIZED = 0x0002,\n WPF_SETMINPOSITION = 0x0001\n }\n\n\n /// <summary>\n /// The length of the structure, in bytes. Before calling the GetWindowPlacement or SetWindowPlacement functions, set this member to sizeof(WINDOWPLACEMENT).\n /// </summary>\n public uint length;\n /// <summary>\n /// The flags that control the position of the minimized window and the method by which the window is restored. This member can be one or more of the following values.\n /// </summary>\n /// \n public Flags flags;//uint flags;\n /// <summary>\n /// The current show state of the window. This member can be one of the following values.\n /// </summary>\n public uint showCmd;\n /// <summary>\n /// The coordinates of the window's upper-left corner when the window is minimized.\n /// </summary>\n public POINT ptMinPosition;\n /// <summary>\n /// The coordinates of the window's upper-left corner when the window is maximized.\n /// </summary>\n public POINT ptMaxPosition;\n /// <summary>\n /// The window's coordinates when the window is in the restored position.\n /// </summary>\n public RECT rcNormalPosition;\n}\n\npublic class UnMinimizeClass\n{\n [DllImport(\"user32.dll\")]\n public static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);\n\n [DllImport(\"user32.dll\")]\n public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\n const int SW_MAXIMIZE = 3;\n const int SW_RESTORE = 9;\n\n public static void UnMinimize(IntPtr handle)\n {\n WINDOWPLACEMENT WinPlacement = new WINDOWPLACEMENT();\n GetWindowPlacement(handle, out WinPlacement);\n if (WinPlacement.flags.HasFlag(WINDOWPLACEMENT.Flags.WPF_RESTORETOMAXIMIZED))\n {\n ShowWindow(handle, SW_MAXIMIZE);\n }\n else\n {\n ShowWindow(handle, (int)SW_RESTORE);\n }\n }\n}\n"
},
{
"answer_id": 58137756,
"author": "李起升",
"author_id": 8638027,
"author_profile": "https://Stackoverflow.com/users/8638027",
"pm_score": 0,
"selected": false,
"text": " [DllImport(\"user32.dll\")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool GetWindowRect(IntPtr hWnd, ref wndRect lpRect);\n [DllImport(\"user32.dll\")] public static extern bool IsWindowVisible(IntPtr hWnd);\n [DllImport(\"user32.dll\")] public static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);//用来遍历所有窗口 \n [DllImport(\"user32.dll\")] public static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);//获取窗口Text \n [DllImport(\"user32.dll\")] public static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);//获取窗口类名 \n\n public static List<wndInfo> GetAllDesktopWindows(bool? isVisitable_)\n {\n //用来保存窗口对象\n List<wndInfo> wndList = new List<wndInfo>();\n\n //enum all desktop windows \n EnumWindows(delegate (IntPtr hWnd, int lParam)\n {\n wndInfo wnd = new wndInfo();\n StringBuilder sb = new StringBuilder(256);\n //get hwnd \n wnd.hWnd = hWnd;\n if (isVisitable_ == null || IsWindowVisible(wnd.hWnd) == isVisitable_)\n {\n //get window name \n GetWindowTextW(hWnd, sb, sb.Capacity);\n wnd.szWindowName = sb.ToString();\n\n //get window class \n GetClassNameW(hWnd, sb, sb.Capacity);\n wnd.szClassName = sb.ToString();\n\n wndList.Add(wnd);\n }\n return true;\n\n }, 0);\n\n return wndList;\n }\n\n private void Btn_Test5_Click(object sender, RoutedEventArgs e)\n {\n var ws = WSys.GetAllDesktopWindows(true);\n foreach (var w in ws)\n {\n if (w.szWindowName == \"计算器\")\n {\n WSys.ShowWindow(w.hWnd, 5);\n WSys.ShowWindow(w.hWnd, 9);\n Log.WriteLine(w.szWindowName);\n }\n }\n }\n"
},
{
"answer_id": 59719760,
"author": "Dmytro Koshel",
"author_id": 12705259,
"author_profile": "https://Stackoverflow.com/users/12705259",
"pm_score": 2,
"selected": false,
"text": "MainWindow.WindowState = WindowState.Normal; MainWindow.WindowState = WindowState.Normal;\nMainWindow.Show();\nMainWindow.Activate();\n"
},
{
"answer_id": 60350829,
"author": "shashwat",
"author_id": 1306394,
"author_profile": "https://Stackoverflow.com/users/1306394",
"pm_score": 1,
"selected": false,
"text": "public static class Utilities\n{\n [DllImport(\"user32.dll\")]\n private static extern int ShowWindow(IntPtr hWnd, uint Msg);\n\n private const uint SW_RESTORE = 0x09;\n\n public static void Restore(this Form form)\n {\n if (form.WindowState == FormWindowState.Minimized)\n {\n ShowWindow(form.Handle, SW_RESTORE);\n }\n }\n\n public static void CreateOrRestoreForm<T>() where T: Form\n {\n Form form = Application.OpenForms.OfType<T>().FirstOrDefault();\n\n if (form == null)\n {\n form = Activator.CreateInstance<T>();\n form.Show();\n }\n else\n {\n form.Restore();\n form.Focus();\n }\n }\n}\n Utilities.CreateOrRestoreForm<AboutForm>();\n"
},
{
"answer_id": 69002289,
"author": "Rob",
"author_id": 594308,
"author_profile": "https://Stackoverflow.com/users/594308",
"pm_score": 1,
"selected": false,
"text": " FormWindowState _PreviousWindowState;\n\n private void TestForm_Resize(object sender, EventArgs e)\n {\n if (WindowState != FormWindowState.Minimized)\n _PreviousWindowState = WindowState;\n }\n private void Tray_MouseClick(object sender, MouseEventArgs e)\n {\n Activate();\n if (WindowState == FormWindowState.Minimized)\n WindowState = _PreviousWindowState; // former glory\n }\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44770/"
] |
354,449 | <p>Anyone know the <code><%= %></code> or <code>Response.Write()</code> code for getting the version of .Net my web app is running on?</p>
| [
{
"answer_id": 354460,
"author": "jlew",
"author_id": 7450,
"author_profile": "https://Stackoverflow.com/users/7450",
"pm_score": 5,
"selected": true,
"text": "System.Environment.Version"
},
{
"answer_id": 623246,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13954/"
] |
354,473 | <p>What's the best way to load HTML markup for a custom jQuery UI widget?</p>
<p>So far, I've seen elements simply created using strings (i.e. <code>$(...).wrap('<div></div>')</code>) which is fine for something simple. However, this makes it extremely difficult to modify later for more complex elements.</p>
<p>This seems like a fairly common problem, but I also know that the jQuery UI library is new enough that there may not be a widely accepted solution for this. Any ideas?</p>
| [
{
"answer_id": 354537,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 4,
"selected": true,
"text": "var newDiv = $(\"<div></div>\"); //Create a new element and save a reference\nnewDiv.attr(\"id\",\"someid\").appendTo(\"body\");\n"
},
{
"answer_id": 1457191,
"author": "sparkey0",
"author_id": 176659,
"author_profile": "https://Stackoverflow.com/users/176659",
"pm_score": 1,
"selected": false,
"text": "var temp = {\n header : \"<div class='foo'><h3>{HEADER}</h3></div>\",\n content : \"<div class='bar'><p>{COPY}</p></div>\"\n}\n var text = \"I am the header text\";\nvar head = new String(temp.header);\n$(target).append(head.replace(\"{HEADER}\",text));\n"
},
{
"answer_id": 14553227,
"author": "Alex K",
"author_id": 1356465,
"author_profile": "https://Stackoverflow.com/users/1356465",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/template\" id=\"template-example\">\n <!-- All of your markup here -->\n <% // do some JavaScript in here... %>\n <%= echo_this_variable %>\n</script>\n var markup = $('#template-example').html();\n"
}
] | 2008/12/09 | [
"https://Stackoverflow.com/questions/354473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.