qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
267,707
|
<p>I have a View that allows a user to enter/edit data for a new Widget. I'd like to form up that data into a json object and send it to my controller via AJAX so I can do the validation on the server without a postback.</p>
<p>I've got it all working, except I can't figure out how to pass the data so my controller method can accept a complex Widget type instead of individual parameters for each property.</p>
<p>So, if this is my object:</p>
<pre><code>public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
</code></pre>
<p>I'd like my controller method to look something like this:</p>
<pre><code>public JsonResult Save(Widget widget)
{
...
}
</code></pre>
<p>Currently, my jQuery looks like this:</p>
<pre><code>var formData = $("#Form1").serializeArray();
$.post("/Widget/Save",
formData,
function(result){}, "json");
</code></pre>
<p>My form (Form1) has an input field for each property on the Widget (Id, Name, Price). This works great, but it ultimately passes each property of the Widget as a separate parameter to my controller method.</p>
<p>Is there a way I could "intercept" the data, maybe using an ActionFilterAttribute, and deserialize it to a Widget object before my controller method gets called?</p>
|
[
{
"answer_id": 267731,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 2,
"selected": false,
"text": "{ Id : \"id\", Name : \"name\", Price : 1.0 }\n"
},
{
"answer_id": 269127,
"author": "MrDustpan",
"author_id": 34720,
"author_profile": "https://Stackoverflow.com/users/34720",
"pm_score": 6,
"selected": true,
"text": "public class Widget\n{\n public int Id;\n public string Name;\n public decimal Price;\n}\n <%@ Page Title=\"\" Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" AutoEventWireup=\"true\" CodeBehind=\"Widget.aspx.cs\" Inherits=\"MvcAjaxApp2.Views.Home.Widget\" %>\n<asp:Content ID=\"Content1\" ContentPlaceHolderID=\"MainContent\" runat=\"server\">\n <script src=\"../../Scripts/jquery-1.2.6.js\" type=\"text/javascript\"></script> \n <script type=\"text/javascript\"> \n function SaveWidget()\n {\n var formData = $(\"#Form1\").serializeArray();\n\n $.post(\"/Home/SaveWidget\",\n formData,\n function(data){\n alert(data.Result);\n }, \"json\");\n }\n </script>\n <form id=\"Form1\">\n <input type=\"hidden\" name=\"widget.Id\" value=\"1\" />\n <input type=\"text\" name=\"widget.Name\" value=\"my widget\" />\n <input type=\"text\" name=\"widget.Price\" value=\"5.43\" />\n <input type=\"button\" value=\"Save\" onclick=\"SaveWidget()\" />\n </form>\n</asp:Content>\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Ajax;\n\nnamespace MvcAjaxApp2.Controllers\n{\n [HandleError]\n public class HomeController : Controller\n {\n public ActionResult Index()\n {\n ViewData[\"Title\"] = \"Home Page\";\n ViewData[\"Message\"] = \"Welcome to ASP.NET MVC!\";\n return View();\n }\n\n public ActionResult About()\n {\n ViewData[\"Title\"] = \"About Page\";\n return View();\n }\n\n public ActionResult Widget()\n {\n ViewData[\"Title\"] = \"Widget\";\n return View();\n }\n\n public JsonResult SaveWidget(Widget widget)\n {\n // Save the Widget\n return Json(new { Result = String.Format(\"Saved widget: '{0}' for ${1}\", widget.Name, widget.Price) });\n }\n }\n public class Widget\n {\n public int Id { get; set; }\n public string Name { get; set; }\n public decimal Price { get; set; }\n }\n}\n"
},
{
"answer_id": 463907,
"author": "Simon Sanderson",
"author_id": 57335,
"author_profile": "https://Stackoverflow.com/users/57335",
"pm_score": 3,
"selected": false,
"text": "<input type=\"text\" name=\"widget.Text\" value=\"Hello\" /> - OK\n<input type=\"text\" name=\"mywidget.Text\" value=\"Hello\" /> - FAILS\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] |
267,719
|
<p>I just recently installed the MVC beta.
However, I assumed because the versioning numbers have changed and because it now uses the GAC instead of the bin folder that it wouldn't break existing applications.</p>
<p>However, it has.</p>
<p>What steps do I need to follow to ensure my existing preview 3 applications use a bin copy of the .dlls and are not broken by the installation of the beta?</p>
|
[
{
"answer_id": 267762,
"author": "Raj",
"author_id": 219862,
"author_profile": "https://Stackoverflow.com/users/219862",
"pm_score": 3,
"selected": true,
"text": "* System.Web.Mvc\n* System.Web.Routing\n* System.Web.Abstractions\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
267,721
|
<p>I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05'</p>
<p>Currently i am doing this:</p>
<pre><code>SELECT from_days(to_days(my_date))
</code></pre>
<p>Is there a proper way of doing this?</p>
|
[
{
"answer_id": 267732,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 9,
"selected": true,
"text": "SELECT date(my_date)\n"
},
{
"answer_id": 267733,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 2,
"selected": false,
"text": "date_col = CAST(NOW() AS DATE)\n"
},
{
"answer_id": 267743,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "select date(somedate) SELECT DATE_FORMAT(your_date, '%Y-%m-%d');\n"
},
{
"answer_id": 12590455,
"author": "Jupirao Bolado",
"author_id": 1617912,
"author_profile": "https://Stackoverflow.com/users/1617912",
"pm_score": -1,
"selected": false,
"text": "ToShortDateString();"
},
{
"answer_id": 16407166,
"author": "Rajeev Kumar",
"author_id": 1214848,
"author_profile": "https://Stackoverflow.com/users/1214848",
"pm_score": 0,
"selected": false,
"text": "date(\"d F Y\",strtotime($row['date'])) $row['date']"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24390/"
] |
267,724
|
<p>I'm writing code to do Xml serialization. With below function.</p>
<pre><code>public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
</code></pre>
<p>If the argument is a instance of class without parameterless constructor, it will throw a exception.</p>
<blockquote>
<p>Unhandled Exception:
System.InvalidOperationException:
CSharpConsole.Foo cannot be serialized
because it does not have a
parameterless constructor. at
System.Xml.Serialization.TypeDesc.CheckSupported()
at
System.Xml.Serialization.TypeScope.GetTypeDesc(Type
type, MemberInfo sourc e, Boolean
directReference, Boolean throwOnError)
at
System.Xml.Serialization.ModelScope.GetTypeModel(Type
type, Boolean direct Reference) at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type
type , XmlRootAttribute root, String
defaultNamespace) at
System.Xml.Serialization.XmlSerializer..ctor(Type
type, String defaultName space) at
System.Xml.Serialization.XmlSerializer..ctor(Type
type)</p>
</blockquote>
<p>Why must there be a parameterless constructor in order to allow xml serialization to succeed?</p>
<p>EDIT: thanks for cfeduke's answer. The parameterless constructor can be private or internal.</p>
|
[
{
"answer_id": 267727,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 9,
"selected": true,
"text": "private internal"
},
{
"answer_id": 267904,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "XmlSerializer BinaryFormatter DataContractSerializer DataContractSerializer [DataContract] [DataMember [XmlAttribute] BinaryFormatter FormatterServices.GetUninitializedObject() FormatterServices"
},
{
"answer_id": 58674797,
"author": "Mike Nakis",
"author_id": 773113,
"author_profile": "https://Stackoverflow.com/users/773113",
"pm_score": 3,
"selected": false,
"text": "XmlSerializer XmlSerializer XmlSerializer XmlSerializer readonly XmlSerializer"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
267,750
|
<p>What is the difference in the accessibility of the following variables in Java?</p>
<pre><code>public class Joe {
public int a;
protected int b;
private int b;
int c;
}
</code></pre>
<p>I'm most interested in what the last one is doing.</p>
|
[
{
"answer_id": 267756,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 4,
"selected": true,
"text": "public protected private int c private"
},
{
"answer_id": 267772,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "public"
},
{
"answer_id": 267877,
"author": "jfpoilpret",
"author_id": 1440720,
"author_profile": "https://Stackoverflow.com/users/1440720",
"pm_score": 2,
"selected": false,
"text": "public protected int c private public private"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
267,752
|
<p>So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232. The documementation is sparse and the examples are non-existent. Can't figure out exactly how to communicate with the device. The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated. What code I have so far follows.</p>
<pre><code>#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;
int main()
{
io_service io;
serial_port port( io, "COM3" );
port.set_option( serial_port_base::baud_rate( 19200 ) );
unsigned char commands[4] = { 1, 128, 240, 0 };
// write the commands to the device
return 0;
}
</code></pre>
<p>In short: need help with the io part of the serial_port.</p>
|
[
{
"answer_id": 269148,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 5,
"selected": true,
"text": "boost::asio::write(port, boost::asio::buffer(commands, 4));\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176/"
] |
267,754
|
<p>I'm impressed with the simplicity of Microsoft's Virtual Earth Street Address search service.</p>
<p>My requirement is to type rough address info with no comma separators into a simple text box, press a find button, wait a few seconds and then observe a result picklist.</p>
<p>I mocked up something <a href="http://www.garyrusso.org/map.html" rel="nofollow noreferrer">here</a> using the <a href="http://dev.live.com/virtualearth/sdk/" rel="nofollow noreferrer">virtual earth SDK</a>.</p>
<p>Does Google Maps have a similar API?</p>
<p>Which street address search service is better?</p>
|
[
{
"answer_id": 269148,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 5,
"selected": true,
"text": "boost::asio::write(port, boost::asio::buffer(commands, 4));\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048/"
] |
267,763
|
<p>Ever since I first wrote</p>
<pre><code>if ($a = 5) {
# do something with $a, e.g.
print "$a";
}
</code></pre>
<p>and went through the normal puzzling session of </p>
<ul>
<li>why is the result always true</li>
<li>why is $a always 5</li>
</ul>
<p>until I realized, I'd assigned 5 to $a, instead of performing a comparison.</p>
<p>So I decided to write that kind of condition above as </p>
<pre><code> if (5 == $a)
</code></pre>
<p>in other words: </p>
<p><strong>always place the constant value to the left side of the comparison operator, resulting in a compilation error, should you forget to add the second "=" sign.</strong></p>
<p>I tend to call this <strong>defensive coding</strong> and tend to believe it's <strong>a cousin to defensive-programming</strong>, not on the algorithmic scale, but keyword by keyword. </p>
<p>What defensive coding practices have you developed? </p>
<hr>
<p><strong>One Week Later:</strong> </p>
<p>A big "thank you" to all who answered or might add another answer in the future. </p>
<p>Unfortunately (or rather fortunately!) there is no single correct answer. For that my question was to broad, asking more for opinions or learnings of experience, rather than facts. </p>
|
[
{
"answer_id": 267778,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "if a = 5: print a\n if for"
},
{
"answer_id": 267802,
"author": "Wairapeti",
"author_id": 34370,
"author_profile": "https://Stackoverflow.com/users/34370",
"pm_score": 4,
"selected": false,
"text": "if(boolean)\n oneliner();\nnextLineOfCode();\n if(boolean)\n{\n oneliner();\n}\nnextLineOfCode();\n"
},
{
"answer_id": 267837,
"author": "Tom Barta",
"author_id": 29839,
"author_profile": "https://Stackoverflow.com/users/29839",
"pm_score": 3,
"selected": false,
"text": "const mutable -Wall -Wextra -ansi -pedantic -Werror bash grep"
},
{
"answer_id": 267897,
"author": "Tal",
"author_id": 11287,
"author_profile": "https://Stackoverflow.com/users/11287",
"pm_score": 3,
"selected": false,
"text": "#pragma warning(3,4706)\n"
},
{
"answer_id": 267948,
"author": "Tobias Schulte",
"author_id": 969,
"author_profile": "https://Stackoverflow.com/users/969",
"pm_score": 3,
"selected": false,
"text": "if (\"blah\".equals(value)){}\n if (value.equals(\"blah\")){}\n"
},
{
"answer_id": 267967,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 3,
"selected": false,
"text": "function one(){\n return {\n result:\"result\"\n };\n}\n\nfunction two(){\n return \n {\n result:\"result\"\n };\n}\n undefined return"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31472/"
] |
267,764
|
<p>I need to copy a set of rows from one tab to another tab of the same Excel document by just clicking a button. </p>
<p>Also, can I also get information on how can I copy a set of rows that are hidden and paste it in the same tab without copying the "hidden" format?</p>
|
[
{
"answer_id": 270326,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 1,
"selected": false,
"text": "Sub Copybutton_Click()\n\nRange(\"Copyend\").value = Range(\"Copystart\").value\nRange(\"Copyend\").visible = True\n\nEnd Sub\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
267,766
|
<p>Is it possible to develop custom PLAF themes for Swing?
I would appreciate constructive suggestions in this topic
Thanks</p>
|
[
{
"answer_id": 270452,
"author": "BCunningham",
"author_id": 7689,
"author_profile": "https://Stackoverflow.com/users/7689",
"pm_score": 0,
"selected": false,
"text": "[javax.swing.plaf.synth][1]"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
267,781
|
<p>Slightly related to my <a href="https://stackoverflow.com/questions/267750/java-instance-variable-accessibility">other question</a>: What is the difference between the following:</p>
<pre><code>private class Joe
protected class Joe
public class Joe
class Joe
</code></pre>
<p>Once again, the difference between the last 2 is what I'm most interested in.</p>
|
[
{
"answer_id": 267793,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": true,
"text": "class Joe"
},
{
"answer_id": 267815,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "package humanity;\nclass Person {}\n\npackage family;\nimport humanity.Person;\nclass Child extends Person {}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
267,804
|
<p>I'm trying to figure out the best way to insert a record into a single table but only if the item doesn't already exist. The KEY in this case is an NVARCHAR(400) field. For this example, lets pretend it's the name of a <em>word</em> in the Oxford English Dictionary / insert your fav dictionary here. Also, i'm guessing i will need to make the Word field a primary key. (the table will also have a unique identifier PK also).</p>
<p>So .. i might get these words that i need to add to the table...</p>
<p>eg.</p>
<ul>
<li>Cat </li>
<li>Dog </li>
<li>Foo</li>
<li>Bar</li>
<li>PewPew </li>
<li>etc...</li>
</ul>
<p>So traditionally, i would try the following (pseudo code)</p>
<pre><code>SELECT WordID FROM Words WHERE Word = @Word
IF WordID IS NULL OR WordID <= 0
INSERT INTO Words VALUES (@Word)
</code></pre>
<p>ie. <em>If the word doesn't exist, then insert it.</em></p>
<p>Now .. the problem i'm worried about is that we're getting LOTS of hits .. so is it possible that the word could be inserted from another process in between the SELECT and the INSERT .. which would then throw a constraint error? (ie. a <a href="http://en.wikipedia.org/wiki/Race_condition" rel="noreferrer" title="Race Condition">Race Condition</a>).</p>
<p>I then thought that i might be able to do the following ...</p>
<pre><code>INSERT INTO Words (Word)
SELECT @Word
WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)
</code></pre>
<p>basically, <em>insert a word when it doesn't exist.</em></p>
<p>Bad syntax aside, i'm not sure if this is bad or good because of how it locks down the table (if it does) and is not that performant on a table that it getting massive reads and plenty of writes.</p>
<p>So - what do you Sql gurus think / do?</p>
<p>I was hoping to have a simple insert and 'catch' that for any errors thrown.</p>
|
[
{
"answer_id": 267859,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 6,
"selected": true,
"text": "INSERT INTO Words (Word)\n SELECT @Word\nWHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)\n INSERT INTO Words (Word)\n SELECT @Word\nWHERE NOT EXISTS (SELECT * FROM Words WHERE Word = @Word)\n"
},
{
"answer_id": 267863,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 2,
"selected": false,
"text": "CREATE UNIQUE [ CLUSTERED | NONCLUSTERED ] INDEX <index_name>\n ON Words ( word [ ASC | DESC ])\n Clustered NonClustered ASC DESC UNIQUE CONSTRAINTS ALTER TABLE Words\nADD CONSTRAINT UniqueWord\nUNIQUE (Word); \n"
},
{
"answer_id": 268293,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": -1,
"selected": false,
"text": "declare @Error int\n\nbegin transaction\n INSERT INTO Words (Word) values(@word)\n set @Error = @@ERROR\n if @Error <> 0 --if error is raised\n begin\n goto LogError\n end\ncommit transaction\ngoto ProcEnd\n\nLogError:\nrollback transaction\n"
},
{
"answer_id": 915165,
"author": "Pbearne",
"author_id": 3582,
"author_profile": "https://Stackoverflow.com/users/3582",
"pm_score": 2,
"selected": false,
"text": "insert into Words\n( selectWord , Fixword)\nSELECT word,'theFixword'\nFROM OldWordsTable\nWHERE \n(\n (word LIKE 'junk%') OR\n (word LIKE 'orSomthing') \n\n)\nand word not in \n (\n SELECT selectWord FROM words WHERE selectWord = word\n ) \n"
},
{
"answer_id": 7838850,
"author": "Dennis Hostetler",
"author_id": 695823,
"author_profile": "https://Stackoverflow.com/users/695823",
"pm_score": 3,
"selected": false,
"text": "CREATE UNIQUE NONCLUSTERED INDEX [IndexTableUniqueRows] ON [dbo].[table] \n(\n [Col1] ASC,\n [Col2] ASC,\n\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = ON, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
267,808
|
<p>(Note: This is for MySQL's SQL, not SQL Server.)</p>
<p>I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.</p>
|
[
{
"answer_id": 267910,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 4,
"selected": true,
"text": "SELECT * FROM `articles` WHERE `body` REGEXP '[[:<:]][acgj]'\n"
},
{
"answer_id": 267912,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "LIKE SELECT\n StringCol\nFROM\n MyTable\nWHERE\n ' ' + StringCol LIKE '% ' + MyLetterParam + '%'\n MyLetterParam '[acgj]'\n WHERE\n ' ' + StringCol LIKE '%['+' '+CHAR(9)+CHAR(10)+CHAR(13)+CHAR(160)+'][acgj]%'\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17307/"
] |
267,825
|
<p>When we perform a fork in Unix, open file handles are inherited, and if we don't need to use them we should close them. However, when we use libraries, file handles may be opened for which we do not have access to the handle. How do we check for these open file handles?</p>
|
[
{
"answer_id": 267857,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 4,
"selected": false,
"text": "/proc/<pid>/fd lsof man lsof"
},
{
"answer_id": 267937,
"author": "C Pirate",
"author_id": 34990,
"author_profile": "https://Stackoverflow.com/users/34990",
"pm_score": 2,
"selected": false,
"text": "dup() dup2() EBADF int newfd = dup(oldfd);\nif (newfd > 0)\n{\n close(newfd);\n close(oldfd);\n}\n close(oldfd) sysconf(_SC_OPEN_MAX)"
},
{
"answer_id": 268273,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 2,
"selected": false,
"text": "fork() exec() fork() FD_CLOEXEC FD_CLOEXEC fork() O_CLOEXEC"
},
{
"answer_id": 268341,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "lsof -P -n -p _PID_"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267825",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30333/"
] |
267,832
|
<p>Hey, in the Programming Pearls book, there is a source code for setting, clearing and testing a bit of the given index in an array of ints that is actually a set representation.</p>
<p>The code is the following:</p>
<pre><code>#include<stdio.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1+ N/BITSPERWORD];
void set(int i)
{
a[i>>SHIFT] |= (1<<(i & MASK));
}
void clr(int i)
{
a[i>>SHIFT] &= ~(1<<(i & MASK));
}
int test(int i)
{
a[i>>SHIFT] & (1<<(i & MASK));
}
</code></pre>
<p>Could somebody explain me the reason of the SHIFT and the MASK defines? And what are their purposes in the code?</p>
<p>I've already read the previous related <a href="https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c">question</a>.</p>
|
[
{
"answer_id": 267839,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "#define MASK 0x0038\n#define SHIFT 3\n var & MASK\n var & ~MASK\n var &= ~MASK;\n var &= MASK;\n var |= MASK;\n var |= ~MASK;\n (var & MASK) >> SHIFT\n var &= ~MASK;\nvar |= (newValue << SHIFT) & MASK;\n"
},
{
"answer_id": 267844,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 4,
"selected": true,
"text": "a[0] a[1] i>>SHIFT i / 32 a a 1 << i 1 << (i & 0x1F) 0x1F i a"
},
{
"answer_id": 267848,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 3,
"selected": false,
"text": "BITSPERWORD i i>>SHIFT i & MASK"
},
{
"answer_id": 267885,
"author": "tingyu",
"author_id": 18612,
"author_profile": "https://Stackoverflow.com/users/18612",
"pm_score": 0,
"selected": false,
"text": "N BITSPERWORD i i/32 i>>SHIFT (i & MASK) (1<<(i & MASK)) a[i>>SHIFT] (1<<i & MASK)) i"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20915/"
] |
267,841
|
<p>I am writing a Rails app that processes data into a graph (using Scruffy). I am wondering how can I render the graph to a blog/string and then send the blog/string directly to the the browser to be displayed (without saving it to a file)? Or do I need to render it, save it to a file, then display the saved image file in the browser? </p>
|
[
{
"answer_id": 268036,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": 3,
"selected": false,
"text": "send_data data_string, :filename => 'icon.jpg', :type => 'image/jpeg', :disposition => 'inline'\n <%= image_tag picture_path(@picture) %>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
267,843
|
<p>My Visual Studio (2008) Editor has stopped to underline Errors (this nifty wavy red lines). I can't really tell when, but it can be related to the installation of .Net Framework 3.5 SP 1 or the MVC Beta (which I guess is unlikely). Furthermore have I installed and uninstalled both CodeRush and Resharper for evaluation purposes (decided not to keep either one of them).</p>
<p>Does anyone know the problem and how to restore this functionality again?</p>
|
[
{
"answer_id": 52571863,
"author": "Magmus",
"author_id": 7933665,
"author_profile": "https://Stackoverflow.com/users/7933665",
"pm_score": 2,
"selected": false,
"text": "class A { \npublic int x; \ns;\n}\n"
},
{
"answer_id": 65788594,
"author": "Jan Macháček",
"author_id": 1220616,
"author_profile": "https://Stackoverflow.com/users/1220616",
"pm_score": 3,
"selected": false,
"text": "Tools > Options > Text Editor > General > Show error squiggles"
},
{
"answer_id": 73132519,
"author": "Sahil Rajpal",
"author_id": 12982968,
"author_profile": "https://Stackoverflow.com/users/12982968",
"pm_score": 0,
"selected": false,
"text": "\"C_Cpp.errorSquiggles\": \"Disabled\""
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16440/"
] |
267,858
|
<p>Can anyone please tell me if Certifying Authorities (CAs) are allowed to make modifications to the Certificate Signing Request (CSR) before actually signing the certificate with their own private key? </p>
<p>Specifically, I'd like to know if it's valid for the CA to insert additional fields (such as EKUs) into the cert before adding their signature.</p>
|
[
{
"answer_id": 267891,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "certreq -attrib"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34985/"
] |
267,861
|
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p>
<p>For example, if an object "parent" has a "children" relation that has
3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to
fetch the parent object with just two children..<br>
How should I do it? By adding an "and" condition to the primaryjoin
parameter of the relation? (e.g. "<code>Children.parent_id == Parent.id and Children.logically_deleted == False</code>", but is it correct to write "and" in this way?)</p>
<p><strong>Edit:</strong><br>
I managed to do it in this way</p>
<pre><code>children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False))
</code></pre>
<p>but is there a way to use a string as primaryjoin instead?</p>
|
[
{
"answer_id": 267975,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "db.query(Object).filter(Object.first==value).filter(Object.second==False).all()\n"
},
{
"answer_id": 278710,
"author": "Ants Aasma",
"author_id": 107366,
"author_profile": "https://Stackoverflow.com/users/107366",
"pm_score": 3,
"selected": true,
"text": "mapper(Something, select([sometable], sometable.c.deleted == False))\n"
},
{
"answer_id": 13887876,
"author": "Stanislav",
"author_id": 1905415,
"author_profile": "https://Stackoverflow.com/users/1905415",
"pm_score": 3,
"selected": false,
"text": "children = relationship(\"Children\", primaryjoin=\"and_(Parent.id==Children.parent_id, Children.logically_deleted==False)\"\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
] |
267,862
|
<p>Reading <a href="http://www.paulgraham.com/articles.html" rel="noreferrer">Paul Graham's essays</a> on programming languages one would think that <a href="http://wiki.c2.com/?LispMacro" rel="noreferrer">Lisp macros</a> are the only way to go. As a busy developer, working on other platforms, I have not had the privilege of using Lisp macros. As someone who wants to understand the buzz, please explain what makes this feature so powerful.</p>
<p>Please also relate this to something I would understand from the worlds of Python, Java, C# or C development.</p>
|
[
{
"answer_id": 267880,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": false,
"text": " (setf x whatever)\n (setf (car somelist) whatever)\n (rplaca somelist whatever)\n"
},
{
"answer_id": 268041,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 6,
"selected": false,
"text": "expr1 && expr2 && expr3 ...\n expr1 expr2 && and(expr1, expr2, expr3)\n exprs expr1 (defmacro && (expr1 &rest exprs)\n `(if ,expr1 ;` Warning: I have not tested\n (&& ,@exprs) ; this and might be wrong!\n nil))\n && (&& (very-cheap-operation)\n (very-expensive-operation)\n (operation-with-serious-side-effects))\n and(very_cheap_operation(),\n very_expensive_operation(),\n operation_with_serious_side_effects());\n (loop ...) (setvar *rows* (sql select count(*)\n from some-table\n where column1 = \"Yes\"\n and column2 like \"some%string%\")\n"
},
{
"answer_id": 268226,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 4,
"selected": false,
"text": "for each using select using define macro \"using\":\n using ($type $varname = $expression) $block\ninto:\n $type $varname;\n try {\n $varname = $expression;\n $block;\n } finally {\n $varname.Dispose();\n }\n"
},
{
"answer_id": 268492,
"author": "dmitry_vk",
"author_id": 35054,
"author_profile": "https://Stackoverflow.com/users/35054",
"pm_score": 3,
"selected": false,
"text": "(iter (for (id name) in-clsql-query \"select id, name from users\" on-database *users-database*)\n (format t \"User with ID of ~A has name ~A.~%\" id name))\n"
},
{
"answer_id": 268878,
"author": "dnolen",
"author_id": 32797,
"author_profile": "https://Stackoverflow.com/users/32797",
"pm_score": 3,
"selected": false,
"text": "__repr__ __str__ __str__ __repr__"
},
{
"answer_id": 4621882,
"author": "gte525u",
"author_id": 194605,
"author_profile": "https://Stackoverflow.com/users/194605",
"pm_score": 9,
"selected": false,
"text": "divisibleByTwo = [x for x in range(10) if x % 2 == 0]\n divisibleByTwo = []\nfor x in range( 10 ):\n if x % 2 == 0:\n divisibleByTwo.append( x )\n ;; the following two functions just make equivalent of Python's range function\n;; you can safely ignore them unless you are running this code\n(defun range-helper (x)\n (if (= x 0)\n (list x)\n (cons x (range-helper (- x 1)))))\n\n(defun range (x)\n (reverse (range-helper (- x 1))))\n\n;; equivalent to the python example:\n;; define a variable\n(defvar divisibleByTwo nil)\n\n;; loop from 0 upto and including 9\n(loop for x in (range 10)\n ;; test for divisibility by two\n if (= (mod x 2) 0) \n ;; append to the list\n do (setq divisibleByTwo (append divisibleByTwo (list x))))\n ' ` '(1 2 3) [1, 2, 3] `(1 2 ,x) [1, 2, x] x lcomp [x for x in range(10) if x % 2 == 0] (lcomp x for x in (range 10) if (= (% x 2) 0)) (defmacro lcomp (expression for var in list conditional conditional-test)\n ;; create a unique variable name for the result\n (let ((result (gensym)))\n ;; the arguments are really code so we can substitute them \n ;; store nil in the unique variable name generated above\n `(let ((,result nil))\n ;; var is a variable name\n ;; list is the list literal we are suppose to iterate over\n (loop for ,var in ,list\n ;; conditional is if or unless\n ;; conditional-test is (= (mod x 2) 0) in our examples\n ,conditional ,conditional-test\n ;; and this is the action from the earlier lisp example\n ;; result = result + [x] in python\n do (setq ,result (append ,result (list ,expression))))\n ;; return the result \n ,result)))\n CL-USER> (lcomp x for x in (range 10) if (= (mod x 2) 0))\n(0 2 4 6 8)\n with"
},
{
"answer_id": 15769736,
"author": "nilsi",
"author_id": 804440,
"author_profile": "https://Stackoverflow.com/users/804440",
"pm_score": 0,
"selected": false,
"text": "(setq2 x y (+ z 3))\n z=8 x=50 y=-5 (setq2 v1 v2 e) (progn (setq v1 e) (setq v2 e)) (setq2 v1 v2 e) (progn ...)"
},
{
"answer_id": 44060981,
"author": "Joerg Schmuecker",
"author_id": 2899748,
"author_profile": "https://Stackoverflow.com/users/2899748",
"pm_score": 2,
"selected": false,
"text": "(defmacro working-timer (b) \n (let (\n (start (get-universal-time))\n (result (eval b))) ;; not splicing here to keep stuff simple\n ((- (get-universal-time) start))))\n\n(defun my-broken-timer (b)\n (let (\n (start (get-universal-time))\n (result (eval b))) ;; doesn't even need eval\n ((- (get-universal-time) start))))\n\n(working-timer (sleep 10)) => 10\n\n(broken-timer (sleep 10)) => 0\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
267,869
|
<p>What is the best way to configure Tomcat 5.5 or later to authenticate users from Windows Active Directory?</p>
|
[
{
"answer_id": 267906,
"author": "Blauohr",
"author_id": 22176,
"author_profile": "https://Stackoverflow.com/users/22176",
"pm_score": 5,
"selected": false,
"text": "<Realm className=\"org.apache.catalina.realm.JNDIRealm\" debug=\"99\"\n connectionURL=\"ldap://youradsserver:389\"\n alternateURL=\"ldap://youradsserver:389\" \n userRoleName=\"member\"\n userBase=\"cn=Users,dc=yourdomain\"\n userPattern=\"cn={0},cn=Users,dc=yourdomain\"\n roleBase=\"cn=Users,dc=yourdomain\"\n roleName=\"cn\"\n roleSearch=\"(member={0})\"\n roleSubtree=\"false\"\n userSubtree=\"true\"/>\n webapp_root/WEB_INF/Web.xml <security-constraint>\n <display-name>your web app display name</display-name>\n <web-resource-collection>\n <web-resource-name>Protected Area</web-resource-name>\n <url-pattern>*.jsp</url-pattern>\n <url-pattern>*.html</url-pattern>\n <url-pattern>*.xml</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>yourrolname(ADS Group)</role-name>\n </auth-constraint>\n </security-constraint>\n <login-config>\n <auth-method>FORM</auth-method>\n <form-login-config>\n <form-login-page>/login.jsp</form-login-page>\n <form-error-page>/error.jsp</form-error-page>\n </form-login-config>\n </login-config>\n <security-role>\n <description>your role description</description>\n <role-name>yourrolename(i.e ADS group)</role-name>\n </security-role>\n"
},
{
"answer_id": 5860845,
"author": "Doug",
"author_id": 543770,
"author_profile": "https://Stackoverflow.com/users/543770",
"pm_score": 4,
"selected": false,
"text": "CN AD saMAccountName userPattern <Realm className=\"org.apache.catalina.realm.JNDIRealm\" debug=\"99\"\n connectionURL=\"ldap://DOMAIN_CONTROLLER:389\"\n connectionName=\"USERID@DOMAIN.com\"\n connectionPassword=\"USER_PASSWORD\"\n referrals=\"follow\"\n userBase=\"OU=USER_GROUP,DC=DOMAIN,DC=com\"\n userSearch=\"(sAMAccountName={0})\"\n userSubtree=\"true\"\n roleBase=\"OU=GROUPS_GROUP,DC=DOMAIN,DC=com\"\n roleName=\"name\"\n roleSubtree=\"true\"\n roleSearch=\"(member={0})\"/>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34986/"
] |
267,872
|
<p>I've got a web form with Password and Confirm Password text boxes. I've got a RegularExpressionValidator attached to the first one and CompareValidator to the second one.
Now the problem is when i have something in the Password field and nothing in Confirm Password field it does not display an error that fields don't match. As soon as i put something in the Confirm Password field it shows the error.
I also want to allow to leave both fields blank.</p>
<p>I'm using .NET 2.0</p>
<p>What might it be?</p>
|
[
{
"answer_id": 1051581,
"author": "David",
"author_id": 83852,
"author_profile": "https://Stackoverflow.com/users/83852",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\">\n<!--\n function cvPasswordRpt_Validate(source, args)\n {\n args.IsValid = (args.Value ==\n document.getElementsByName(\"fv$tbPassword\").item(0).value);\n }\n//-->\n</script>\n <label>New Password:</label>\n<asp:TextBox ID=\"tbPassword\" runat=\"server\" CssClass=\"stdTextField\" \n TextMode=\"Password\" ValidationGroup=\"edit\" />\n<br />\n<label>Repeat New Password:</label>\n<asp:TextBox ID=\"tbPasswordRpt\" runat=\"server\" CssClass=\"stdTextField\"\n TextMode=\"Password\" ValidationGroup=\"edit\" />\n<asp:CustomValidator ID=\"cvPasswordRpt\" runat=\"server\" Display=\"Dynamic\"\n EnableClientScript=\"true\" ValidationGroup=\"edit\"\n ControlToValidate=\"tbPasswordRpt\" ValidateEmptyText=\"true\"\n ErrorMessage=\"Your passwords do not match.\"\n ClientValidationFunction=\"cvPasswordRpt_Validate\"\n OnServerValidate=\"cvPasswordRpt_ServerValidate\" />\n Protected Sub cvPasswordRpt_ServerValidate(ByVal sender As Object, \n ByVal e As ServerValidateEventArgs)\n Dim _newPassword As String = DirectCast(fv.FindControl(\"tbPassword\"), \n TextBox).Text\n e.IsValid = e.Value.Equals(_newPassword)\nEnd Sub\n"
},
{
"answer_id": 9310758,
"author": "Mad Pierre",
"author_id": 1051562,
"author_profile": "https://Stackoverflow.com/users/1051562",
"pm_score": 0,
"selected": false,
"text": "public class CompareIfRequiredPasswordValidator : BaseValidator\n{\n private const string SCRIPTBLOCK = \"UNIQUE1\";\n\n private string controlToCompare;\n\n [Browsable(true)]\n [Category(\"Behavior\")]\n [DefaultValue(\"\")]\n [IDReferenceProperty]\n public string ControlToCompare\n {\n get { return controlToCompare; }\n set { controlToCompare = value; }\n }\n\n /// <summary>\n /// Server side validation function\n /// </summary>\n /// <returns></returns>\n protected override bool EvaluateIsValid()\n {\n TextBox txCompare = (TextBox)FindControl(ControlToValidate);\n TextBox txPassword = (TextBox)FindControl(ControlToCompare);\n if (txPassword.Text.Length == 0)\n {\n //No password entered so don't compare\n return true;\n }\n else\n {\n if (txCompare.Text == txPassword.Text)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n }\n\n protected override void OnPreRender(EventArgs e)\n {\n base.OnPreRender(e);\n if (EnableClientScript) { this.ClientScript(); }\n\n }\n\n //Add the custom attribute here\n protected override void AddAttributesToRender(HtmlTextWriter writer)\n {\n base.AddAttributesToRender(writer);\n if (this.RenderUplevel)\n {\n Page.ClientScript.RegisterExpandoAttribute(this.ClientID, \"controltocompare\", base.GetControlRenderID(ControlToCompare));\n }\n }\n\n //Generate and register the script for client side validation\n private void ClientScript()\n {\n StringBuilder sb_Script = new StringBuilder();\n sb_Script.Append(\"<script language=\\\"javascript\\\">\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"function pw_verify(sender) {\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"var txCompare = document.getElementById(document.getElementById(sender.id).controltovalidate);\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"var txPassword = document.getElementById(document.getElementById(sender.id).controltocompare);\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"if (txPassword.value == '')\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"{\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"return true;\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"}\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"else\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"{\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"if (txCompare.value == txPassword.value)\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"{\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"return true;\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"}\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"else\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"{\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"return false;\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"}\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"}\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"}\");\n sb_Script.Append(\"\\r\");\n sb_Script.Append(\"</script>\");\n Page.ClientScript.RegisterClientScriptBlock(GetType(), SCRIPTBLOCK, sb_Script.ToString());\n Page.ClientScript.RegisterExpandoAttribute(ClientID, \"evaluationfunction\", \"pw_verify\");\n }\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10793/"
] |
267,892
|
<p>How are paged results commonly implemented in PHP?</p>
<p>I'd like to have a results page with 10 results. Paging forward in the navigation would give me the next and previous sets.</p>
<p>Is there a way this is commonly done? Does anyone have simple advice on getting started?</p>
|
[
{
"answer_id": 267902,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 3,
"selected": false,
"text": "stackoverflow.com/myResults.php?page=1\n stackoverflow.com/myResults.php?page=2\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
267,893
|
<p>Is there a way to customize Firebug's keyboard shortcuts? I love being able to step through JavaScript code using Firebug's <em>Script</em> panel, but it looks like I'm limited to either using the default keyboard shortcuts for stepping over/into/out of code or using the mouse to click the appropriate button. </p>
<p>Am I missing something? </p>
<p>Is there some secret <strong>about:config</strong> hack in Firefox/Firebug that would help me?</p>
|
[
{
"answer_id": 438518,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 1,
"selected": false,
"text": "%APPDATA%\\Mozilla\\Firefox\\Profiles\\<profile>\\extensions\\firebug@software.joehewitt.com\\content\\firebug\\browserOverlay.xul\n"
},
{
"answer_id": 4687500,
"author": "lepe",
"author_id": 196507,
"author_profile": "https://Stackoverflow.com/users/196507",
"pm_score": 4,
"selected": true,
"text": ".mozilla/firefox/*****.default/extensions/firebug@software.joehewitt.com/ \n %APPDATA%\\Mozilla\\Firefox\\Profiles\\<profile>\\extensions\\firebug@software.joehewitt.com\\\n this.keyListeners =\n [\n chrome.keyCodeListen(\"F5\", Events.isShift, Obj.bind(this.rerun, this, context), true),\n chrome.keyCodeListen(\"F5\", null, Obj.bind(this.resume, this, context), true),\n chrome.keyCodeListen(\"F6\", null, Obj.bind(this.stepOver, this, context), true),\n chrome.keyCodeListen(\"F7\", null, Obj.bind(this.stepInto, this, context)),\n chrome.keyCodeListen(\"F8\", null, Obj.bind(this.stepOut, this, context))\n ];\n this.keyListeners =\n [\n chrome.keyCodeListen(\"F5\", null, Obj.bind(this.resume, this, context), true),\n chrome.keyListen(\"/\", Events.isControl, Obj.bind(this.resume, this, context)),\n chrome.keyCodeListen(\"F6\", null, Obj.bind(this.stepOver, this, context), true),\n chrome.keyListen(\"'\", Events.isControl, Obj.bind(this.stepOver, this, context)),\n chrome.keyCodeListen(\"F7\", null, Obj.bind(this.stepInto, this, context)),\n chrome.keyListen(\";\", Events.isControl, Obj.bind(this.stepInto, this, context)),\n chrome.keyCodeListen(\"F8\", null, Obj.bind(this.stepOut, this, context)),\n chrome.keyListen(\",\", Events.isControlShift, Obj.bind(this.stepOut, this, context))\n ];\n firebug.Continue=Continue (F5)\nfirebug.StepOver=Step Over (F6)\nfirebug.StepInto=Step Into (F7)\nfirebug.StepOut=Step Out (F8)\n"
},
{
"answer_id": 37293421,
"author": "Sebastian Zartner",
"author_id": 432681,
"author_profile": "https://Stackoverflow.com/users/432681",
"pm_score": 0,
"selected": false,
"text": "oncommand Firebug.Debugger.resume(Firebug.currentContext) cmd_firebug_resumeExecution"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19020/"
] |
267,908
|
<p>I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored?</p>
<p>For example, I have a type that I need to use all over a particular application - should I define it thus:</p>
<pre><code>mytypes.h
typedef int MY_TYPE;
foo.cpp
MY_TYPE myType;
</code></pre>
<p>Or use a namespace:</p>
<pre><code>mytypes.h
namespace ns {
typedef int MY_TYPE;
}
foo.cpp
ns::MY_TYPE myType;
...
using namespace ns;
MY_TYPE myType;
</code></pre>
<p>Which do you prefer? Are there times when it is acceptable to use the first method?</p>
|
[
{
"answer_id": 267914,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 4,
"selected": true,
"text": "MY_TYPE"
},
{
"answer_id": 267917,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "main using namespace .cpp #include"
},
{
"answer_id": 267918,
"author": "Igor Semenov",
"author_id": 11401,
"author_profile": "https://Stackoverflow.com/users/11401",
"pm_score": 3,
"selected": false,
"text": "using ns::MY_TYPE;\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
267,941
|
<p>We have an issue related to a Java application running under a (rather old) FC3 on an Advantech POS board with a Via C3 processor. The java application has several compiled shared libs that are accessed via JNI.</p>
<p>Via C3 processor is supposed to be i686 compatible. Some time ago after installing Ubuntu 6.10 on a MiniItx board with the same processor, I found out that the previous statement is not 100% true. The Ubuntu kernel hanged on startup due to the lack of some specific and optional instructions of the i686 set in the C3 processor. These instructions missing in C3 implementation of i686 set are used by default by GCC compiler when using i686 optimizations. The solution, in this case, was to go with an i386 compiled version of Ubuntu distribution.</p>
<p>The base problem with the Java application is that the FC3 distribution was installed on the HD by cloning from an image of the HD of another PC, this time an Intel P4. Afterwards, the distribution needed some hacking to have it running such as replacing some packages (such as the kernel one) with the i386 compiled version.</p>
<p>The problem is that after working for a while the system completely hangs without a trace. I am afraid that some i686 code is left somewhere in the system and could be executed randomly at any time (for example after recovering from suspend mode or something like that).</p>
<p>My question is: </p>
<ul>
<li>Is there any tool or way to find out at what specific architecture extensions a binary file (executable or library) requires? <code>file</code> does not give enough information.</li>
</ul>
|
[
{
"answer_id": 267957,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 5,
"selected": true,
"text": "objdump | grep"
},
{
"answer_id": 2902650,
"author": "Tim Kane",
"author_id": 349660,
"author_profile": "https://Stackoverflow.com/users/349660",
"pm_score": 7,
"selected": false,
"text": "file file hex: ELF 32-bit LSB executable, ARM, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.17, not stripped\n objdump -f <fileName> architecture: arm, flags 0x00000112:\nEXEC_P, HAS_SYMS, D_PAGED\nstart address 0x0000876c\n"
},
{
"answer_id": 24577159,
"author": "Hi-Angel",
"author_id": 2388257,
"author_profile": "https://Stackoverflow.com/users/2388257",
"pm_score": 5,
"selected": false,
"text": "file objdump grep readelf -a -W ELF Header:\n Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n Class: ELF32\n Data: 2's complement, little endian\n Version: 1 (current)\n OS/ABI: UNIX - System V\n ABI Version: 0\n Type: EXEC (Executable file)\n Machine: ARM\n Version: 0x1\n Entry point address: 0x83f8\n Start of program headers: 52 (bytes into file)\n Start of section headers: 2388 (bytes into file)\n Flags: 0x5000202, has entry point, Version5 EABI, soft-float ABI\n Size of this header: 52 (bytes)\n Size of program headers: 32 (bytes)\n Number of program headers: 8\n Size of section headers: 40 (bytes)\n Number of section headers: 31\n Section header string table index: 28\n...\nDisplaying notes found at file offset 0x00000148 with length 0x00000020:\n Owner Data size Description\n GNU 0x00000010 NT_GNU_ABI_TAG (ABI version tag)\n OS: Linux, ABI: 2.6.16\nAttribute Section: aeabi\nFile Attributes\n Tag_CPU_name: \"7-A\"\n Tag_CPU_arch: v7\n Tag_CPU_arch_profile: Application\n Tag_ARM_ISA_use: Yes\n Tag_THUMB_ISA_use: Thumb-2\n Tag_FP_arch: VFPv3\n Tag_Advanced_SIMD_arch: NEONv1\n Tag_ABI_PCS_wchar_t: 4\n Tag_ABI_FP_rounding: Needed\n Tag_ABI_FP_denormal: Needed\n Tag_ABI_FP_exceptions: Needed\n Tag_ABI_FP_number_model: IEEE 754\n Tag_ABI_align_needed: 8-byte\n Tag_ABI_align_preserved: 8-byte, except leaf SP\n Tag_ABI_enum_size: int\n Tag_ABI_HardFP_use: SP and DP\n Tag_CPU_unaligned_access: v6\n"
},
{
"answer_id": 30176446,
"author": "jcoffland",
"author_id": 364248,
"author_profile": "https://Stackoverflow.com/users/364248",
"pm_score": 2,
"selected": false,
"text": "readelf -a -W libsomefile.a | grep Class: | sort | uniq\n libsomefile.a"
},
{
"answer_id": 44201505,
"author": "Shailesh",
"author_id": 3656720,
"author_profile": "https://Stackoverflow.com/users/3656720",
"pm_score": 2,
"selected": false,
"text": "objdump -f testFile | grep architecture\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34880/"
] |
267,944
|
<p>Some background info;</p>
<ul>
<li>LanguageResource is the base class</li>
<li>LanguageTranslatorResource and LanguageEditorResource inherit from LanguageResource</li>
<li>LanguageEditorResource defines an IsDirty property</li>
<li>LanguageResourceCollection is a collection of LanguageResource</li>
<li>LanguageResourceCollection internally holds LanguageResources in <code>Dictionary<string, LanguageResource> _dict</code></li>
<li>LanguageResourceCollection.GetEnumerator() returns <code>_dict.Values.GetEnumerator()</code></li>
</ul>
<p>I have a LanguageResourceCollection _resources that contains only LanguageEditorResource objects and want to use LINQ to enumerate those that are dirty so I have tried the following. My specific questions are in bold.</p>
<ol>
<li><p><code>_resources.Where(r => (r as LanguageEditorResource).IsDirty)</code><br/><br/>
neither Where not other LINQ methods are displayed by Intellisense but I code it anyway and am told "LanguageResourceCollection does not contain a definition for 'Where' and no extension method...".<br/><br/>
<strong>Why does the way that LanguageResourceCollection implements IEnumerable preclude it from supporting LINQ?</strong></p></li>
<li><p>If I change the query to<br/><br/>
<code>(_resources as IEnumerable<LanguageEditorResource>).Where(r => r.IsDirty)</code><br/><br/>
Intellisense displays the LINQ methods and the solution compiles. But at runtime I get an ArgumentNullException "Value cannot be null. Parameter name: source".<br/><br/>
<strong>Is this a problem in my LINQ code?<br>
Is it a problem with the general design of the classes?<br>
How can I dig into what LINQ generates to try and see what the problem is?</strong></p></li>
</ol>
<p>My aim with this question is not to get a solution for the specific problem, as I will have to solve it now using other (non LINQ) means, but rather to try and improve my understanding of LINQ and learn how I can improve the design of my classes to work better with LINQ.</p>
|
[
{
"answer_id": 267964,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "IEnumerable IEnumerable<T> _resources.Cast<LanguageEditorResource>().Where(r => r.IsDirty)\n Enumerable.Where IEnumerable<T> IEnumerable Cast<T> OfType<T> Cast<T> T OfType<T> T LanguageEditorResource Cast<T> Where IEnumerable<LanguageResource> Cast<T> yield return T : LanguageResource T Dictionary<string,T> IEnumerable<T> ICollection<T>"
},
{
"answer_id": 267997,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 1,
"selected": false,
"text": "LanguageResourceCollection List<LanguageResource>"
},
{
"answer_id": 269312,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "public IEnumerable<T> ParticularResources<T>()\n{\n return _dict.Values.OfType<T>();\n}\n _resources\n .ParticularResources<LanguageEditorResource>()\n .Where(r => r.IsDirty)\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535/"
] |
267,949
|
<p>I'm working on a code base in which we have several configurable types. One of those types is 64 bit integer. When we compile for platforms that have no native 64 bit integer type, we simple represent 64 bit integers using a struct similar to</p>
<pre><code>typedef struct {
unsigned int hi, lo;
} int64;
</code></pre>
<p>In order to make this type useful, all common operations are defined as functions such as</p>
<pre><code>int64 int64_add(int64 x, int64 y);
</code></pre>
<p>On platforms where a native 64 bit integer type is available, these operations simply look like</p>
<pre><code>#define int64_add(x, y) ((x) + (y))
</code></pre>
<p>Anyway, on to the question. I am implementing some functionality regarding time and I want to represent my time using the 64 bit integer:</p>
<pre><code>typedef int64 mytime;
</code></pre>
<p>I also want all the common operations available to the int64 type to be available for my time type as well:</p>
<pre><code>#define mytime_add(x, y) (mytime) int64_add((int64) (x), (int64) (y))
</code></pre>
<p>The problem with this is that the casts between the types mytime and int64 isn't allowed in C (as far as I can tell anyhow). Is there any way to do this without having to reimplement all the add, sub, mul, div, etc functions for the mytime type?</p>
<p>One option is of course to never do the mytime typedef and simply use int64 everywhere I need to represent time. The problem with this is that I'm not sure if I always want to represent time as a 64 bit integer. Then there's the issue of readable code as well... :-)</p>
|
[
{
"answer_id": 267965,
"author": "Dan Fego",
"author_id": 34426,
"author_profile": "https://Stackoverflow.com/users/34426",
"pm_score": 1,
"selected": false,
"text": "#define mytime int64\n"
},
{
"answer_id": 268065,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 3,
"selected": true,
"text": "\ntypedef struct int64 int64;\n\nstruct int64\n{\n unsigned int hi, lo;\n};\n\ntypedef int64 mytime;\n\nint64\nadd_int64(int64 a, int64 b)\n{\n int64 c;\n /* I know that is wrong */\n c.hi = a.hi + b.hi;\n c.lo = a.lo + b.lo;\n\n return c;\n}\n\nint\nmain(void)\n{\n mytime a = {1, 2};\n mytime b = {3, 4};\n mytime c;\n\n c = add_int64(a, b);\n\n return 0;\n}\n"
},
{
"answer_id": 268309,
"author": "Walter Bright",
"author_id": 33949,
"author_profile": "https://Stackoverflow.com/users/33949",
"pm_score": 2,
"selected": false,
"text": "#define mytime_add(x, y) int64_add((x), (y))\n mytime mytime_add(mytime x, mytime y) { return int64_add(x, y); }\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398/"
] |
267,953
|
<p>I have two applications under <code>tomcat/webapps</code> folder. </p>
<pre><code>tomcat/webapps/App1
tomcat/webapps/App2
</code></pre>
<p>Both applications share the same libraries. Which are stored for example in <code>tomcat/webapps/App1/WEB-INF/lib</code>.</p>
<p>Are both libraries loaded twice in memory?</p>
<p>Should I put these shared libraries in <code>tomcat/server/lib</code>?</p>
|
[
{
"answer_id": 24514449,
"author": "Toni Bünter",
"author_id": 2729120,
"author_profile": "https://Stackoverflow.com/users/2729120",
"pm_score": 3,
"selected": false,
"text": "common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,\n ${catalina.home}/lib,${catalina.home}/lib/*.jar,\n {catalina.home}/mylibs/*.jar\n"
},
{
"answer_id": 28270570,
"author": "Kevin Panko",
"author_id": 125389,
"author_profile": "https://Stackoverflow.com/users/125389",
"pm_score": 2,
"selected": false,
"text": "$CATALINA_HOME/lib $CATALINA_HOME/common/lib"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
267,962
|
<p>I have some text displaying in a larger font size than what it is supposed to. I used Firebug and it shows that the text is 12px as defined in the element's CSS. However Web Developer and CSSViewer both report that the text is 16px, which is what is currently displaying.</p>
<p>With all these tools I am unable to quickly determine the source of the 16px font size. It should be 12px. </p>
<p>What's the best way to use these tools (or others) to determine how the 16px are calculated? While I can find that out by going through the cascade hierarchy, I was wondering if there's a way to get the info more easily.</p>
|
[
{
"answer_id": 30796389,
"author": "Sebastian Zartner",
"author_id": 432681,
"author_profile": "https://Stackoverflow.com/users/432681",
"pm_score": 0,
"selected": false,
"text": ".wmd-preview"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
] |
267,977
|
<p>I often find a need to put paths in my code in order to find data or in some cases tool-specific modules. I've so far always used autotools because of this--it's just so easy to call sed to replace a few strings at build time. However, I'd like to find a more Pythonic way of doing this, i.e. use distutils or some other blessed way of building/installing. I've never managed to find anything relating to this in distutils documentation though so how do other people solve this problem?</p>
|
[
{
"answer_id": 268189,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 1,
"selected": false,
"text": "__file__"
},
{
"answer_id": 348082,
"author": "Magnus",
"author_id": 34996,
"author_profile": "https://Stackoverflow.com/users/34996",
"pm_score": 0,
"selected": false,
"text": "/usr/lib/python2.5/site-packages"
},
{
"answer_id": 349509,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 1,
"selected": false,
"text": "pkg_resources from pkg_resources import resource_filename, resource_stream\nstream = resource_stream(\"PACKAGE\", \"path/to/data_f.ile\")\n pkg_resources"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
267,982
|
<p>IMHO Radio buttons should retire. The ComboBox (Drop-Down list mode) should always be preferred.<br>Drop-Down list takes minimal screen space, and you can add/remove items programmatically.<br>No need to resize anything (hard), or disable irrelevant options (ugly).</p>
<p>Can you think of a situation when a Radio button is still useful?</p>
|
[
{
"answer_id": 268008,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "* *"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11287/"
] |
267,998
|
<p>I have a QGraphicsScene that I want to copy and append to the start of a list. What is the best method of doing this?</p>
<pre><code>QGraphicsScene* m_scene = new QGraphicsScene();
QGraphicsScene* m_DuplicateScene;
QList<QGraphicsScene *>m_list;
</code></pre>
|
[
{
"answer_id": 312047,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 4,
"selected": true,
"text": "m_scene dynamic_cast clone() QGraphicsItem QGraphicsItem QGraphicsScene QGraphicsItem QList<T *>::push_front m_list.push_front m_DuplicateScene"
},
{
"answer_id": 52384499,
"author": "Mahdi",
"author_id": 9682880,
"author_profile": "https://Stackoverflow.com/users/9682880",
"pm_score": 1,
"selected": false,
"text": "class DiagramScene : public QGraphicsScene\n{\n[some datas]\n}\n class DiagramItem : public QGraphicsItem\n{\n}\n Diagram_Scene myScene;\n\nforeach (QGraphicsItem *item, diagram_scene1->items()) \n{\n if(item->type() == DiagramItem::Type)\n {\n DiagramItem *di = qgraphicsitem_cast<DiagramItem*>(item);\n myScene.addItem(di);\n }\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24459/"
] |
268,010
|
<p>Is there anyway to decompile java webstart application? </p>
|
[
{
"answer_id": 47574843,
"author": "Dragas",
"author_id": 6523288,
"author_profile": "https://Stackoverflow.com/users/6523288",
"pm_score": 0,
"selected": false,
"text": "codebase resources resources href"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9774/"
] |
268,013
|
<p>Basically I am inserting an image using the listviews inserting event, trying to resize an image from the fileupload control, and then save it in a SQL database using LINQ.</p>
<p>I found some code to create a new bitmap of the content in the fileupload control, but this was to store it in a file on the server, from <a href="http://forums.asp.net/t/1208353.aspx" rel="noreferrer">this source</a>, but I need to save the bitmap back into the SQL database, which I think I need to convert back into a byte[] format.</p>
<p>So how do I convert the bitmap to a byte[] format?</p>
<p>If I am going about this the wrong way I would be grateful it you could correct me.</p>
<p>Here is my code:</p>
<pre><code> // Find the fileUpload control
string filename = uplImage.FileName;
// Create a bitmap in memory of the content of the fileUpload control
Bitmap originalBMP = new Bitmap(uplImage.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 100;
int newHeight = sngRatio * newWidth;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
PHJamesDataContext db = new PHJamesDataContext();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = new byte[stream.Length];
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = data,
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
db.PHJProjectPhotos.InsertOnSubmit(myPhoto);
db.SubmitChanges();
</code></pre>
|
[
{
"answer_id": 268026,
"author": "Tamir",
"author_id": 30879,
"author_profile": "https://Stackoverflow.com/users/30879",
"pm_score": 3,
"selected": false,
"text": "byte[] data;\nusing(System.IO.MemoryStream stream = new System.IO.MemoryStream()) {\n bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);\n stream.Position = 0;\n data = new byte[stream.Length];\n stream.Read(data, 0, stream.Length);\n stream.Close();\n}\n"
},
{
"answer_id": 268028,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "MemoryStream MemoryStream.ToArray"
},
{
"answer_id": 268034,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 6,
"selected": true,
"text": " System.IO.MemoryStream stream = new System.IO.MemoryStream();\n newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);\n\n PHJProjectPhoto myPhoto =\n new PHJProjectPhoto\n {\n ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[]\n OrderDate = DateTime.Now,\n ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,\n ProjectId = selectedProjectId\n };\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32792/"
] |
268,023
|
<p>I have read the answers for <a href="https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform">What's the best way to check if a file exists in C? (cross platform)</a>, but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all. </p>
<p>Both <code>stat</code> and <code>access</code> are pretty much ungoogleable. What should I <code>#include</code> to use these?</p>
|
[
{
"answer_id": 268047,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 9,
"selected": true,
"text": "#include <boost/filesystem.hpp>\n\nif ( !boost::filesystem::exists( \"myfile.txt\" ) )\n{\n std::cout << \"Can't find my file!\" << std::endl;\n}\n"
},
{
"answer_id": 268147,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 3,
"selected": false,
"text": "access #include <io.h>\n\nif (_access(filename, 0) == -1)\n{\n // File does not exist\n}\n"
},
{
"answer_id": 268525,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": 5,
"selected": false,
"text": "ifstream file(argv[1]);\nif (!file)\n{\n // Can't open file\n}\n"
},
{
"answer_id": 17195806,
"author": "Samer",
"author_id": 1707083,
"author_profile": "https://Stackoverflow.com/users/1707083",
"pm_score": 3,
"selected": false,
"text": "good() #include <fstream> \nbool checkExistence(const char* filename)\n{\n ifstream Infield(filename);\n return Infield.good();\n}\n"
},
{
"answer_id": 38628843,
"author": "gsamaras",
"author_id": 2411320,
"author_profile": "https://Stackoverflow.com/users/2411320",
"pm_score": 2,
"selected": false,
"text": "#include <sys/stat.h>\n#include <iostream>\n\n// true if file exists\nbool fileExists(const std::string& file) {\n struct stat buf;\n return (stat(file.c_str(), &buf) == 0);\n}\n\nint main() {\n if(!fileExists(\"test.txt\")) {\n std::cerr << \"test.txt doesn't exist, exiting...\\n\";\n return -1;\n }\n return 0;\n}\n C02QT2UBFVH6-lm:~ gsamaras$ ls test.txt\nls: test.txt: No such file or directory\nC02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp\nC02QT2UBFVH6-lm:~ gsamaras$ ./a.out\ntest.txt doesn't exist, exiting...\n"
},
{
"answer_id": 52527922,
"author": "Reza Saadati",
"author_id": 4641680,
"author_profile": "https://Stackoverflow.com/users/4641680",
"pm_score": 0,
"selected": false,
"text": "ifstream fail() ifstream myFile;\n\nmyFile.open(\"file.txt\");\n\n// Check for errors\nif (myFile.fail()) {\n cerr << \"Error: File could not be found\";\n exit(1);\n}\n"
},
{
"answer_id": 54992948,
"author": "AlbertM",
"author_id": 8469676,
"author_profile": "https://Stackoverflow.com/users/8469676",
"pm_score": 4,
"selected": false,
"text": "std::filesystem::exists #include <iostream> // only for std::cout\n#include <filesystem>\n\nif (!std::filesystem::exists(\"myfile.txt\"))\n{\n std::cout << \"File not found!\" << std::endl;\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2079/"
] |
268,025
|
<p>The install instructions are:</p>
<pre><code>$ python setup.py build
$ sudo python setup.py install # or su first
</code></pre>
<p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 268054,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "easy_install -Z mysql_python"
},
{
"answer_id": 268101,
"author": "monk.e.boy",
"author_id": 563932,
"author_profile": "https://Stackoverflow.com/users/563932",
"pm_score": 4,
"selected": true,
"text": "$ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg\n"
},
{
"answer_id": 268111,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 1,
"selected": false,
"text": "sudo python setup.py install --single-version-externally-managed\n"
},
{
"answer_id": 1460602,
"author": "jps",
"author_id": 98088,
"author_profile": "https://Stackoverflow.com/users/98088",
"pm_score": 2,
"selected": false,
"text": "sudo python setup.py install --single-version-externally-managed --root=/\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563932/"
] |
268,037
|
<p>I am working on creating a custom project template with Visual Studio 2008 Team System edition. I have also created a custom wizard for the custom template.</p>
<p>So I have to update the vstemplate file to tell the template to use my custom wizard. But the archive is corrupted!</p>
<p>7zip thinks folders within the archive are using non-standard zip compression. The latest winzip thinks the CRC header on the folders doesn't match the main CRC header.</p>
<p>What am I doing wrong?</p>
<p>If I don't change the template zip file created by VS2008, it works just fine. But I need to be able to update the zip file. If I do, 7zip/winzip fixes the zip file structure and then VS2008 doesn't like the template anymore. Files that are in folders within the zip file are inaccessible.</p>
<p>I do notice that the standard templates seem to keep a flat file structure. That is no nested folders or anything. But the vstemplate file has targetfilename attributes that recreate the original folder structure.</p>
<p>For example instead of...</p>
<pre><code><Folder Name="My Project" TargetFolderName="My Project">
<ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</Folder>
</code></pre>
<p>the standard vstemplate defines the following...</p>
<pre><code><ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</code></pre>
<p>I've just had a little think about the above. Are they actually the same thing?</p>
<p>Is the problem with the creation of the original zip file?</p>
<p>Is the folder structure within the zip file tripping everything up?</p>
<p>Should it have added all the files to the zip archive in as flat folder structure? If so is there a fix for VS2008 so that I do not have to manually fix the template archives?</p>
|
[
{
"answer_id": 603214,
"author": "penyaskito",
"author_id": 3008,
"author_profile": "https://Stackoverflow.com/users/3008",
"pm_score": 0,
"selected": false,
"text": "<ProjectItem>MyFolder\\MyFile.cs</ProjectItem> <Folder>...<Folder>"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377/"
] |
268,045
|
<p>I am looking for a tool to replace multiple lines through out a project. For example:</p>
<pre><code>#include "../DiscreteIO/Discrete.h"
#include "../PCI/pci.h"
#include "../Arinc429/ARINC429.h"
</code></pre>
<p>with</p>
<pre><code>#include "../PCI/pci.h"
#include "../DiscreteIO/DiscreteHW.h"
#include "../DiscreteIO/Discrete.h"
</code></pre>
<p>I have tried two tools that work for this type of search and replace. <a href="http://www.textpad.com/products/wildedit/index.html" rel="noreferrer">Wildedit</a> and <a href="http://www.divlocsoft.com/" rel="noreferrer">Actual search and replace</a> Both seem to be excellent tools but are shareware. Do anybody know of similar tools? Anything free or is it time to part with some money?</p>
<p><strong>Clarification:</strong> </p>
<p><strong>through out a project</strong> in this case means a thousand plus c files. The text editors can do this only one file at a time (Textpad, Programmers notepad) or in all open files(nodepad++). I haven't tried any of the other editors but I assume they will have similar problems. Please correct me if I am wrong.</p>
<p>Tools like sed & awk is a solution but present problems since I do not use them regularly and need to spend some time getting something to work since I am not a expert on the tools.</p>
<p><strong>The answer is:</strong> All of it...</p>
<p>Ultra edit can work but I already have an editor and the price is steep if I am just going to use it as a search and replace tool.</p>
<p>Sed, AWK and regular expression based tools can work but can be a pain in some cases.</p>
<p>Wild Edit can work and is not that expensive.</p>
<p>My decision in the end is to work my Regular expression skills.</p>
|
[
{
"answer_id": 596755,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 0,
"selected": false,
"text": "#see docs at the bottom \nuse strict;\nuse warnings;\nuse Cwd;\n\nuse File::Find;\n\nmy $search_patternFilePath=$ARGV[0] ;\nmy $replace_patternFilePath =$ARGV[1];\nmy $file_pattern = $ARGV[2];\n\n# Usage\n\n(@ARGV == 3 ) || die (\"Usage: FindAndReplace.pl pathToFileContaingTheMultiLineSearchText FullPathToFileContainingMultiLineReplaceText FilePattern . Example: perl MultiLineFindAndReplace.pl \\\"D:\\Opera\\New Folder\\search.txt\\\" \\\"D:\\Opera\\replace.txt\\\" bak\");\n\n\n\nfind(\\&d, cwd);\n\nsub d {\nmy $file = $File::Find::name;\n$file =~ s,/,\\\\,g;\n\nreturn unless -f $file;\nreturn unless $file =~ /$file_pattern/;\n\nmy $searchPatternString = &slurpFile ( $search_patternFilePath ) ; \nmy $replacePatternString = &slurpFile ( $replace_patternFilePath ) ; \nmy $fileStr = &slurpFile ( $file ) ; \n\n$fileStr =~ s/$searchPatternString/$replacePatternString/igo ; \nopen(FILEHANDLE,\">$file\") || die \"cannot open output file\";\nprint (FILEHANDLE \"$fileStr\");\nclose FILEHANDLE ;\n\n}\n\nsub slurpFile \n{\nmy $file = shift ;\nprint \"\\$file is $file\" ;\nlocal( $/, *FILE ) ; \nopen (FILE , $file) or \ndie \"Cannot find $file !!! \" ; \nmy $fileString = <FILE>; #slurp the whole file into one string !!! \nclose FILE ;\nreturn $fileString ;\n}\n#Purpose : performs recursive find and replace based on pеrl regexes from the current directory\n#the search and replace is case insensitive\n#Usage\n#perl MultiLineFindAndReplace.pl \"D:\\Opera\\New Folder\\search.txt\" \"D:\\Opera\\replace.txt\" bak\n"
},
{
"answer_id": 596781,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 2,
"selected": false,
"text": "cd $PROJECTDIR && find . -iname '*.*' -exec vim -c 's:^first line of text\\nsecond line of text\\n3rd line of text:new 1st line\\rnew 2nd\\rnew 3rd:' -c 'w!' -c 'q' {} \\;\n"
},
{
"answer_id": 14839167,
"author": "Rich",
"author_id": 8261,
"author_profile": "https://Stackoverflow.com/users/8261",
"pm_score": 4,
"selected": false,
"text": "ctrl-shift-F \\n"
},
{
"answer_id": 39280154,
"author": "sporker",
"author_id": 435515,
"author_profile": "https://Stackoverflow.com/users/435515",
"pm_score": 2,
"selected": false,
"text": "s,[/\\.*[],\\\\&,g\n s,[/\\[.*],\\\\&,g\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34989/"
] |
268,048
|
<p>Take the following function:</p>
<pre><code>DataTable go() {
return someTableAdapter.getSomeData();
}
</code></pre>
<p>When I set a breakpoint in this function, is there a possibility to inspect the returned value? <code>go()</code> is directly coupled to a datagrid in an <code>.aspx</code> page.</p>
<p>The only way to inspect the returned datatable is to use a temporary variable. However, that's a bit inconvenient. Isn't there another way?</p>
|
[
{
"answer_id": 268052,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 9,
"selected": true,
"text": "$ReturnValue"
},
{
"answer_id": 268059,
"author": "Yann Semet",
"author_id": 5788,
"author_profile": "https://Stackoverflow.com/users/5788",
"pm_score": 0,
"selected": false,
"text": "\"someTableAdapter.getSomeData();\""
},
{
"answer_id": 456659,
"author": "Sylvain Rodrigue",
"author_id": 54783,
"author_profile": "https://Stackoverflow.com/users/54783",
"pm_score": 2,
"selected": false,
"text": "someTableAdapter.getSomeData();\n"
},
{
"answer_id": 526853,
"author": "Pita.O",
"author_id": 40406,
"author_profile": "https://Stackoverflow.com/users/40406",
"pm_score": 0,
"selected": false,
"text": "return someTableAdapter.getSomeData();\n someTableAdapter.getSomeData()\n"
},
{
"answer_id": 527408,
"author": "doekman",
"author_id": 56,
"author_profile": "https://Stackoverflow.com/users/56",
"pm_score": 3,
"selected": false,
"text": "return unsafe {\n int * sp = stackalloc int[1];\n try {\n return a+b;\n }\n finally {\n Trace.WriteLine(\"return is \" + *(sp+3));\n }\n}\n"
},
{
"answer_id": 5473135,
"author": "Ross Buggins",
"author_id": 1310391,
"author_profile": "https://Stackoverflow.com/users/1310391",
"pm_score": 4,
"selected": false,
"text": "DataTable go(){return someTableAdapter.getSomeData();}\n someTableAdapter.getSomeData() int go(){return 100 * 99;}\n"
},
{
"answer_id": 24835720,
"author": "Tom",
"author_id": 401246,
"author_profile": "https://Stackoverflow.com/users/401246",
"pm_score": 1,
"selected": false,
"text": "Exit Function Exit Function Exit Function"
},
{
"answer_id": 37556591,
"author": "splttingatms",
"author_id": 550608,
"author_profile": "https://Stackoverflow.com/users/550608",
"pm_score": 3,
"selected": false,
"text": "$ResultValueX Multiply(Five(), Six()) Five() | $ResultValue1 = 5\nSix() | $ResultValue2 = 6\nMultiply() | $ResultValue3 = 30\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56/"
] |
268,062
|
<p>In Delphi 2009 whereabouts do you turn on the option to treat warnings as errors?</p>
|
[
{
"answer_id": 268067,
"author": "Jamie",
"author_id": 922,
"author_profile": "https://Stackoverflow.com/users/922",
"pm_score": 5,
"selected": true,
"text": "Project -> Options - > Delphi Compiler -> Hints and Warnings Output Warnings as errors"
},
{
"answer_id": 15983831,
"author": "user424855",
"author_id": 424855,
"author_profile": "https://Stackoverflow.com/users/424855",
"pm_score": 2,
"selected": false,
"text": "SET CompilerParams=-B -M \"-W^\" -U\"..\\Source;%dcuoutdir%;%DUnitPath%\" -I\"..\\Source\\inc\" \"-N0%dcuoutdir%\" -DDebugMode\n\"%dcc%bin\\dcc32.exe\" %FuTFolder%ADDTests.dpr %CompilerParams% -U\"%FuTSource%\" %ExtraPath32%>%DCCLogFilename%\nif errorlevel 1 %Alerter% %DCCLogFilename%\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/922/"
] |
268,064
|
<p>Looking at <code>System.Collections.Generic.Dictionary<TKey, TValue></code>, it clearly implements <code>ICollection<KeyValuePair<TKey, TValue>></code>, but doesn't have the required "<code>void Add(KeyValuePair<TKey, TValue> item)</code>" function.</p>
<p>This can also be seen when trying to initialize a <code>Dictionary</code> like this:</p>
<pre><code>private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>()
{
new KeyValuePair<string,int>("muh", 2)
};
</code></pre>
<p>which fails with </p>
<blockquote>
<p>No overload for method 'Add' takes '1' arguments</p>
</blockquote>
<p>Why is that so?</p>
|
[
{
"answer_id": 268083,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "Add(key,value) this[key] Add(KeyValuePair<,>) IDictionary<string, int> Dictionary<string, int> PropertyIDs = new Dictionary<string, int> {\n {\"abc\",1}, {\"def\",2}, {\"ghi\",3}\n}\n Add(key,value)"
},
{
"answer_id": 268092,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair);\nbool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair);\nvoid ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index);\nbool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair);\nIEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator();\nvoid ICollection.CopyTo(Array array, int index);\nvoid IDictionary.Add(object key, object value);\nbool IDictionary.Contains(object key);\nIDictionaryEnumerator IDictionary.GetEnumerator();\nvoid IDictionary.Remove(object key);\nIEnumerator IEnumerable.GetEnumerator();\n"
},
{
"answer_id": 268112,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 0,
"selected": false,
"text": "ICollection<KeyValuePair<K,V>> IDictionary<K,V> IDictionary<K,V> ICollection<KeyValuePair<K,V>>"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
268,069
|
<p>I have been trying to include a file in a included file e.g</p>
<p><strong>main.cpp file</strong></p>
<pre><code>#include <includedfile.cpp>
int main(){
cout<<name<<endl;
}
</code></pre>
<p><strong>includedfile.cpp</strong></p>
<pre><code>#include <iostream>
using namespace std;
string name;
name = "jim";
</code></pre>
<p>this code does not work, the debuger says that name is not defined.</p>
|
[
{
"answer_id": 268085,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 3,
"selected": false,
"text": "name = \"jim\"; // This is outside of any method, so it is an error.\n string name = \"jim\";\n"
},
{
"answer_id": 268339,
"author": "tragomaskhalos",
"author_id": 31140,
"author_profile": "https://Stackoverflow.com/users/31140",
"pm_score": 0,
"selected": false,
"text": "string name = \"jim\";\n #include <string>\n"
},
{
"answer_id": 1226093,
"author": "bgee",
"author_id": 7003,
"author_profile": "https://Stackoverflow.com/users/7003",
"pm_score": 0,
"selected": false,
"text": "#include <includedfile.h>\n#include <iostream>\nint main()\n{ \n std::cout << name << endl;\n}\n\n//includedfile.cpp\nvoid DoSomething()\n{\n std::string name;\n name = \"jim\";\n}\n\n//includedfile.h\nvoid DoSomething();\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
268,079
|
<p>I have 3 lists, I will make them simple here. </p>
<p>list of letters<br>
A<br>
B<br>
C </p>
<p>list of numbers<br>
1<br>
2<br>
3 </p>
<p>Mixed<br>
A,1<br>
A,2<br>
B,2<br>
B,3<br>
C,1<br>
C,3</p>
<p>I need to know what is missing:<br>
A,3<br>
B,1<br>
C,2</p>
<p>The list of letters has about 85 entries<br>
and the list of numbers has about 500 entries.</p>
<p>The mixed list has about 75,000 entries.</p>
<p>I can use either a database query (mysql 5.0) or Turbo Delphi 2006 to process text files. What would be the best way to find what is missing?</p>
<p>Thanks,<br>
Dave</p>
|
[
{
"answer_id": 268099,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "SELECT\n Letter + ',' + Number AS Combination\nFROM\n NumberList,\n LetterList\n SELECT\n Combination\nFROM\n AllCombinations AS a\nWHERE\n NOT EXISTS \n (SELECT 1 FROM MyCombitations AS m WHERE m.Combination = a.Combination)\n MyCombitations MyCombitations.Combination"
},
{
"answer_id": 268126,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 1,
"selected": false,
"text": "var\n i1, i2: integer;\n sl1, sl2: TStringList;\n cross: array of array of boolean;\nbegin\n // load data into sl1, sl2\n SetLength(cross, sl1.Count, sl2.Count);\n for i1 := 0 to sl1.Count - 1 do\n for i2 := 0 to sl2.Count - 1 do\n cross[i1, i2] := false;\n // for each element in 'combined' list\n // split it into elements s1, s2\n i1 := sl1.IndexOf(s1);\n i2 := sl2.IndexOf(s2);\n if (i1 < 0) or (i2 < 0) then\n // report error\n else\n cross[i1, i2] := true;\n for i1 := 0 to sl1.Count - 1 do\n for i2 := 0 to sl2.Count - 1 do\n if not cross[i1, i2] then\n // output sl1[i1], sl2[i2]\nend;\n"
},
{
"answer_id": 268183,
"author": "Yann Semet",
"author_id": 5788,
"author_profile": "https://Stackoverflow.com/users/5788",
"pm_score": 1,
"selected": false,
"text": "SELECT letter,number FROM lettersTable l , numbersTable n WHERE\n(\n SELECT count(*) \n FROM \n (\n SELECT * \n FROM combinationsTable \n WHERE l.letter=combinationsTable.letter AND n.number = combinationsTable .number\n ) AS temp\n) = 0;\n"
},
{
"answer_id": 269225,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 1,
"selected": false,
"text": "var\n ListL : tStringList; // the left list\n ListR : tSTringList; // the right list\n ListA : tSTringList; // the Add List (should start empty)\n ListD : tStringList; // the Delete list (should start empty)\n iCurL : integer; // Left Cursor\n iCurR : integer; // Right Cursor\n iRes : integer; // result of compare\nbegin\n iCurL := 0;\n iCurR := 0;\n ListL := tStringList.create;\n ListR := tSTringList.create;\n ListA := tSTringList.create;\n ListD := tStringList.create;\n InitAndLoadLists(ListL,ListR,ListA,ListD);\n while (iCurL <= ListL.Count-1) and (iCurR <= ListR.Count-1) do\n begin\n iRes := CompareStr(ListL.Strings[iCurL],ListR.Strings[iCurR]);\n if iRes = 0 then\n begin\n inc(iCurL);\n inc(iCurR);\n end;\n if iRes < 0 then\n begin\n ListA.Add(ListL.Strings[iCurL]);\n inc(iCurL);\n end;\n if iRes > 0 then\n begin\n listD.Add(ListR.Strings[iCurR]);\n inc(iCurR);\n end;\n end;\n while (iCurL <= ListL.Count-1) do\n begin\n listA.Add(ListL.Strings[iCurL]);\n inc(iCurL);\n end;\n while (iCurR <= ListR.Count-1) do\n begin\n listD.Add(ListR.Strings[iCurR]);\n inc(iCurR);\n end;\n ShowMessage( 'ADDS' + ^M+^J + ListA.Text);\n ShowMessage( 'DELS' + ^M+^J + ListD.Text);\nend;\n procedure InitAndLoadLists(ListL, ListR, ListA, ListD: TStringList);\nbegin\n ListL.Add('A,1');\n ListL.Add('B,3');\n ListL.Add('C,2');\n ListR.Add('A,2');\n ListR.Add('B,3');\n ListR.Add('C,4');\nend;\n"
},
{
"answer_id": 269732,
"author": "user34850",
"author_id": 34850,
"author_profile": "https://Stackoverflow.com/users/34850",
"pm_score": 3,
"selected": true,
"text": "SELECT c.chr, n.num\nFROM chars c, nums n\n WHERE NOT EXISTS (SELECT 1\n FROM mix m\n WHERE m.chr = c.chr AND m.num = n.num)\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35003/"
] |
268,084
|
<p>What is the most efficient way to create a <strong>constant</strong> (never changes at runtime) mapping of <code>string</code>s to <code>int</code>s? </p>
<p>I've tried using a <a href="https://stackoverflow.com/questions/268064/c-how-can-dictionarykv-implement-icollectionkeyvaluepairkv-without-having-addke">const Dictionary</a>, but that didn't work out. </p>
<p>I could implement a <a href="https://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary">immutable wrapper</a> with appropriate semantics, but that still doesn't seem totally right.</p>
<hr>
<p>For those who have asked, I'm implementing <a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo(v=vs.110).aspx" rel="noreferrer">IDataErrorInfo</a> in a generated class and am looking for a way to make the columnName lookup into my array of descriptors. </p>
<p>I wasn't aware (typo when testing! d'oh!) that switch accepts strings, so that's what I'm gonna use. Thanks!</p>
|
[
{
"answer_id": 268097,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 1,
"selected": false,
"text": "interface IActiveUserCountProvider\n{\n int GetMaxForServer(string serverName);\n}\n"
},
{
"answer_id": 268103,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "Enumerable.ToLookup() Lookup<,> Dictionary<,> Dictionary<string, int> ids = new Dictionary<string, int> {\n {\"abc\",1}, {\"def\",2}, {\"ghi\",3}\n };\n ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);\n int i = lookup[\"def\"].Single();\n"
},
{
"answer_id": 268138,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 4,
"selected": false,
"text": "enum Constants\n{\n Abc = 1,\n Def = 2,\n Ghi = 3\n}\n\n...\n\nint i = (int)Enum.Parse(typeof(Constants), \"Def\");\n"
},
{
"answer_id": 268223,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 9,
"selected": true,
"text": "switch (myString)\n{\n case \"cat\": return 0;\n case \"dog\": return 1;\n case \"elephant\": return 3;\n}\n"
},
{
"answer_id": 268249,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 4,
"selected": false,
"text": "public static int GetValueByName(string name)\n{\n switch (name)\n {\n case \"bob\": return 1;\n case \"billy\": return 2;\n default: return -1;\n }\n}\n"
},
{
"answer_id": 3343754,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "public class MyClass\n{\n private Dictionary<string, int> _myCollection = new Dictionary<string, int>() { { \"A\", 1 }, { \"B\", 2 }, { \"C\", 3 } };\n\n public IEnumerable<KeyValuePair<string,int>> MyCollection\n {\n get { return _myCollection.AsEnumerable<KeyValuePair<string, int>>(); }\n }\n}"
},
{
"answer_id": 49759219,
"author": "Joshua",
"author_id": 3470291,
"author_profile": "https://Stackoverflow.com/users/3470291",
"pm_score": 2,
"selected": false,
"text": "public static class ParentClass\n{\n // here is the \"dictionary\" class\n public static class FooDictionary\n {\n public const string Key1 = \"somevalue\";\n public const string Foobar = \"fubar\";\n }\n}\n"
},
{
"answer_id": 53072313,
"author": "Kram",
"author_id": 7346935,
"author_profile": "https://Stackoverflow.com/users/7346935",
"pm_score": 3,
"selected": false,
"text": "static class SomeClass\n{\n static readonly ReadOnlyDictionary<string,int> SOME_MAPPING \n = new ReadOnlyDictionary<string,int>(\n new Dictionary<string,int>()\n {\n { \"One\", 1 },\n { \"Two\", 2 }\n }\n )\n} \n"
},
{
"answer_id": 57414953,
"author": "Suleman",
"author_id": 7116068,
"author_profile": "https://Stackoverflow.com/users/7116068",
"pm_score": 4,
"selected": false,
"text": "public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()\n {\n { \"Reference1\", Array1 },\n { \"Reference2\", Array2 },\n { \"Reference3\", Array3 },\n { \"Reference4\", Array4 },\n { \"Reference5\", Array5 }\n };\n"
},
{
"answer_id": 58547393,
"author": "Gina Marano",
"author_id": 1301310,
"author_profile": "https://Stackoverflow.com/users/1301310",
"pm_score": 2,
"selected": false,
"text": "public enum DateRange {\n [Display(Name = \"None\")]\n None = 0,\n [Display(Name = \"Today\")]\n Today = 1,\n [Display(Name = \"Tomorrow\")]\n Tomorrow = 2,\n [Display(Name = \"Yesterday\")]\n Yesterday = 3,\n [Display(Name = \"Last 7 Days\")]\n LastSeven = 4,\n [Display(Name = \"Custom\")]\n Custom = 99\n };\n\nint something = (int)DateRange.None;\n public static class EnumHelper<T>\n{\n public static T GetValueFromName(string name)\n {\n var type = typeof(T);\n if (!type.IsEnum) throw new InvalidOperationException();\n\n foreach (var field in type.GetFields())\n {\n var attribute = Attribute.GetCustomAttribute(field,\n typeof(DisplayAttribute)) as DisplayAttribute;\n if (attribute != null)\n {\n if (attribute.Name == name)\n {\n return (T)field.GetValue(null);\n }\n }\n else\n {\n if (field.Name == name)\n return (T)field.GetValue(null);\n }\n }\n\n throw new ArgumentOutOfRangeException(\"name\");\n }\n}\n var z = (int)EnumHelper<DateRange>.GetValueFromName(\"Last 7 Days\");\n"
},
{
"answer_id": 69175477,
"author": "PawZaw",
"author_id": 12417800,
"author_profile": "https://Stackoverflow.com/users/12417800",
"pm_score": 1,
"selected": false,
"text": "int value = inputString switch {\n \"one\" => 1,\n \"two\" => 2,\n _ => -1\n};\n int GetValue(string inputString) => inputString switch {\n \"one\" => 1,\n \"two\" => 2,\n _ => -1\n};\n int value = -1;\nswitch (inputString){\n case \"one\": value=1; break;\n case \"two\": value=2; break;\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
268,088
|
<p>After I open something with emacsclient, when I kill that buffer (C-x k) I get a confirmation dialog:</p>
<pre><code>Buffer `blah' still has clients; kill it? (yes or no)
</code></pre>
<p>But when I kill buffers opened directly from Emacs I don't. Is there a way not to get them when emacsclient opened them?</p>
|
[
{
"answer_id": 268205,
"author": "Touko",
"author_id": 28482,
"author_profile": "https://Stackoverflow.com/users/28482",
"pm_score": 5,
"selected": true,
"text": "(remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)\n"
},
{
"answer_id": 268859,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 5,
"selected": false,
"text": "-n emacsclient emacsclient -n myfile.txt\n"
},
{
"answer_id": 16782311,
"author": "RussellStewart",
"author_id": 2237635,
"author_profile": "https://Stackoverflow.com/users/2237635",
"pm_score": 0,
"selected": false,
"text": "(defalias 'server-kill-buffer-query-function '(lambda () t))\n"
},
{
"answer_id": 28002666,
"author": "mzuther",
"author_id": 161979,
"author_profile": "https://Stackoverflow.com/users/161979",
"pm_score": 1,
"selected": false,
"text": "(add-hook 'server-switch-hook\n (lambda ()\n (when (current-local-map)\n (use-local-map (copy-keymap (current-local-map))))\n (when server-buffer-clients\n (local-set-key (kbd \"C-x k\") 'server-edit))))\n M-x list-buffers ;; When you finish editing a Server buffer, again call server-edit\n;; to mark that buffer as done for the client and switch to the next\n;; Server buffer. When all the buffers for a client have been edited\n;; and exited with server-edit, the client \"editor\" will return\n;; to the program that invoked it.\n ;; Ask before killing a server buffer.\n;; It was suggested to release its client instead,\n;; but I think that is dangerous--the client would proceed\n;; using whatever is on disk in that file. -- rms.\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
268,089
|
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p>
<p>Can anyone please tell me how one can achieve multiple database connections in Django.</p>
<p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
|
[
{
"answer_id": 271220,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 0,
"selected": false,
"text": "django/db/__init__.py connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS)"
},
{
"answer_id": 1836058,
"author": "Dave Aaron Smith",
"author_id": 223268,
"author_profile": "https://Stackoverflow.com/users/223268",
"pm_score": 3,
"selected": false,
"text": "from django.db import load_backend\nmyBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle'\nmyConnection = myBackend.DatabaseWrapper({\n 'DATABASE_HOST': '192.168.1.1',\n 'DATABASE_NAME': 'my_database',\n 'DATABASE_OPTIONS': {},\n 'DATABASE_PASSWORD': \"\",\n 'DATABASE_PORT': \"\",\n 'DATABASE_USER': \"my_user\",\n 'TIME_ZONE': \"America/New_York\",})\n# Now we can do all the standard raw sql stuff with myConnection.\nmyCursor = myConnection.cursor()\nmyCursor.execute(\"SELECT COUNT(1) FROM my_table;\")\nmyCursor.fetchone()\n"
},
{
"answer_id": 14604432,
"author": "Aventador",
"author_id": 1822871,
"author_profile": "https://Stackoverflow.com/users/1822871",
"pm_score": 2,
"selected": false,
"text": "DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'mupltiple_datab_app1', \n 'USER': 'root', \n 'PASSWORD': 'admin', \n 'HOST': \"\", \n 'PORT': \"\", \n },\n 'user1':{\n 'ENGINE': 'django.db.backends.mysql', \n 'NAME': 'mupltiple_datab_app2', \n 'USER': 'root', \n 'PASSWORD': 'admin', \n 'HOST': \"\", \n 'PORT': \"\", \n\n },\n 'user2':{\n 'ENGINE': 'django.db.backends.mysql', \n 'NAME': 'mupltiple_datab_app3', \n 'USER': 'root', \n 'PASSWORD': 'admin', \n 'HOST':\"\" , \n 'PORT': \"\" , \n\n }\n}\n manage.py syncdb --database=user1\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35009/"
] |
268,093
|
<p>I'd like to create a webpage layout with the sidebar to the right and the main content flowing around the sidebar.</p>
<p>Requirements:</p>
<ol>
<li>Content below the sidebar should occupy all of the available width</li>
<li>Content below the sidebar should not wrap when it hits the left of the sidebar</li>
<li>Main content should <em>precede</em> the sidebar in the markup</li>
<li>Sidebar has fixed width but unknown/variable height</li>
<li>CSS-only - no JavaScript solutions</li>
</ol>
<p>This could be achieved without the third requirement: if the sidebar is before the main content in the markup and is within the same containing element, a simple right float does the job. A sidebar before the main content in the markup is not an option here. The sidebar will contain supplemental information and adverts. If this is before the main content in the markup it will be annoying to CSSless browsers and screenreader users (even with 'skip to ...' links).</p>
<p>This could be achieved without the fourth requirement. If the sidebar had a fixed height I could put a containing element before the main content, float it right and give it a suitable width and height and then use absolute positioning to put the sidebar on top of the pre-made space.</p>
<p>Example markup (without CSS, relevant bits only):</p>
<pre><code><body>
<div id="content">
<p>
Lorem ipsum ....
</p>
<p>
Pellentesque ....
</p>
<div id="sidebar">
/* has some form of fixed width */
</div>
</div>
</body>
</code></pre>
<p>Example layout:</p>
<p><a href="http://webignition.net/images/layoutexample.png">alt text http://webignition.net/images/layoutexample.png</a></p>
<p>I'm not sure if this is possible. I'm happy to accept an authoritative answer stating that this cannot be achieved. If this can't be achieved I'd appreciate an explanation - knowing why it can't be achieved is much more valuable than just being told it can't.</p>
<p><strong>Update</strong>: I'm happy to see answers that don't meet all of the five requirements, so long as an answer states which requirement is being ignored plus the consequences (pros and cons) of ignoring the requirement. I can then make an informed compromise.</p>
<p><strong>Update 2</strong>: I can't ignore requirement 3 - the sidebar cannot precede the content.</p>
|
[
{
"answer_id": 268135,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": false,
"text": "float div#sidebar div#sidebar #sidebar {\n float: right;\n width: 50px;\n}\n <body>\n <div id=\"content\">\n <div id=\"sidebar\">\n /* has some form of fixed width */\n </div>\n\n <!-- paragraphs -->\n </div>\n</body>\n"
},
{
"answer_id": 268155,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "#sidebar { float: right; width: 150px; }\n #content"
},
{
"answer_id": 268178,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "#sidebar {\n float: left;\n width: 100px;\n}\n#actualContent {\n width: 700px;\n float: left;\n}\n <div id=\"content\">\n <div id=\"actualContent\">\n <p>...</p>\n <p>...</p>\n </div>\n <div id=\"sidebar\">\n <p>...</p>\n </div>\n</div>\n"
},
{
"answer_id": 268181,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 0,
"selected": false,
"text": "#content { position: relative; } #sidebar { position: absolute; right: 0; top: 0; } #content #sidebar"
},
{
"answer_id": 268828,
"author": "Steve Clay",
"author_id": 3779,
"author_profile": "https://Stackoverflow.com/users/3779",
"pm_score": 3,
"selected": true,
"text": "<div id=\"content\" class=\"noJs\">\n <div id=\"floatSpace\"></div>\n <p>Lorem ipsum ....</p>\n <p>Pellentesque ....</p>\n <div id=\"sidebar\">content</div>\n</div>\n #content {position:relative;}\n#sidebar {width:150px; position:absolute; top:0; right:0;}\n.noJs {padding-right:150px;}\n.noJs #floatSpace {display:none;}\n.js #floatSpace {float:right; width:150px;}\n $(function () {\n // make floatSpace the same height as sidebar\n $('#floatSpace').height($('#sidebar').height());\n // trigger alternate layout\n $('#content')[0].className = 'js';\n});\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5343/"
] |
268,105
|
<p>In a table I have the following schema</p>
<pre><code>table1:
playerID int primary key,
nationalities nvarchar
table2:
playerID int,
pubVisited nvarchar
</code></pre>
<p>Now, I want to set all the players' playedVisited to null, for player whose nationality is "England", any idea on how to do this? </p>
|
[
{
"answer_id": 268127,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 2,
"selected": false,
"text": "UPDATE table2\nSET\n table2.pubVisited = null\nFROM table1\nWHERE\n table2.playerID = table1.playerID and table1.nationalities = 'England'\n"
},
{
"answer_id": 268128,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 0,
"selected": false,
"text": "update table2\nset playedvisited = NULL\nwhere playerID in (select playerID \n from table1 \n where nationalities = 'England')\n"
},
{
"answer_id": 268136,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "update table2 set pubVisited = NULL \nfrom \n table1 t1 \n inner join \n table2 t2 \n on (t1.playerID = t2.playerID and t1.nationalities = 'England')\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
268,107
|
<pre>
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`
</pre>
<p>I want to obtain the name from t1 and the number of rows in t2 where the id is the same as on t1.</p>
<p>I've got the above so far, however it won't return any data if there are no rows in t2 that match. I'd prefer <code>count</code> to be 0 (or NULL) if there are no rows, and the name still returns.</p>
<p><em>Edit:</em> I'd like to be able to sort by the <code>count</code> descending. (or <code>name</code> ASC) is that possible?</p>
|
[
{
"answer_id": 268118,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 0,
"selected": false,
"text": "SELECT `name` , COUNT(*) AS `count`\nFROM `t1`, `t2`\nWHERE `t2`.`id` = `t1`.`id`\nGROUP BY `t2`.`id`\nUNION\nSelect name, 0 as count\nfrom t1\nwhere NOT EXISTS (select 1 from t2 where `t2`.`id` = `t1`.`id`)\n"
},
{
"answer_id": 268158,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 3,
"selected": true,
"text": "SELECT `t1`.`id` , COUNT(`t2`.`id`) AS `count`\nFROM `t1` LEFT JOIN `t2` ON `t1`.`id` = `t2`.`id`\nGROUP BY `t1`.`id`\n t2 id"
},
{
"answer_id": 268204,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "name t2 SELECT \n `t1`.`name`, \n COUNT(`t2`.`id`) AS `count`\nFROM \n `t1` \n LEFT JOIN `t2` ON`t2`.`id` = `t1`.`id`\nGROUP BY\n `t1`.`name`\nORDER BY\n COUNT(`t2`.`id`) DESC,\n `t1`.`name`\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
268,116
|
<p>I have the following code block in my xslt;</p>
<pre><code> <xsl:when test="StatusData/Status/Temperature > 27">
<td bgcolor="#ffaaaa">
<xsl:value-of select="StatusData/Status/Temperature" />
</td>
</xsl:when>
</code></pre>
<p>But as you might guess when the value is 34,5 instead of 34.5 it is recognised as a string which makes integer comparison not possible. I thought replacing , with . would be solution that needs a char replace. My question is how I can do this
or
It would be great to know more about string operations in XSLT...</p>
|
[
{
"answer_id": 268140,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "translate() test=\"translate(StatusData/Status/Temperature, \",\", \".\") > 27\"\n test=\"number(translate(StatusData/Status/Temperature, \",\", \".\")) > 27.0\"\n translate() number()"
},
{
"answer_id": 268171,
"author": "yusuf",
"author_id": 35012,
"author_profile": "https://Stackoverflow.com/users/35012",
"pm_score": 0,
"selected": false,
"text": "test=\"number(translate(StatusData/Status/Temperature, ',', '.')) > 27.0\"\n"
},
{
"answer_id": 433238,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "replace()"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35012/"
] |
268,120
|
<p>I am having an string like this</p>
<p>string str = "dfdsfdsf8fdfdfd9dfdfd4"</p>
<p>I need to check whether the string contains number by looping through the array.</p>
|
[
{
"answer_id": 268148,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 6,
"selected": true,
"text": "bool val = System.Text.RegularExpressions.Regex.IsMatch(str, @\"\\d\");\n"
},
{
"answer_id": 268151,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "int result;\nif (int.TryParse(\"123\", out result))\n{\n Debug.WriteLine(\"Valid integer: \" + result);\n}\nelse\n{\n Debug.WriteLine(\"Not a valid integer\");\n}\n return System.Text.RegularExpressions.Regex.IsMatch(\n TextValue, @\"^-?\\d+([\\.]{1}\\d*)?$\");\n Microsoft.VisualBasic.Information.IsNumeric(\"abc\"); \n"
},
{
"answer_id": 268168,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 0,
"selected": false,
"text": "string s = \"abc1def2ghi\";\nbool HasNumber = (from a in s.ToCharArray() where a >= '0' && a <= '9' select a).Count() > 0;\n"
},
{
"answer_id": 268186,
"author": "Arief",
"author_id": 34096,
"author_profile": "https://Stackoverflow.com/users/34096",
"pm_score": 0,
"selected": false,
"text": " string str = \"dfdsfdsf8fdfdfd9dfdfd4\";\n\n for (int i = 0; i < str.Length; i++)\n {\n int result;\n if (int.TryParse(str[i].ToString(), out result))\n {\n //element is a number \n }\n else\n {\n // not a number\n }\n }\n"
},
{
"answer_id": 268234,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "foreach (char c in myString)\n if (char.IsNumber(c))\n return true;\n"
},
{
"answer_id": 11145727,
"author": "Kamal",
"author_id": 906340,
"author_profile": "https://Stackoverflow.com/users/906340",
"pm_score": 2,
"selected": false,
"text": "str.ToCharArray().Any(x => char.IsNumber(x));\n"
},
{
"answer_id": 12015197,
"author": "TriStar",
"author_id": 510161,
"author_profile": "https://Stackoverflow.com/users/510161",
"pm_score": 0,
"selected": false,
"text": "str.ToCharArray().Any(char.IsNumber)\n"
},
{
"answer_id": 44905588,
"author": "andrewtatham",
"author_id": 352059,
"author_profile": "https://Stackoverflow.com/users/352059",
"pm_score": 1,
"selected": false,
"text": "str.Any(char.IsNumber)\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
268,121
|
<p>I have to deal with very large text files (2 GBs), it is mandatory to read/write them line by line. To write 23 millions of lines using ofstream is really slow so, at the beginning, I tried to speed up the process writing large chunks of lines in a memory buffer (for example 256 MB or 512 MB) and then write the buffer into the file. This did not work, the performance is more or less the same. I have the same problem reading the files. I know the I/O operations are buffered by the STL I/O system and this also depends on the disk scheduler policy (managed by the OS, in my case Linux). </p>
<p>Any idea about how to improve the performance?</p>
<p>PS: I have been thinking about using a background child process (or a thread) to read/write the data chunks while the program is processing data but I do not know (mainly in the case of the subprocess) if this will be worthy. </p>
|
[
{
"answer_id": 268335,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 5,
"selected": true,
"text": "dd if=/dev/zero bs=1024 count=2000000 of=file_2GB"
},
{
"answer_id": 268542,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "unsigned int buffer_size = 64 * 1024 * 1024; // 64 MB for instance.\nstd::vector<char> data_buffer(buffer_size);\n_file->read(&data_buffer[0], buffer_size);\n"
},
{
"answer_id": 268614,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "// Unbuffered Accesses:\nfstream file;\nfile.rdbuf()->pubsetbuf(NULL,0);\nfile.open(\"PLOP\");\n\n// Larger Buffer\nstd::vector<char> buffer(64 * 1024 * 1024);\nfstream file;\nfile.rdbuf()->pubsetbuf(&buffer[0],buffer.size());\nfile.open(\"PLOP\");\n\nstd::string line;\nline.reserve(64 * 1024 * 1024);\n\nwhile(getline(file,line))\n{\n // Do Stuff.\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35004/"
] |
268,123
|
<p>Is there a single shortcut to start inserting in the new line at end of the file?</p>
<p>I'm aware of <kbd>G</kbd> + <kbd>o</kbd> combo.</p>
|
[
{
"answer_id": 268143,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 4,
"selected": false,
"text": ":nmap ^A Go\n"
},
{
"answer_id": 27207461,
"author": "gautam",
"author_id": 4307380,
"author_profile": "https://Stackoverflow.com/users/4307380",
"pm_score": 2,
"selected": false,
"text": "echo >> myfile.txt && vim -c 'startinsert' + myfile.txt\n myvim myfile.txt\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11439/"
] |
268,132
|
<p>When I ran <a href="http://en.wikipedia.org/wiki/ReSharper" rel="noreferrer">ReSharper</a> on my code, for example:</p>
<pre><code> if (some condition)
{
Some code...
}
</code></pre>
<p>ReSharper gave me the above warning (Invert "if" statement to reduce nesting), and suggested the following correction:</p>
<pre><code> if (!some condition) return;
Some code...
</code></pre>
<p>I would like to understand why that's better. I always thought that using "return" in the middle of a method problematic, somewhat like "goto".</p>
|
[
{
"answer_id": 268166,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 4,
"selected": false,
"text": "condition"
},
{
"answer_id": 268170,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 4,
"selected": false,
"text": "if if (something) {\n // a lot of indented code\n}\n if (!something) return false; // or another value to show your other code the function did not execute\n\n// all the code from before, save a lot of tabs\n return goto if (something) {\n do-something();\n if (something-else) {\n do-another-thing();\n } else {\n do-something-else();\n }\n}\n if (!something) return;\ndo-something();\n\nif (!something-else) return do-something-else();\ndo-another-thing();\n"
},
{
"answer_id": 268187,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 9,
"selected": true,
"text": "double getPayAmount() {\n double result;\n if (_isDead) result = deadAmount();\n else {\n if (_isSeparated) result = separatedAmount();\n else {\n if (_isRetired) result = retiredAmount();\n else result = normalPayAmount();\n };\n }\n return result;\n};\n _isDead double getPayAmount() {\n if (_isDead) return deadAmount();\n if (_isSeparated) return separatedAmount();\n if (_isRetired) return retiredAmount();\n\n return normalPayAmount();\n}; \n"
},
{
"answer_id": 268218,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 4,
"selected": false,
"text": "try finally using"
},
{
"answer_id": 268318,
"author": "graffic",
"author_id": 15987,
"author_profile": "https://Stackoverflow.com/users/15987",
"pm_score": 3,
"selected": false,
"text": "using System;\n\npublic class Test {\n public static void Main(string[] args) {\n if (args.Length == 0) return;\n if ((args.Length+2)/3 == 5) return;\n Console.WriteLine(\"hey!!!\");\n }\n}\n .exe ildasm false true Console.WriteLine false true using System;\n\npublic class Test {\n public static void Main(string[] args) {\n if (args.Length != 0 && (args.Length+2)/3 != 5) \n {\n Console.WriteLine(\"hey!!!\");\n }\n }\n}\n false true false"
},
{
"answer_id": 271465,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 3,
"selected": false,
"text": " bool PerformDefaultOperation()\n {\n bool succeeded = false;\n\n DataStructure defaultParameters;\n if ((defaultParameters = this.GetApplicationDefaults()) != null)\n {\n succeeded = this.DoSomething(defaultParameters);\n }\n\n return succeeded;\n }\n"
},
{
"answer_id": 8437941,
"author": "Ryan Ternier",
"author_id": 324516,
"author_profile": "https://Stackoverflow.com/users/324516",
"pm_score": 3,
"selected": false,
"text": "if"
},
{
"answer_id": 8438213,
"author": "Michael McGowan",
"author_id": 387852,
"author_profile": "https://Stackoverflow.com/users/387852",
"pm_score": 6,
"selected": false,
"text": "double public void myfunction(double exampleParam){\n if(exampleParam > 0){\n //Body will *not* be executed if Double.IsNan(exampleParam)\n }\n}\n public void myfunction(double exampleParam){\n if(exampleParam <= 0)\n return;\n //Body *will* be executed if Double.IsNan(exampleParam)\n}\n if"
},
{
"answer_id": 8509008,
"author": "shibumi",
"author_id": 895131,
"author_profile": "https://Stackoverflow.com/users/895131",
"pm_score": 3,
"selected": false,
"text": "if"
},
{
"answer_id": 8624570,
"author": "jfg956",
"author_id": 851677,
"author_profile": "https://Stackoverflow.com/users/851677",
"pm_score": 3,
"selected": false,
"text": "if"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278/"
] |
268,153
|
<p>I am writing code in VS2005 using its STL.
I have one UI thread to read a vector, and a work thread to write to a vector.
I use ::boost::shared_ptr as vector element.</p>
<pre><code>vector<shared_ptr<Class>> vec;
</code></pre>
<p>but I find, if I manipulate the vec in both thread in the same time(I can guarantee they do not visit the same area, UI Thread always read the area that has the information)</p>
<p>vec.clear() seem can not release the resource. problem happend in shared_ptr, it can not release its resource.</p>
<p>What is the problem?
Does it because when the vector reach its order capacity, it reallocates in memory, then the original part is invalidated.</p>
<p>As far as I know when reallocating, iterator will be invalid, why some problem also happened when I used vec[i].
//-----------------------------------------------</p>
<p>What kinds of lock is needed?
I mean: If the vector's element is a shared_ptr, when a thread A get the point smart_p, the other thread B will wait till A finishes the operation on smart_p right?
Or just simply add lock when thread is trying to read the point, when the read opeation is finished, thread B can continu to do something.</p>
|
[
{
"answer_id": 268177,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 3,
"selected": true,
"text": "shared_mutex"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
268,180
|
<p>Ok guys and gals, here is my problem:</p>
<p>I've built a custom control that uses a textbox to present data to the user. </p>
<p>When the user interacts with the control the <strong>value of that textbox is altered with client side javascript</strong>.</p>
<p>I also have a button on my page. When the user clicks the button I want to take the value from the custom control (aka. the textbox) and use it elsewhere.</p>
<p>So, in the onClick event for the button I do something like this:</p>
<pre><code>this.myLabel.Text = this.customControl.Value;
</code></pre>
<p>The problem is that the custom control does not have the new textbox value available. In the custom control the textbox is empty. However, I can see the correct value in the Request.Form collection.</p>
<p>Am I doing something wrong here? Or should I be reading from Request.Form?!</p>
|
[
{
"answer_id": 268297,
"author": "James",
"author_id": 7837,
"author_profile": "https://Stackoverflow.com/users/7837",
"pm_score": 2,
"selected": true,
"text": "this.textBox.Attributes.Add(\"readonly\", \"readonly\");\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7837/"
] |
268,182
|
<p>We've just been given the following code as a solution for a complicated search query in a new application provided by offshore developers. I'm skeptical of the use of dynamic SQL because I could close the SQL statement using '; and then excute a nasty that will be performed on the database!</p>
<p>Any ideas on how to fix the injection attack?</p>
<pre><code>ALTER procedure [dbo].[SearchVenues] --'','',10,1,1,''
@selectedFeature as varchar(MAX),
@searchStr as varchar(100),
@pageCount as int,
@startIndex as int,
@searchId as int,
@venueName as varchar(100),
@range int,
@latitude varchar(100),
@longitude varchar(100),
@showAll int,
@OrderBy varchar(50),
@SearchOrder varchar(10)
AS
DECLARE @sqlRowNum as varchar(max)
DECLARE @sqlRowNumWhere as varchar(max)
DECLARE @withFunction as varchar(max)
DECLARE @withFunction1 as varchar(max)
DECLARE @endIndex as int
SET @endIndex = @startIndex + @pageCount -1
SET @sqlRowNum = ' SELECT Row_Number() OVER (ORDER BY '
IF @OrderBy = 'Distance'
SET @sqlRowNum = @sqlRowNum + 'dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') ' +@SearchOrder
ELSE
SET @sqlRowNum = @sqlRowNum + @OrderBy + ' '+ @SearchOrder
SET @sqlRowNum = @sqlRowNum + ' ) AS RowNumber,ID,RecordId,EliteStatus,Name,Description,
Address,TotalReviews,AverageFacilityRating,AverageServiceRating,Address1,Address2,Address3,Address4,Address5,Address6,PhoneNumber,
visitCount,referalCount,requestCount,imgUrl,Latitude,Longitude,
Convert(decimal(10,2),dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ')) as distance
FROM VenueAllData '
SET @sqlRowNumWhere = 'where Enabled=1 and EliteStatus <> 3 '
--PRINT('@sqlRowNum ='+@sqlRowNum)
IF @searchStr <> ''
BEGIN
IF (@searchId = 1) -- county search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address5 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 2 ) -- Town search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address4 like ''' + @searchStr + '%'''
END
ELSE IF(@searchId = 3 ) -- postcode search
BEGIN
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and Address6 like ''' + @searchStr + '%'''
END
IF (@searchId = 4) -- Search By Name
BEGIN
IF @venueName <> ''
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
ELSE
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @searchStr + '%'' OR Address like ''%'+ @searchStr+'%'' ) '
END
END
IF @venueName <> '' AND @searchId <> 4
SET @sqlRowNumWhere = @sqlRowNumWhere + ' and ( Name like ''%' + @venueName + '%'' OR Address like ''%'+ @venueName+'%'' ) '
set @sqlRowNum = @sqlRowNum + ' ' + @sqlRowNumWhere
--PRINT(@sqlRowNum)
IF @selectedFeature <> ''
BEGIN
DECLARE @val1 varchar (255)
Declare @SQLAttributes varchar(max)
Set @SQLAttributes = ''
Declare @tempAttribute varchar(max)
Declare @AttrId int
while (@selectedFeature <> '')
BEGIN
SET @AttrId = CAST(SUBSTRING(@selectedFeature,1,CHARINDEX(',',@selectedFeature)-1) AS Int)
Select @tempAttribute = ColumnName from Attribute where id = @AttrId
SET @selectedFeature = SUBSTRING(@selectedFeature,len(@AttrId)+2,len(@selectedFeature))
SET @SQLAttributes = @SQLAttributes + ' ' + @tempAttribute + ' = 1 And '
END
Set @SQLAttributes = SUBSTRING(@SQLAttributes,0,LEN(@SQLAttributes)-3)
set @sqlRowNum = @sqlRowNum + ' and ID in (Select VenueId from '
set @sqlRowNum = @sqlRowNum + ' CachedVenueAttributes WHERE ' + @SQLAttributes + ') '
END
IF @showAll <> 1
set @sqlRowNum = @sqlRowNum + ' and dbo.GeocodeDistanceMiles(Latitude,Longitude,' + @latitude + ',' + @longitude + ') <= ' + convert(varchar,@range )
set @withFunction = 'WITH LogEntries AS (' + @sqlRowNum + ')
SELECT * FROM LogEntries WHERE RowNumber between '+ Convert(varchar,@startIndex) +
' and ' + Convert(varchar,@endIndex) + ' ORDER BY ' + @OrderBy + ' ' + @SearchOrder
print(@withFunction)
exec(@withFunction)
</code></pre>
|
[
{
"answer_id": 268199,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 4,
"selected": true,
"text": "EXEC sp_executesql"
},
{
"answer_id": 268378,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 1,
"selected": false,
"text": "Declare @selectedFeature as varchar(MAX),\n@searchStr as varchar(100),\n@pageCount as int,\n@startIndex as int,\n@searchId as int,\n@venueName as varchar(100),\n@range int,\n@latitude varchar(100),\n@longitude varchar(100),\n@showAll int,\n@OrderBy varchar(50),\n@SearchOrder varchar(10)\n\nSet @startIndex = 1\nSet @pageCount = 50\n\n\n\nSet @searchStr = 'e'\nSet @searchId = 4\nSet @OrderBy = 'Address1'\nSet @showAll = 1\n--Select dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude)\n\n\nDECLARE @endIndex int\nSET @endIndex = @startIndex + @pageCount -1\n;\n\nWITH LogEntries as (\nSELECT \n Row_Number() \n OVER (ORDER BY \n CASE @OrderBy\n WHEN 'Distance' THEN Cast(dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude) as varchar(10))\n WHEN 'Name' THEN Name\n WHEN 'Address1' THEN Address1\n WHEN 'RecordId' THEN Cast(RecordId as varchar(10))\n WHEN 'EliteStatus' THEN Cast(EliteStatus as varchar(10))\n END) AS RowNumber,\nRecordId,EliteStatus,Name,Description,\nAddress,TotalReviews,AverageFacilityRating,AverageServiceRating,Address1,Address2,Address3,Address4,Address5,Address6,PhoneNumber,\nvisitCount,referalCount,requestCount,imgUrl,Latitude,Longitude,\nConvert(decimal(10,2),dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude)) as distance\nFROM VenueAllData \nwhere Enabled=1 and EliteStatus <> 3\nAnd \n (\n (Address5 like @searchStr + '%' And @searchId = 1) OR\n (Address4 like @searchStr + '%' And @searchId = 2) OR\n (Address6 like @searchStr + '%' And @searchId = 3) OR\n (\n (\n @searchId = 4 And \n (Name like '%' + @venueName + '%' OR Address like '%'+ @searchStr+'%')\n )\n )\n )\nAnd\n ID in (\n Select VenueID \n From CachedVenueAttributes \n --Extra Where Clause for the processing of VenueAttributes using @selectedFeature\n )\nAnd\n ( \n (@showAll = 1) Or\n (@showAll <> 1 and dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude) <= convert(varchar,@range )) \n )\n)\n\nSELECT * FROM LogEntries \nWHERE RowNumber between @startIndex and @endIndex \nORDER BY CASE @OrderBy\n WHEN 'Distance' THEN Cast(Distance as varchar(10))\n WHEN 'Name' THEN Name\n WHEN 'Address1' THEN Address1\n WHEN 'RecordId' THEN Cast(RecordId as varchar(10))\n WHEN 'EliteStatus' THEN Cast(EliteStatus as varchar(10))\n END\n"
},
{
"answer_id": 51430681,
"author": "Jeremy Giaco",
"author_id": 4325690,
"author_profile": "https://Stackoverflow.com/users/4325690",
"pm_score": 0,
"selected": false,
"text": " AND\n ( \n (@showAll = 1) \n OR (@showAll <> 1 \n AND dbo.GeocodeDistanceMiles(Latitude,Longitude,@latitude,@longitude) <= convert(varchar,@range)) \n )\n OPTION(RECOMPILE)"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
268,184
|
<p>I have classX: </p>
<p>Sub New(ByVal item_line_no As String, ByVal item_text As String)</p>
<pre><code> ' check to ensure that the parameters do not exceed the file template limits
Select Case item_line_no.Length
Case Is > m_item_line_no_capacity
Throw New ArgumentOutOfRangeException(item_line_no, "Line No exceeds 4 characters")
Case Else
Me.m_item_line_no = item_line_no
End Select
Select Case item_text.Length
Case Is > m_item_free_text_capacity
Throw New ArgumentOutOfRangeException("Free Text Exceeds 130 characters")
Case Else
Me.m_item_free_text = item_text
End Select
End Sub
</code></pre>
<p>and the following unti to test one point of failure</p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")> _
<Test()> _
Sub testLineNoExceedsMaxLength()
Dim it As New X("aaaaa", "Test")
End Sub
</code></pre>
<p>When I run the test I expect to get the message thrown in the exception "Line No exceeds 4 characters"</p>
<p>However the unit test fails with the following message</p>
<pre><code>RecordTests.testLineNoExceedsMaxLength : FailedExpected exception message: Line No exceeds 4 characters
got: Line No exceeds 4 characters
Parameter name: aaaaa
</code></pre>
<p>I think the something simple but it driving me insane. </p>
<p>NOTE: in the declaration of the ExpectedException I get an obsolete warning stating that instead of </p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), "Line No exceeds 4 characters")>
</code></pre>
<p>it should be </p>
<pre><code><ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedException="Line No exceeds 4 characters")>
</code></pre>
<p>However this throws a ExpectedException is not declared error! </p>
|
[
{
"answer_id": 268276,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "ExpectedExceptionAttribute <Test()> _\nSub testLineNoExceedsMaxLength()\n Try\n\n Dim it As New X(\"aaaaa\", \"Test\")\n\n Catch ex as ArgumentOutOfRangeExcpetion\n\n Assert.That ( ex.Message, Is.Equal(\"Line No exceeds 4 characters\") )\n\n End Try\n\nEnd Sub\n"
},
{
"answer_id": 268313,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 3,
"selected": true,
"text": "<ExpectedException(GetType(ArgumentOutOfRangeException), ExpectedMessage=\"Line No exceeds 4 characters\" & VbCrLf & \"Parameter name: aaaaa\")>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
268,207
|
<p>As the title says really.
I've had a look at inheriting from TextBox, but the only sensible override was "OnKeyDown", but that just gives me a key from the Key enum (with no way to use Char.IsNumeric()).</p>
|
[
{
"answer_id": 2927764,
"author": "Nidhal",
"author_id": 352729,
"author_profile": "https://Stackoverflow.com/users/352729",
"pm_score": 3,
"selected": false,
"text": "private void Numclient_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.Key < Key.D0 || e.Key > Key.D9)\n {\n if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)\n {\n if (e.Key != Key.Back && e.Key != Key.Shift)\n {\n e.Handled = true;\n }\n }\n }\n}\n"
},
{
"answer_id": 4098241,
"author": "amurra",
"author_id": 299592,
"author_profile": "https://Stackoverflow.com/users/299592",
"pm_score": 3,
"selected": false,
"text": "private void NumClient_KeyDown(object sender, KeyEventArgs e)\n{ \n // Handle Shift case\n if (Keyboard.Modifiers == ModifierKeys.Shift)\n {\n e.Handled = true;\n }\n\n // Handle all other cases\n if (!e.Handled && (e.Key < Key.D0 || e.Key > Key.D9))\n {\n if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)\n {\n if (e.Key != Key.Back)\n {\n e.Handled = true;\n }\n }\n } \n}\n"
},
{
"answer_id": 5741866,
"author": "Emy",
"author_id": 718583,
"author_profile": "https://Stackoverflow.com/users/718583",
"pm_score": 1,
"selected": false,
"text": "static bool AltGrIsPressed;\n\nvoid Numclient_KeyUp(object sender, KeyEventArgs e)\n{\n if (e.Key == Key.Alt)\n {\n AltGrIsPressed = false;\n }\n}\n\nvoid Numclient_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.Key == Key.Alt)\n {\n AltGrIsPressed = true;\n }\n\n if (Keyboard.Modifiers == ModifierKeys.Shift || AltGrIsPressed == true)\n {\n e.Handled = true;\n }\n\n if (e.Handled == false && (e.Key < Key.D0 || e.Key > Key.D9))\n {\n if (e.Key < Key.NumPad0 || e.Key > Key.NumPad9)\n {\n if (e.Key != Key.Back)\n {\n e.Handled = true;\n }\n }\n } \n}\n"
},
{
"answer_id": 6187046,
"author": "Nauman",
"author_id": 777590,
"author_profile": "https://Stackoverflow.com/users/777590",
"pm_score": 1,
"selected": false,
"text": "private void txtbox_KeyDown(object sender, KeyEventArgs e)\n{\n if (e.Key == Key.D0 || e.Key == Key.D1 || e.Key == Key.D2 || e.Key == Key.D3 || e.Key == Key.D4 || e.Key == Key.D5 || e.Key == Key.D6 || e.Key == Key.D7 || e.Key == Key.D8 || e.Key == Key.D9 || e.Key == Key.NumPad0 || e.Key == Key.NumPad1 || e.Key == Key.NumPad2 || e.Key == Key.NumPad3 || e.Key == Key.NumPad4 || e.Key == Key.NumPad5 || e.Key == Key.NumPad6 || e.Key == Key.NumPad7 || e.Key == Key.NumPad8 || e.Key == Key.NumPad9)\n e.Handled = false;\n else\n e.Handled = true;\n}\n"
},
{
"answer_id": 7265684,
"author": "Ross Brigoli",
"author_id": 902296,
"author_profile": "https://Stackoverflow.com/users/902296",
"pm_score": 0,
"selected": false,
"text": "string nums = \"1234567890\";\nstring lastText = \"\";\nint lastSelStart = 0;\n\nprotected override void TextChanged(object sender, TextChangedEventArgs e)\n{\n if(!nums.Contains(this.Text.Substring(this.Text.Length -1)))\n {\n this.Text = lastText;\n this.SelectionStart = lastSelStart;\n return;\n }\n\n lastText = this.Text;\n lastSelStart = this.SelectionStart;\n\n}\n"
},
{
"answer_id": 7318801,
"author": "Sameh Deabes",
"author_id": 249336,
"author_profile": "https://Stackoverflow.com/users/249336",
"pm_score": 1,
"selected": false,
"text": "public class IntegerTextBox : TextBox\n {\n /// <summary>\n /// To be raised whenever integer value changed\n /// </summary>\n public event EventHandler ValueChanged;\n\n /// <summary>\n /// To restore if the user entered invalid characters\n /// </summary>\n private int lastSavedValue = 0;\n\n private int lastSelectionStart = 0;\n private int lastSelectionLength = 0;\n\n\n public int IntegerValue\n {\n get\n {\n //the default value is 0 if there is no text in the textbox\n int value = 0;\n int.TryParse(Text, out value);\n return value;\n }\n set\n {\n if (this.Text.Trim() != value.ToString())\n {\n Text = value.ToString();\n }\n }\n }\n\n public IntegerTextBox()\n : base()\n {\n this.LostFocus += (sender, e) =>\n {\n //if the user clears the text the text box and leaves it, set it to default value\n if (string.IsNullOrWhiteSpace(this.Text))\n IntegerValue = 0;\n };\n this.Loaded += (sender, e) =>\n {\n //populate the textbox with Initial IntegerValue (default = 0)\n this.Text = this.IntegerValue.ToString();\n };\n\n this.TextChanged += (sender, e) =>\n {\n int newValue = 0;\n if (int.TryParse(this.Text, out newValue)) //this will handle most cases like number exceeds the int max limits, negative numbers, ...etc.\n {\n if (string.IsNullOrWhiteSpace(Text) || lastSavedValue != newValue)\n {\n lastSavedValue = newValue;\n //raise the event\n EventHandler handler = ValueChanged;\n if (handler != null)\n handler(this, EventArgs.Empty);\n\n }\n }\n else \n {\n //restore previous number\n this.Text = lastSavedValue.ToString();\n //restore selected text\n this.SelectionStart = lastSelectionStart;\n this.SelectionLength = lastSelectionLength;\n }\n };\n\n this.KeyDown += (sender, e) =>\n {\n //before every key press, save selection start and length to handle overwriting selected numbers\n lastSelectionStart = this.SelectionStart;\n lastSelectionLength = this.SelectionLength;\n };\n }\n } \n integer ValueChanged"
},
{
"answer_id": 8237300,
"author": "Jerry Nixon",
"author_id": 265706,
"author_profile": "https://Stackoverflow.com/users/265706",
"pm_score": -1,
"selected": false,
"text": "<TextBox KeyDown=\"TextBox_KeyDown\" />\n\nprivate void TextBox_KeyDown(object sender, KeyEventArgs e)\n{\n var _Letter = string.Empty;\n switch (e.Key)\n {\n case Key.A: _Letter = \"A\"; break;\n case Key.Add: _Letter = \"+\"; break;\n case Key.Alt: break;\n case Key.B: _Letter = \"B\"; break;\n case Key.Back: break;\n case Key.C: _Letter = \"C\"; break;\n case Key.CapsLock: break;\n case Key.Ctrl: break;\n case Key.D: _Letter = \"D\"; break;\n case Key.D0: _Letter = \"0\"; break;\n case Key.D1: _Letter = \"1\"; break;\n case Key.D2: _Letter = \"2\"; break;\n case Key.D3: _Letter = \"3\"; break;\n case Key.D4: _Letter = \"4\"; break;\n case Key.D5: _Letter = \"5\"; break;\n case Key.D6: _Letter = \"6\"; break;\n case Key.D7: _Letter = \"7\"; break;\n case Key.D8: _Letter = \"8\"; break;\n case Key.D9: _Letter = \"9\"; break;\n case Key.Decimal: _Letter = \".\"; break;\n case Key.Delete: break;\n case Key.Divide: _Letter = \"/\"; break;\n case Key.Down: break;\n case Key.E: _Letter = \"E\"; break;\n case Key.End: break;\n case Key.Enter: break;\n case Key.Escape: break;\n case Key.F: _Letter = \"F\"; break;\n case Key.F1: break;\n case Key.F10: break;\n case Key.F11: break;\n case Key.F12: break;\n case Key.F2: break;\n case Key.F3: break;\n case Key.F4: break;\n case Key.F5: break;\n case Key.F6: break;\n case Key.F7: break;\n case Key.F8: break;\n case Key.F9: break;\n case Key.G: _Letter = \"G\"; break;\n case Key.H: _Letter = \"H\"; break;\n case Key.Home: break;\n case Key.I: _Letter = \"I\"; break;\n case Key.Insert: break;\n case Key.J: _Letter = \"J\"; break;\n case Key.K: _Letter = \"K\"; break;\n case Key.L: _Letter = \"L\"; break;\n case Key.Left: break;\n case Key.M: _Letter = \"M\"; break;\n case Key.Multiply: _Letter = \"*\"; break;\n case Key.N: _Letter = \"N\"; break;\n case Key.None: break;\n case Key.NumPad0: _Letter = \"0\"; break;\n case Key.NumPad1: _Letter = \"1\"; break;\n case Key.NumPad2: _Letter = \"2\"; break;\n case Key.NumPad3: _Letter = \"3\"; break;\n case Key.NumPad4: _Letter = \"4\"; break;\n case Key.NumPad5: _Letter = \"5\"; break;\n case Key.NumPad6: _Letter = \"6\"; break;\n case Key.NumPad7: _Letter = \"7\"; break;\n case Key.NumPad8: _Letter = \"8\"; break;\n case Key.NumPad9: _Letter = \"9\"; break;\n case Key.O: _Letter = \"O\"; break;\n case Key.P: _Letter = \"P\"; break;\n case Key.PageDown: break;\n case Key.PageUp: break;\n case Key.Q: _Letter = \"Q\"; break;\n case Key.R: _Letter = \"R\"; break;\n case Key.Right: break;\n case Key.S: _Letter = \"S\"; break;\n case Key.Shift: break;\n case Key.Space: _Letter = \" \"; break;\n case Key.Subtract: _Letter = \"-\"; break;\n case Key.T: _Letter = \"T\"; break;\n case Key.Tab: break;\n case Key.U: _Letter = \"U\"; break;\n case Key.Unknown: break;\n case Key.Up: break;\n case Key.V: _Letter = \"V\"; break;\n case Key.W: _Letter = \"W\"; break;\n case Key.X: _Letter = \"X\"; break;\n case Key.Y: _Letter = \"Y\"; break;\n case Key.Z: _Letter = \"Z\"; break;\n default: break;\n }\n var _Text = (sender as TextBox).Text + _Letter;\n double _Double;\n e.Handled = !double.TryParse(_Text, out _Double);\n}\n"
},
{
"answer_id": 8385738,
"author": "xidius",
"author_id": 1039857,
"author_profile": "https://Stackoverflow.com/users/1039857",
"pm_score": 3,
"selected": false,
"text": " using System;\n using System.Windows;\n using System.Windows.Controls;\n using System.Windows.Input;\n using System.Windows.Interactivity;\n\n namespace DataArtist\n {\npublic class NumericOnly : Behavior<TextBox>\n{\n private string Text { get; set; }\n private bool shiftKey;\n public bool StripOnExit { get; set; }\n\n public NumericOnly()\n {\n StripOnExit = false;\n }\n\n protected override void OnAttached()\n {\n base.OnAttached();\n AssociatedObject.KeyDown += KeyDown;\n AssociatedObject.KeyUp += KeyUp;\n AssociatedObject.GotFocus += GotFocus;\n AssociatedObject.LostFocus += LostFocus;\n }\n\n void KeyUp(object sender, KeyEventArgs e)\n {\n if (e.Key == Key.Shift)\n {\n shiftKey = false;\n }\n }\n\n void KeyDown(object sender, KeyEventArgs e)\n {\n if (StripOnExit != false || e.Key == Key.Tab || e.Key == Key.Enter)\n {\n return;\n }\n\n if (e.Key == Key.Shift)\n {\n shiftKey = true;\n }\n else\n {\n if (IsNumericKey(e.Key) == false)\n {\n e.Handled = true;\n }\n }\n }\n\n void GotFocus(object sender, RoutedEventArgs e)\n {\n Text = AssociatedObject.Text;\n }\n\n private void LostFocus(object sender, RoutedEventArgs e)\n {\n if (AssociatedObject.Text == Text)\n {\n return;\n }\n\n string content = string.Empty;\n\n foreach (var c in AssociatedObject.Text)\n {\n if (Char.IsNumber(c) == true)\n {\n content += c;\n }\n }\n\n AssociatedObject.Text = content;\n }\n\n public bool IsNumericKey(Key key)\n {\n if (shiftKey == true)\n {\n return false;\n }\n\n string code = key.ToString().Replace(\"NumPad\", \"D\");\n\n if (code[0] == 'D' && code.Length > 1)\n {\n return (Char.IsNumber(code[1]));\n }\n\n return false;\n }\n\n protected override void OnDetaching()\n {\n base.OnDetaching();\n AssociatedObject.KeyDown -= KeyDown;\n AssociatedObject.LostFocus -= LostFocus;\n AssociatedObject.GotFocus -= GotFocus;\n }\n} \n }\n"
},
{
"answer_id": 20514135,
"author": "Muhammad Bilal",
"author_id": 1310771,
"author_profile": "https://Stackoverflow.com/users/1310771",
"pm_score": 2,
"selected": false,
"text": " private void TextBox_KeyDown(object sender, KeyEventArgs e)\n {\n bool isDigit = e.Key >= Key.D0 && e.Key < Key.D9 || e.Key == Key.NumPad0 || e.Key == Key.NumPad1 || e.Key == Key.NumPad2 || e.Key == Key.NumPad3 || e.Key == Key.NumPad4 || e.Key == Key.NumPad5 || e.Key == Key.NumPad6 ||\n e.Key == Key.NumPad7 || e.Key == Key.NumPad8 || e.Key == Key.NumPad9 ||e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Left || e.Key == Key.Right;\n\n if (isDigit) { }\n else\n e.Handled = true; \n }\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
268,208
|
<p>I have a Windows Service written in Delphi which runs a number of programs. </p>
<p>On Stopping the service, I want to also close these programs. When the service was originally written, this worked fine, but I think I've updated the tProcess component and now - The subordinate programs are not being closed. </p>
<p>in tProcess - Here's the code which starts the new processes. </p>
<pre><code> if CreateProcess( nil , PChar( FProcess.Command ) , nil , nil , False ,
NORMAL_PRIORITY_CLASS , nil , Directory ,
StartupInfo , ProcessInfo ) then
begin
if FProcess.Wait then
begin
WaitForSingleObject( ProcessInfo.hProcess , Infinite );
GetExitCodeProcess( ProcessInfo.hProcess , ExitCode );
if Assigned( FProcess.FOnFinished ) then
FProcess.FOnFinished( FProcess , ExitCode );
end;
CloseHandle( ProcessInfo.hProcess );
CloseHandle( ProcessInfo.hThread );
end;
</code></pre>
<p>Each of the executables called by this are Windows GUI Programs (With a close button at the top). </p>
<p>When I stop the service, I also want to stop (not kill) the programs I've started up via the createProcess procedure. </p>
<p>How would you do this? </p>
|
[
{
"answer_id": 277086,
"author": "Darian Miller",
"author_id": 35696,
"author_profile": "https://Stackoverflow.com/users/35696",
"pm_score": 2,
"selected": true,
"text": "uses Windows;\n\ninterface \n\nfunction MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean; stdcall;\n\nimplementation\n\nfunction MyTerminateAppEnum(hHwnd:HWND; dwData:LPARAM):Boolean; \nvar \n vID:DWORD; \nbegin \n GetWindowThreadProcessID(hHwnd, @vID); \n if vID = dwData then \n begin\n PostMessage(hHwnd, WM_CLOSE, 0, 0); //tell window to close gracefully\n Result := False; //can stop enumerating \n end \n else \n begin\n Result := TRUE; //keep enumerating until you find your id \n end; \nend;\n Procedure TerminateMe(YourSavedProcessInfo:TProcessInformation);\nvar\n vExitCode:UINT;\nbegin\n GetExitCodeProcess(YourSavedProcessInfo.hProcess, vExitCode);\n if (vExitCode = STILL_ACTIVE) then //launched app still running..\n begin\n //tell it to close\n EnumWindows(@MyTerminateAppEnum, YourSavedProcessInfo.dwProcessId);\n\n if WaitForSingleObject(YourSavedProcessInfo.hProcess, TIMEOUT_VAL) <> WAIT_OBJECT_0 then\n begin\n if not TerminateProcess(YourSavedProcessInfo.hProcess, 0) then //didn't close, try to terminate\n begin\n //uh-oh Didn't close, didn't terminate..\n end;\n end;\n end;\n CloseHandle(YourSavedProcessInfo.hProcess);\n CloseHandle(YourSavedProcessInfo.hThread);\nend;\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] |
268,251
|
<p>I'd like to hear what is the motivation behind the bulk of sealed classes in the .Net framework. What is the benefit of sealing a class? I cannot fathom how not allowing inheritance can be useful and most likely not the only one fighting these classes.</p>
<p>So, why is the framework designed this way and wouldn't it be unbreaking change to unseal everything? There must be another reason than just being evil?</p>
|
[
{
"answer_id": 44872265,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 4,
"selected": false,
"text": "sealed class"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6846/"
] |
268,260
|
<p>I have a written a Visual C++ console application (i.e. subsystem:console) that prints useful diagnositic messages to the console.</p>
<p>However, I would like to keep the application minimized most of the time, and instead of minimizing to the taskbar, appear as a nice icon on the system tray. I would also like to restore the console when the system tray icon is clicked.</p>
<p>How should I change my program to do this?</p>
|
[
{
"answer_id": 268286,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 5,
"selected": true,
"text": "hWnd hInstance CoCreateGuid() SetConsoleTitle() hWnd FindWindow()"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30333/"
] |
268,272
|
<p>I have a dictionary where keys are strings, and values are integers.</p>
<pre><code>stats = {'a': 1, 'b': 3000, 'c': 0}
</code></pre>
<p>How do I get the key with the maximum value? In this case, it is <code>'b'</code>.</p>
<hr />
<p>Is there a nicer approach than using an intermediate list with reversed key-value tuples?</p>
<pre><code>inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])
</code></pre>
|
[
{
"answer_id": 268285,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 11,
"selected": true,
"text": "operator.itemgetter import operator\nstats = {'a': 1000, 'b': 3000, 'c': 100}\nmax(stats.iteritems(), key=operator.itemgetter(1))[0]\n stats.iteritems() key max() >>> import operator\n>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}\n>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]\n'b' \n >>> max(stats.items(), key=operator.itemgetter(1))[0]\n'b'\n"
},
{
"answer_id": 268350,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "stats = {'a':1000, 'b':3000, 'c': 100}\nmax(stats.iterkeys(), key=lambda k: stats[k])\n key max()"
},
{
"answer_id": 272269,
"author": "Tim Ottinger",
"author_id": 15929,
"author_profile": "https://Stackoverflow.com/users/15929",
"pm_score": 5,
"selected": false,
"text": "key, value = max(stats.iteritems(), key=lambda x:x[1])\n key, _ = max(stats.iteritems(), key=lambda x:x[1])\n"
},
{
"answer_id": 280156,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 11,
"selected": false,
"text": "max(stats, key=stats.get)\n"
},
{
"answer_id": 12343826,
"author": "the wolf",
"author_id": 455276,
"author_profile": "https://Stackoverflow.com/users/455276",
"pm_score": 8,
"selected": false,
"text": "def keywithmaxval(d):\n \"\"\" a) create a list of the dict's keys and values; \n b) return the key with the max value\"\"\" \n v = list(d.values())\n k = list(d.keys())\n return k[v.index(max(v))]\n def f1(): \n v = list(d1.values())\n k = list(d1.keys())\n return k[v.index(max(v))]\n \ndef f2():\n d3 = {v: k for k,v in d1.items()}\n return d3[max(d3)]\n \ndef f3():\n return list(filter(lambda t: t[1] == max(d1.values()), d1.items()))[0][0] \n \ndef f3b():\n # same as f3 but remove the call to max from the lambda\n m = max(d1.values())\n return list(filter(lambda t: t[1] == m, d1.items()))[0][0] \n \ndef f4():\n return [k for k, v in d1.items() if v == max(d1.values())][0] \n \ndef f4b():\n # same as f4 but remove the max from the comprehension\n m = max(d1.values())\n return [k for k,v in d1.items() if v == m][0] \n \ndef f5():\n return max(d1.items(), key=operator.itemgetter(1))[0] \n \ndef f6():\n return max(d1, key=d1.get) \n \ndef f7():\n \"\"\" a) create a list of the dict's keys and values; \n b) return the key with the max value\"\"\" \n v = list(d1.values())\n return list(d1.keys())[v.index(max(v))] \n \ndef f8():\n return max(d1, key=lambda k: d1[k]) \n \ntl = [f1, f2, f3b, f4b, f5, f6, f7, f8, f4, f3] \ncmpthese.cmpthese(tl, c=100) \n d1 = {1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15, \n 12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8, \n 21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19, \n 30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, 4102: 39, 38: 22, \n 39: 35, 40: 9, 41: 110, 42: 9, 43: 30, 44: 17, 45: 17, 46: 17, 47: 105, 48: 12, \n 49: 25, 50: 25, 51: 25, 52: 12, 53: 12, 54: 113, 1079: 50, 56: 20, 57: 33, \n 58: 20, 59: 33, 60: 20, 61: 20, 62: 108, 63: 108, 64: 7, 65: 28, 66: 28, 67: 28, \n 68: 15, 69: 15, 70: 15, 71: 103, 72: 23, 73: 116, 74: 23, 75: 15, 76: 23, 77: 23, \n 78: 36, 79: 36, 80: 10, 81: 23, 82: 111, 83: 111, 84: 10, 85: 10, 86: 31, 87: 31, \n 88: 18, 89: 31, 90: 18, 91: 93, 92: 18, 93: 18, 94: 106, 95: 106, 96: 13, 9232: 35, \n 98: 26, 99: 26, 100: 26, 101: 26, 103: 88, 104: 13, 106: 13, 107: 101, 1132: 63, \n 2158: 51, 112: 21, 113: 13, 116: 21, 118: 34, 119: 34, 7288: 45, 121: 96, 122: 21, \n 124: 109, 125: 109, 128: 8, 1154: 32, 131: 29, 134: 29, 136: 16, 137: 91, 140: 16, \n 142: 104, 143: 104, 146: 117, 148: 24, 149: 24, 152: 24, 154: 24, 155: 86, 160: 11, \n 161: 99, 1186: 76, 3238: 49, 167: 68, 170: 11, 172: 32, 175: 81, 178: 32, 179: 32, \n 182: 94, 184: 19, 31: 107, 188: 107, 190: 107, 196: 27, 197: 27, 202: 27, 206: 89, \n 208: 14, 214: 102, 215: 102, 220: 115, 37: 22, 224: 22, 226: 14, 232: 22, 233: 84, \n 238: 35, 242: 97, 244: 22, 250: 110, 251: 66, 1276: 58, 256: 9, 2308: 33, 262: 30, \n 263: 79, 268: 30, 269: 30, 274: 92, 1300: 27, 280: 17, 283: 61, 286: 105, 292: 118, \n 296: 25, 298: 25, 304: 25, 310: 87, 1336: 71, 319: 56, 322: 100, 323: 100, 325: 25, \n 55: 113, 334: 69, 340: 12, 1367: 40, 350: 82, 358: 33, 364: 95, 376: 108, \n 377: 64, 2429: 46, 394: 28, 395: 77, 404: 28, 412: 90, 1438: 53, 425: 59, 430: 103, \n 1456: 97, 433: 28, 445: 72, 448: 23, 466: 85, 479: 54, 484: 98, 485: 98, 488: 23, \n 6154: 37, 502: 67, 4616: 34, 526: 80, 538: 31, 566: 62, 3644: 44, 577: 31, 97: 119, \n 592: 26, 593: 75, 1619: 48, 638: 57, 646: 101, 650: 26, 110: 114, 668: 70, 2734: 41, \n 700: 83, 1732: 30, 719: 52, 728: 96, 754: 65, 1780: 74, 4858: 47, 130: 29, 790: 78, \n 1822: 43, 2051: 38, 808: 29, 850: 60, 866: 29, 890: 73, 911: 42, 958: 55, 970: 99, \n 976: 24, 166: 112}\n rate/sec f4 f3 f3b f8 f5 f2 f4b f6 f7 f1\nf4 454 -- -2.5% -96.9% -97.5% -98.6% -98.6% -98.7% -98.7% -98.9% -99.0%\nf3 466 2.6% -- -96.8% -97.4% -98.6% -98.6% -98.6% -98.7% -98.9% -99.0%\nf3b 14,715 3138.9% 3057.4% -- -18.6% -55.5% -56.0% -56.4% -58.3% -63.8% -68.4%\nf8 18,070 3877.3% 3777.3% 22.8% -- -45.4% -45.9% -46.5% -48.8% -55.5% -61.2%\nf5 33,091 7183.7% 7000.5% 124.9% 83.1% -- -1.0% -2.0% -6.3% -18.6% -29.0%\nf2 33,423 7256.8% 7071.8% 127.1% 85.0% 1.0% -- -1.0% -5.3% -17.7% -28.3%\nf4b 33,762 7331.4% 7144.6% 129.4% 86.8% 2.0% 1.0% -- -4.4% -16.9% -27.5%\nf6 35,300 7669.8% 7474.4% 139.9% 95.4% 6.7% 5.6% 4.6% -- -13.1% -24.2%\nf7 40,631 8843.2% 8618.3% 176.1% 124.9% 22.8% 21.6% 20.3% 15.1% -- -12.8%\nf1 46,598 10156.7% 9898.8% 216.7% 157.9% 40.8% 39.4% 38.0% 32.0% 14.7% --\n rate/sec f3 f4 f8 f3b f6 f5 f2 f4b f7 f1\nf3 384 -- -2.6% -97.1% -97.2% -97.9% -97.9% -98.0% -98.2% -98.5% -99.2%\nf4 394 2.6% -- -97.0% -97.2% -97.8% -97.9% -98.0% -98.1% -98.5% -99.1%\nf8 13,079 3303.3% 3216.1% -- -5.6% -28.6% -29.9% -32.8% -38.3% -49.7% -71.2%\nf3b 13,852 3504.5% 3412.1% 5.9% -- -24.4% -25.8% -28.9% -34.6% -46.7% -69.5%\nf6 18,325 4668.4% 4546.2% 40.1% 32.3% -- -1.8% -5.9% -13.5% -29.5% -59.6%\nf5 18,664 4756.5% 4632.0% 42.7% 34.7% 1.8% -- -4.1% -11.9% -28.2% -58.8%\nf2 19,470 4966.4% 4836.5% 48.9% 40.6% 6.2% 4.3% -- -8.1% -25.1% -57.1%\nf4b 21,187 5413.0% 5271.7% 62.0% 52.9% 15.6% 13.5% 8.8% -- -18.5% -53.3%\nf7 26,002 6665.8% 6492.4% 98.8% 87.7% 41.9% 39.3% 33.5% 22.7% -- -42.7%\nf1 45,354 11701.5% 11399.0% 246.8% 227.4% 147.5% 143.0% 132.9% 114.1% 74.4% -- \n f1 keywithmaxval"
},
{
"answer_id": 17217820,
"author": "Erika Sawajiri",
"author_id": 2369716,
"author_profile": "https://Stackoverflow.com/users/2369716",
"pm_score": 2,
"selected": false,
"text": "Counter = 0\nfor word in stats.keys():\n if stats[word]> counter:\n Counter = stats [word]\nprint Counter\n"
},
{
"answer_id": 23428922,
"author": "Climbs_lika_Spyder",
"author_id": 1290485,
"author_profile": "https://Stackoverflow.com/users/1290485",
"pm_score": 5,
"selected": false,
"text": ">>> stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}\n>>> [key for m in [max(stats.values())] for key,val in stats.iteritems() if val == m]\n['b', 'd']\n stats.items() stats.iteritems()"
},
{
"answer_id": 30043094,
"author": "watsonic",
"author_id": 695804,
"author_profile": "https://Stackoverflow.com/users/695804",
"pm_score": 4,
"selected": false,
"text": "max(stats.keys(), key=(lambda k: stats[k]))\n max(stats.iterkeys(), key=(lambda k: stats[k]))\n"
},
{
"answer_id": 35256685,
"author": "I159",
"author_id": 629685,
"author_profile": "https://Stackoverflow.com/users/629685",
"pm_score": 6,
"selected": false,
"text": "iterkeys iteritems max_key = max(stats, key=lambda k: stats[k])\n key lambda <item>: return <a result of operation with item> \n stats __closure__ lambda"
},
{
"answer_id": 35585900,
"author": "ukrutt",
"author_id": 3061818,
"author_profile": "https://Stackoverflow.com/users/3061818",
"pm_score": 3,
"selected": false,
"text": "collections.Counter >>> import collections\n>>> stats = {'a':1000, 'b':3000, 'c': 100}\n>>> stats = collections.Counter(stats)\n>>> stats.most_common(1)\n[('b', 3000)]\n collections.Counter >>> stats = collections.Counter()\n>>> stats['a'] += 1\n:\netc. \n"
},
{
"answer_id": 44088725,
"author": "Woooody Amadeus",
"author_id": 7375748,
"author_profile": "https://Stackoverflow.com/users/7375748",
"pm_score": 2,
"selected": false,
"text": "stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}\n\nimport random\nmaxV = max(stats.values())\n# Choice is one of the keys with max value\nchoice = random.choice([key for key, value in stats.items() if value == maxV])\n"
},
{
"answer_id": 45035132,
"author": "ragardner",
"author_id": 7655687,
"author_profile": "https://Stackoverflow.com/users/7655687",
"pm_score": 0,
"selected": false,
"text": "import time\nimport operator\n\n\nd = {\"a\"+str(i): i for i in range(1000000)}\n\ndef t1(dct):\n mx = float(\"-inf\")\n key = None\n for k,v in dct.items():\n if v > mx:\n mx = v\n key = k\n return key\n\ndef t2(dct):\n v=list(dct.values())\n k=list(dct.keys())\n return k[v.index(max(v))]\n\ndef t3(dct):\n return max(dct.items(),key=operator.itemgetter(1))[0]\n\nstart = time.time()\nfor i in range(25):\n m = t1(d)\nend = time.time()\nprint (\"Iterating: \"+str(end-start))\n\nstart = time.time()\nfor i in range(25):\n m = t2(d)\nend = time.time()\nprint (\"List creating: \"+str(end-start))\n\nstart = time.time()\nfor i in range(25):\n m = t3(d)\nend = time.time()\nprint (\"Accepted answer: \"+str(end-start))\n Iterating: 3.8201940059661865\nList creating: 6.928712844848633\nAccepted answer: 5.464320182800293\n"
},
{
"answer_id": 46043740,
"author": "user2399453",
"author_id": 2399453,
"author_profile": "https://Stackoverflow.com/users/2399453",
"pm_score": 1,
"selected": false,
"text": " max(zip(stats.keys(), stats.values()), key=lambda t : t[1])[0]\n"
},
{
"answer_id": 47854612,
"author": "Karim Sonbol",
"author_id": 1802750,
"author_profile": "https://Stackoverflow.com/users/1802750",
"pm_score": 5,
"selected": false,
"text": "stats stats = {'a':1000, 'b':3000, 'c': 100}\n >>> max(stats.items(), key = lambda x: x[0])\n('c', 100) >>> max(stats.items(), key = lambda x: x[1])\n('b', 3000) >>> max(stats.items(), key = lambda x: x[1])[0]\n'b' items() max (key, value) >>> list(stats.items())\n[('c', 100), ('b', 3000), ('a', 1000)] lambda lambda x: x[1] x (key, value) iteritems() items()"
},
{
"answer_id": 48180876,
"author": "Jasha",
"author_id": 4256346,
"author_profile": "https://Stackoverflow.com/users/4256346",
"pm_score": 3,
"selected": false,
"text": "max((value, key) for key, value in stats.items())[1]"
},
{
"answer_id": 50168872,
"author": "priya khokher",
"author_id": 5638335,
"author_profile": "https://Stackoverflow.com/users/5638335",
"pm_score": 4,
"selected": false,
"text": "d = {'A': 4,'B':10}\n\nmin_v = min(zip(d.values(), d.keys()))\n# min_v is (4,'A')\n\nmax_v = max(zip(d.values(), d.keys()))\n# max_v is (10,'B')\n"
},
{
"answer_id": 51978193,
"author": "leo022",
"author_id": 10132167,
"author_profile": "https://Stackoverflow.com/users/10132167",
"pm_score": 6,
"selected": false,
"text": "stats = {'a':1000, 'b':3000, 'c': 100}\n max(stats, key=stats.get)\n"
},
{
"answer_id": 52292146,
"author": "ron_g",
"author_id": 4916945,
"author_profile": "https://Stackoverflow.com/users/4916945",
"pm_score": 4,
"selected": false,
"text": "mydict.keys() mydict.values() max() stats = {'a':1000, 'b':3000, 'c': 100}\n\nx = sorted(stats, key=(lambda key:stats[key]), reverse=True)\n['b', 'a', 'c']\n x[0]\n['b']\n x[:2]\n['b', 'a']\n"
},
{
"answer_id": 53100002,
"author": "jpp",
"author_id": 9209546,
"author_profile": "https://Stackoverflow.com/users/9209546",
"pm_score": 3,
"selected": false,
"text": "from heapq import nlargest\n\nstats = {'a':1000, 'b':3000, 'c': 100}\n\nres1 = nlargest(1, stats, key=stats.__getitem__) # ['b']\nres2 = nlargest(2, stats, key=stats.__getitem__) # ['b', 'a']\n\nres1_val = next(iter(res1)) # 'b'\n dict.__getitem__ dict[] dict.get KeyError"
},
{
"answer_id": 57559867,
"author": "kslote1",
"author_id": 2507311,
"author_profile": "https://Stackoverflow.com/users/2507311",
"pm_score": 4,
"selected": false,
"text": "max def keys_with_top_values(my_dict):\n return [key for (key, value) in my_dict.items() if value == max(my_dict.values())]\n"
},
{
"answer_id": 60209561,
"author": "Ignacio Alorre",
"author_id": 1773841,
"author_profile": "https://Stackoverflow.com/users/1773841",
"pm_score": 0,
"selected": false,
"text": "stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000, 'e':3000}\n from collections import defaultdict\nfrom collections import OrderedDict\n\ngroupedByValue = defaultdict(list)\nfor key, value in sorted(stats.items()):\n groupedByValue[value].append(key)\n\n# {1000: ['a'], 3000: ['b', 'd', 'e'], 100: ['c']}\n\ngroupedByValue[max(groupedByValue)]\n# ['b', 'd', 'e']\n"
},
{
"answer_id": 60219795,
"author": "wkzhu",
"author_id": 7327411,
"author_profile": "https://Stackoverflow.com/users/7327411",
"pm_score": 2,
"selected": false,
"text": "import pandas as pd\npd.Series({'a': 1000, 'b': 3000, 'c': 100}).idxmax()\n\n>>> b\n"
},
{
"answer_id": 60230912,
"author": "pk786",
"author_id": 3827844,
"author_profile": "https://Stackoverflow.com/users/3827844",
"pm_score": 7,
"selected": false,
"text": "max(d, key=d.get) \n# which is equivalent to \nmax(d, key=lambda k: d.get(k))\n max(d.items(), key=lambda k: k[1])\n"
},
{
"answer_id": 62152615,
"author": "Ali Sajjad",
"author_id": 12065150,
"author_profile": "https://Stackoverflow.com/users/12065150",
"pm_score": 3,
"selected": false,
"text": "mydict = { 'a':302, 'e':53, 'g':302, 'h':100 }\nmax_value_keys = [key for key in mydict.keys() if mydict[key] == max(mydict.values())]\nprint(max_value_keys) # prints a list of keys with max value\n maximum = mydict[max_value_keys[0]]\n"
},
{
"answer_id": 63745002,
"author": "Bhindi",
"author_id": 3839900,
"author_profile": "https://Stackoverflow.com/users/3839900",
"pm_score": 5,
"selected": false,
"text": "max(stats, key=stats.get, default=None)\n stats max(stats, key=stats.get) ValueError None"
},
{
"answer_id": 66924717,
"author": "Shaonsani",
"author_id": 7248950,
"author_profile": "https://Stackoverflow.com/users/7248950",
"pm_score": 2,
"selected": false,
"text": "stats = {'a':1000, 'b':3000, 'c': 100}\nmax_key = None\nif bool(stats):\n max_key = max(stats, key=stats.get)\nprint(max_key)\n >>> b\n"
},
{
"answer_id": 69237479,
"author": "BusBar_යසස්",
"author_id": 11327125,
"author_profile": "https://Stackoverflow.com/users/11327125",
"pm_score": 1,
"selected": false,
"text": "sorted(dict_name, key=dict_name.__getitem__, reverse=True)[0]\n"
},
{
"answer_id": 69237779,
"author": "Ashutosh",
"author_id": 6418029,
"author_profile": "https://Stackoverflow.com/users/6418029",
"pm_score": 3,
"selected": false,
"text": "import time\nstats = {\n \"a\" : 1000,\n \"b\" : 3000,\n \"c\" : 90,\n \"d\" : 74,\n \"e\" : 72,\n }\n\nstart_time = time.time_ns()\nmax_key = max(stats, key = stats.get)\nprint(\"Max Key [\", max_key, \"]Time taken (ns)\", time.time_ns() - start_time)\n\nstart_time = time.time_ns()\nmax_key = max(stats, key=lambda key: stats[key])\nprint(\"Max Key with Lambda[\", max_key, \"]Time taken (ns)\", time.time_ns() - start_time)\n Max Key [ b ] Time taken (ns) 3100\nMax Key with Lambda [ b ] Time taken (ns) 1782\n"
},
{
"answer_id": 73439643,
"author": "Allan",
"author_id": 13356494,
"author_profile": "https://Stackoverflow.com/users/13356494",
"pm_score": 0,
"selected": false,
"text": "stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000, 'e':3000}\nkeys_to_search = [\"a\", \"b\", \"c\"]\n\nmax([k for k in keys_to_search], key=lambda x: stats[x])```\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34598/"
] |
268,277
|
<p>We want to throw an exception, if a user calls DataContext.SubmitChanges() and the DataContext is not tracking anything.</p>
<p>That is... it is OK to call SubmitChanges if there are no inserts, updates or deletes. But we want to ensure that the developer didn't forget to attach the entity to the DataContext.</p>
<p>Even better... is it possible to get a collection of all entities that the DataContext is tracking (including those that are not changed)?</p>
<p>PS: The <a href="https://stackoverflow.com/questions/259219/how-can-i-reject-all-changes-in-a-linq-to-sqls-datacontext">last question I asked</a> were answered with: "do it this way instead"... please don't :-)</p>
|
[
{
"answer_id": 268472,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "ChangeTracker Services"
},
{
"answer_id": 736871,
"author": "bytebender",
"author_id": 86452,
"author_profile": "https://Stackoverflow.com/users/86452",
"pm_score": 0,
"selected": false,
"text": "DataContext.GetChangeSet().Inserts;\nDataContext.GetChangeSet().Deletes;\nDataContext.GetChangeSet().Updates;\n if (DataContext.GetChageSet().Inserts.Count = 0\n && DataContext.GetChageSet().Deletes.Count\n && DataContext.GetChageSet().Updates.Count)\n{\n throw new Exception(\"You forgot to do something with your DataContext...\");\n}\nelse\n{\n DataContext.SubmitChanges();\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547/"
] |
268,289
|
<p>I have a Nant build script which CruiseControl uses to build a solution on-demand.</p>
<p>However, we only recently got CruiseControl so our official build number is different from what is listed in CruiseControl.</p>
<p>I know CruiseControl injects some properties into build scripts so that I can access the CC build number in the script (CCNetLabel) but how do I pass a value back to CC to use as the build number on the UI screen?</p>
<p>Example, CC says build number 2</p>
<p>nAnt script increments a buildnumber.xml value every build, and the official build number is on 123.</p>
<p>I want the CC UI to show last successful build number: 123, not 2, so how do I pass that value back up?</p>
|
[
{
"answer_id": 269236,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 4,
"selected": true,
"text": "/// <summary>\n/// Gets the latest change list number from perforce, for ccnet to consume as a build label.\n/// </summary>\n[ReflectorType( \"p4labeller\" )]\npublic class PerforceLabeller : ILabeller\n{\n // perforce executable (optional)\n [ReflectorProperty(\"executable\", Required = false)]\n public string P4Executable = \"p4.exe\";\n\n // perforce port (i.e. myserver:1234)\n [ReflectorProperty(\"port\", Required = false)]\n public string P4Port = String.Empty;\n\n // perforce user\n [ReflectorProperty(\"user\", Required = false)]\n public string P4User = String.Empty;\n\n // perforce client\n [ReflectorProperty(\"client\", Required = false)]\n public string P4Client = String.Empty;\n\n // perforce view (i.e. //Dev/Code1/...)\n [ReflectorProperty(\"view\", Required = false)]\n public string P4View = String.Empty;\n\n // Returns latest change list\n public string Generate( IIntegrationResult previousLabel )\n {\n return GetLatestChangelist(); \n }\n\n // Stores latest change list into a label\n public void Run( IIntegrationResult result )\n {\n result.Label = GetLatestChangelist();\n }\n\n // Gets the latest change list\n public string GetLatestChangelist()\n {\n // Build the arguments to pass to p4 to get the latest changelist\n string theArgs = \"-p \" + P4Port + \" -u \" + P4User + \" -c \" + P4Client + \" changes -m 1 -s submitted \" + P4View;\n Log.Info( string.Format( \"Getting latest change from Perforce using --> \" + theArgs ) );\n\n // Execute p4\n ProcessResult theProcessResult = new ProcessExecutor().Execute( new ProcessInfo( P4Executable, theArgs ) );\n\n // Extract the changelist # from the result\n Regex theRegex = new Regex( @\"\\s[0-9]+\\s\", RegexOptions.IgnoreCase );\n Match theMatch = theRegex.Match( theProcessResult.StandardOutput );\n return theMatch.Value.Trim();\n }\n}\n <project>\n<labeller type=\"p4labeller\">\n <client>myclient</client>\n <executable>p4.exe</executable>\n <port>myserver:1234</port>\n <user>myuser</user>\n <view>//Code1/...</view>\n</labeller>\n<!-- Other project configuration to go here -->\n</project>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18818/"
] |
268,296
|
<p>is there a way to have a mysql select statement return fully qualified column names like "table.field" without using AS for every single field?</p>
<p>like so:</p>
<pre><code>SELECT *
FROM table1
LEFT JOIN table2 on table1.f_ID = table2.ID
</code></pre>
<p>and the result would be:
"table1.ID", "table1.name", "table2.ID", "table2.name", ...</p>
|
[
{
"answer_id": 2309403,
"author": "Mihai Stancu",
"author_id": 278509,
"author_profile": "https://Stackoverflow.com/users/278509",
"pm_score": 1,
"selected": false,
"text": "SELECT table1.ID, table1.name, table2.ID, table2.name\nFROM table1 \nLEFT JOIN table2 on table1.f_ID = table2.ID\n"
},
{
"answer_id": 2675118,
"author": "user321297",
"author_id": 321297,
"author_profile": "https://Stackoverflow.com/users/321297",
"pm_score": 1,
"selected": false,
"text": " SELECT table1.*, table2.*\n FROM table1 \nLEFT JOIN table2 on table1.f_ID = table2.ID\n"
},
{
"answer_id": 8608381,
"author": "Paul Hutchinson",
"author_id": 511334,
"author_profile": "https://Stackoverflow.com/users/511334",
"pm_score": 2,
"selected": false,
"text": "$PDO->setAttribute(PDO::ATTR_FETCH_TABLE_NAMES, true);"
},
{
"answer_id": 37485622,
"author": "MarkZ",
"author_id": 6391390,
"author_profile": "https://Stackoverflow.com/users/6391390",
"pm_score": 0,
"selected": false,
"text": "select table1.* , table1='<======'\n\n table2.* , table2='<======'\n\nfrom table1 \n\n left join table2 on table1.f_ID = table2.ID\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427/"
] |
268,321
|
<p>I am looking for a generic, bidirectional 1 to 1 Dictionary class in C# (2), ie. a <code>BiDictionaryOneToOne<T, S></code> which is guaranteed to only contain one of each value and key (up to RefEquals anyway), and which can be searched using either key or value. Anyone know of one, or should I just implement it myself? I can't believe that I'm the first person to need this...</p>
<p>There is a BiDictionary in the answers to <a href="https://stackoverflow.com/questions/255341/getting-key-of-value-of-a-generic-dictionary">this question</a>, but it is not for unique elements (and also does not implement RemoveByFirst(T t) or RemoveBySecond(S s)). </p>
<p>Thanks!</p>
|
[
{
"answer_id": 268380,
"author": "Tomas Pajonk",
"author_id": 4694,
"author_profile": "https://Stackoverflow.com/users/4694",
"pm_score": 2,
"selected": false,
"text": "public class Mapper<K,T> : IEnumerable<T>\n\n{\n C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();\n C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();\n\n\n /// <summary>\n /// Initializes a new instance of the Mapper class.\n /// </summary>\n public Mapper()\n {\n KToTMap = new TreeDictionary<K,T>();\n TToKMap = new HashDictionary<T,K>();\n }\n\n\n public void Add(K key, T value)\n {\n KToTMap.Add(key, value);\n TToKMap.Add(value, key);\n }\n\n public bool ContainsKey(K key)\n {\n return KToTMap.Contains(key);\n }\n\n public int Count\n {\n get { return KToTMap.Count; }\n }\n\n\n public K this[T obj]\n {\n get\n {\n return TToKMap[obj];\n }\n }\n\n public T this[K obj]\n {\n get\n {\n return KToTMap[obj];\n }\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n return KToTMap.Values.GetEnumerator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return KToTMap.Values.GetEnumerator();\n }\n}\n"
},
{
"answer_id": 268545,
"author": "Joel in Gö",
"author_id": 6091,
"author_profile": "https://Stackoverflow.com/users/6091",
"pm_score": 7,
"selected": true,
"text": "/// <summary>\n/// This is a dictionary guaranteed to have only one of each value and key. \n/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.\n/// </summary>\n/// <typeparam name=\"TFirst\">The type of the \"key\"</typeparam>\n/// <typeparam name=\"TSecond\">The type of the \"value\"</typeparam>\npublic class BiDictionaryOneToOne<TFirst, TSecond>\n{\n IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();\n IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();\n\n #region Exception throwing methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Throws an exception if either element is already in the dictionary\n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n public void Add(TFirst first, TSecond second)\n {\n if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))\n throw new ArgumentException(\"Duplicate first or second\");\n\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n }\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first\n /// Throws an exception if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <returns>the value corresponding to first</returns>\n public TSecond GetByFirst(TFirst first)\n {\n TSecond second;\n if (!firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n return second; \n }\n\n /// <summary>\n /// Find the TFirst corresponing to the Second second.\n /// Throws an exception if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <returns>the value corresponding to second</returns>\n public TFirst GetBySecond(TSecond second)\n {\n TFirst first;\n if (!secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n return first; \n }\n\n\n /// <summary>\n /// Remove the record containing first.\n /// If first is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"first\">the key of the record to delete</param>\n public void RemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n firstToSecond.Remove(first);\n secondToFirst.Remove(second);\n }\n\n /// <summary>\n /// Remove the record containing second.\n /// If second is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"second\">the key of the record to delete</param>\n public void RemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n secondToFirst.Remove(second);\n firstToSecond.Remove(first);\n }\n\n #endregion\n\n #region Try methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Returns false if either element is already in the dictionary \n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n /// <returns>true if successfully added, false if either element are already in the dictionary</returns>\n public Boolean TryAdd(TFirst first, TSecond second)\n {\n if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))\n return false;\n\n firstToSecond.Add(first, second);\n secondToFirst.Add(second, first);\n return true;\n }\n\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first.\n /// Returns false if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <param name=\"second\">the corresponding value</param>\n /// <returns>true if first is in the dictionary, false otherwise</returns>\n public Boolean TryGetByFirst(TFirst first, out TSecond second)\n {\n return firstToSecond.TryGetValue(first, out second);\n }\n\n /// <summary>\n /// Find the TFirst corresponding to the TSecond second.\n /// Returns false if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <param name=\"first\">the corresponding value</param>\n /// <returns>true if second is in the dictionary, false otherwise</returns>\n public Boolean TryGetBySecond(TSecond second, out TFirst first)\n {\n return secondToFirst.TryGetValue(second, out first);\n }\n\n /// <summary>\n /// Remove the record containing first, if there is one.\n /// </summary>\n /// <param name=\"first\"></param>\n /// <returns> If first is not in the dictionary, returns false, otherwise true</returns>\n public Boolean TryRemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!firstToSecond.TryGetValue(first, out second))\n return false;\n\n firstToSecond.Remove(first);\n secondToFirst.Remove(second);\n return true;\n }\n\n /// <summary>\n /// Remove the record containing second, if there is one.\n /// </summary>\n /// <param name=\"second\"></param>\n /// <returns> If second is not in the dictionary, returns false, otherwise true</returns>\n public Boolean TryRemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!secondToFirst.TryGetValue(second, out first))\n return false;\n\n secondToFirst.Remove(second);\n firstToSecond.Remove(first);\n return true;\n }\n\n #endregion \n\n /// <summary>\n /// The number of pairs stored in the dictionary\n /// </summary>\n public Int32 Count\n {\n get { return firstToSecond.Count; }\n }\n\n /// <summary>\n /// Removes all items from the dictionary.\n /// </summary>\n public void Clear()\n {\n firstToSecond.Clear();\n secondToFirst.Clear();\n }\n}\n"
},
{
"answer_id": 15852877,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 2,
"selected": false,
"text": "Update public class BiDictionary<TKey1, TKey2> : IEnumerable<Tuple<TKey1, TKey2>>\n{\n Dictionary<TKey1, TKey2> _forwards;\n Dictionary<TKey2, TKey1> _reverses;\n\n public int Count\n {\n get\n {\n if (_forwards.Count != _reverses.Count)\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n return _forwards.Count;\n }\n }\n\n public ICollection<TKey1> Key1s\n {\n get { return _forwards.Keys; }\n }\n\n public ICollection<TKey2> Key2s\n {\n get { return _reverses.Keys; }\n }\n\n public BiDictionary(IEqualityComparer<TKey1> comparer1 = null, IEqualityComparer<TKey2> comparer2 = null)\n {\n _forwards = new Dictionary<TKey1, TKey2>(comparer1);\n _reverses = new Dictionary<TKey2, TKey1>(comparer2);\n }\n\n\n\n public bool ContainsKey1(TKey1 key)\n {\n return ContainsKey(key, _forwards);\n }\n\n private static bool ContainsKey<S, T>(S key, Dictionary<S, T> dict)\n {\n return dict.ContainsKey(key);\n }\n\n public bool ContainsKey2(TKey2 key)\n {\n return ContainsKey(key, _reverses);\n }\n\n public TKey2 GetValueByKey1(TKey1 key)\n {\n return GetValueByKey(key, _forwards);\n }\n\n private static T GetValueByKey<S, T>(S key, Dictionary<S, T> dict)\n {\n return dict[key];\n }\n\n public TKey1 GetValueByKey2(TKey2 key)\n {\n return GetValueByKey(key, _reverses);\n }\n\n public bool TryGetValueByKey1(TKey1 key, out TKey2 value)\n {\n return TryGetValue(key, _forwards, out value);\n }\n\n private static bool TryGetValue<S, T>(S key, Dictionary<S, T> dict, out T value)\n {\n return dict.TryGetValue(key, out value);\n }\n\n public bool TryGetValueByKey2(TKey2 key, out TKey1 value)\n {\n return TryGetValue(key, _reverses, out value);\n }\n\n public bool Add(TKey1 key1, TKey2 key2)\n {\n if (ContainsKey1(key1) || ContainsKey2(key2)) // very important\n return false;\n\n AddOrUpdate(key1, key2);\n return true;\n }\n\n public void AddOrUpdateByKey1(TKey1 key1, TKey2 key2)\n {\n if (!UpdateByKey1(key1, key2))\n AddOrUpdate(key1, key2);\n }\n\n // dont make this public; a dangerous method used cautiously in this class\n private void AddOrUpdate(TKey1 key1, TKey2 key2)\n {\n _forwards[key1] = key2;\n _reverses[key2] = key1;\n }\n\n public void AddOrUpdateKeyByKey2(TKey2 key2, TKey1 key1)\n {\n if (!UpdateByKey2(key2, key1))\n AddOrUpdate(key1, key2);\n }\n\n public bool UpdateKey1(TKey1 oldKey, TKey1 newKey)\n {\n return UpdateKey(oldKey, _forwards, newKey, (key1, key2) => AddOrUpdate(key1, key2));\n }\n\n private static bool UpdateKey<S, T>(S oldKey, Dictionary<S, T> dict, S newKey, Action<S, T> updater)\n {\n T otherKey;\n if (!TryGetValue(oldKey, dict, out otherKey) || ContainsKey(newKey, dict))\n return false;\n\n Remove(oldKey, dict);\n updater(newKey, otherKey);\n return true;\n }\n\n public bool UpdateKey2(TKey2 oldKey, TKey2 newKey)\n {\n return UpdateKey(oldKey, _reverses, newKey, (key1, key2) => AddOrUpdate(key2, key1));\n }\n\n public bool UpdateByKey1(TKey1 key1, TKey2 key2)\n {\n return UpdateByKey(key1, _forwards, _reverses, key2, (k1, k2) => AddOrUpdate(k1, k2));\n }\n\n private static bool UpdateByKey<S, T>(S key1, Dictionary<S, T> forwards, Dictionary<T, S> reverses, T key2,\n Action<S, T> updater)\n {\n T otherKey;\n if (!TryGetValue(key1, forwards, out otherKey) || ContainsKey(key2, reverses))\n return false;\n\n if (!Remove(otherKey, reverses))\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n updater(key1, key2);\n return true;\n }\n\n public bool UpdateByKey2(TKey2 key2, TKey1 key1)\n {\n return UpdateByKey(key2, _reverses, _forwards, key1, (k1, k2) => AddOrUpdate(k2, k1));\n }\n\n public bool RemoveByKey1(TKey1 key)\n {\n return RemoveByKey(key, _forwards, _reverses);\n }\n\n private static bool RemoveByKey<S, T>(S key, Dictionary<S, T> keyDict, Dictionary<T, S> valueDict)\n {\n T otherKey;\n if (!TryGetValue(key, keyDict, out otherKey))\n return false;\n\n if (!Remove(key, keyDict) || !Remove(otherKey, valueDict))\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n return true;\n }\n\n private static bool Remove<S, T>(S key, Dictionary<S, T> dict)\n {\n return dict.Remove(key);\n }\n\n public bool RemoveByKey2(TKey2 key)\n {\n return RemoveByKey(key, _reverses, _forwards);\n }\n\n public void Clear()\n {\n _forwards.Clear();\n _reverses.Clear();\n }\n\n public IEnumerator<Tuple<TKey1, TKey2>> GetEnumerator()\n {\n if (_forwards.Count != _reverses.Count)\n throw new Exception(\"somewhere logic went wrong and your data got corrupt\");\n\n foreach (var item in _forwards)\n yield return Tuple.Create(item.Key, item.Value);\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n IEnumerable<> ICollection<> IEnumerable<> var p = new BiDictionary<int, string> { 1, \"a\" }, { 2, \"b\" } };\n Value Keys Get Contains Add Update Remove"
},
{
"answer_id": 15927912,
"author": "Athari",
"author_id": 293099,
"author_profile": "https://Stackoverflow.com/users/293099",
"pm_score": 4,
"selected": false,
"text": "Dictionary<TKey,TValue> IDictionary<TKey, TValue> IReadOnlyDictionary<TKey, TValue> IDictionary ICollection<KeyValuePair<TKey, TValue>> ICollection IReadOnlyCollection<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>> IEnumerable SerializableAttribute DebuggerDisplayAttribute DebuggerTypeProxyAttribute IDictionary<TValue, TKey> Reverse var dic = new BiDictionary<int, string>();\ndic.Add(1, \"1\");\ndic[2] = \"2\";\ndic.Reverse.Add(\"3\", 3);\ndic.Reverse[\"4\"] = 4;\ndic.Clear();\n [Serializable]\n[DebuggerDisplay (\"Count = {Count}\"), DebuggerTypeProxy (typeof(DictionaryDebugView<,>))]\npublic class BiDictionary<TFirst, TSecond> : IDictionary<TFirst, TSecond>, IReadOnlyDictionary<TFirst, TSecond>, IDictionary\n{\n private readonly IDictionary<TFirst, TSecond> _firstToSecond = new Dictionary<TFirst, TSecond>();\n [NonSerialized]\n private readonly IDictionary<TSecond, TFirst> _secondToFirst = new Dictionary<TSecond, TFirst>();\n [NonSerialized]\n private readonly ReverseDictionary _reverseDictionary;\n\n public BiDictionary ()\n {\n _reverseDictionary = new ReverseDictionary(this);\n }\n\n public IDictionary<TSecond, TFirst> Reverse\n {\n get { return _reverseDictionary; }\n }\n\n public int Count\n {\n get { return _firstToSecond.Count; }\n }\n\n object ICollection.SyncRoot\n {\n get { return ((ICollection)_firstToSecond).SyncRoot; }\n }\n\n bool ICollection.IsSynchronized\n {\n get { return ((ICollection)_firstToSecond).IsSynchronized; }\n }\n\n bool IDictionary.IsFixedSize\n {\n get { return ((IDictionary)_firstToSecond).IsFixedSize; }\n }\n\n public bool IsReadOnly\n {\n get { return _firstToSecond.IsReadOnly || _secondToFirst.IsReadOnly; }\n }\n\n public TSecond this [TFirst key]\n {\n get { return _firstToSecond[key]; }\n set\n {\n _firstToSecond[key] = value;\n _secondToFirst[value] = key;\n }\n }\n\n object IDictionary.this [object key]\n {\n get { return ((IDictionary)_firstToSecond)[key]; }\n set\n {\n ((IDictionary)_firstToSecond)[key] = value;\n ((IDictionary)_secondToFirst)[value] = key;\n }\n }\n\n public ICollection<TFirst> Keys\n {\n get { return _firstToSecond.Keys; }\n }\n\n ICollection IDictionary.Keys\n {\n get { return ((IDictionary)_firstToSecond).Keys; }\n }\n\n IEnumerable<TFirst> IReadOnlyDictionary<TFirst, TSecond>.Keys\n {\n get { return ((IReadOnlyDictionary<TFirst, TSecond>)_firstToSecond).Keys; }\n }\n\n public ICollection<TSecond> Values\n {\n get { return _firstToSecond.Values; }\n }\n\n ICollection IDictionary.Values\n {\n get { return ((IDictionary)_firstToSecond).Values; }\n }\n\n IEnumerable<TSecond> IReadOnlyDictionary<TFirst, TSecond>.Values\n {\n get { return ((IReadOnlyDictionary<TFirst, TSecond>)_firstToSecond).Values; }\n }\n\n public IEnumerator<KeyValuePair<TFirst, TSecond>> GetEnumerator ()\n {\n return _firstToSecond.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator ()\n {\n return GetEnumerator();\n }\n\n IDictionaryEnumerator IDictionary.GetEnumerator ()\n {\n return ((IDictionary)_firstToSecond).GetEnumerator();\n }\n\n public void Add (TFirst key, TSecond value)\n {\n _firstToSecond.Add(key, value);\n _secondToFirst.Add(value, key);\n }\n\n void IDictionary.Add (object key, object value)\n {\n ((IDictionary)_firstToSecond).Add(key, value);\n ((IDictionary)_secondToFirst).Add(value, key);\n }\n\n public void Add (KeyValuePair<TFirst, TSecond> item)\n {\n _firstToSecond.Add(item);\n _secondToFirst.Add(item.Reverse());\n }\n\n public bool ContainsKey (TFirst key)\n {\n return _firstToSecond.ContainsKey(key);\n }\n\n public bool Contains (KeyValuePair<TFirst, TSecond> item)\n {\n return _firstToSecond.Contains(item);\n }\n\n public bool TryGetValue (TFirst key, out TSecond value)\n {\n return _firstToSecond.TryGetValue(key, out value);\n }\n\n public bool Remove (TFirst key)\n {\n TSecond value;\n if (_firstToSecond.TryGetValue(key, out value)) {\n _firstToSecond.Remove(key);\n _secondToFirst.Remove(value);\n return true;\n }\n else\n return false;\n }\n\n void IDictionary.Remove (object key)\n {\n var firstToSecond = (IDictionary)_firstToSecond;\n if (!firstToSecond.Contains(key))\n return;\n var value = firstToSecond[key];\n firstToSecond.Remove(key);\n ((IDictionary)_secondToFirst).Remove(value);\n }\n\n public bool Remove (KeyValuePair<TFirst, TSecond> item)\n {\n return _firstToSecond.Remove(item);\n }\n\n public bool Contains (object key)\n {\n return ((IDictionary)_firstToSecond).Contains(key);\n }\n\n public void Clear ()\n {\n _firstToSecond.Clear();\n _secondToFirst.Clear();\n }\n\n public void CopyTo (KeyValuePair<TFirst, TSecond>[] array, int arrayIndex)\n {\n _firstToSecond.CopyTo(array, arrayIndex);\n }\n\n void ICollection.CopyTo (Array array, int index)\n {\n ((IDictionary)_firstToSecond).CopyTo(array, index);\n }\n\n [OnDeserialized]\n internal void OnDeserialized (StreamingContext context)\n {\n _secondToFirst.Clear();\n foreach (var item in _firstToSecond)\n _secondToFirst.Add(item.Value, item.Key);\n }\n\n private class ReverseDictionary : IDictionary<TSecond, TFirst>, IReadOnlyDictionary<TSecond, TFirst>, IDictionary\n {\n private readonly BiDictionary<TFirst, TSecond> _owner;\n\n public ReverseDictionary (BiDictionary<TFirst, TSecond> owner)\n {\n _owner = owner;\n }\n\n public int Count\n {\n get { return _owner._secondToFirst.Count; }\n }\n\n object ICollection.SyncRoot\n {\n get { return ((ICollection)_owner._secondToFirst).SyncRoot; }\n }\n\n bool ICollection.IsSynchronized\n {\n get { return ((ICollection)_owner._secondToFirst).IsSynchronized; }\n }\n\n bool IDictionary.IsFixedSize\n {\n get { return ((IDictionary)_owner._secondToFirst).IsFixedSize; }\n }\n\n public bool IsReadOnly\n {\n get { return _owner._secondToFirst.IsReadOnly || _owner._firstToSecond.IsReadOnly; }\n }\n\n public TFirst this [TSecond key]\n {\n get { return _owner._secondToFirst[key]; }\n set\n {\n _owner._secondToFirst[key] = value;\n _owner._firstToSecond[value] = key;\n }\n }\n\n object IDictionary.this [object key]\n {\n get { return ((IDictionary)_owner._secondToFirst)[key]; }\n set\n {\n ((IDictionary)_owner._secondToFirst)[key] = value;\n ((IDictionary)_owner._firstToSecond)[value] = key;\n }\n }\n\n public ICollection<TSecond> Keys\n {\n get { return _owner._secondToFirst.Keys; }\n }\n\n ICollection IDictionary.Keys\n {\n get { return ((IDictionary)_owner._secondToFirst).Keys; }\n }\n\n IEnumerable<TSecond> IReadOnlyDictionary<TSecond, TFirst>.Keys\n {\n get { return ((IReadOnlyDictionary<TSecond, TFirst>)_owner._secondToFirst).Keys; }\n }\n\n public ICollection<TFirst> Values\n {\n get { return _owner._secondToFirst.Values; }\n }\n\n ICollection IDictionary.Values\n {\n get { return ((IDictionary)_owner._secondToFirst).Values; }\n }\n\n IEnumerable<TFirst> IReadOnlyDictionary<TSecond, TFirst>.Values\n {\n get { return ((IReadOnlyDictionary<TSecond, TFirst>)_owner._secondToFirst).Values; }\n }\n\n public IEnumerator<KeyValuePair<TSecond, TFirst>> GetEnumerator ()\n {\n return _owner._secondToFirst.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator ()\n {\n return GetEnumerator();\n }\n\n IDictionaryEnumerator IDictionary.GetEnumerator ()\n {\n return ((IDictionary)_owner._secondToFirst).GetEnumerator();\n }\n\n public void Add (TSecond key, TFirst value)\n {\n _owner._secondToFirst.Add(key, value);\n _owner._firstToSecond.Add(value, key);\n }\n\n void IDictionary.Add (object key, object value)\n {\n ((IDictionary)_owner._secondToFirst).Add(key, value);\n ((IDictionary)_owner._firstToSecond).Add(value, key);\n }\n\n public void Add (KeyValuePair<TSecond, TFirst> item)\n {\n _owner._secondToFirst.Add(item);\n _owner._firstToSecond.Add(item.Reverse());\n }\n\n public bool ContainsKey (TSecond key)\n {\n return _owner._secondToFirst.ContainsKey(key);\n }\n\n public bool Contains (KeyValuePair<TSecond, TFirst> item)\n {\n return _owner._secondToFirst.Contains(item);\n }\n\n public bool TryGetValue (TSecond key, out TFirst value)\n {\n return _owner._secondToFirst.TryGetValue(key, out value);\n }\n\n public bool Remove (TSecond key)\n {\n TFirst value;\n if (_owner._secondToFirst.TryGetValue(key, out value)) {\n _owner._secondToFirst.Remove(key);\n _owner._firstToSecond.Remove(value);\n return true;\n }\n else\n return false;\n }\n\n void IDictionary.Remove (object key)\n {\n var firstToSecond = (IDictionary)_owner._secondToFirst;\n if (!firstToSecond.Contains(key))\n return;\n var value = firstToSecond[key];\n firstToSecond.Remove(key);\n ((IDictionary)_owner._firstToSecond).Remove(value);\n }\n\n public bool Remove (KeyValuePair<TSecond, TFirst> item)\n {\n return _owner._secondToFirst.Remove(item);\n }\n\n public bool Contains (object key)\n {\n return ((IDictionary)_owner._secondToFirst).Contains(key);\n }\n\n public void Clear ()\n {\n _owner._secondToFirst.Clear();\n _owner._firstToSecond.Clear();\n }\n\n public void CopyTo (KeyValuePair<TSecond, TFirst>[] array, int arrayIndex)\n {\n _owner._secondToFirst.CopyTo(array, arrayIndex);\n }\n\n void ICollection.CopyTo (Array array, int index)\n {\n ((IDictionary)_owner._secondToFirst).CopyTo(array, index);\n }\n }\n}\n\ninternal class DictionaryDebugView<TKey, TValue>\n{\n private readonly IDictionary<TKey, TValue> _dictionary;\n\n [DebuggerBrowsable (DebuggerBrowsableState.RootHidden)]\n public KeyValuePair<TKey, TValue>[] Items\n {\n get\n {\n var array = new KeyValuePair<TKey, TValue>[_dictionary.Count];\n _dictionary.CopyTo(array, 0);\n return array;\n }\n }\n\n public DictionaryDebugView (IDictionary<TKey, TValue> dictionary)\n {\n if (dictionary == null)\n throw new ArgumentNullException(\"dictionary\");\n _dictionary = dictionary;\n }\n}\n\npublic static class KeyValuePairExts\n{\n public static KeyValuePair<TValue, TKey> Reverse<TKey, TValue> (this KeyValuePair<TKey, TValue> @this)\n {\n return new KeyValuePair<TValue, TKey>(@this.Value, @this.Key);\n }\n}\n"
},
{
"answer_id": 33674856,
"author": "Chris Chilvers",
"author_id": 35233,
"author_profile": "https://Stackoverflow.com/users/35233",
"pm_score": 1,
"selected": false,
"text": "A => 1 1 => A' Inverse var map = new BidirectionalDictionary<int, int>();\nmap.Add(1, 2);\nvar result = map.Inverse[2]; // result is 1\n //\n// BidirectionalDictionary.cs\n//\n// Author:\n// Chris Chilvers <chilversc@googlemail.com>\n//\n// Copyright (c) 2009 Chris Chilvers\n//\n// Permission is hereby granted, free of charge, to any person obtaining\n// a copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to\n// the following conditions:\n//\n// The above copyright notice and this permission notice shall be\n// included in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n//\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\n\nnamespace Cadenza.Collections\n{\n public class BidirectionalDictionary<TKey, TValue> : IDictionary<TKey, TValue>\n {\n private readonly IEqualityComparer<TKey> keyComparer;\n private readonly IEqualityComparer<TValue> valueComparer;\n private readonly Dictionary<TKey, TValue> keysToValues;\n private readonly Dictionary<TValue, TKey> valuesToKeys;\n private readonly BidirectionalDictionary<TValue, TKey> inverse;\n\n\n public BidirectionalDictionary () : this (10, null, null) {}\n\n public BidirectionalDictionary (int capacity) : this (capacity, null, null) {}\n\n public BidirectionalDictionary (IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)\n : this (10, keyComparer, valueComparer)\n {\n }\n\n public BidirectionalDictionary (int capacity, IEqualityComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer)\n {\n if (capacity < 0)\n throw new ArgumentOutOfRangeException (\"capacity\", capacity, \"capacity cannot be less than 0\");\n\n this.keyComparer = keyComparer ?? EqualityComparer<TKey>.Default;\n this.valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;\n\n keysToValues = new Dictionary<TKey, TValue> (capacity, this.keyComparer);\n valuesToKeys = new Dictionary<TValue, TKey> (capacity, this.valueComparer);\n\n inverse = new BidirectionalDictionary<TValue, TKey> (this);\n }\n\n private BidirectionalDictionary (BidirectionalDictionary<TValue, TKey> inverse)\n {\n this.inverse = inverse;\n keyComparer = inverse.valueComparer;\n valueComparer = inverse.keyComparer;\n valuesToKeys = inverse.keysToValues;\n keysToValues = inverse.valuesToKeys;\n }\n\n\n public BidirectionalDictionary<TValue, TKey> Inverse {\n get { return inverse; }\n }\n\n\n public ICollection<TKey> Keys {\n get { return keysToValues.Keys; }\n }\n\n public ICollection<TValue> Values {\n get { return keysToValues.Values; }\n }\n\n public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator ()\n {\n return keysToValues.GetEnumerator ();\n }\n\n IEnumerator IEnumerable.GetEnumerator ()\n {\n return GetEnumerator ();\n }\n\n void ICollection<KeyValuePair<TKey, TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex)\n {\n ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).CopyTo (array, arrayIndex);\n }\n\n\n public bool ContainsKey (TKey key)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n return keysToValues.ContainsKey (key);\n }\n\n public bool ContainsValue (TValue value)\n {\n if (value == null)\n throw new ArgumentNullException (\"value\");\n return valuesToKeys.ContainsKey (value);\n }\n\n bool ICollection<KeyValuePair<TKey, TValue>>.Contains (KeyValuePair<TKey, TValue> item)\n {\n return ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).Contains (item);\n }\n\n public bool TryGetKey (TValue value, out TKey key)\n {\n if (value == null)\n throw new ArgumentNullException (\"value\");\n return valuesToKeys.TryGetValue (value, out key);\n }\n\n public bool TryGetValue (TKey key, out TValue value)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n return keysToValues.TryGetValue (key, out value);\n }\n\n public TValue this[TKey key] {\n get { return keysToValues [key]; }\n set {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n if (value == null)\n throw new ArgumentNullException (\"value\");\n\n //foo[5] = \"bar\"; foo[6] = \"bar\"; should not be valid\n //as it would have to remove foo[5], which is unexpected.\n if (ValueBelongsToOtherKey (key, value))\n throw new ArgumentException (\"Value already exists\", \"value\");\n\n TValue oldValue;\n if (keysToValues.TryGetValue (key, out oldValue)) {\n // Use the current key for this value to stay consistent\n // with Dictionary<TKey, TValue> which does not alter\n // the key if it exists.\n TKey oldKey = valuesToKeys [oldValue];\n\n keysToValues [oldKey] = value;\n valuesToKeys.Remove (oldValue);\n valuesToKeys [value] = oldKey;\n } else {\n keysToValues [key] = value;\n valuesToKeys [value] = key;\n }\n }\n }\n\n public int Count {\n get { return keysToValues.Count; }\n }\n\n bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {\n get { return false; }\n }\n\n\n public void Add (TKey key, TValue value)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n if (value == null)\n throw new ArgumentNullException (\"value\");\n\n if (keysToValues.ContainsKey (key))\n throw new ArgumentException (\"Key already exists\", \"key\");\n if (valuesToKeys.ContainsKey (value))\n throw new ArgumentException (\"Value already exists\", \"value\");\n\n keysToValues.Add (key, value);\n valuesToKeys.Add (value, key);\n }\n\n public void Replace (TKey key, TValue value)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n if (value == null)\n throw new ArgumentNullException (\"value\");\n\n // replaces a key value pair, if the key or value already exists those mappings will be replaced.\n // e.g. you have; a -> b, b -> a; c -> d, d -> c\n // you add the mapping; a -> d, d -> a\n // this will remove both of the original mappings\n Remove (key);\n inverse.Remove (value);\n Add (key, value);\n }\n\n void ICollection<KeyValuePair<TKey, TValue>>.Add (KeyValuePair<TKey, TValue> item)\n {\n Add (item.Key, item.Value);\n }\n\n public bool Remove (TKey key)\n {\n if (key == null)\n throw new ArgumentNullException (\"key\");\n\n TValue value;\n if (keysToValues.TryGetValue (key, out value)) {\n keysToValues.Remove (key);\n valuesToKeys.Remove (value);\n return true;\n }\n else {\n return false;\n }\n }\n\n bool ICollection<KeyValuePair<TKey, TValue>>.Remove (KeyValuePair<TKey, TValue> item)\n {\n bool removed = ((ICollection<KeyValuePair<TKey, TValue>>) keysToValues).Remove (item);\n if (removed)\n valuesToKeys.Remove (item.Value);\n return removed;\n }\n\n public void Clear ()\n {\n keysToValues.Clear ();\n valuesToKeys.Clear ();\n }\n\n\n private bool ValueBelongsToOtherKey (TKey key, TValue value)\n {\n TKey otherKey;\n if (valuesToKeys.TryGetValue (value, out otherKey))\n // if the keys are not equal the value belongs to another key\n return !keyComparer.Equals (key, otherKey);\n else\n // value doesn't exist in map, thus it cannot belong to another key\n return false;\n }\n }\n}\n"
},
{
"answer_id": 35949314,
"author": "Lukas Z.",
"author_id": 2855278,
"author_profile": "https://Stackoverflow.com/users/2855278",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// This is a dictionary guaranteed to have only one of each value and key. \n/// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.\n/// It implements garbage-collector-friendly IEnumerable.\n/// </summary>\n/// <typeparam name=\"TFirst\">The type of the \"key\"</typeparam>\n/// <typeparam name=\"TSecond\">The type of the \"value\"</typeparam>\npublic class BiDictionary<TFirst, TSecond> : IEnumerable<BiDictionary<TFirst, TSecond>.Pair>\n{\n\n\n public struct Pair\n {\n public TFirst First;\n public TSecond Second;\n }\n\n\n public struct Enumerator : IEnumerator<Pair>, IEnumerator\n {\n\n public Enumerator(Dictionary<TFirst, TSecond>.Enumerator dictEnumerator)\n {\n _dictEnumerator = dictEnumerator;\n }\n\n public Pair Current\n {\n get\n {\n Pair pair;\n pair.First = _dictEnumerator.Current.Key;\n pair.Second = _dictEnumerator.Current.Value;\n return pair;\n }\n }\n\n object IEnumerator.Current\n {\n get\n {\n return Current;\n }\n }\n\n public void Dispose()\n {\n _dictEnumerator.Dispose();\n }\n\n public bool MoveNext()\n {\n return _dictEnumerator.MoveNext();\n }\n\n public void Reset()\n {\n throw new NotSupportedException();\n }\n\n private Dictionary<TFirst, TSecond>.Enumerator _dictEnumerator;\n\n }\n\n #region Exception throwing methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Throws an exception if either element is already in the dictionary\n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n public void Add(TFirst first, TSecond second)\n {\n if (_firstToSecond.ContainsKey(first) || _secondToFirst.ContainsKey(second))\n throw new ArgumentException(\"Duplicate first or second\");\n\n _firstToSecond.Add(first, second);\n _secondToFirst.Add(second, first);\n }\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first\n /// Throws an exception if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <returns>the value corresponding to first</returns>\n public TSecond GetByFirst(TFirst first)\n {\n TSecond second;\n if (!_firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n return second;\n }\n\n /// <summary>\n /// Find the TFirst corresponing to the Second second.\n /// Throws an exception if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <returns>the value corresponding to second</returns>\n public TFirst GetBySecond(TSecond second)\n {\n TFirst first;\n if (!_secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n return first;\n }\n\n\n /// <summary>\n /// Remove the record containing first.\n /// If first is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"first\">the key of the record to delete</param>\n public void RemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!_firstToSecond.TryGetValue(first, out second))\n throw new ArgumentException(\"first\");\n\n _firstToSecond.Remove(first);\n _secondToFirst.Remove(second);\n }\n\n /// <summary>\n /// Remove the record containing second.\n /// If second is not in the dictionary, throws an Exception.\n /// </summary>\n /// <param name=\"second\">the key of the record to delete</param>\n public void RemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!_secondToFirst.TryGetValue(second, out first))\n throw new ArgumentException(\"second\");\n\n _secondToFirst.Remove(second);\n _firstToSecond.Remove(first);\n }\n\n #endregion\n\n #region Try methods\n\n /// <summary>\n /// Tries to add the pair to the dictionary.\n /// Returns false if either element is already in the dictionary \n /// </summary>\n /// <param name=\"first\"></param>\n /// <param name=\"second\"></param>\n /// <returns>true if successfully added, false if either element are already in the dictionary</returns>\n public bool TryAdd(TFirst first, TSecond second)\n {\n if (_firstToSecond.ContainsKey(first) || _secondToFirst.ContainsKey(second))\n return false;\n\n _firstToSecond.Add(first, second);\n _secondToFirst.Add(second, first);\n return true;\n }\n\n\n /// <summary>\n /// Find the TSecond corresponding to the TFirst first.\n /// Returns false if first is not in the dictionary.\n /// </summary>\n /// <param name=\"first\">the key to search for</param>\n /// <param name=\"second\">the corresponding value</param>\n /// <returns>true if first is in the dictionary, false otherwise</returns>\n public bool TryGetByFirst(TFirst first, out TSecond second)\n {\n return _firstToSecond.TryGetValue(first, out second);\n }\n\n /// <summary>\n /// Find the TFirst corresponding to the TSecond second.\n /// Returns false if second is not in the dictionary.\n /// </summary>\n /// <param name=\"second\">the key to search for</param>\n /// <param name=\"first\">the corresponding value</param>\n /// <returns>true if second is in the dictionary, false otherwise</returns>\n public bool TryGetBySecond(TSecond second, out TFirst first)\n {\n return _secondToFirst.TryGetValue(second, out first);\n }\n\n /// <summary>\n /// Remove the record containing first, if there is one.\n /// </summary>\n /// <param name=\"first\"></param>\n /// <returns> If first is not in the dictionary, returns false, otherwise true</returns>\n public bool TryRemoveByFirst(TFirst first)\n {\n TSecond second;\n if (!_firstToSecond.TryGetValue(first, out second))\n return false;\n\n _firstToSecond.Remove(first);\n _secondToFirst.Remove(second);\n return true;\n }\n\n /// <summary>\n /// Remove the record containing second, if there is one.\n /// </summary>\n /// <param name=\"second\"></param>\n /// <returns> If second is not in the dictionary, returns false, otherwise true</returns>\n public bool TryRemoveBySecond(TSecond second)\n {\n TFirst first;\n if (!_secondToFirst.TryGetValue(second, out first))\n return false;\n\n _secondToFirst.Remove(second);\n _firstToSecond.Remove(first);\n return true;\n }\n\n #endregion \n\n /// <summary>\n /// The number of pairs stored in the dictionary\n /// </summary>\n public Int32 Count\n {\n get { return _firstToSecond.Count; }\n }\n\n /// <summary>\n /// Removes all items from the dictionary.\n /// </summary>\n public void Clear()\n {\n _firstToSecond.Clear();\n _secondToFirst.Clear();\n }\n\n\n public Enumerator GetEnumerator()\n {\n //enumerator.Reset(firstToSecond.GetEnumerator());\n return new Enumerator(_firstToSecond.GetEnumerator());\n }\n\n IEnumerator<Pair> IEnumerable<Pair>.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n\n\n private Dictionary<TFirst, TSecond> _firstToSecond = new Dictionary<TFirst, TSecond>();\n private Dictionary<TSecond, TFirst> _secondToFirst = new Dictionary<TSecond, TFirst>();\n\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
] |
268,322
|
<p>Why doesn't this work?</p>
<pre><code>DECLARE @temp table
(ShipNo int,
Supplier varchar(10)
)
INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')
Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp
</code></pre>
<p>But if you cast the ShipNo to a varchar in the Case statement it DOES work?</p>
|
[
{
"answer_id": 268367,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 1,
"selected": false,
"text": "CASE\nWHEN Boolean_expression THEN result_expression \n [ ...n ] \n[ \n ELSE else_result_expression \n] \nEND\n"
},
{
"answer_id": 2745328,
"author": "Tins",
"author_id": 329833,
"author_profile": "https://Stackoverflow.com/users/329833",
"pm_score": 3,
"selected": true,
"text": "SELECT ROW_NUMBER() OVER (ORDER BY \nCASE @OrderBy \n WHEN 'Supplier' THEN Supplier\nEND\nCASE @OrderBy\n WHEN 'ShipNo' THEN ShipNo \nEND \n)\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
268,338
|
<p>Im trying to craft a regex that only returns <code><link></code> tag hrefs</p>
<p>Why does this regex return all hrefs including <a hrefs?</p>
<pre><code>(?&lt;=&lt;link\s+.*?)href\s*=\s*[\'\"][^\'\"]+
</code></pre>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" rev="stylesheet" href="idlecore-tidied.css?T_2_5_0_228" media="screen">
<a href="anotherurl">Slash Boxes&lt;/a>
</code></pre>
|
[
{
"answer_id": 268354,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "/(?<=<link\\s+.*?)href\\s*=\\s*[\\'\\\"][^\\'\\\"]+[^>]*>/\n /(<link\\s+.*?)href\\s*=\\s*[\\'\\\"][^\\'\\\"]+[^>]*>/\n"
},
{
"answer_id": 268371,
"author": "Tim Pietzcker",
"author_id": 20670,
"author_profile": "https://Stackoverflow.com/users/20670",
"pm_score": 0,
"selected": false,
"text": "(?<=<link\\b[^<>]*?)href\\s*=\\s*(['\"])(?:(?!\\1).)+\\1\n (?:<link\\b[^<>]*?)(href\\s*=\\s*(['\"])(?:(?!\\2).)+\\2)\n"
},
{
"answer_id": 268373,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 0,
"selected": false,
"text": "(?<=<link\\s+.*?)href\\s*=\\s*[\\'\\\"][^\\'\\\"]+\n ' \" (?<=<link\\s+.*?)href\\s*=\\s*([\\'\\\"])[^\\'\\\"]+(\\1)\n (?:<link\\s+.*?)(href\\s*=\\s*([\\'\\\"])[^\\'\\\"]+(\\2))\n"
},
{
"answer_id": 268405,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": true,
"text": "/(?<=<link\\b[^<>]*?)\\bhref=\\s*=\\s*(?:\"[^\"]*\"|'[^']'|\\S+)/\n /<link\\b[^<>]*?\\b(href=\\s*=\\s*(?:\"[^\"]*\"|'[^']'|\\S+))/\n [^<>]*? .*?"
},
{
"answer_id": 268546,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<link\\s+[^>]*(href\\s*=\\s*(['\"]).*?\\2)"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
268,357
|
<p>I have a couple of dropdown boxes on a normal ASP.Net page.</p>
<p>I would like the user to be able to change these and to have the page Pseudo-post back to the server and store these changes without the user having to hit a save button.</p>
<p>I don't really need to display anything additional as the dropdown itself will reflect the new value, but I would like to post this change back without having the entire page flash due to postback </p>
<p>I have heard that this is possible using AJAX.Net... </p>
<p>Can someone point me in the right direction?</p>
|
[
{
"answer_id": 268673,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 3,
"selected": true,
"text": "<asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\" />\n<asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\">\n <ContentTemplate>\n\n<asp:DropDownList ID=\"DropDownList1\" runat=\"server\" AutoPostBack=\"true\" OnSelectedIndexChanged=\"yourDDL_SelectedIndexChanged\">\n</asp:DropDownList>\n\n </ContentTemplate>\n</asp:UpdatePanel>\n\nprotected void yourDDL_SelectedIndexChanged(object sender, EventArgs e)\n{\n// do whatever you want\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
268,381
|
<p>I am trying to make a copy of a database to a new database on the same server. The server is my local computer running SQL 2008 Express under Windows XP.
Doing this should be quite easy using the SMO.Transfer class and it almost works!</p>
<p>My code is as follows (somewhat simplified):</p>
<pre><code>Server server = new Server("server");
Database sourceDatabase = server.Databases["source database"];
Database newDatbase = new Database(server, "new name");
newDatbase.Create();
Transfer transfer = new Transfer(sourceDatabase);
transfer.CopyAllObjects = true;
transfer.Options.WithDependencies = true;
transfer.DestinationDatabase = newDatbase.Name;
transfer.CopySchema = true;
transfer.CopyData = true;
StringCollection transferScript = transfer.ScriptTransfer();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand switchDatabase = new SqlCommand("USE " + newDatbase.Name, conn))
{
switchDatabase.ExecuteNonQuery();
}
foreach (string scriptLine in transferScript)
{
using (SqlCommand scriptCmd = new SqlCommand(scriptLine, conn, transaction))
{
int res = scriptCmd.ExecuteNonQuery();
}
}
}
</code></pre>
<p>What I do here is to first create a new database, then generate a copy script using the <code>Transfer</code> class and finally running the script in the new database. </p>
<p>This works fine for copying the structure, but the <code>CopyData</code> option doesn't work!</p>
<p>Are there any undocumented limits to the <code>CopyData</code> option? The documentation only says that the option specifies whether data is copied. </p>
<p>I tried using the <code>TransferData()</code> method to copy the databse without using a script but then I get an exception that says "Failed to connect to server" with an inner exception that says "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"</p>
<p>I also tried to enable Named Pipes on the server, but that doesn't help. </p>
<p>Edit:
I found a solution that works by making a backup and then restoring it to a new database. It's quite clumsy though, and slower than it should be, so I'm still looking for a better solution.</p>
|
[
{
"answer_id": 320877,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 5,
"selected": true,
"text": "ServerConnection conn = new ServerConnection(\"rune\\\\sql2008\");\nServer server = new Server(conn);\n\nDatabase newdb = new Database(server, \"new database\");\nnewdb.Create();\n\nTransfer transfer = new Transfer(server.Databases[\"source database\"]);\ntransfer.CopyAllObjects = true;\ntransfer.CopyAllUsers = true;\ntransfer.Options.WithDependencies = true;\ntransfer.DestinationDatabase = newdb.Name;\ntransfer.DestinationServer = server.Name;\ntransfer.DestinationLoginSecure = true;\ntransfer.CopySchema = true;\ntransfer.CopyData = true;\ntransfer.Options.ContinueScriptingOnError = true;\ntransfer.TransferData();\n"
},
{
"answer_id": 7807931,
"author": "emy",
"author_id": 1001194,
"author_profile": "https://Stackoverflow.com/users/1001194",
"pm_score": 2,
"selected": false,
"text": " public bool CreateScript(string oldDatabase, string newDatabase)\n {\n SqlConnection conn = new SqlConnection(\"Data Source=.;Initial Catalog=\" + newDatabase + \";User Id=sa;Password=sa;\");\n try\n {\n Server sv = new Server();\n Database db = sv.Databases[oldDatabase];\n\n Database newDatbase = new Database(sv, newDatabase);\n newDatbase.Create(); \n\n ScriptingOptions options = new ScriptingOptions();\n StringBuilder sb = new StringBuilder();\n options.ScriptData = true;\n options.ScriptDrops = false;\n options.ScriptSchema = true;\n options.EnforceScriptingOptions = true;\n options.Indexes = true;\n options.IncludeHeaders = true;\n options.WithDependencies = true;\n\n TableCollection tables = db.Tables;\n\n conn.Open();\n foreach (Table mytable in tables)\n {\n foreach (string line in db.Tables[mytable.Name].EnumScript(options))\n {\n sb.Append(line + \"\\r\\n\");\n }\n }\n string[] splitter = new string[] { \"\\r\\nGO\\r\\n\" };\n string[] commandTexts = sb.ToString().Split(splitter, StringSplitOptions.RemoveEmptyEntries);\n foreach (string command in commandTexts)\n {\n SqlCommand comm = new SqlCommand(command, conn);\n comm.ExecuteNonQuery();\n }\n return true;\n }\n catch (Exception e)\n {\n System.Diagnostics.Debug.WriteLine(\"PROGRAM FAILED: \" + e.Message);\n return false;\n }\n finally\n {\n conn.Close();\n }\n }\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30366/"
] |
268,384
|
<p>Why does the PRINT statement in T-SQL seem to only sometimes work? What are the constraints on using it? It seems sometimes if a result set is generated, it becomes a null function, I assumed to prevent corrupting the resultset, but could it's output not go out in another result set, such as the row count?</p>
|
[
{
"answer_id": 2928995,
"author": "JimCarden",
"author_id": 352896,
"author_profile": "https://Stackoverflow.com/users/352896",
"pm_score": 5,
"selected": false,
"text": "RAISERROR ('Your message', 0, 1) WITH NOWAIT\n"
},
{
"answer_id": 11162818,
"author": "WEFX",
"author_id": 590719,
"author_profile": "https://Stackoverflow.com/users/590719",
"pm_score": 5,
"selected": false,
"text": "declare @myID int=null\nprint 'First Statement: ' + convert(varchar(4), @myID)\n declare @myID int=null\nprint 'Second Statement: ' + coalesce(Convert(varchar(4), @myID),'@myID is null')\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
268,391
|
<p>I want to use Visual Studio snippets to generate SQL code, for example we have standard naming conventions for foreign keys etc and it would be great if I could just expand a snippet in my SQL script file. </p>
<p>However as far as I can tell the only languages that are supported by the Snippet manager are C#, VB J# and XML</p>
<p><a href="http://msdn.microsoft.com/en-gb/library/ms171421(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-gb/library/ms171421(VS.80).aspx</a></p>
<p>Does anyone know of a way to have a snippet expand to SQL?</p>
<p>Derek</p>
|
[
{
"answer_id": 2928995,
"author": "JimCarden",
"author_id": 352896,
"author_profile": "https://Stackoverflow.com/users/352896",
"pm_score": 5,
"selected": false,
"text": "RAISERROR ('Your message', 0, 1) WITH NOWAIT\n"
},
{
"answer_id": 11162818,
"author": "WEFX",
"author_id": 590719,
"author_profile": "https://Stackoverflow.com/users/590719",
"pm_score": 5,
"selected": false,
"text": "declare @myID int=null\nprint 'First Statement: ' + convert(varchar(4), @myID)\n declare @myID int=null\nprint 'Second Statement: ' + coalesce(Convert(varchar(4), @myID),'@myID is null')\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28584/"
] |
268,418
|
<p>I generate a XMLDocument based on a dataset by binding the dataset to the XMLDocument object and then display it to user in vb.net. I have a requirement in which certain tags to contain cdata sections rather than text value. After generating the XMLDocument how to change only certain tag to cdata section and keeping all else as it is? Or is there a way to modify while binding itself?</p>
|
[
{
"answer_id": 268489,
"author": "lakshminb7",
"author_id": 3113,
"author_profile": "https://Stackoverflow.com/users/3113",
"pm_score": 0,
"selected": false,
"text": "\"<tag><![CDATA[Sample HTML tag <head> ]]> </tag>\"\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3113/"
] |
268,421
|
<p>Heres a tricky one . .</p>
<p>I have a webpage (called PageA) that has a header and then simply includes an iframe. Lets call the page within the iframe PageB. PageB simply has a bunch of thumbnails but there are a lot so you have to scroll down on PageA to view them all. </p>
<p>When i scroll down to the bottom of the pageB and click on a thumbnail it looks like it takes me to a blank page. What actually happens is that it bring up the image but since the page that is just the image is much shorter in height, the scroll bar stays at the same location and doesn't adjust for it. I have to scroll up to the top of the page to view the picture.</p>
<p>Is there anyway when i click a link on a page that is within an iframe, the outer pages scroll bar goes back up to the top</p>
<p>thks,
ak</p>
|
[
{
"answer_id": 624093,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 4,
"selected": true,
"text": "<script type=\"text/javascript\">\n function gotop() {\n scroll(0,0);\n } \n</script>\n <iframe id=\"myframe\" \n onload=\"try { gotop() } catch (e) {}\" \n src=\"http://yourframesource\"\n width=\"100%\" height=\"999\"\n scrolling=\"auto\" marginwidth=\"0\" marginheight=\"0\" \n frameborder=\"0\" vspace=\"0\" hspace=\"0\" >\n</iframe>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
268,425
|
<p>In our code base we have a dependency on the ant version used in eclipse.</p>
<p>In the the ant.jar has been set up as a library which the project uses</p>
<p>This is a pain when moving versions of eclipse as the Ant plugin folder name changes (although I see it is now just called Ant1.7)</p>
<p>Is there a way to access eclipses reference to ANT Home which appears in the workspace preferences so that I don't have to explicitly set a variable that has the hard coded path to the ant plugins folder</p>
|
[
{
"answer_id": 322434,
"author": "clayless",
"author_id": 37989,
"author_profile": "https://Stackoverflow.com/users/37989",
"pm_score": 0,
"selected": false,
"text": "<echo> ${ant.home} </echo>\n [echo] D:\\java\\eclipse_3.4_jee\\plugins\\org.apache.ant_1.7.0.v200803061910 \n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15352/"
] |
268,426
|
<p>We're using Microsoft.Practices.CompositeUI.EventBroker to handle event subscription and publication in our application. The way that works is that you add an attribute to your event, specifying a topic name, like this:</p>
<pre><code>[EventPublication("example", PublicationScope.Global)]
public event EventHandler Example;
</code></pre>
<p>then you add another attribute to your handler, with the same topic name, like this:</p>
<pre><code>[EventSubscription("example", ThreadOption.Publisher)]
public void OnExample(object sender, EventArgs e)
{
...
}
</code></pre>
<p>Then you pass your objects to an EventInspector which matches everything up.</p>
<p>We need to debug this, so we're trying to create a debug class that subscribes to <em>all</em> the events. I can get a list of all the topic names... but only at runtime. So I need to be able to add attributes to a method at runtime, before we pass our debug object to the EventInspector.</p>
<p>How do I add attributes to a method at runtime?</p>
|
[
{
"answer_id": 268486,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "DynamicMethod"
},
{
"answer_id": 268576,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 5,
"selected": true,
"text": "AbstractEventDebugger Search event IdentifyEvent dynamic type TypeBuilder debugger Reflection.Emit.MethodBuilder IdentifyEvent Reflection.Emit CustomAttributeBuilder dynamic :)"
},
{
"answer_id": 268733,
"author": "Mike Minutillo",
"author_id": 358,
"author_profile": "https://Stackoverflow.com/users/358",
"pm_score": 1,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.diagnostics>\n <switches>\n <add name=\"Microsoft.Practices.CompositeUI.EventBroker.EventTopic\" value=\"All\" />\n </switches>\n </system.diagnostics>\n</configuration>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
268,429
|
<p>How to 'group by' a query using an alias, for example:</p>
<pre><code>select count(*), (select * from....) as alias_column
from table
group by alias_column
</code></pre>
<p>I get 'alias_column' : INVALID_IDENTIFIER error message. Why? How to group this query?</p>
|
[
{
"answer_id": 268447,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": true,
"text": "select\n count(count_col),\n alias_column\nfrom\n (\n select \n count_col, \n (select value from....) as alias_column \n from \n table\n ) as inline\ngroup by \n alias_column\n"
},
{
"answer_id": 268474,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 3,
"selected": false,
"text": "select count(*), alias_column\nfrom\n( select empno, (select deptno from emp where emp.empno = e.empno) as alias_column\n from emp e\n)\ngroup by alias_column;\n"
},
{
"answer_id": 268494,
"author": "ian_scho",
"author_id": 15530,
"author_profile": "https://Stackoverflow.com/users/15530",
"pm_score": 2,
"selected": false,
"text": "select count(*), (select * from....) as alias_column \nfrom table \ngroup by (select * from....)\n"
},
{
"answer_id": 5720745,
"author": "Andrew",
"author_id": 561698,
"author_profile": "https://Stackoverflow.com/users/561698",
"pm_score": 2,
"selected": false,
"text": "select count(*), (select * from....) as alias_column \nfrom table \ngroup by (select * from....)\n select count, alias_column \nfrom\n (select count(*) as count, (select * from....) as alias_column \n from table)\ngroup by alias_column \n"
},
{
"answer_id": 50260305,
"author": "augre",
"author_id": 4192212,
"author_profile": "https://Stackoverflow.com/users/4192212",
"pm_score": -1,
"selected": false,
"text": "select \nEXTRACT(year from CURRENT_DATE), count(*) from something\ngroup by EXTRACT(year from CURRENT_DATE)\norder by EXTRACT(year from CURRENT_DATE)\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3221/"
] |
268,432
|
<p>ASP.NET 3.5 SP1 adds a great new ScriptCombining feature to the ScriptManager object as demonstrated on <a href="http://www.asp.net/learn/3.5-SP1/video-296.aspx?wwwaspnetrdirset=1" rel="nofollow noreferrer">this video</a>. However he only demonstrates how to use the feature with the ScriptManager on the same page. I'd like to use this feature on a site where the scriptmanager is on the master page but can't figure out how to add the scripts I need for each page programmatically to the manager. I've found <a href="http://seejoelprogram.wordpress.com/2008/08/19/net-35-sp1-doesnt-provide-composite-script-registration-from-an-iscriptcontrol-out-of-the-box/" rel="nofollow noreferrer">this post</a> to use as a starting point, but I'm not really getting very far. can anyone give me a helping hand?</p>
<p>Thanks, Dan</p>
|
[
{
"answer_id": 269785,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 3,
"selected": true,
"text": " ScriptReference SRef = new ScriptReference();\n SRef.Path = \"~/Scripts/Script.js\";\n\n\n ScriptManager.GetCurrent(Page).CompositeScript.Scripts.Add(SRef);\n"
},
{
"answer_id": 4622604,
"author": "Chris Herring",
"author_id": 77067,
"author_profile": "https://Stackoverflow.com/users/77067",
"pm_score": 1,
"selected": false,
"text": "<asp:ScriptManager ID=\"ScriptManager\" runat=\"server\">\n <CompositeScript>\n <Scripts>\n <asp:ScriptReference name=\"WebForms.js\" assembly=\"System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n <asp:ScriptReference name=\"MicrosoftAjax.js\" assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n <asp:ScriptReference name=\"MicrosoftAjaxWebForms.js\" assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n </Scripts>\n </CompositeScript>\n</asp:ScriptManager>\n <asp:Content ID=\"HomeContent\" ContentPlaceHolderID=\"PlaceHolder\" runat=\"Server\">\n <asp:ScriptManagerProxy runat=\"server\">\n <CompositeScript>\n <Scripts>\n <asp:ScriptReference Path=\"~/yourscript.js\" />\n </Scripts>\n </CompositeScript>\n </asp:ScriptManagerProxy>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268432",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2756/"
] |
268,444
|
<p>I'm hoping that someone has found a way of doing this already or that there is a library already in existence. It's one of those things that would be nice but is in no way necessary for the time being.</p>
<p>The functionality I'm looking for is something like <a href="http://www.datejs.com/" rel="nofollow noreferrer">datejs</a> in reverse.</p>
<p>Thanks,</p>
<p>Simon.</p>
<hr>
<p>Thanks, using something like the dddd example might be a good start towards usability. The more I think about this problem the more it depends on the values being used. I'm specifically dealing with a series of timestamped versions of a document so there is a good chance that they will be clustered. Today isn't so hot if you have saved it three times in the last five minutes.</p>
<p>If I come up with something I'll share it with the community.</p>
|
[
{
"answer_id": 268529,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "DateTime.Now.ToString(\"ggyyyy$dd-MMM (dddd)\")\n DateTime.ParseExact()"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35047/"
] |
268,464
|
<pre><code><form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" >
</form>
<form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
</form>
<a onclick="test(event, '1'); " href="#" >Click Here</a>
<script>
function test(event, id){
document.getElementById("frm_"+id).submit;
document.getElementById("tgt_"+id).submit;
}
</script>
</code></pre>
<p>Is it possible to open a new tab/window and change the current page ?</p>
|
[
{
"answer_id": 268477,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<a\n href=\"http://www.google.com\"\n target=\"_blank\"\n onclick=\"document.location.href='http://www.yahoo.com'\"\n>Click here to open Google in a new window and yahoo in this window</a>\n"
},
{
"answer_id": 268502,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 0,
"selected": false,
"text": "<form id=\"frm_1\" name=\"frm_1\" target=\"_self\" method=\"GET\" action=\"local_page.php\" >\n</form>\n<a onclick=\"test(event, '1'); \" href=\"#\" >Click Here</a>\n<script>\n function test(event, id){\n window.open(\"http://stackoverflow.com/\", \"_blank\");\n document.getElementById(\"tgt_\"+id).submit();\n }\n</script>\n"
},
{
"answer_id": 268831,
"author": "John Griffiths",
"author_id": 24765,
"author_profile": "https://Stackoverflow.com/users/24765",
"pm_score": 2,
"selected": true,
"text": "<form id=\"frm_1\" name=\"frm_1\" target=\"_self\" method=\"POST\" action=\"local_page.php\" >\n<input type=\"hidden\" name=\"vital_param\" value=\"<?= $something ?>\">\n</form>\n\n<form id=\"tgt_1\" name=\"tgt_1\" target=\"_blank\" method=\"POST\" action=\"http://stackoverflow.com/\" >\n</form>\n\n<button type=\"submit\" onclick=\"test(event, '1'); \" >Click Here</button>\n\n<script>\n function test(event, id){\n window.open( document.getElementById(\"tgt_\"+id).action, \"_blank\");\n setTimeout('document.getElementById(\"frm_'+id+'\").submit();', 1000);\n\n return true;\n }\n</script>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24765/"
] |
268,468
|
<p>I noticed that the ASP.NET cache items are inspected (and possibly removed) every 20 seconds (and oddly enough each time at HH:MM:00, HH:MM:20 and HH:MM:40). I spent about 15 minutes looking how to change this parameter without any success. I also tried to set the following in web.config, but it did not help:</p>
<pre><code><cache privateBytesPollTime="00:00:05" />
</code></pre>
<p>I’m not trying to do anything crazy, but it would be nice if it was, say, 5 seconds instead of 20, or at least 10 for my application.</p>
|
[
{
"answer_id": 270374,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 5,
"selected": true,
"text": "CacheExpires _tsPerBucket = new TimeSpan(0, 0, 20);\n _tsPerBucket readonly CacheExpires.EnableExpirationTimer() DateTime utcNow = DateTime.UtcNow;\nTimeSpan span = _tsPerBucket - new TimeSpan(utcNow.Ticks % _tsPerBucket.Ticks);\nthis._timer = new Timer(new TimerCallback(this.TimerCallback), null,\n span.Ticks / 0x2710L, _tsPerBucket.Ticks / 0x2710L);\n span internal Cache.Get() null"
},
{
"answer_id": 7272610,
"author": "mipo",
"author_id": 923708,
"author_profile": "https://Stackoverflow.com/users/923708",
"pm_score": 2,
"selected": false,
"text": "// New value for cache expiration cycle\n// System.Web.Caching.CacheExpires._tsPerBucket;\n// Set 1 seconds instead of 20sec\nconst string assembly = \"System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\";\nvar type = Type.GetType(\"System.Web.Caching.CacheExpires, \" + assembly, true, true);\nvar field = type.GetField(\"_tsPerBucket\", BindingFlags.Static | BindingFlags.NonPublic);\nfield.SetValue(null, TimeSpan.FromSeconds(1));\n\n// Recreate cache\n// HttpRuntime._theRuntime._cacheInternal = null;\n// HttpRuntime._theRuntime._cachePublic = null;\ntype = typeof (HttpRuntime);\nfield = type.GetField(\"_theRuntime\", BindingFlags.Static | BindingFlags.NonPublic);\nvar runtime = field.GetValue(null);\nfield = type.GetField(\"_cachePublic\", BindingFlags.NonPublic | BindingFlags.Instance);\nfield.SetValue(runtime, null);\nfield = type.GetField(\"_cacheInternal\", BindingFlags.NonPublic | BindingFlags.Instance);\nfield.SetValue(runtime, null);\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15716/"
] |
268,475
|
<p>Within an article-oriented page (such as a blog post), the <code><h1></code> element (level 1 heading) is commonly used to markup either:</p>
<ul>
<li>the blog title (i.e. the often-large site title at the top of the page, <em>not</em> to the <code><title></code> element), or</li>
<li>the article title</li>
</ul>
<p>What is the best choice and why?</p>
<p>To the site owner, who may want to shout out to the world the name of their site/blog, using a level 1 heading around the site title might seem to make sense.</p>
<p>From the perspective of what you are trying to communicate to the user, the site title is of less relevance - the article content is what you're trying to communicate and all other site content is secondary. Therefore using <code><h1></code> for the article title seems best.</p>
<p>I feel the <code><h1></code> element should focus on the article title, not the site title or other content. This does not appear to be a popular convention by any means.</p>
<p>Examples:</p>
<ul>
<li><a href="http://joelonsoftware.com/" rel="noreferrer">Joel Spolsky</a> uses <code><h1></code> for the article title, and an anchor for the site title</li>
<li><a href="http://codinghorror.com/" rel="noreferrer">Jeff Atwood</a> uses <em>no <code><h1></code> at all</em>, <code><h2></code> for the article title and an anchor for the site title</li>
<li><a href="http://37signals.com/svn/" rel="noreferrer">37 Signals' SVN</a> uses <code><h1></code> for the site title and an anchor for the article title</li>
</ul>
<p>That's three different approaches across three sites where you might expect a strong consideration for correct semantic markup.</p>
<p>I think Joel has it right with Jeff a close second. I'm quite surprised at the markup choices by the 37Signals people.</p>
<p>To me it seems quite a simple decision: what is of greatest relevance to the consumer of the article? The article title. Therefore wrap the article title in an <code><h1></code> element. Done.</p>
<p>Am I wrong? Are there further considerations I'm missing? Am I right? If so, why is the '<code><h1></code> for article title' approach not more commonly used?</p>
<p>Is the decision of where to use the <code><h1></code> element as invariable as I put it? Or are there some subjective considerations to be made as well?</p>
<p><strong>Update</strong>: Thanks for all the answers so far. I'd really appreciate some angle on how the use of the <code><h1></code> for the article title instead of site title benefits usability and accessibility (or doesn't, as the case may or may not be). Answers based on fact instead of just personal supposition will get many bonus points!</p>
|
[
{
"answer_id": 268506,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 6,
"selected": true,
"text": "<h1> <h1>Dogs</h1>"
},
{
"answer_id": 268519,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 2,
"selected": false,
"text": "<head> <title> <div> <span> <h2>Sub Header</h2>\n <div class=\"header2>Sub Header</div>\n <div> <div> <h2> <title> <h1> <html>\n<head>\n<title>SOME TITLE</title>\n</head>\n:\n<body>\n<div id=\"title\">SOME TITLE</div>\n:\n</body>\n</html>\n #title"
},
{
"answer_id": 17246352,
"author": "unor",
"author_id": 1591669,
"author_profile": "https://Stackoverflow.com/users/1591669",
"pm_score": 1,
"selected": false,
"text": "h1 <ul id=\"site-navigation\">\n <li><a href=\"/\">Home</a></li>\n <li><a href=\"/about\">About me</a></li>\n <li><a href=\"/contact\">Contact</a></li>\n</ul>\n #site-navigation h1 <body>\n <div>John’s blog</div> <!-- the site title -->\n <h1>My first blog post</h1> <!-- the article title -->\n <p>…</p>\n <h2>Navigation</h2>\n <ul id=\"site-navigation\">…</ul> <!-- the site-wide navigation -->\n</body>\n h2 h1 <body>\n <div>John’s blog</div> <!-- the site title -->\n <h1>My first blog post</h1> <!-- the article title -->\n <p>…</p>\n <h2>Why I’m blogging</h2>\n <p>…</p>\n <h2>Why you should read my blog</h2>\n <p>…</p>\n <h2>Navigation</h2>\n <ul id=\"site-navigation\">…</ul> <!-- the site-wide navigation -->\n</body>\n h1 h2 h2 <body>\n <h1>John’s blog</h1> <!-- the site title -->\n <h2>My first blog post</h2> <!-- the article title -->\n <p>…</p>\n <h2>Navigation</h2>\n <ul id=\"site-navigation\">…</ul> <!-- the site-wide navigation -->\n</body>\n h1 h2 h2 h3 h1 section article nav aside h1 body"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5343/"
] |
268,476
|
<p>Take a very simple case as an example, say I have this URL:</p>
<pre><code>http://www.example.com/65167.html
</code></pre>
<p>and I wish to serve that content under:</p>
<pre><code>http://www.example.com/about
</code></pre>
<p><strong>UPDATE</strong>: Note that the 'bad' URL is the canonical one (it's produced by a CMS which uses it internally for linking), so <code>"/about"</code> is just a way of polishing it.</p>
<p>I have two broad options: a server-side redirect or a client-side one. I always thought that server-side would be preferable since it's more efficient, i.e. HTTP traffic is approximately halved. However, SEO techniques tend to favour a single URL for a resource, thus client-side is to be preferred.</p>
<p>How do you resolve this conflict, and are there other factors I've omitted?</p>
|
[
{
"answer_id": 268487,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 3,
"selected": true,
"text": "RewriteEngine on\nRewriteRule ^/about$ /65167.html [L]\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] |
268,483
|
<p>I'm currently in the process of writing a wizard and want to make each page validate before moving onto the next page.</p>
<p>I want to prevent the user from progressing by calling the Validate() method on every child control on the page and and stopping navigation if any of them fail.</p>
<p>The problem is that the Validate() method on every child control is a private method so I can't access it directly. Can anyone give me some advice on how to get a result from the Validate() method on a TextBox (For example) using Reflection?</p>
<p>Many thanks!</p>
<p><strong>Edit: Sorry - should have specified, this is Windows Forms, .Net 2.0</strong></p>
|
[
{
"answer_id": 268514,
"author": "Jamey McElveen",
"author_id": 30099,
"author_profile": "https://Stackoverflow.com/users/30099",
"pm_score": 1,
"selected": false,
"text": "this.Validate(\"GroupName\") Validate()"
},
{
"answer_id": 2136871,
"author": "Eric Smith",
"author_id": 86356,
"author_profile": "https://Stackoverflow.com/users/86356",
"pm_score": 2,
"selected": false,
"text": "private void ValidateControl(Control control)\n{\n Type type = control.GetType();\n type.InvokeMember(\"PerformControlValidation\", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, control, new object[] { true });\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4019/"
] |
268,490
|
<p>I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.</p>
<pre><code>var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;
var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);
</code></pre>
<p>I would like to know if there is a better way to do this using jQuery. I've been experimenting with:</p>
<pre><code>var odv = $.create("div");
$.append(odv);
// And many more
</code></pre>
<p>But I'm not sure if this is any better.</p>
|
[
{
"answer_id": 268507,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 7,
"selected": false,
"text": "$() append() var t = $(\"<table cellspacing='0' class='text'></table>\");\n$.append(t);\n createElement cellSpacing className"
},
{
"answer_id": 268520,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 11,
"selected": true,
"text": "this.$OuterDiv = $('<div></div>')\n .hide()\n .append($('<table></table>')\n .attr({ cellSpacing : 0 })\n .addClass(\"text\")\n )\n;\n $(\"<div>\") $(\"<div></div>\") $(document.createElement('div')) Chrome 11 Firefox 4 IE9\n<div> 440ms 640ms 460ms\n<div></div> 420ms 650ms 480ms\ncreateElement 100ms 180ms 300ms\n Chrome 11\n<div> 770ms\n<div></div> 3800ms\ncreateElement 100ms\n Chrome 11\n<div> 3500ms\n<div></div> 3500ms\ncreateElement 100ms\n document.createElement JSBen.ch"
},
{
"answer_id": 2906828,
"author": "Randy",
"author_id": 338457,
"author_profile": "https://Stackoverflow.com/users/338457",
"pm_score": 2,
"selected": false,
"text": "var $example = $( XMLDocRoot );\n var $element = $( $example[0].createElement('tag') );\n// Note the [0], which is the root\n\n$element.attr({\nid: '1',\nhello: 'world'\n});\n var $example.find('parent > child').append( $element );\n"
},
{
"answer_id": 3253261,
"author": "abernier",
"author_id": 133327,
"author_profile": "https://Stackoverflow.com/users/133327",
"pm_score": 6,
"selected": false,
"text": "jQuery()"
},
{
"answer_id": 4207056,
"author": "Shimon Doodkin",
"author_id": 466363,
"author_profile": "https://Stackoverflow.com/users/466363",
"pm_score": 4,
"selected": false,
"text": "var mydiv = $('<div />') // also works\n"
},
{
"answer_id": 4514397,
"author": "AcidicChip",
"author_id": 551783,
"author_profile": "https://Stackoverflow.com/users/551783",
"pm_score": 3,
"selected": false,
"text": "var div = $('<div/>');\ndiv.append('Hello World!');\n"
},
{
"answer_id": 13544029,
"author": "kami",
"author_id": 163456,
"author_profile": "https://Stackoverflow.com/users/163456",
"pm_score": 6,
"selected": false,
"text": "$('<div/>',{\n text: 'Div text',\n class: 'className'\n}).appendTo('#parentDiv');\n"
},
{
"answer_id": 14493220,
"author": "Brian",
"author_id": 938380,
"author_profile": "https://Stackoverflow.com/users/938380",
"pm_score": 6,
"selected": false,
"text": "jQuery1.8 $.parseHTML() $(string) $.parseHTML() var userInput = window.prompt(\"please enter selector\");\n $(userInput).hide();\n <script src=\"xss-attach.js\"></script> $.parseHTML() var a = $('<div>')\n// a is [<div></div>]\nvar b = $.parseHTML('<div>')\n// b is [<div></div>]\n$('<script src=\"xss-attach.js\"></script>')\n// jQuery returns [<script src=\"xss-attach.js\"></script>]\n$.parseHTML('<script src=\"xss-attach.js\"></script>')\n// jQuery returns []\n a b a.html('123')\n// [<div>123</div>]\nb.html('123')\n// TypeError: Object [object HTMLDivElement] has no method 'html'\n$(b).html('123')\n// [<div>123</div>]\n"
},
{
"answer_id": 17161445,
"author": "Om Shankar",
"author_id": 1249219,
"author_profile": "https://Stackoverflow.com/users/1249219",
"pm_score": 5,
"selected": false,
"text": "document.createElement('div') jQuery $(document.createElement('div'), {\n text: 'Div text',\n 'class': 'className'\n}).appendTo('#parentDiv');\n"
},
{
"answer_id": 18255277,
"author": "ern0",
"author_id": 185881,
"author_profile": "https://Stackoverflow.com/users/185881",
"pm_score": 3,
"selected": false,
"text": "var myDiv = $.create(\"div\");\n var secondItem = $.create(\"div\",\"item2\");\n $(\"#container\").append( $.create(\"div\").addClass(\"box\").html(\"Hello, world!\") );\n"
},
{
"answer_id": 19082040,
"author": "Adam Zielinski",
"author_id": 1510277,
"author_profile": "https://Stackoverflow.com/users/1510277",
"pm_score": 5,
"selected": false,
"text": "$('(html code goes here)') this.$OuterDiv = $($.parseHTML('<div></div>'))\n .hide()\n .append($($.parseHTML('<table></table>'))\n .attr({ cellSpacing : 0 })\n .addClass(\"text\")\n )\n;\n $() onclick > $.parseHTML('<div onclick=\"a\"></div><script></script>')\n[<div onclick=\"a\"></div>]\n\n> $.parseHTML('<div onclick=\"a\"></div><script></script>', document, true)\n[<div onclick=\"a\"></div>, <script></script>]\n parseHTML createElement $()"
},
{
"answer_id": 56297382,
"author": "Vladislav Ladicky",
"author_id": 9805590,
"author_profile": "https://Stackoverflow.com/users/9805590",
"pm_score": 2,
"selected": false,
"text": "const mountpoint = 'https://jsonplaceholder.typicode.com/users'\n\nconst $button = $('button')\nconst $tbody = $('tbody')\n\nconst loadAndRender = () => {\n $.getJSON(mountpoint).then(data => {\n\n $.each(data, (index, { id, username, name, email }) => {\n let row = $('<tr>')\n .append($('<td>', { text: id }))\n .append($('<td>', {\n text: username,\n class: 'click-me',\n on: {\n click: _ => {\n console.log(name)\n }\n }\n }))\n .append($('<td>', { text: email }))\n\n $tbody.append(row)\n })\n\n })\n}\n\n$button.on('click', loadAndRender) .click-me {\n background-color: lightgrey\n} <table style=\"width: 100%\">\n <thead>\n <tr>\n <th>ID</th>\n <th>Username</th>\n <th>Email</th>\n </tr>\n </thead>\n <tbody>\n \n </tbody>\n</table>\n\n<button>Load and render</button>\n\n<script src=\"https://code.jquery.com/jquery-3.3.1.min.js\"></script>"
},
{
"answer_id": 64067381,
"author": "João Pimentel Ferreira",
"author_id": 1243247,
"author_profile": "https://Stackoverflow.com/users/1243247",
"pm_score": 2,
"selected": false,
"text": "<option> <select> $('<option/>')\n .val(optionVal)\n .text('some option')\n .appendTo('#mySelect')\n $('<div/>')\n .css('border-color', red)\n .text('some text')\n .appendTo('#parentDiv')\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950/"
] |
268,496
|
<p>The default output from Drupal's Form API is:</p>
<pre><code><input id="edit-submit" class="form-submit" type="submit" value="Save" name="op"/>
</code></pre>
<p>How do I theme that so I get:</p>
<pre><code><button id="edit-submit" class="form-submit" type="submit">
<span>Save</span>
</button>
</code></pre>
<p>I need the inner span-tag so I can use the sliding doors CSS technique.</p>
<p>I guess I need to override theme_button($element) from form.inc but my attempts so far have been unsuccessful.</p>
|
[
{
"answer_id": 271635,
"author": "larssg",
"author_id": 3842,
"author_profile": "https://Stackoverflow.com/users/3842",
"pm_score": 2,
"selected": false,
"text": "function mytheme_button($element) {\n return \"<button><span></span></button>\"; # lots of code missing here for clarity\n}\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842/"
] |
268,497
|
<p>The <a href="https://stackoverflow.com/questions/19235/agile-architectures">Agile architecture question</a> makes me wonder this. </p>
<p>Does it depends of what is being build ? Do applications (I mean single
computing program here) have an architecture ? </p>
<p>UPDATE: to try to clarify the question, I'll give my opinion on the question: I defined the architecture as the cutting of the system in components, and the relationships between the components ;while the design is about the interns of the component. Is this opinion shared ? </p>
|
[
{
"answer_id": 268512,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "In my experience, about $30k. \n I would say that \"design\" is what is done to achieve an architecture\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18804/"
] |
268,499
|
<p>I can use an bitmap in a menu</p>
<pre><code>CMenu men;
CBitmap b;
b.LoadBitmap(IDB_0);
men.AppendMenu( MF_ENABLED,1,&b);
</code></pre>
<p>I can draw an icon into a DC</p>
<pre><code> CImageList IL;
IL.Create(70, 14, ILC_COLOR16 | ILC_MASK, 1, 0);
IL.Add(AfxGetApp()->LoadIcon(IDI_0));
IL.Draw ( pDC, 0, rcIcon.TopLeft(), ILD_BLEND50 );
</code></pre>
<p>But I cannot find a simple way to show an icon in a menu. I would like to do this</p>
<pre><code>CMenu men;
CBitmap b;
// here the miracle happens, load the icon into the bitmap
men.AppendMenu( MF_ENABLED,1,&b);
</code></pre>
<p>Seems like this should be possible.</p>
<hr>
<p>This is the same question as <a href="https://stackoverflow.com/questions/70386/icons-on-menus-of-mfc-feature-pack-classes">this</a>. However that question referred to the MFC feature pack, did not get answered, and has shown no activity for a month, so I thought it would be worthwhile to ask it again in reference to basic MFC.</p>
|
[
{
"answer_id": 269027,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": -1,
"selected": false,
"text": "MENUITEMINFO mii;\nmii.cbSize = sizeof mii;\nmii.fMask = MIIM_BITMAP;\nmii.hbmpItem = bitmapHandle;\nmenu.SetMenuItemInfo(menuItem,&mii,TRUE);\n"
},
{
"answer_id": 896676,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " MENUINFO mi;\n mi.cbSize = sizeof(mi);\n mi.fMask = MIM_STYLE;\n mi.dwStyle = MNS_NOCHECK;\n pcSubMenu->SetMenuInfo(&mi);\n\n MENUITEMINFO mii;\n mii.cbSize = sizeof mii;\n mii.fMask = MIIM_BITMAP;\n\n mii.hbmpItem = (HBITMAP)::LoadImage(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDB_16_HELP),IMAGE_BITMAP,0,0,LR_SHARED |LR_VGACOLOR |LR_LOADTRANSPARENT);\n pcSubMenu->SetMenuItemInfo(ID_CONTENTS,&mii,FALSE);\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16582/"
] |
268,501
|
<p>On a Windows 2003 server I have a pure .NET 3.5 <code>C#</code> app (no unmanaged code). It connects to various other remote systems via sockets and acts like a data hub. It runs for 10-15 hours fine with no problem but from time to time it just disappears. If I watch the app using task manager the memory usage remains constant.</p>
<p>In the <code>Main()</code> function I wrap the invocation of the rest of the app in a <code>try .. catch</code> block which it just blows completely past - the catch block which logs the exception to a file is ignored. If I manually raise an exception for testing, the catch block is invoked.</p>
<p>Prior to entering the <code>try .. catch</code> I do :</p>
<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
</code></pre>
<p>The system has Dr. Watson on it, but nothing gets written in the directory <code>DRWTSN32.EXE</code> is pointing to.</p>
<p>How can I catch whatever exception is causing this?</p>
|
[
{
"answer_id": 268511,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "Application.ThreadException"
},
{
"answer_id": 268616,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 2,
"selected": false,
"text": "Application.ThreadException += new Threading.ThreadExceptionHandler(CatchExceptions);\n"
},
{
"answer_id": 269387,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 1,
"selected": false,
"text": "!printexception"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35055/"
] |
268,513
|
<p>Is there an efficient way to take a subset of a C# array and pass it to another peice of code (without modifying the original array)? I use CUDA.net which has a function which copies an array to the GPU. I would like to e.g. pass the function a 10th of the array and thus copy each 10th of the array to the GPU seperately (for pipelining purposes).</p>
<p>Copying the array in this way should be as efficient as copying it in one go. It can be done with unsafe code and just referencing the proper memory location but other than that I'm not sure. The CopyTo function copies the entire array to another array so this does not appear useful.</p>
|
[
{
"answer_id": 268551,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 2,
"selected": false,
"text": "int[] myInts = new int[100];\n\n//Code to populate original arrray\n\nfor (int i = 0; i < myInts.Length; i += 10)\n{\n int[] newarray = myInts.Skip(i).Take(10).ToArray();\n //Do stuff with new array\n}\n"
},
{
"answer_id": 268554,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 0,
"selected": false,
"text": "public static IEnumerable Part<T>(this T[] array, int startIndex, int endIndex )\n{\n for ( var currentIndex = startIndex; currentIndex < endIndex; ++currentIndex )\n yield return array[currentIndex];\n}\n"
},
{
"answer_id": 268732,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 1,
"selected": false,
"text": "void CopyToGpu(byte[] source, int start, int length);\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
268,526
|
<p>A site I am working on that is built using PHP is sometimes showing a completely blank page.
There are no error messages on the client or on the server.
The same page may display sometimes but not others.
All pages are working fine in IE7, Firefox 3, Safari and Opera.
All pages are XHTML with this meta element:</p>
<pre><code><meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
</code></pre>
<p>It <em>appears</em> that I have fixed the problem by adding this PHP code:</p>
<pre><code>header('Content-type: text/html; charset=utf-8');
</code></pre>
<p>I have read that this problem may be caused by XHTML, encoding, gzip compression, or caching, but nobody has been able to backup these guesses.</p>
<p>As the problem was intermittent I am not confident that my solution has actually solved the problem.</p>
<p>My question is, are there <em>reproducible</em> ways of having IE6 show a blank page when other browsers display content?
If so, what causes it and what solves it?</p>
|
[
{
"answer_id": 268571,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 0,
"selected": false,
"text": "<script language=\"javascript\"> // no closing tag\nalert('hello world');\n<body>\nhello world\n</body>\n <div> <script> </script> <div> <textarea>"
},
{
"answer_id": 268683,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 1,
"selected": false,
"text": "<script src=\"....\" />\n <script src=\"....\"></script>\n"
},
{
"answer_id": 1729360,
"author": "Baha14",
"author_id": 210479,
"author_profile": "https://Stackoverflow.com/users/210479",
"pm_score": 0,
"selected": false,
"text": "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-15\" />\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18333/"
] |
268,543
|
<p>I have an application with a main form. In this form I have placed three TActionMainMenuBars, because the application essentially runs in three different modes. </p>
<p>The menu bars are all constructed from actions stored(proxied) in an TActionManager on the main form. The ActionManager actually references actionlists on various other forms. </p>
<p>The menu bars are then shown+enabled and hidden+disabled such that only one is visible at a time. This works well, with the actions operating if clicked on or if navigated through using ALT and then the arrow keys or the character underlined in their caption. </p>
<p>The problem is however that the actions do not seem to respond to any shortcut key presses.</p>
<p>Does anyone know what could be causing the actions not to fire?</p>
<p>I will happily provide more information if needed, I am programming in C++Builder 2007 RAD Studio in WinXP SP3.</p>
<p>Thanks to anyone who reads this, or even reads this and comes up with a solution!</p>
<p>PeterMJ</p>
<p><strong>Update:</strong> I failed to stated that the shortcuts in the different menus overlap in that the same shortcuts are used in the different menus for different actions, but all shortcuts are unique in there own menu.</p>
<p>I have also since simplified the problem in a test application, with two TActionMainMenuBars, and all actions shared a single action manager. In this case I have two actions with the same shortcut. They are placed on different menus. Then one menu is enabled at a time. In this case the shortcuts do work, BUT when using the common shortcut only the action in the first menu is fired, <em>even</em> when the holding menu is disabled. </p>
<p>This is slightly better than my actual problem in that some actions do fire, but highlights that the actions are not being triggered correctly. Does anyone no of a solution?</p>
|
[
{
"answer_id": 821813,
"author": "NineBerry",
"author_id": 101087,
"author_profile": "https://Stackoverflow.com/users/101087",
"pm_score": 2,
"selected": false,
"text": " if CheckBox1.Checked then\n begin\n Action1.Enabled:= False;\n Action2.Enabled:= True;\n end\n else\n begin\n Action1.Enabled:= True;\n Action2.Enabled:= False;\n end;\n if CheckBox1.Checked then\n begin\n Action1.Enabled:= False;\n Action1.ShortCut:= scNone;\n\n Action2.Enabled:= True;\n Action2.ShortCut:= ShortCut(ord('A'), [ssCtrl]);\n end\n else\n begin\n Action2.Enabled:= False;\n Action2.ShortCut:= scNone;\n\n Action1.Enabled:= True;\n Action1.ShortCut:= ShortCut(ord('A'), [ssCtrl]);\n end;\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
268,548
|
<p>I use CruiseControl.NET to automatically build my .NET 3.5 web applications, which works a treat. However, is there any way to automatically create a ZIP file of these builds, and put the ZIP's into a separate directory?</p>
<p>I have seen this is possible using NAnt but cannot find an example of how to get this working.</p>
<p>Can anyone offer help/examples?</p>
|
[
{
"answer_id": 268635,
"author": "domruf",
"author_id": 7029,
"author_profile": "https://Stackoverflow.com/users/7029",
"pm_score": 0,
"selected": false,
"text": "<target name=\"zipProject\">\n <mkdir dir=\"output\"/>\n <zip destfile=\"output\\sources.zip\" basedir=\"C:\\project\\src\" />\n</target>\n"
},
{
"answer_id": 268925,
"author": "Alex York",
"author_id": 35064,
"author_profile": "https://Stackoverflow.com/users/35064",
"pm_score": 0,
"selected": false,
"text": "<tasks> <schedule>"
},
{
"answer_id": 877579,
"author": "foolshat",
"author_id": 108773,
"author_profile": "https://Stackoverflow.com/users/108773",
"pm_score": 2,
"selected": false,
"text": " <zip zipfile=\"${sourcebackup.zip}\" includeemptydirs=\"true\" verbose=\"true\"> \n <fileset basedir=\"${allcode.dir}\"> \n <include name=\"**/*\" /> \n <exclude name=\"**/_resharper*/**\" /> \n <exclude name=\"**/build/**\" /> \n <exclude name=\"**/obj/**\" /> \n <exclude name=\"**/bin/**\" /> \n <exclude name=\"**/*.dll\" /> \n <exclude name=\"**/*.scc\" /> \n <exclude name=\"**/*.log\" /> \n <exclude name=\"**/*.vssscc\" /> \n <exclude name=\"**/*.suo\" /> \n <exclude name=\"**/*.user\" /> \n <exclude name=\"**/*.pdb\" /> \n <exclude name=\"**/*.cache\" /> \n <exclude name=\"**/*.vspscc\" /> \n <exclude name=\"**/*.msi\" /> \n <exclude name=\"**/*.irs\" /> \n <exclude name=\"**/*.exe\" /> \n </fileset> \n <echo message=\"########## Zipped##########\" />\n <targetList>\n <target>Build</target>\n </targetList>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35064/"
] |
268,553
|
<p>I've just come across a property setter that catches exceptions (all Exceptions; I know that's bad, but it's not relevant here), and <em>only</em> logs them. First of all, I think it should through them again as well; why wait for a crash and a log study when you can know something is wrong right away?</p>
<p>However, my main question is, do I validate against invalid date values, add a RuleViolation object to a ValidationRules object on my document, or throw an InvalidDate exception, or just let the CLR throw the exception for me (invalid dates are nothing but invalid dates, not checked for range etc.)</p>
|
[
{
"answer_id": 268573,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 0,
"selected": false,
"text": "if(Page.IsValid)\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
268,574
|
<p>What good ruby gem sources would you recommend, besides <a href="http://gems.rubyforge.org/" rel="noreferrer">http://gems.rubyforge.org/</a> and <a href="http://gems.github.com/" rel="noreferrer">http://gems.github.com/</a>? It seems that RubyForge is missing most of the gems I look for these days...</p>
|
[
{
"answer_id": 268764,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 4,
"selected": false,
"text": "gem sources -a http://gems.github.com\ngem install person-gemname\n gem install person-gemname --source http://gems.github.com\n rubygems.org"
},
{
"answer_id": 3651224,
"author": "Željko Filipin",
"author_id": 17469,
"author_profile": "https://Stackoverflow.com/users/17469",
"pm_score": 5,
"selected": false,
"text": "https://rubygems.org/\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7202/"
] |
268,584
|
<p>Is there any way to catch all syscalls on Linux? The only solution I know of is using LD_PRELOAD à la <a href="http://packages.qa.debian.org/f/fakeroot.html" rel="nofollow noreferrer">fakeroot</a>, but that only works for dynamically linked applications. Furthermore, this approach requires enumerating all syscalls which is something I'd like to avoid.</p>
|
[
{
"answer_id": 268611,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "strace LD_PRELOAD"
},
{
"answer_id": 268636,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 3,
"selected": true,
"text": "ptrace(2)"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35070/"
] |
268,587
|
<pre><code>
class C {
T a;
public:
C(T a): a(a) {;}
};
</code></pre>
<p>Is it legal?</p>
|
[
{
"answer_id": 268591,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": true,
"text": "class A\n{\n\n A(int a)\n : a(5)//<--- try to initialize a non member variable to 5\n {\n }\n};\n class A\n{\n\n A(int myVarriable)\n : myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly\n {\n }\n int myVariable;\n};\n class A\n{\n\n A(int myVariable_)\n {\n //<-- do something with _myVariable, oops _myVariable wasn't initialized yet\n ...\n _myVariable = myVariable_;\n }\n int _myVariable;\n};\n"
},
{
"answer_id": 268646,
"author": "Suma",
"author_id": 16673,
"author_profile": "https://Stackoverflow.com/users/16673",
"pm_score": 2,
"selected": false,
"text": "class C {\n T a_;\npublic:\n C(T a): a_(a) {}\n};\n\n\nclass C {\n T a;\n public:\n C(T value): a(value) {}\n};\n"
},
{
"answer_id": 272167,
"author": "yesraaj",
"author_id": 22076,
"author_profile": "https://Stackoverflow.com/users/22076",
"pm_score": 3,
"selected": false,
"text": "class C {\n T a;\npublic:\n C(T a): a(a) {\nthis->a.sort ;//correct\na.sort();//will not affect the actual member variable\n}\n};\n"
},
{
"answer_id": 7740954,
"author": "Dragonion",
"author_id": 877194,
"author_profile": "https://Stackoverflow.com/users/877194",
"pm_score": 5,
"selected": false,
"text": "MyClass(int a) : a(a)\n{\n}\n MyClass(int a)\n{\n a=a;\n}\n MyClass(int a)\n{\n this->a=a;\n}\n MyClass() : a(a)\n{\n}\n MyClass(int x) : x(100) // error: the class doesn't have a member called \"x\"\n{\n}\n"
},
{
"answer_id": 68510992,
"author": "Soumadip Dey",
"author_id": 10439615,
"author_profile": "https://Stackoverflow.com/users/10439615",
"pm_score": 2,
"selected": false,
"text": ":: this-> class Student{\n private :\n string name;\n int rollNumber;\n\n public:\n Student()\n {\n // default constructor\n }\n\n // parameterized constructor\n Student(string name, int rollNumber)\n {\n this->name = name;\n Student::rollNumber = rollNumber;\n }\n\n void display()\n {\n cout<<\"Name: \"<<name <<endl;\n cout<<\"Roll Number: \"<<rollNumber<<endl;\n }\n\n void setName(string name)\n {\n this->name = name;\n }\n\n void setrollNumber(int rollNumber)\n {\n Student::rollNumber = rollNumber;\n }\n\n};\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12151/"
] |
268,588
|
<p>I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.</p>
<p>The other factor to be taken into account is that the button is within a asp:Login control template.</p>
<p>I've no idea how to do this, suggestions on a postcard please.</p>
|
[
{
"answer_id": 268612,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 0,
"selected": false,
"text": "$('#myTextBox').keypress(function(e){\n if(e.which == 13)\n $('#myBtn').click();\n});\n"
},
{
"answer_id": 268613,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 4,
"selected": true,
"text": "DefaultButton"
},
{
"answer_id": 268626,
"author": "Andrew Van Slaars",
"author_id": 8087,
"author_profile": "https://Stackoverflow.com/users/8087",
"pm_score": 2,
"selected": false,
"text": "Page.Form.DefaultButton = \"btnSubmit\"\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11508/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.