qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
271,340 | <p>I'm trying to use a dojo combobox with an Ajax data source. What I have is </p>
<pre><code><div dojoType="dojo.data.ItemFileReadStore"
jsId="tags"
url="<%=ResolveClientUrl("~/Tag/TagMatches")%>" >
</div>
<select dojoType="dijit.form.ComboBox"
store="tags"
value=""
name="tagName">
</select>
</code></pre>
<p>Which does work except that I can't restrict the search set on the server side because I don't know how to change the url from which the data is pulled in order to specify a parameter. Any hints? </p>
| [
{
"answer_id": 271443,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": true,
"text": "<div>"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361/"
] |
271,347 | <p>I have a class that stores a serialized value and a type. I want to have a property/method returning the value already casted:</p>
<pre><code>public String Value { get; set; }
public Type TheType { get; set; }
public typeof(TheType) CastedValue { get { return Convert.ChangeType(Value, typeof(_Type)); }
</code></pre>
<p>Is this possible in C#?</p>
| [
{
"answer_id": 271356,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 7,
"selected": false,
"text": "class Foo<TValue> {\n public string Value { get; set; }\n public TValue TypedValue {\n get {\n return (TValue)Convert.ChangeType(Value, typeof(TValue));\n }\n }\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,364 | <p><code>:vimgrep</code> looks like a really useful thing.</p>
<p>Here's how to use it:</p>
<pre><code>:vim[grep][!] /{pattern}/[g][j] {file} ...
</code></pre>
<p><code>:help</code> says that you can essentially glob <code>{file}</code> to name, say, <code>*.c</code> for the current directory. I may have started Vim with a list of files that is complicated enough that I don't want to manually type it in for <code>{file}</code>, and besides Vim already knows what those files are.</p>
<p>What I would like to do is vimgrep over any of:</p>
<ul>
<li><code>:args</code></li>
<li><code>:files</code></li>
<li><code>:buffers</code></li>
</ul>
<p>What variable(s) would I use in place of <code>{file}</code> to name, respectively, any of those lists in a <code>vimgrep</code> command?</p>
| [
{
"answer_id": 271381,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 3,
"selected": false,
"text": ":bufdo vimgrep /pattern/ %\n"
},
{
"answer_id": 271709,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 5,
"selected": true,
"text": ":h :redir"
},
{
"answer_id": 8414211,
"author": "baltazar",
"author_id": 258421,
"author_profile": "https://Stackoverflow.com/users/258421",
"pm_score": 2,
"selected": false,
"text": ":cex [] | tabdo vimgrepa /pattern/ %\n"
},
{
"answer_id": 19365379,
"author": "Steve",
"author_id": 1173869,
"author_profile": "https://Stackoverflow.com/users/1173869",
"pm_score": 3,
"selected": false,
"text": "##"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35221/"
] |
271,378 | <p>I have designed my site with a 900 x 600 fixed background image. On the computer it looks fine. How will it look on a PDA device? Will I have to design it separately for PDA?</p>
<p>How should check whether my site can be browsed effectively from mobile phone?</p>
<p>What should I do?</p>
| [
{
"answer_id": 271452,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "<link rel=\"stylesheet\" href=\"small.css\" type=\"text/css\" media=\"handheld\">\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,380 | <p>One of the files in my current head revision got corrupted. I want to make an older revision of that file the head revision as usually people sync to head revsion in my project. How to do that?</p>
| [
{
"answer_id": 271387,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 7,
"selected": true,
"text": "svn merge -rHEAD:oldrev filename\nsvn commit -m \"rolled back to oldrev\"\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13440/"
] |
271,384 | <ul>
<li>What are the pros and cons of LINQ (Language-Integrated Query)?</li>
<li>What are the best and worst cases in which to use LINQ?</li>
<li>How have you benefitted or not benefitted from using LINQ?</li>
<li>Which data sources benefit the least and the most from LINQ?</li>
</ul>
| [
{
"answer_id": 271415,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "OrderBy"
},
{
"answer_id": 271462,
"author": "Toby",
"author_id": 291137,
"author_profile": "https://Stackoverflow.com/users/291137",
"pm_score": 2,
"selected": false,
"text": "var l = new List<int>() {1, 2, 3};\ntry\n{\n l.Select(x => x / 0);\n}\ncatch\n{\n // error\n}\n\nl.elementAt(0); // exception occurs here outside of the try catch\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35331/"
] |
271,394 | <p>A class I am taking currently requires us to do all of our coding in smalltalk (it's a Design class). On one of our projects, I am looking to do some things, and am having a tough time finding how to do them. It seems that what most people do is modify their own version of smalltalk to do what they need it to do. I am not at liberty to do this, as this would cause an error on my prof's computer when he doesn't have the same built-in methods I do.</p>
<p>Here's what I'm looking to do:</p>
<p>Random Numbers. I need to create a random number between 1 and 1000. Right now I'm faking it by doing </p>
<pre><code>rand := Random new.
rand := (rand nextValue) * 1000.
rand := rand asInteger.
</code></pre>
<p>This gives me a number between 0 and 1000. Is there a way to do this in one command? similar to </p>
<pre><code>Random between: 0 and: 1000
</code></pre>
<p>And/Or statements. This one bugs the living daylights out of me. I have tried several different configurations of </p>
<pre><code>(statement) and: (statement) ifTrue...
(statement) and (statement) ifTrue...
</code></pre>
<p>So I'm faking it with nested ifTrue statements:</p>
<pre><code>(statement) ifTrue:[
(statement) ifTrue:[...
</code></pre>
<p>What is the correct way to do and/or and Random in smalltalk?</p>
| [
{
"answer_id": 271402,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 4,
"selected": true,
"text": " (expr) and: (expr) ifTrue: aBlock\n"
},
{
"answer_id": 271500,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "Random>>#nextInt:"
},
{
"answer_id": 285651,
"author": "Rydier",
"author_id": 22434,
"author_profile": "https://Stackoverflow.com/users/22434",
"pm_score": 3,
"selected": false,
"text": "(aBoolean and: [anotherBoolean]) ifTrue: [doSomething].\n"
},
{
"answer_id": 311121,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "(1 to: 1000) atRandom\n"
},
{
"answer_id": 33855293,
"author": "Euan M",
"author_id": 1970590,
"author_profile": "https://Stackoverflow.com/users/1970590",
"pm_score": 0,
"selected": false,
"text": "aRandomSeries := Random new .\n \"Seed a new series of random numbers\" \n\naRandomInt := aRandomSeries newInt: 1000 . \n \"generate a random integer between 0 and 1000\"\n\nanotherRandomInt := aRandomSeries newInt: 1000 .\n \"generate another random integer between 0 and 1000\"\n"
},
{
"answer_id": 33866017,
"author": "John Pfersich",
"author_id": 5561176,
"author_profile": "https://Stackoverflow.com/users/5561176",
"pm_score": 0,
"selected": false,
"text": "(statement) and: (statement) ifTrue...\n(statement) and (statement) ifTrue...\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
] |
271,398 | <p>Let's make a list of answers where you post your excellent and favorite <a href="http://en.wikipedia.org/wiki/Extension_method" rel="nofollow noreferrer">extension methods</a>. </p>
<p>The requirement is that the full code must be posted and a example and an explanation on how to use it.</p>
<p>Based on the high interest in this topic I have setup an Open Source Project called extensionoverflow on <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer"><strong>Codeplex</strong></a>. </p>
<p><strong>Please mark your answers with an acceptance to put the code in the Codeplex project.</strong></p>
<p><strong>Please post the full sourcecode and not a link.</strong></p>
<p><strong>Codeplex News:</strong></p>
<p>24.08.2010 The Codeplex page is now here: <a href="http://extensionoverflow.codeplex.com/" rel="nofollow noreferrer">http://extensionoverflow.codeplex.com/</a></p>
<p>11.11.2008 <strong>XmlSerialize / XmlDeserialize</strong> is now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&changeSetId=17001" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&changeSetId=17001" rel="nofollow noreferrer">Unit Tested</a>.</p>
<p>11.11.2008 There is still room for more developers. ;-) <strong>Join NOW!</strong></p>
<p>11.11.2008 Third contributer joined <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer">ExtensionOverflow</a>, welcome to <a href="http://www.codeplex.com/site/users/view/BKristensen" rel="nofollow noreferrer">BKristensen</a></p>
<p>11.11.2008 <strong>FormatWith</strong> is now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284374&changeSetId=16839" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=288847&changeSetId=16839" rel="nofollow noreferrer">Unit Tested</a>.</p>
<p>09.11.2008 Second contributer joined <a href="http://www.codeplex.com/extensionoverflow" rel="nofollow noreferrer">ExtensionOverflow</a>. welcome to <a href="https://stackoverflow.com/users/3055/chakrit">chakrit</a>.</p>
<p>09.11.2008 We need more developers. ;-)</p>
<p>09.11.2008 <strong>ThrowIfArgumentIsNull</strong> in now <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=278942&changeSetId=16468" rel="nofollow noreferrer">Implemented</a> and <a href="http://www.codeplex.com/extensionoverflow/SourceControl/FileView.aspx?itemId=284112&changeSetId=16468" rel="nofollow noreferrer">Unit Tested</a> on Codeplex.</p>
| [
{
"answer_id": 271409,
"author": "bovium",
"author_id": 11135,
"author_profile": "https://Stackoverflow.com/users/11135",
"pm_score": 5,
"selected": false,
"text": "public static class Extensions\n{\n public static void ThrowIfArgumentIsNull<T>(this T obj, string parameterName) where T : class\n {\n if (obj == null) throw new ArgumentNullException(parameterName + \" not allowed to be null\");\n }\n}\n"
},
{
"answer_id": 271411,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 7,
"selected": false,
"text": "public static class StringExtensions\n{\n // Enable quick and more natural string.Format calls\n public static string F(this string s, params object[] args)\n {\n return string.Format(s, args);\n }\n}\n"
},
{
"answer_id": 271418,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": false,
"text": "public static class ExtensionMethods \n{\n public static string ToCurrency(this double value, string cultureName)\n {\n CultureInfo currentCulture = new CultureInfo(cultureName);\n return (string.Format(currentCulture, \"{0:C}\", value));\n }\n}\n"
},
{
"answer_id": 271421,
"author": "mlarsen",
"author_id": 17700,
"author_profile": "https://Stackoverflow.com/users/17700",
"pm_score": 5,
"selected": false,
"text": "public static class StringExtensions {\n\n /// <summary>\n /// Parses a string into an Enum\n /// </summary>\n /// <typeparam name=\"T\">The type of the Enum</typeparam>\n /// <param name=\"value\">String value to parse</param>\n /// <returns>The Enum corresponding to the stringExtensions</returns>\n public static T EnumParse<T>(this string value) {\n return StringExtensions.EnumParse<T>(value, false);\n }\n\n public static T EnumParse<T>(this string value, bool ignorecase) {\n\n if (value == null) {\n throw new ArgumentNullException(\"value\");\n }\n\n value = value.Trim();\n\n if (value.Length == 0) {\n throw new ArgumentException(\"Must specify valid information for parsing in the string.\", \"value\");\n }\n\n Type t = typeof(T);\n\n if (!t.IsEnum) {\n throw new ArgumentException(\"Type provided must be an Enum.\", \"T\");\n }\n\n return (T)Enum.Parse(t, value, ignorecase);\n }\n}\n"
},
{
"answer_id": 271423,
"author": "TWith2Sugars",
"author_id": 35389,
"author_profile": "https://Stackoverflow.com/users/35389",
"pm_score": 6,
"selected": false,
"text": "/// <summary>Serializes an object of type T in to an xml string</summary>\n/// <typeparam name=\"T\">Any class type</typeparam>\n/// <param name=\"obj\">Object to serialize</param>\n/// <returns>A string that represents Xml, empty otherwise</returns>\npublic static string XmlSerialize<T>(this T obj) where T : class, new()\n{\n if (obj == null) throw new ArgumentNullException(\"obj\");\n\n var serializer = new XmlSerializer(typeof(T));\n using (var writer = new StringWriter())\n {\n serializer.Serialize(writer, obj);\n return writer.ToString();\n }\n}\n\n/// <summary>Deserializes an xml string in to an object of Type T</summary>\n/// <typeparam name=\"T\">Any class type</typeparam>\n/// <param name=\"xml\">Xml as string to deserialize from</param>\n/// <returns>A new object of type T is successful, null if failed</returns>\npublic static T XmlDeserialize<T>(this string xml) where T : class, new()\n{\n if (xml == null) throw new ArgumentNullException(\"xml\");\n\n var serializer = new XmlSerializer(typeof(T));\n using (var reader = new StringReader(xml))\n {\n try { return (T)serializer.Deserialize(reader); }\n catch { return null; } // Could not be deserialized to this type.\n }\n}\n"
},
{
"answer_id": 271426,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 5,
"selected": false,
"text": "DateTime firstDayOfMonth = DateTime.Now.First();\nDateTime lastdayOfMonth = DateTime.Now.Last();\nDateTime lastFridayInMonth = DateTime.Now.Last(DayOfWeek.Friday);\nDateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);\nDateTime lunchTime = DateTime.Now.SetTime(11, 30);\nDateTime noonOnFriday = DateTime.Now.Next(DayOfWeek.Friday).Noon();\nDateTime secondMondayOfMonth = DateTime.Now.First(DayOfWeek.Monday).Next(DayOfWeek.Monday).Midnight();\n"
},
{
"answer_id": 271433,
"author": "sontek",
"author_id": 17176,
"author_profile": "https://Stackoverflow.com/users/17176",
"pm_score": -1,
"selected": false,
"text": "public static string ToXml<T>(this T obj) where T : class\n{\n XmlSerializer s = new XmlSerializer(obj.GetType());\n using (StringWriter writer = new StringWriter())\n {\n s.Serialize(writer, obj);\n return writer.ToString();\n }\n}\n\n\"<root><child>foo</child</root>\".ToXml<MyCustomType>();\n"
},
{
"answer_id": 271435,
"author": "TWith2Sugars",
"author_id": 35389,
"author_profile": "https://Stackoverflow.com/users/35389",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Converts any type in to an Int32\n/// </summary>\n/// <typeparam name=\"T\">Any Object</typeparam>\n/// <param name=\"value\">Value to convert</param>\n/// <returns>The integer, 0 if unsuccessful</returns>\npublic static int ToInt32<T>(this T value)\n{\n int result;\n if (int.TryParse(value.ToString(), out result))\n {\n return result;\n }\n return 0;\n}\n\n/// <summary>\n/// Converts any type in to an Int32 but if null then returns the default\n/// </summary>\n/// <param name=\"value\">Value to convert</param>\n/// <typeparam name=\"T\">Any Object</typeparam>\n/// <param name=\"defaultValue\">Default to use</param>\n/// <returns>The defaultValue if unsuccessful</returns>\npublic static int ToInt32<T>(this T value, int defaultValue)\n{\n int result;\n if (int.TryParse(value.ToString(), out result))\n {\n return result;\n }\n return defaultValue;\n}\n"
},
{
"answer_id": 271437,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": false,
"text": "var birthday = 19.June(1976);\nvar workingDay = 7.Hours() + 30.Minutes();\n"
},
{
"answer_id": 271444,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 6,
"selected": false,
"text": "public static class ComparableExtensions\n{\n public static bool Between<T>(this T actual, T lower, T upper) where T : IComparable<T>\n {\n return actual.CompareTo(lower) >= 0 && actual.CompareTo(upper) < 0;\n }\n}\n"
},
{
"answer_id": 271451,
"author": "Alan",
"author_id": 31223,
"author_profile": "https://Stackoverflow.com/users/31223",
"pm_score": 2,
"selected": false,
"text": "public static void LoadFrom(this ApplicationSettingsBase settings, NameValueCollection configuration)\n{\n if (configuration != null)\n foreach (string key in configuration.AllKeys)\n if (!String.IsNullOrEmpty(key))\n try\n {\n settings[key] = configuration.Get(key);\n }\n catch (SettingsPropertyNotFoundException)\n {\n // handle bad arguments as you wish\n }\n}\n"
},
{
"answer_id": 271478,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "public static IList<T> Clone<T>(this IList<T> list) where T : ICloneable\n{\n var ret = new List<T>(list.Count);\n foreach (var item in list)\n ret.Add((T)item.Clone());\n\n // done\n return ret;\n}\n"
},
{
"answer_id": 271611,
"author": "stiduck",
"author_id": 35398,
"author_profile": "https://Stackoverflow.com/users/35398",
"pm_score": 6,
"selected": false,
"text": "public static void AddRange<T, S>(this ICollection<T> list, params S[] values)\n where S : T\n{\n foreach (S value in values)\n list.Add(value);\n}\n"
},
{
"answer_id": 271656,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Text;\n\nnamespace Insert.Your.Namespace.Here.Helpers\n{\n public static class Extensions\n {\n public static bool IsNullOrEmpty<T>(this IEnumerable<T> iEnumerable)\n {\n // Cheers to Joel Mueller for the bugfix. Was .Count(), now it's .Any()\n return iEnumerable == null ||\n !iEnumerable.Any();\n }\n\n public static IList<T> ToListIfNotNullOrEmpty<T>(this IList<T> iList)\n {\n return iList.IsNullOrEmpty() ? null : iList;\n }\n\n public static PagedList<T> ToPagedListIfNotNullOrEmpty<T>(this PagedList<T> pagedList)\n {\n return pagedList.IsNullOrEmpty() ? null : pagedList;\n }\n\n public static string ToPluralString(this int value)\n {\n return value == 1 ? string.Empty : \"s\";\n }\n\n public static string ToReadableTime(this DateTime value)\n {\n TimeSpan span = DateTime.Now.Subtract(value);\n const string plural = \"s\";\n\n\n if (span.Days > 7)\n {\n return value.ToShortDateString();\n }\n\n switch (span.Days)\n {\n case 0:\n switch (span.Hours)\n {\n case 0:\n if (span.Minutes == 0)\n {\n return span.Seconds <= 0\n ? \"now\"\n : string.Format(\"{0} second{1} ago\",\n span.Seconds,\n span.Seconds != 1 ? plural : string.Empty);\n }\n return string.Format(\"{0} minute{1} ago\",\n span.Minutes,\n span.Minutes != 1 ? plural : string.Empty);\n default:\n return string.Format(\"{0} hour{1} ago\",\n span.Hours,\n span.Hours != 1 ? plural : string.Empty);\n }\n default:\n return string.Format(\"{0} day{1} ago\",\n span.Days,\n span.Days != 1 ? plural : string.Empty);\n }\n }\n\n public static string ToShortGuidString(this Guid value)\n {\n return Convert.ToBase64String(value.ToByteArray())\n .Replace(\"/\", \"_\")\n .Replace(\"+\", \"-\")\n .Substring(0, 22);\n }\n\n public static Guid FromShortGuidString(this string value)\n {\n return new Guid(Convert.FromBase64String(value.Replace(\"_\", \"/\")\n .Replace(\"-\", \"+\") + \"==\"));\n }\n\n public static string ToStringMaximumLength(this string value, int maximumLength)\n {\n return ToStringMaximumLength(value, maximumLength, \"...\");\n }\n\n public static string ToStringMaximumLength(this string value, int maximumLength, string postFixText)\n {\n if (string.IsNullOrEmpty(postFixText))\n {\n throw new ArgumentNullException(\"postFixText\");\n }\n\n return value.Length > maximumLength\n ? string.Format(CultureInfo.InvariantCulture,\n \"{0}{1}\",\n value.Substring(0, maximumLength - postFixText.Length),\n postFixText)\n :\n value;\n }\n\n public static string SlugDecode(this string value)\n {\n return value.Replace(\"_\", \" \");\n }\n\n public static string SlugEncode(this string value)\n {\n return value.Replace(\" \", \"_\");\n }\n }\n}\n"
},
{
"answer_id": 271884,
"author": "xyz",
"author_id": 82,
"author_profile": "https://Stackoverflow.com/users/82",
"pm_score": 6,
"selected": false,
"text": "public static bool CoinToss(this Random rng)\n{\n return rng.Next(2) == 0;\n}\n\npublic static T OneOf<T>(this Random rng, params T[] things)\n{\n return things[rng.Next(things.Length)];\n}\n\nRandom rand;\nbool luckyDay = rand.CoinToss();\nstring babyName = rand.OneOf(\"John\", \"George\", \"Radio XBR74 ROCKS!\");\n"
},
{
"answer_id": 271941,
"author": "Venr",
"author_id": 20385,
"author_profile": "https://Stackoverflow.com/users/20385",
"pm_score": 5,
"selected": false,
"text": "public static string ToTitleCase(this string mText)\n{\n if (mText == null) return mText;\n\n System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;\n System.Globalization.TextInfo textInfo = cultureInfo.TextInfo;\n\n // TextInfo.ToTitleCase only operates on the string if is all lower case, otherwise it returns the string unchanged.\n return textInfo.ToTitleCase(mText.ToLower());\n}\n"
},
{
"answer_id": 273648,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 4,
"selected": false,
"text": "public static DateTime? GetNullableDateTime(this MySqlDataReader dr, string fieldName)\n{\n DateTime? nullDate = null;\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? nullDate : dr.GetDateTime(fieldName);\n}\n\npublic static string GetNullableString(this MySqlDataReader dr, string fieldName)\n{\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? String.Empty : dr.GetString(fieldName);\n}\n\npublic static char? GetNullableChar(this MySqlDataReader dr, string fieldName)\n{\n char? nullChar = null;\n return dr.IsDBNull(dr.GetOrdinal(fieldName)) ? nullChar : dr.GetChar(fieldName);\n}\n"
},
{
"answer_id": 273665,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Checks the Request.QueryString for the specified value and returns it, if none \n/// is found then the default value is returned instead\n/// </summary>\npublic static T QueryValue<T>(this HtmlHelper helper, string param, T defaultValue) {\n object value = HttpContext.Current.Request.QueryString[param] as object;\n if (value == null) { return defaultValue; }\n try {\n return (T)Convert.ChangeType(value, typeof(T));\n } catch (Exception) {\n return defaultValue;\n }\n}\n"
},
{
"answer_id": 274524,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 5,
"selected": false,
"text": "int i = myString.To<int>();\n"
},
{
"answer_id": 274649,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 6,
"selected": false,
"text": "public static class FrameworkExtensions\n{\n // a map function\n public static void ForEach<T>(this IEnumerable<T> @enum, Action<T> mapFunction)\n {\n foreach (var item in @enum) mapFunction(item);\n }\n}\n"
},
{
"answer_id": 274652,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 3,
"selected": false,
"text": "DirectoryInfo dir = new DirectoryInfo(@\"C:\\test\\myShareDir\");\nConsole.WriteLine(dir.IsSameFileAs(@\"\\\\myMachineName\\myShareDir\"));\n\nFileInfo file = new FileInfo(@\"C:\\test\\myShareDir\\file.txt\");\nConsole.WriteLine(file.IsSameFileAs(@\"\\\\myMachineName\\myShareDir\\file.txt\"));\n"
},
{
"answer_id": 275303,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "public static class MyExtensions\n{\n public static bool IsInteger(this string input)\n {\n int temp;\n\n return int.TryParse(input, out temp);\n }\n\n public static bool IsDecimal(this string input)\n {\n decimal temp;\n\n return decimal.TryParse(input, out temp);\n }\n\n public static int ToInteger(this string input, int defaultValue)\n {\n int temp;\n\n return (int.TryParse(input, out temp)) ? temp : defaultValue;\n }\n\n public static decimal ToDecimal(this string input, decimal defaultValue)\n {\n decimal temp;\n\n return (decimal.TryParse(input, out temp)) ? temp : defaultValue;\n }\n\n public static DateTime ToFirstOfTheMonth(this DateTime input)\n {\n return input.Date.AddDays(-1 * input.Day + 1);\n }\n\n // Intentionally returns 0 if the target date is before the input date.\n public static int MonthsUntil(this DateTime input, DateTime targetDate)\n {\n input = input.ToFirstOfTheMonth();\n\n targetDate = targetDate.ToFirstOfTheMonth();\n\n int result = 0;\n\n while (input < targetDate)\n {\n input = input.AddMonths(1);\n result++;\n }\n\n return result;\n }\n\n // Used for backwards compatibility in a system built before my time.\n public static DataTable ToDataTable(this IEnumerable input)\n {\n // too much code to show here right now...\n }\n}\n"
},
{
"answer_id": 275611,
"author": "µBio",
"author_id": 9796,
"author_profile": "https://Stackoverflow.com/users/9796",
"pm_score": 4,
"selected": false,
"text": "public static string Wordify( this string camelCaseWord )\n{\n // if the word is all upper, just return it\n if( !Regex.IsMatch( camelCaseWord, \"[a-z]\" ) )\n return camelCaseWord;\n\n return string.Join( \" \", Regex.Split( camelCaseWord, @\"(?<!^)(?=[A-Z])\" ) );\n}\n"
},
{
"answer_id": 275620,
"author": "TraumaPony",
"author_id": 18658,
"author_profile": "https://Stackoverflow.com/users/18658",
"pm_score": 3,
"selected": false,
"text": "public static class EnumerableExtensions\n{\n [Pure]\n public static U MapReduce<T, U>(this IEnumerable<T> enumerable, Func<T, U> map, Func<U, U, U> reduce)\n {\n CodeContract.RequiresAlways(enumerable != null);\n CodeContract.RequiresAlways(enumerable.Skip(1).Any());\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n return enumerable.AsParallel().Select(map).Aggregate(reduce);\n }\n [Pure]\n public static U MapReduce<T, U>(this IList<T> list, Func<T, U> map, Func<U, U, U> reduce)\n {\n CodeContract.RequiresAlways(list != null);\n CodeContract.RequiresAlways(list.Count >= 2);\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n U result = map(list[0]);\n for (int i = 1; i < list.Count; i++)\n {\n result = reduce(result,map(list[i]));\n }\n return result;\n }\n\n //Parallel version; creates garbage\n [Pure]\n public static U MapReduce<T, U>(this IList<T> list, Func<T, U> map, Func<U, U, U> reduce)\n {\n CodeContract.RequiresAlways(list != null);\n CodeContract.RequiresAlways(list.Skip(1).Any());\n CodeContract.RequiresAlways(map != null);\n CodeContract.RequiresAlways(reduce != null);\n\n U[] mapped = new U[list.Count];\n Parallel.For(0, mapped.Length, i =>\n {\n mapped[i] = map(list[i]);\n });\n U result = mapped[0];\n for (int i = 1; i < list.Count; i++)\n {\n result = reduce(result, mapped[i]);\n }\n return result;\n }\n\n}\n"
},
{
"answer_id": 275640,
"author": "Zack Elan",
"author_id": 2461,
"author_profile": "https://Stackoverflow.com/users/2461",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// If a key exists in a dictionary, return its value, \n/// otherwise return the default value for that type.\n/// </summary>\npublic static U GetWithDefault<T, U>(this Dictionary<T, U> dict, T key)\n{\n return dict.GetWithDefault(key, default(U));\n}\n\n/// <summary>\n/// If a key exists in a dictionary, return its value,\n/// otherwise return the provided default value.\n/// </summary>\npublic static U GetWithDefault<T, U>(this Dictionary<T, U> dict, T key, U defaultValue)\n{\n return dict.ContainsKey(key)\n ? dict[key]\n : defaultValue;\n}\n"
},
{
"answer_id": 276307,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Reverse a String\n/// </summary>\n/// <param name=\"input\">The string to Reverse</param>\n/// <returns>The reversed String</returns>\npublic static string Reverse(this string input)\n{\n char[] array = input.ToCharArray();\n Array.Reverse(array);\n return new string(array);\n}\n"
},
{
"answer_id": 276331,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "public static void Log(this Exception obj)\n{\n //your logging logic here\n}\n"
},
{
"answer_id": 279789,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "[ThreadStatic]\nprivate static string lastMethodName = null;\n\n[ThreadStatic]\nprivate static int lastParamIndex = 0;\n\n[MethodImpl(MethodImplOptions.NoInlining)]\npublic static void ThrowIfNull<T>(this T parameter)\n{\n var currentStackFrame = new StackFrame(1);\n var props = currentStackFrame.GetMethod().GetParameters();\n\n if (!String.IsNullOrEmpty(lastMethodName)) {\n if (currentStackFrame.GetMethod().Name != lastMethodName) {\n lastParamIndex = 0;\n } else if (lastParamIndex >= props.Length - 1) {\n lastParamIndex = 0;\n } else {\n lastParamIndex++;\n }\n } else {\n lastParamIndex = 0;\n }\n\n if (!typeof(T).IsValueType) {\n for (int i = lastParamIndex; i < props.Length; i++) {\n if (props[i].ParameterType.IsValueType) {\n lastParamIndex++;\n } else {\n break;\n }\n }\n }\n\n if (parameter == null) {\n string paramName = props[lastParamIndex].Name;\n throw new ArgumentNullException(paramName);\n }\n\n lastMethodName = currentStackFrame.GetMethod().Name;\n}\n"
},
{
"answer_id": 280230,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 2,
"selected": false,
"text": "if (guid != Guid.Empty) return guid;\nelse return Guid.NewGuid();\n"
},
{
"answer_id": 280252,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "public static FileInfo SetExtension(this FileInfo fileInfo, string extension)\n{\n return new FileInfo(Path.ChangeExtension(fileInfo.FullName, extension));\n}\n\npublic static FileInfo SetDirectory(this FileInfo fileInfo, string directory)\n{\n return new FileInfo(Path.Combine(directory, fileInfo.Name));\n}\n"
},
{
"answer_id": 280322,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 4,
"selected": false,
"text": "<label />"
},
{
"answer_id": 286327,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 2,
"selected": false,
"text": "public static class StringExtensions\n{\n /// <summary>\n /// Returns a Subset string starting at the specified start index and ending and the specified end\n /// index.\n /// </summary>\n /// <param name=\"s\">The string to retrieve the subset from.</param>\n /// <param name=\"startIndex\">The specified start index for the subset.</param>\n /// <param name=\"endIndex\">The specified end index for the subset.</param>\n /// <returns>A Subset string starting at the specified start index and ending and the specified end\n /// index.</returns>\n public static string Subsetstring(this string s, int startIndex, int endIndex)\n {\n if (startIndex > endIndex)\n {\n throw new InvalidOperationException(\"End Index must be after Start Index.\");\n }\n\n if (startIndex < 0)\n {\n throw new InvalidOperationException(\"Start Index must be a positive number.\");\n }\n\n if(endIndex <0)\n {\n throw new InvalidOperationException(\"End Index must be a positive number.\");\n }\n\n return s.Substring(startIndex, (endIndex - startIndex));\n }\n\n /// <summary>\n /// Finds the specified Start Text and the End Text in this string instance, and returns a string\n /// containing all the text starting from startText, to the begining of endText. (endText is not\n /// included.)\n /// </summary>\n /// <param name=\"s\">The string to retrieve the subset from.</param>\n /// <param name=\"startText\">The Start Text to begin the Subset from.</param>\n /// <param name=\"endText\">The End Text to where the Subset goes to.</param>\n /// <param name=\"ignoreCase\">Whether or not to ignore case when comparing startText/endText to the string.</param>\n /// <returns>A string containing all the text starting from startText, to the begining of endText.</returns>\n public static string Subsetstring(this string s, string startText, string endText, bool ignoreCase)\n {\n if (string.IsNullOrEmpty(startText) || string.IsNullOrEmpty(endText))\n {\n throw new ArgumentException(\"Start Text and End Text cannot be empty.\");\n }\n string temp = s;\n if (ignoreCase)\n {\n temp = s.ToUpperInvariant();\n startText = startText.ToUpperInvariant();\n endText = endText.ToUpperInvariant();\n }\n int start = temp.IndexOf(startText);\n int end = temp.IndexOf(endText, start);\n return Subsetstring(s, start, end);\n }\n}\n"
},
{
"answer_id": 286753,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public static T ToEnum<T>(this string str) where T : struct\n{\n return (T)Enum.Parse(typeof(T), str);\n}\n\n//DayOfWeek sunday = \"Sunday\".ToEnum<DayOfWeek>();\n\npublic static string ToString<T>(this IEnumerable<T> collection, string separator)\n{\n return ToString(collection, t => t.ToString(), separator);\n}\n\npublic static string ToString<T>(this IEnumerable<T> collection, Func<T, string> stringElement, string separator)\n{\n StringBuilder sb = new StringBuilder();\n foreach (var item in collection)\n {\n sb.Append(stringElement(item));\n sb.Append(separator);\n }\n return sb.ToString(0, Math.Max(0, sb.Length - separator.Length)); // quita el ultimo separador\n}\n\n//new []{1,2,3}.ToString(i=>i*2, \", \") --> \"2, 4, 6\"\n"
},
{
"answer_id": 291402,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 5,
"selected": false,
"text": "if (\"IV\".IsValidRomanNumeral())\n{\n // Do useful stuff with the number 4.\n}\n\nConsole.WriteLine(\"MMMDCCCLXXXVIII\".ParseRomanNumeral());\nConsole.WriteLine(3888.ToRomanNumeralString());\n"
},
{
"answer_id": 326701,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Wrap an object in a list\n/// </summary>\npublic static IList<T> WrapInList<T>(this T item)\n{\n List<T> result = new List<T>();\n result.Add(item);\n return result;\n}\n"
},
{
"answer_id": 329561,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 2,
"selected": false,
"text": "public static int? ToInt(this string input) \n{\n int val;\n if (int.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static DateTime? ToDate(this string input)\n{\n DateTime val;\n if (DateTime.TryParse(input, out val))\n return val;\n return null;\n}\n\npublic static decimal? ToDecimal(this string input)\n{\n decimal val;\n if (decimal.TryParse(input, out val))\n return val;\n return null;\n}\n"
},
{
"answer_id": 330044,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 2,
"selected": false,
"text": "public static bool AnyOf(this object mask, object flags)\n{\n return ((int)mask & (int)flags) != 0;\n}\npublic static bool AllOf(this object mask, object flags)\n{\n return ((int)mask & (int)flags) == (int)flags;\n}\npublic static object SetOn(this object mask, object flags)\n{\n return (int)mask | (int)flags;\n}\netc.\n"
},
{
"answer_id": 346181,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 3,
"selected": false,
"text": "public static TimeSpan Seconds(this int seconds)\n{\n return TimeSpan.FromSeconds(seconds);\n}\n\npublic static TimeSpan Minutes(this int minutes)\n{\n return TimeSpan.FromMinutes(minutes);\n}\n"
},
{
"answer_id": 357344,
"author": "Robert Dean",
"author_id": 3396,
"author_profile": "https://Stackoverflow.com/users/3396",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Security.Principal;\nusing System.Web.Routing;\nusing System.Web.Mvc;\nusing System.Collections;\nusing System.Reflection;\nnamespace System.Web.Mvc.Html\n{\n public static class HtmlHelperExtensions\n {\n\n /// <summary>\n /// Shows or hides an action link based on the user's membership status\n /// and the controller's authorize attributes\n /// </summary>\n /// <param name=\"linkText\">The link text.</param>\n /// <param name=\"action\">The controller action name.</param>\n /// <param name=\"controller\">The controller name.</param>\n /// <returns></returns>\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper,\n string linkText,\n string action,\n string controller)\n {\n return SecurityTrimmedActionLink(htmlHelper, linkText, action, controller, false, null);\n }\n\n /// <summary>\n /// Enables, disables or hides an action link based on the user's membership status\n /// and the controller's authorize attributes\n /// </summary>\n /// <param name=\"linkText\">The link text.</param>\n /// <param name=\"action\">The action name.</param>\n /// <param name=\"controller\">The controller name.</param>\n /// <param name=\"showDisabled\">if set to <c>true</c> [show link as disabled - \n /// using a span tag instead of an anchor tag ].</param>\n /// <param name=\"disabledAttributeText\">Use this to add attributes to the disabled\n /// span tag.</param>\n /// <returns></returns>\n public static string SecurityTrimmedActionLink(\n this HtmlHelper htmlHelper, \n string linkText, \n string action, \n string controller, \n bool showDisabled, \n string disabledAttributeText)\n {\n if (IsAccessibleToUser(action, controller, HttpContext.Current ))\n {\n return htmlHelper.ActionLink(linkText, action, controller);\n }\n else\n {\n return showDisabled ? \n String.Format(\n \"<span{1}>{0}</span>\", \n linkText, \n disabledAttributeText==null?\"\":\" \"+disabledAttributeText\n ) : \"\";\n }\n }\n\n private static IController GetControllerInstance(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n Type controllerType = GetControllerType(controllerName);\n return (IController)Activator.CreateInstance(controllerType);\n }\n\n private static ArrayList GetControllerAttributes(string controllerName, HttpContext context)\n {\n if (context.Cache[controllerName + \"_ControllerAttributes\"] == null)\n {\n var controller = GetControllerInstance(controllerName);\n\n context.Cache.Add(\n controllerName + \"_ControllerAttributes\",\n new ArrayList(controller.GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true)),\n null,\n Caching.Cache.NoAbsoluteExpiration,\n Caching.Cache.NoSlidingExpiration,\n Caching.CacheItemPriority.Default,\n null);\n\n }\n return (ArrayList)context.Cache[controllerName + \"_ControllerAttributes\"];\n\n }\n\n private static ArrayList GetMethodAttributes(string controllerName, string actionName, HttpContext context)\n {\n if (context.Cache[controllerName + \"_\" + actionName + \"_ActionAttributes\"] == null)\n {\n ArrayList actionAttrs = new ArrayList();\n var controller = GetControllerInstance(controllerName);\n MethodInfo[] methods = controller.GetType().GetMethods();\n\n foreach (MethodInfo method in methods)\n {\n object[] attributes = method.GetCustomAttributes(typeof(ActionNameAttribute), true);\n\n if ((attributes.Length == 0 && method.Name == actionName)\n ||\n (attributes.Length > 0 && ((ActionNameAttribute)attributes[0]).Name == actionName))\n {\n actionAttrs.AddRange(method.GetCustomAttributes(typeof(AuthorizeAttribute), true));\n }\n }\n\n context.Cache.Add(\n controllerName + \"_\" + actionName + \"_ActionAttributes\",\n actionAttrs,\n null,\n Caching.Cache.NoAbsoluteExpiration,\n Caching.Cache.NoSlidingExpiration,\n Caching.CacheItemPriority.Default,\n null);\n\n }\n\n return (ArrayList)context.Cache[controllerName + \"_\" + actionName+ \"_ActionAttributes\"]; \n }\n\n public static bool IsAccessibleToUser(string actionToAuthorize, string controllerToAuthorize, HttpContext context)\n {\n IPrincipal principal = context.User;\n\n //cache the attribute list for both controller class and it's methods\n\n ArrayList controllerAttributes = GetControllerAttributes(controllerToAuthorize, context);\n\n ArrayList actionAttributes = GetMethodAttributes(controllerToAuthorize, actionToAuthorize, context); \n\n if (controllerAttributes.Count == 0 && actionAttributes.Count == 0)\n return true;\n\n string roles = \"\";\n string users = \"\";\n if (controllerAttributes.Count > 0)\n {\n AuthorizeAttribute attribute = controllerAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n if (actionAttributes.Count > 0)\n {\n AuthorizeAttribute attribute = actionAttributes[0] as AuthorizeAttribute;\n roles += attribute.Roles;\n users += attribute.Users;\n }\n\n if (string.IsNullOrEmpty(roles) && string.IsNullOrEmpty(users) && principal.Identity.IsAuthenticated)\n return true;\n\n string[] roleArray = roles.Split(',');\n string[] usersArray = users.Split(',');\n foreach (string role in roleArray)\n {\n if (role == \"*\" || principal.IsInRole(role))\n return true;\n }\n foreach (string user in usersArray)\n {\n if (user == \"*\" && (principal.Identity.Name == user))\n return true;\n }\n return false;\n }\n\n private static Type GetControllerType(string controllerName)\n {\n Assembly assembly = Assembly.GetExecutingAssembly();\n foreach (Type type in assembly.GetTypes())\n {\n if (\n type.BaseType!=null \n && type.BaseType.Name == \"Controller\" \n && (type.Name.ToUpper() == (controllerName.ToUpper() + \"Controller\".ToUpper())))\n {\n return type;\n }\n }\n return null;\n }\n\n }\n}\n"
},
{
"answer_id": 358259,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "static string Format( this string str,\n , params Expression<Func<string,object>>[] args)\n{\n var parameters = args.ToDictionary\n ( e=>string.Format(\"{{{0}}}\",e.Parameters[0].Name)\n , e=>e.Compile()(e.Parameters[0].Name));\n\n var sb = new StringBuilder(str);\n foreach(var kv in parameters)\n {\n sb.Replace( kv.Key\n , kv.Value != null ? kv.Value.ToString() : \"\");\n }\n\n return sb.ToString();\n}\n"
},
{
"answer_id": 375076,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "collection.Add(item1, item2, itemN);"
},
{
"answer_id": 398308,
"author": "Mark Maxham",
"author_id": 49737,
"author_profile": "https://Stackoverflow.com/users/49737",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Replace \"Enumerable.Range(n)\" with \"n.Range()\":\n/// </summary>\n/// <param name=\"n\">iterations</param>\n/// <returns>0..n-1</returns>\npublic static IEnumerable<int> Range(this int n)\n{\n for (int i = 0; i < n; i++)\n yield return i;\n}\n"
},
{
"answer_id": 398423,
"author": "Mark Maxham",
"author_id": 49737,
"author_profile": "https://Stackoverflow.com/users/49737",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// same as python 'join'\n/// </summary>\n/// <typeparam name=\"T\">list type</typeparam>\n/// <param name=\"separator\">string separator </param>\n/// <param name=\"list\">list of objects to be ToString'd</param>\n/// <returns>a concatenated list interleaved with separators</returns>\nstatic public string Join<T>(this string separator, IEnumerable<T> list)\n{\n var sb = new StringBuilder();\n bool first = true;\n\n foreach (T v in list)\n {\n if (!first)\n sb.Append(separator);\n first = false;\n\n if (v != null)\n sb.Append(v.ToString());\n }\n\n return sb.ToString();\n}\n"
},
{
"answer_id": 414561,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public static Dictionary<string, object> ToDictionary(this object o)\n{\n var dictionary = new Dictionary<string, object>();\n\n foreach (var propertyInfo in o.GetType().GetProperties())\n {\n if (propertyInfo.GetIndexParameters().Length == 0)\n {\n dictionary.Add(propertyInfo.Name, propertyInfo.GetValue(o, null));\n }\n }\n\n return dictionary;\n}\n"
},
{
"answer_id": 423447,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "// Calls the underlying int.TryParse method to convert a string\n// representation of a number to its 32-bit signed integer equivalent.\n// Returns Zero if conversion fails. \npublic static int ToInt32(this string s)\n{\n int retInt;\n int.TryParse(s, out retInt);\n return retInt;\n}\n"
},
{
"answer_id": 423553,
"author": "Chris",
"author_id": 52811,
"author_profile": "https://Stackoverflow.com/users/52811",
"pm_score": 0,
"selected": false,
"text": "// Values ordered true/false\n// True/false values separated by a capital letter\n// Only two values allowed\n// ---------------------------\n// Limited, but could be useful\npublic enum BooleanFormat\n{\n OneZero,\n YN,\n YesNo,\n TF,\n TrueFalse,\n PassFail,\n YepNope\n}\n\npublic static class BooleanExtension\n{\n /// <summary>\n /// Converts the boolean value of this instance to the specified string value. \n /// </summary>\n private static string ToString(this bool value, string passValue, string failValue)\n {\n return value ? passValue : failValue;\n }\n\n /// <summary>\n /// Converts the boolean value of this instance to a string. \n /// </summary>\n /// <param name=\"booleanFormat\">A BooleanFormat value. \n /// Example: BooleanFormat.PassFail would return \"Pass\" if true and \"Fail\" if false.</param>\n /// <returns>Boolean formatted string</returns>\n public static string ToString(this bool value, BooleanFormat booleanFormat)\n {\n string booleanFormatString = Enum.GetName(booleanFormat.GetType(), booleanFormat);\n return ParseBooleanString(value, booleanFormatString); \n }\n\n // Parses boolean format strings, not optimized\n private static string ParseBooleanString(bool value, string booleanFormatString)\n {\n StringBuilder trueString = new StringBuilder();\n StringBuilder falseString = new StringBuilder();\n\n int charCount = booleanFormatString.Length;\n\n bool isTrueString = true;\n\n for (int i = 0; i != charCount; i++)\n {\n if (char.IsUpper(booleanFormatString[i]) && i != 0)\n isTrueString = false;\n\n if (isTrueString)\n trueString.Append(booleanFormatString[i]);\n else\n falseString.Append(booleanFormatString[i]);\n }\n\n return (value == true ? trueString.ToString() : falseString.ToString());\n }\n"
},
{
"answer_id": 423555,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 1,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n var z = 0;\n var a = 0.AsDefaultFor(() => 1 / z);\n Console.WriteLine(a);\n Console.ReadLine();\n }\n}\n\npublic static class TryExtensions\n{\n public static T AsDefaultFor<T>(this T @this, Func<T> operation)\n {\n try\n {\n return operation();\n }\n catch\n {\n return @this;\n }\n }\n}\n"
},
{
"answer_id": 450208,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 5,
"selected": false,
"text": "public static void With<T>(this T obj, Action<T> act) { act(obj); }\n"
},
{
"answer_id": 572953,
"author": "andleer",
"author_id": 64262,
"author_profile": "https://Stackoverflow.com/users/64262",
"pm_score": 1,
"selected": false,
"text": "var query = dc.Reviewer \n .Where(r => r.FacilityID == facilityID) \n .WhereIf(CheckBoxActive.Checked, r => r.IsActive); \n\npublic static IEnumerable<TSource> WhereIf<TSource>(\n this IEnumerable<TSource> source,\n bool condition, Func<TSource, bool> predicate) \n{ \n if (condition) \n return source.Where(predicate); \n else \n return source; \n}\n\npublic static IQueryable<TSource> WhereIf<TSource>(\n this IQueryable<TSource> source,\n bool condition, Expression<Func<TSource, bool>> predicate) \n{ \n if (condition) \n return source.Where(predicate); \n else \n return source; \n}\n"
},
{
"answer_id": 572978,
"author": "andleer",
"author_id": 64262,
"author_profile": "https://Stackoverflow.com/users/64262",
"pm_score": 1,
"selected": false,
"text": "public static Int32? AsInt32(this string s)\n{\n Int32 value;\n if (Int32.TryParse(s, out value))\n return value;\n\n return null;\n}\n\npublic static bool IsInt32(this string s)\n{\n return s.AsInt32().HasValue;\n}\n\npublic static Int32 ToInt32(this string s)\n{\n return Int32.Parse(s);\n{\n"
},
{
"answer_id": 833363,
"author": "Stefan Steinegger",
"author_id": 2658202,
"author_profile": "https://Stackoverflow.com/users/2658202",
"pm_score": 2,
"selected": false,
"text": "public static string GetMemberName<T, TResult>(\n this T anyObject, \n Expression<Func<T, TResult>> expression)\n{\n return ((MemberExpression)expression.Body).Member.Name;\n}\n"
},
{
"answer_id": 833477,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 8,
"selected": false,
"text": "public static bool In<T>(this T source, params T[] list)\n{\n if(null==source) throw new ArgumentNullException(\"source\");\n return list.Contains(source);\n}\n"
},
{
"answer_id": 858681,
"author": "Joel Mueller",
"author_id": 24380,
"author_profile": "https://Stackoverflow.com/users/24380",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Creates an <see cref=\"IComparer{T}\"/> instance for the given\n/// delegate function.\n/// </summary>\ninternal class ComparerFactory<T> : IComparer<T>\n{\n public static IComparer<T> Create(Func<T, T, int> comparison)\n {\n return new ComparerFactory<T>(comparison);\n }\n\n private readonly Func<T, T, int> _comparison;\n\n private ComparerFactory(Func<T, T, int> comparison)\n {\n _comparison = comparison;\n }\n\n #region IComparer<T> Members\n\n public int Compare(T x, T y)\n {\n return _comparison(x, y);\n }\n\n #endregion\n}\n"
},
{
"answer_id": 953674,
"author": "Manish Basantani",
"author_id": 93613,
"author_profile": "https://Stackoverflow.com/users/93613",
"pm_score": 0,
"selected": false,
"text": "// Checks for an empty collection, and sends the value set in the default constructor for the desired field\npublic static TResult MinGuarded<T, TResult>(this IEnumerable<T> items, Func<T, TResult> expression) where T : new() {\n if(items.IsEmpty()) {\n return (new List<T> { new T() }).Min(expression);\n }\n return items.Min(expression);\n}\n\n// Checks for an empty collection, and sends the value set in the default constructor for the desired field\npublic static TResult MaxGuarded<T, TResult>(this IEnumerable<T> items, Func<T, TResult> expression) where T : new() {\n if(items.IsEmpty()) {\n return (new List<T> { new T() }).Max(expression);\n }\n return items.Max(expression);\n}\n"
},
{
"answer_id": 958020,
"author": "Vasu Balakrishnan",
"author_id": 1879756,
"author_profile": "https://Stackoverflow.com/users/1879756",
"pm_score": 4,
"selected": false,
"text": "public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> pSeq)\n{\n return pSeq ?? Enumerable.Empty<T>();\n}\n"
},
{
"answer_id": 1110456,
"author": "Fredy Treboux",
"author_id": 55154,
"author_profile": "https://Stackoverflow.com/users/55154",
"pm_score": 1,
"selected": false,
"text": "obj.SafelyNavigate(x => x.SomeProperty.MaybeAMethod().AnotherProperty);\n"
},
{
"answer_id": 1130145,
"author": "Kenny Eliasson",
"author_id": 107342,
"author_profile": "https://Stackoverflow.com/users/107342",
"pm_score": 3,
"selected": false,
"text": "List<Person>"
},
{
"answer_id": 1251338,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 4,
"selected": false,
"text": "byte[] buffer = File.ReadAllBytes(@\"C:\\file.txt\");\nstring content = buffer.GetString();\n"
},
{
"answer_id": 1394563,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 1,
"selected": false,
"text": "StringBuilder"
},
{
"answer_id": 1434207,
"author": "John Kraft",
"author_id": 7495,
"author_profile": "https://Stackoverflow.com/users/7495",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNull(this object o){\n return o == null;\n}\n"
},
{
"answer_id": 1460681,
"author": "Konamiman",
"author_id": 4574,
"author_profile": "https://Stackoverflow.com/users/4574",
"pm_score": 3,
"selected": false,
"text": "public static void Show(this UIElement element)\n{\n element.Visibility = Visibility.Visible;\n}\n\npublic static void Hide(this UIElement element)\n{\n element.Visibility = Visibility.Collapsed;\n}\n"
},
{
"answer_id": 1512463,
"author": "Omar",
"author_id": 160823,
"author_profile": "https://Stackoverflow.com/users/160823",
"pm_score": 2,
"selected": false,
"text": "toLength"
},
{
"answer_id": 1543566,
"author": "Paolo Tedesco",
"author_id": 15622,
"author_profile": "https://Stackoverflow.com/users/15622",
"pm_score": 5,
"selected": false,
"text": "public static class Extensions {\n public static int K(this int value) {\n return value * 1024;\n }\n public static int M(this int value) {\n return value * 1024 * 1024;\n }\n}\n\npublic class Program {\n public void Main() {\n WSHttpContextBinding serviceMultipleTokenBinding = new WSHttpContextBinding() {\n MaxBufferPoolSize = 2.M(), // instead of 2097152\n MaxReceivedMessageSize = 64.K(), // instead of 65536\n };\n }\n}\n"
},
{
"answer_id": 1662833,
"author": "Greg",
"author_id": 12971,
"author_profile": "https://Stackoverflow.com/users/12971",
"pm_score": 2,
"selected": false,
"text": "public static T FindControl<T>(this Control control, string id) where T : Control\n{\n return (T)control.FindControl(id);\n}\n"
},
{
"answer_id": 1662892,
"author": "Greg",
"author_id": 12971,
"author_profile": "https://Stackoverflow.com/users/12971",
"pm_score": 1,
"selected": false,
"text": "out"
},
{
"answer_id": 1742953,
"author": "Dan Diplo",
"author_id": 140392,
"author_profile": "https://Stackoverflow.com/users/140392",
"pm_score": 1,
"selected": false,
"text": "public static bool TryParse<T>(this Control control, string id, out T result) \n where T : Control\n{\n result = control.FindControl(id) as T;\n return result != null;\n}\n"
},
{
"answer_id": 1766663,
"author": "Juliet",
"author_id": 40516,
"author_profile": "https://Stackoverflow.com/users/40516",
"pm_score": 5,
"selected": false,
"text": "public static class PaulaBean\n{\n private static String paula = \"Brillant\";\n public static String GetPaula<T>(this T obj) {\n return paula;\n }\n}\n"
},
{
"answer_id": 1766799,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 3,
"selected": false,
"text": "public static T BinarySearch<T, TKey>(this IList<T> list, Func<T, TKey> keySelector, TKey key)\n where TKey : IComparable<TKey>\n{\n int min = 0;\n int max = list.Count;\n int index = 0;\n while (min < max)\n {\n int mid = (max + min) / 2;\n T midItem = list[mid];\n TKey midKey = keySelector(midItem);\n int comp = midKey.CompareTo(key);\n if (comp < 0)\n {\n min = mid + 1;\n }\n else if (comp > 0)\n {\n max = mid - 1;\n }\n else\n {\n return midItem;\n }\n }\n if (min == max &&\n keySelector(list[min]).CompareTo(key) == 0)\n {\n return list[min];\n }\n throw new InvalidOperationException(\"Item not found\");\n}\n"
},
{
"answer_id": 1767863,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": " public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> selector)\n {\n if (first == null)\n throw new ArgumentNullException(\"first\");\n if (second == null)\n throw new ArgumentNullException(\"second\");\n if (selector == null)\n throw new ArgumentNullException(\"selector\");\n\n using (var enum1 = first.GetEnumerator())\n using (var enum2 = second.GetEnumerator())\n {\n while (enum1.MoveNext() && enum2.MoveNext())\n {\n yield return selector(enum1.Current, enum2.Current);\n }\n }\n }\n"
},
{
"answer_id": 1767920,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 0,
"selected": false,
"text": "internal static class SortingHelpers\n{\n /// <summary>\n /// Performs an insertion sort on this list.\n /// </summary>\n /// <typeparam name=\"T\">The type of the list supplied.</typeparam>\n /// <param name=\"list\">the list to sort.</param>\n /// <param name=\"comparison\">the method for comparison of two elements.</param>\n /// <returns></returns>\n public static void InsertionSort<T>(this IList<T> list, Comparison<T> comparison)\n {\n for (int i = 2; i < list.Count; i++)\n {\n for (int j = i; j > 1 && comparison(list[j], list[j - 1]) < 0; j--)\n {\n T tempItem = list[j];\n list.RemoveAt(j);\n list.Insert(j - 1, tempItem);\n }\n }\n }\n}\n"
},
{
"answer_id": 1804870,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 0,
"selected": false,
"text": "List<dynamic>"
},
{
"answer_id": 1804876,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 2,
"selected": false,
"text": "public static string WrapAt(this string str, int WrapPos)\n{\n if (string.IsNullOrEmpty(str))\n throw new ArgumentNullException(\"str\", \"Cannot wrap a null string\");\n str = str.Replace(\"\\r\", \"\").Replace(\"\\n\", \"\");\n\n if (str.Length <= WrapPos)\n return str;\n\n for (int i = str.Length; i >= 0; i--)\n if (i % WrapPos == 0 && i > 0 && i != str.Length)\n str = str.Insert(i, \"\\r\\n\");\n return str;\n}\n"
},
{
"answer_id": 1804880,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": -1,
"selected": false,
"text": "/// <summary>Gets the root domain of any URI</summary>\n/// <param name=\"uri\">URI to get root domain of</param>\n/// <returns>Root domain with TLD</returns>\npublic static string GetRootDomain(this System.Uri uri)\n{\n if (uri == null)\n return null;\n\n string Domain = uri.Host;\n while (System.Text.RegularExpressions.Regex.Matches(Domain, @\"[\\.]\").Count > 1)\n Domain = Domain.Substring(Domain.IndexOf('.') + 1);\n Domain = Domain.Substring(0, Domain.IndexOf('.'));\n return Domain;\n}\n"
},
{
"answer_id": 1804940,
"author": "CaffGeek",
"author_id": 54746,
"author_profile": "https://Stackoverflow.com/users/54746",
"pm_score": 0,
"selected": false,
"text": "using (DataSet ds = yourcall()) \n{\n if (ds.HasRows())\n {\n foreach (DataRow dr in ds.Tables[0].Rows)\n {\n int id = dr.Field<int>(\"ID\");\n string name = dr.Field<string>(\"Name\");\n string Action = dr.Field<string>(\"Action\", \"N/A\");\n }\n }\n}\n"
},
{
"answer_id": 1812003,
"author": "Matt Kocaj",
"author_id": 56145,
"author_profile": "https://Stackoverflow.com/users/56145",
"pm_score": 1,
"selected": false,
"text": "null"
},
{
"answer_id": 1969365,
"author": "Kaveh Shahbazian",
"author_id": 54467,
"author_profile": "https://Stackoverflow.com/users/54467",
"pm_score": 2,
"selected": false,
"text": "// the most beloved extension method for me is Pipe:\n<%= variable.Pipe(x => this.SomeFunction(x)).Pipe(y =>\n{\n ...;\n return this.SomeOtherFunction(y);\n}) %>\n\nvar d = 28.December(2009); // some extension methods for creating DateTime\nDateTime justDatePart = d.JustDate();\nTimeSpan justTimePart = d.JustTime();\nvar nextTime = d.Add(5.Hours());\n\nusing(StreamReader reader = new StreamReader(\"lines-of-data-file-for-example\")) {\n ...\n // for reading streams line by line and usable in LINQ\n var query = from line in reader.Lines(); \n where line.Contains(_today)\n select new { Parts = PartsOf(line), Time = _now };\n}\n\n500.Sleep();\n\nXmlSerialize and XmlDeserialize\n\nIsNull and IsNotNull\n\nIfTrue, IfFalse and Iff:\ntrue.IfTrue(() => Console.WriteLine(\"it is true then!\");\n\nIfNull and IfNotNull\n"
},
{
"answer_id": 1969663,
"author": "moomi",
"author_id": 50949,
"author_profile": "https://Stackoverflow.com/users/50949",
"pm_score": 1,
"selected": false,
"text": "private bool CreateMode;\nprivate MyClass SomeClass;\n\nprotected override void OnInit (EventArgs e)\n{\n CreateMode = Session.GetSessionValue<bool> (\"someKey1\", () => true);\n SomeClass = Session.GetSessionClass<MyClass> (\"someKey2\", () => new MyClass () \n { \n MyProperty = 123 \n });\n}\n"
},
{
"answer_id": 2016298,
"author": "jpbochi",
"author_id": 123897,
"author_profile": "https://Stackoverflow.com/users/123897",
"pm_score": 3,
"selected": false,
"text": "IEnumerable<>"
},
{
"answer_id": 2153244,
"author": "Gideon",
"author_id": 82004,
"author_profile": "https://Stackoverflow.com/users/82004",
"pm_score": 2,
"selected": false,
"text": "if"
},
{
"answer_id": 2212077,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 3,
"selected": false,
"text": "XmlSerializable"
},
{
"answer_id": 2277064,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static class StringHelper\n{\n public static String F(this String str, params object[] args)\n {\n return String.Format(str, args);\n }\n}\n"
},
{
"answer_id": 2277084,
"author": "moribvndvs",
"author_id": 64750,
"author_profile": "https://Stackoverflow.com/users/64750",
"pm_score": 2,
"selected": false,
"text": "String.As<T>"
},
{
"answer_id": 2437499,
"author": "PhilChuang",
"author_id": 14392,
"author_profile": "https://Stackoverflow.com/users/14392",
"pm_score": 1,
"selected": false,
"text": "CloneableClass cc1 = new CloneableClass ();\nCloneableClass cc2 = null;\nCloneableClass cc3 = null;\n\ncc3 = (CloneableClass) cc1.Clone (); // this is ok\ncc3 = cc2.Clone (); // this throws null ref exception\n// code to handle both cases\ncc3 = cc1 != null ? (CloneableClass) cc1.Clone () : null;\n"
},
{
"answer_id": 2439537,
"author": "Dan Tao",
"author_id": 105570,
"author_profile": "https://Stackoverflow.com/users/105570",
"pm_score": 3,
"selected": false,
"text": "Random"
},
{
"answer_id": 2439988,
"author": "Janko R",
"author_id": 292466,
"author_profile": "https://Stackoverflow.com/users/292466",
"pm_score": 0,
"selected": false,
"text": "public static class DictionaryExtensions\n{\n public static Nullable<TValue> GetValueOrNull<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)\n where TValue : struct\n {\n TValue result;\n if (dictionary.TryGetValue(key, out result))\n return result;\n else\n return null;\n }\n}\n"
},
{
"answer_id": 2549153,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 3,
"selected": false,
"text": "public static bool EqualsIgnoreCase(this string a, string b)\n{\n return string.Equals(a, b, StringComparison.OrdinalIgnoreCase);\n}\n"
},
{
"answer_id": 2550726,
"author": "Max Toro",
"author_id": 39923,
"author_profile": "https://Stackoverflow.com/users/39923",
"pm_score": 4,
"selected": false,
"text": "DbCommand command = connection.CreateCommand();\ncommand.CommandText = \"SELECT @param\";\n\nDbParameter param = command.CreateParameter();\nparam.ParameterName = \"@param\";\nparam.Value = \"Hello World\";\n\ncommand.Parameters.Add(param);\n"
},
{
"answer_id": 2687774,
"author": "Mark Rushakoff",
"author_id": 126042,
"author_profile": "https://Stackoverflow.com/users/126042",
"pm_score": 3,
"selected": false,
"text": "InvokeRequired"
},
{
"answer_id": 2832683,
"author": "ytoledano",
"author_id": 245452,
"author_profile": "https://Stackoverflow.com/users/245452",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNullOrDefault<T>(this T? o) \n where T : struct\n{\n return o == null || o.Value.Equals(default(T));\n}\n"
},
{
"answer_id": 2844557,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": "public static T GetService<T>(this IServiceProvider provider)\n{\n return (T)provider.GetService(typeof(T));\n}\n"
},
{
"answer_id": 2959072,
"author": "Chao",
"author_id": 300996,
"author_profile": "https://Stackoverflow.com/users/300996",
"pm_score": 2,
"selected": false,
"text": "public static class nullpartials\n {\n public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)\n {\n if (Model == null)\n return helper.Partial(NullPartial);\n else\n return helper.Partial(Partial, Model);\n }\n\n public static MvcHtmlString NullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)\n {\n if (Model == null)\n return helper.Partial(NullPartial, viewdata);\n else\n return helper.Partial(Partial, Model, viewdata);\n }\n\n public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model)\n {\n if (Model == null)\n {\n helper.RenderPartial(NullPartial);\n return;\n }\n else\n {\n helper.RenderPartial(Partial, Model);\n return;\n }\n }\n\n public static void RenderNullPartial(this HtmlHelper helper, string Partial, string NullPartial, object Model, ViewDataDictionary viewdata)\n {\n if (Model == null)\n {\n helper.RenderPartial(NullPartial, viewdata);\n return;\n }\n else\n {\n helper.RenderPartial(Partial, Model, viewdata);\n return;\n }\n }\n }\n"
},
{
"answer_id": 2966853,
"author": "si618",
"author_id": 44540,
"author_profile": "https://Stackoverflow.com/users/44540",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Gets the key using <paramref name=\"caseInsensitiveKey\"/> from <paramref name=\"dictionary\"/>.\n/// </summary>\n/// <typeparam name=\"T\">The dictionary value.</typeparam>\n/// <param name=\"dictionary\">The dictionary.</param>\n/// <param name=\"caseInsensitiveKey\">The case insensitive key.</param>\n/// <returns>\n/// An existing key; or <see cref=\"string.Empty\"/> if not found.\n/// </returns>\npublic static string GetKeyIgnoringCase<T>(this IDictionary<string, T> dictionary, string caseInsensitiveKey)\n{\n if (string.IsNullOrEmpty(caseInsensitiveKey)) return string.Empty;\n foreach (string key in dictionary.Keys)\n {\n if (key.Equals(caseInsensitiveKey, StringComparison.InvariantCultureIgnoreCase))\n {\n return key;\n }\n }\n return string.Empty;\n}\n"
},
{
"answer_id": 3098630,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 1,
"selected": false,
"text": "public static void DelimitedAppend(this StringBuilder sb, string value, string delimiter)\n{\n if (sb.Length > 0)\n sb.Append(delimiter);\n sb.Append(value);\n}\n"
},
{
"answer_id": 3098674,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 3,
"selected": false,
"text": "public static class ExtensionMethods_Object\n{\n [DebuggerStepThrough()]\n public static bool Is<T>(this object item) where T : class\n {\n return item is T;\n }\n\n [DebuggerStepThrough()]\n public static bool IsNot<T>(this object item) where T : class\n {\n return !(item.Is<T>());\n }\n\n [DebuggerStepThrough()]\n public static T As<T>(this object item) where T : class\n {\n return item as T;\n }\n}\n"
},
{
"answer_id": 3132635,
"author": "John",
"author_id": 83091,
"author_profile": "https://Stackoverflow.com/users/83091",
"pm_score": 1,
"selected": false,
"text": "/// <summary>\n/// Returns the fiscal year for the passed in date\n/// </summary>\n/// <param name=\"value\">the date</param>\n/// <returns>the fiscal year</returns>\npublic static int FiscalYear(this DateTime value)\n{\n int ret = value.Year;\n if (value.Month >= 7) ret++;\n return ret;\n}\n\n/// <summary>\n/// Returns the fiscal year for the passed in date\n/// </summary>\n/// <param name=\"value\">the date</param>\n/// <returns>the fiscal year</returns>\npublic static string FiscalYearString(this DateTime value)\n{\n int fy = FiscalYear(value);\n return \"{0}/{1}\".Format(fy - 1, fy);\n}\n"
},
{
"answer_id": 3232611,
"author": "fre0n",
"author_id": 252004,
"author_profile": "https://Stackoverflow.com/users/252004",
"pm_score": 5,
"selected": false,
"text": "/// <summary>\n/// Returns whether the function is being executed during design time in Visual Studio.\n/// </summary>\npublic static bool IsDesignTime(this Control control)\n{\n if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n {\n return true;\n }\n\n if (control.Site != null && control.Site.DesignMode)\n {\n return true;\n }\n\n var parent = control.Parent;\n while (parent != null)\n {\n if (parent.Site != null && parent.Site.DesignMode)\n {\n return true;\n }\n parent = parent.Parent;\n }\n return false;\n}\n\n/// <summary>\n/// Sets the DropDownWidth to ensure that no item's text is cut off.\n/// </summary>\npublic static void SetDropDownWidth(this ComboBox comboBox)\n{\n var g = comboBox.CreateGraphics();\n var font = comboBox.Font;\n float maxWidth = 0;\n\n foreach (var item in comboBox.Items)\n {\n maxWidth = Math.Max(maxWidth, g.MeasureString(item.ToString(), font).Width);\n }\n\n if (comboBox.Items.Count > comboBox.MaxDropDownItems)\n {\n maxWidth += SystemInformation.VerticalScrollBarWidth;\n }\n\n comboBox.DropDownWidth = Math.Max(comboBox.Width, Convert.ToInt32(maxWidth));\n}\n"
},
{
"answer_id": 3237976,
"author": "Soonts",
"author_id": 126995,
"author_profile": "https://Stackoverflow.com/users/126995",
"pm_score": 0,
"selected": false,
"text": "// This file contains extension methods for generic List<> class to operate on sorted lists.\n// Duplicate values are OK.\n// O(ln(n)) is still much faster then the O(n) of LINQ's searches/filters.\nstatic partial class SortedList\n{\n // Return the index of the first element with the key greater then provided.\n // If there's no such element within the provided range, it returns iAfterLast.\n public static int sortedFirstGreaterIndex<tElt, tKey>( this IList<tElt> list, Func<tElt, tKey, int> comparer, tKey key, int iFirst, int iAfterLast )\n {\n if( iFirst < 0 || iAfterLast < 0 || iFirst > list.Count || iAfterLast > list.Count )\n throw new IndexOutOfRangeException();\n if( iFirst > iAfterLast )\n throw new ArgumentException();\n if( iFirst == iAfterLast )\n return iAfterLast;\n\n int low = iFirst, high = iAfterLast;\n // The code below is inspired by the following article:\n // http://en.wikipedia.org/wiki/Binary_search#Single_comparison_per_iteration\n while( low < high )\n {\n int mid = ( high + low ) / 2;\n // 'mid' might be 'iFirst' in case 'iFirst+1 == iAfterLast'.\n // 'mid' will never be 'iAfterLast'.\n if( comparer( list[ mid ], key ) <= 0 ) // \"<=\" since we gonna find the first \"greater\" element\n low = mid + 1;\n else\n high = mid;\n }\n return low;\n }\n\n // Return the index of the first element with the key greater then the provided key.\n // If there's no such element, returns list.Count.\n public static int sortedFirstGreaterIndex<tElt, tKey>( this IList<tElt> list, Func<tElt, tKey, int> comparer, tKey key )\n {\n return list.sortedFirstGreaterIndex( comparer, key, 0, list.Count );\n }\n\n // Add an element to the sorted array.\n // This could be an expensive operation if frequently adding elements that sort firstly.\n // This is cheap operation when adding elements that sort near the tail of the list.\n public static int sortedAdd<tElt>( this List<tElt> list, Func<tElt, tElt, int> comparer, tElt elt )\n {\n if( list.Count == 0 || comparer( list[ list.Count - 1 ], elt ) <= 0 )\n {\n // either the list is empty, or the item is greater then all elements already in the collection.\n list.Add( elt );\n return list.Count - 1;\n }\n int ind = list.sortedFirstGreaterIndex( comparer, elt );\n list.Insert( ind, elt );\n return ind;\n }\n\n // Find first exactly equal element, return -1 if not found.\n public static int sortedFindFirstIndex<tElt, tKey>( this List<tElt> list, Func<tElt, tKey, int> comparer, tKey elt )\n {\n int low = 0, high = list.Count - 1;\n\n while( low < high )\n {\n int mid = ( high + low ) / 2;\n if( comparer( list[ mid ], elt ) < 0 )\n low = mid + 1;\n else\n high = mid; // this includes the case when we've found an element exactly matching the key\n }\n if( high >= 0 && 0 == comparer( list[ high ], elt ) )\n return high;\n return -1;\n }\n\n // Return the IEnumerable that returns array elements in the reverse order.\n public static IEnumerable<tElt> sortedReverse<tElt>( this List<tElt> list )\n {\n for( int i=list.Count - 1; i >= 0; i-- )\n yield return list[ i ];\n }\n}\n"
},
{
"answer_id": 3282815,
"author": "Tadas Šukys",
"author_id": 135877,
"author_profile": "https://Stackoverflow.com/users/135877",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNullOrEmpty(this ICollection obj)\n{\n return (obj == null || obj.Count == 0);\n}\n"
},
{
"answer_id": 3317559,
"author": "stoic",
"author_id": 261257,
"author_profile": "https://Stackoverflow.com/users/261257",
"pm_score": 2,
"selected": false,
"text": "public static class DataTableConverter\n{\n /// <summary>\n /// Convert a List{T} to a DataTable.\n /// </summary>\n public static DataTable ToDataTable<T>(this IList<T> items)\n {\n var tb = new DataTable(typeof(T).Name);\n\n PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\n foreach (PropertyInfo prop in props)\n {\n Type t = GetCoreType(prop.PropertyType);\n tb.Columns.Add(prop.Name, t);\n }\n\n foreach (T item in items)\n {\n var values = new object[props.Length];\n\n for (int i = 0; i < props.Length; i++)\n {\n values[i] = props[i].GetValue(item, null);\n }\n\n tb.Rows.Add(values);\n }\n\n return tb;\n }\n\n /// <summary>\n /// Determine of specified type is nullable\n /// </summary>\n public static bool IsNullable(Type t)\n {\n return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));\n }\n\n /// <summary>\n /// Return underlying type if type is Nullable otherwise return the type\n /// </summary>\n public static Type GetCoreType(Type t)\n {\n if (t != null && IsNullable(t))\n {\n if (!t.IsValueType)\n {\n return t;\n }\n else\n {\n return Nullable.GetUnderlyingType(t);\n }\n }\n else\n {\n return t;\n }\n }\n}\n"
},
{
"answer_id": 3321163,
"author": "Krisc",
"author_id": 299946,
"author_profile": "https://Stackoverflow.com/users/299946",
"pm_score": 2,
"selected": false,
"text": "public static bool CompareEx(this string strA, string strB, CultureInfo culture, bool ignoreCase)\n{\n return string.Compare(strA, strB, ignoreCase, culture) == 0;\n}\n"
},
{
"answer_id": 3321394,
"author": "Kenneth J",
"author_id": 195456,
"author_profile": "https://Stackoverflow.com/users/195456",
"pm_score": 2,
"selected": false,
"text": "public static class MailExtension\n{\n // GetEmailCreditial(out strServer) gets credentials from an XML file\n public static void Send(this MailMessage email)\n {\n string strServer = String.Empty;\n NetworkCredential credentials = GetEmailCreditial(out strServer);\n SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };\n client.Send(email);\n }\n\n public static void Send(this IEnumerable<MailMessage> emails)\n {\n string strServer = String.Empty;\n NetworkCredential credentials = GetEmailCreditial(out strServer);\n SmtpClient client = new SmtpClient(strServer) { Credentials = credentials };\n foreach (MailMessage email in emails)\n client.Send(email);\n }\n}\n\n// Example of use: \nnew MailMessage(\"info@myDomain.com\",\"you@gmail.com\",\"This is an important Subject\", \"Body goes here\").Send();\n//Assume email1,email2,email3 are MailMessage objects\nnew List<MailMessage>(){email1, email2, email}.Send();\n"
},
{
"answer_id": 3423109,
"author": "Daniel A.A. Pelsmaeker",
"author_id": 146622,
"author_profile": "https://Stackoverflow.com/users/146622",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Returns a string representation of a byte array.\n/// </summary>\n/// <param name=\"bytearray\">The byte array to represent.</param>\n/// <param name=\"subdivision\">The number of elements per group,\n/// or 0 to not restrict it. The default is 0.</param>\n/// <param name=\"subsubdivision\">The number of elements per line,\n/// or 0 to not restrict it. The default is 0.</param>\n/// <param name=\"divider\">The string dividing the individual bytes. The default is \" \".</param>\n/// <param name=\"subdivider\">The string dividing the groups. The default is \" \".</param>\n/// <param name=\"subsubdivider\">The string dividing the lines. The default is \"\\r\\n\".</param>\n/// <param name=\"uppercase\">Whether the representation is in uppercase hexadecimal.\n/// The default is <see langword=\"true\"/>.</param>\n/// <param name=\"prebyte\">The string to put before each byte. The default is an empty string.</param>\n/// <param name=\"postbyte\">The string to put after each byte. The default is an empty string.</param>\n/// <returns>The string representation.</returns>\n/// <exception cref=\"ArgumentNullException\">\n/// <paramref name=\"bytearray\"/> is <see langword=\"null\"/>.\n/// </exception>\npublic static string ToArrayString(this byte[] bytearray,\n int subdivision = 0,\n int subsubdivision = 0,\n string divider = \" \",\n string subdivider = \" \",\n string subsubdivider = \"\\r\\n\",\n bool uppercase = true,\n string prebyte = \"\",\n string postbyte = \"\")\n{\n #region Contract\n if (bytearray == null)\n throw new ArgumentNullException(\"bytearray\");\n #endregion\n\n StringBuilder sb = new StringBuilder(\n bytearray.Length * (2 + divider.Length + prebyte.Length + postbyte.Length) +\n (subdivision > 0 ? (bytearray.Length / subdivision) * subdivider.Length : 0) +\n (subsubdivision > 0 ? (bytearray.Length / subsubdivision) * subsubdivider.Length : 0));\n int groupElements = (subdivision > 0 ? subdivision - 1 : -1);\n int lineElements = (subsubdivision > 0 ? subsubdivision - 1 : -1);\n for (long i = 0; i < bytearray.LongLength - 1; i++)\n {\n sb.Append(prebyte);\n sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? \"{0:X2}\" : \"{0:x2}\"), bytearray[i]));\n sb.Append(postbyte);\n\n if (lineElements == 0)\n {\n sb.Append(subsubdivider);\n groupElements = subdivision;\n lineElements = subsubdivision;\n }\n else if (groupElements == 0)\n {\n sb.Append(subdivider);\n groupElements = subdivision;\n }\n else\n sb.Append(divider);\n\n lineElements--;\n groupElements--;\n }\n sb.Append(prebyte);\n sb.Append(String.Format(CultureInfo.InvariantCulture, (uppercase ? \"{0:X2}\" : \"{0:x2}\"), bytearray[bytearray.LongLength - 1]));\n sb.Append(postbyte);\n\n return sb.ToString();\n}\n"
},
{
"answer_id": 3524142,
"author": "Luke Puplett",
"author_id": 107783,
"author_profile": "https://Stackoverflow.com/users/107783",
"pm_score": 1,
"selected": false,
"text": "public static string ToHtmlEncodedString(this string s)\n{\n if (String.IsNullOrEmpty(s))\n return s;\n return HttpUtility.HtmlEncode(s);\n}\n"
},
{
"answer_id": 3527407,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": "public static bool MatchesWildcard(this string text, string pattern)\n{\n int it = 0;\n while (text.CharAt(it) != 0 &&\n pattern.CharAt(it) != '*')\n {\n if (pattern.CharAt(it) != text.CharAt(it) && pattern.CharAt(it) != '?')\n return false;\n it++;\n }\n\n int cp = 0;\n int mp = 0;\n int ip = it;\n\n while (text.CharAt(it) != 0)\n {\n if (pattern.CharAt(ip) == '*')\n {\n if (pattern.CharAt(++ip) == 0)\n return true;\n mp = ip;\n cp = it + 1;\n }\n else if (pattern.CharAt(ip) == text.CharAt(it) || pattern.CharAt(ip) == '?')\n {\n ip++;\n it++;\n }\n else\n {\n ip = mp;\n it = cp++;\n }\n }\n\n while (pattern.CharAt(ip) == '*')\n {\n ip++;\n }\n return pattern.CharAt(ip) == 0;\n}\n\npublic static char CharAt(this string s, int index)\n{\n if (index < s.Length)\n return s[index];\n return '\\0';\n}\n"
},
{
"answer_id": 3576617,
"author": "fre0n",
"author_id": 252004,
"author_profile": "https://Stackoverflow.com/users/252004",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.\n/// </summary>\n/// <param name=\"someEvent\">The event to be invoked asynchronously.</param>\n/// <param name=\"sender\">The sender of the event.</param>\n/// <param name=\"args\">The args of the event.</param>\n/// <typeparam name=\"TEventArgs\">The type of <see cref=\"EventArgs\"/> to be used with the event.</typeparam>\npublic static void InvokeAsync<TEventArgs>(this EventHandler<TEventArgs> someEvent, object sender, TEventArgs args)\n where TEventArgs : EventArgs\n{\n if (someEvent == null)\n {\n return;\n }\n\n var eventListeners = someEvent.GetInvocationList();\n\n AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)\n {\n var ar = iar as AsyncResult;\n if (ar == null)\n {\n return;\n }\n\n var invokedMethod = ar.AsyncDelegate as EventHandler<TEventArgs>;\n if (invokedMethod != null)\n {\n invokedMethod.EndInvoke(iar);\n }\n };\n\n foreach (EventHandler<TEventArgs> methodToInvoke in eventListeners)\n {\n methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);\n }\n}\n\n/// <summary>\n/// Invoke an event asynchronously. Each subscriber to the event will be invoked on a separate thread.\n/// </summary>\n/// <param name=\"someEvent\">The event to be invoked asynchronously.</param>\n/// <param name=\"sender\">The sender of the event.</param>\n/// <param name=\"args\">The args of the event.</param>\npublic static void InvokeAsync(this EventHandler someEvent, object sender, EventArgs args)\n{\n if (someEvent == null)\n {\n return;\n }\n\n var eventListeners = someEvent.GetInvocationList();\n\n AsyncCallback endAsyncCallback = delegate(IAsyncResult iar)\n {\n var ar = iar as AsyncResult;\n if (ar == null)\n {\n return;\n }\n\n var invokedMethod = ar.AsyncDelegate as EventHandler;\n if (invokedMethod != null)\n {\n invokedMethod.EndInvoke(iar);\n }\n };\n\n foreach (EventHandler methodToInvoke in eventListeners)\n {\n methodToInvoke.BeginInvoke(sender, args, endAsyncCallback, null);\n }\n}\n"
},
{
"answer_id": 3690091,
"author": "prabir",
"author_id": 157260,
"author_profile": "https://Stackoverflow.com/users/157260",
"pm_score": 2,
"selected": false,
"text": "private static readonly DateTime EPOCH = DateTime.SpecifyKind(new DateTime(1970, 1, 1, 0, 0, 0, 0),DateTimeKind.Utc);\n\npublic static DateTime FromUnixTimestamp(long timestamp)\n{\n return EPOCH.AddSeconds(timestamp);\n}\n\npublic static long ToUnixTimestamp(DateTime date)\n{\n TimeSpan diff = date.ToUniversalTime() - EPOCH;\n return (long)diff.TotalSeconds;\n}\n\npublic static DateTime FromIso8601FormattedDateTime(string iso8601DateTime){\n return DateTime.ParseExact(iso8601DateTime, \"o\", System.Globalization.CultureInfo.InvariantCulture);\n}\n\npublic static string ToIso8601FormattedDateTime(DateTime dateTime)\n{\n return dateTime.ToString(\"o\");\n}\n"
},
{
"answer_id": 3757152,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 1,
"selected": false,
"text": "public static string Overwrite(this string s, int startIndex, string newStringValue)\n{\n return s.Remove(startIndex, newStringValue.Length).Insert(startIndex, newStringValue);\n}\n"
},
{
"answer_id": 3757160,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 3,
"selected": false,
"text": "public static bool IsFuture(this DateTime date, DateTime from)\n{\n return date.Date > from.Date;\n}\n\npublic static bool IsFuture(this DateTime date)\n{\n return date.IsFuture(DateTime.Now);\n}\n\npublic static bool IsPast(this DateTime date, DateTime from)\n{\n return date.Date < from.Date;\n}\n\npublic static bool IsPast(this DateTime date)\n{\n return date.IsPast(DateTime.Now);\n}\n"
},
{
"answer_id": 3834758,
"author": "mattmc3",
"author_id": 83144,
"author_profile": "https://Stackoverflow.com/users/83144",
"pm_score": 4,
"selected": false,
"text": "\"abc\".IsLike(\"a*\"); // true\n\"Abc\".IsLike(\"[A-Z][a-z][a-z]\"); // true\n\"abc123\".IsLike(\"*###\"); // true\n\"hat\".IsLike(\"?at\"); // true\n\"joe\".IsLike(\"[!aeiou]*\"); // true\n\n\"joe\".IsLike(\"?at\"); // false\n\"joe\".IsLike(\"[A-Z][a-z][a-z]\"); // false\n"
},
{
"answer_id": 3842545,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 4,
"selected": false,
"text": "// requires .NET 4\n\npublic static TReturn NullOr<TIn, TReturn>(this TIn obj, Func<TIn, TReturn> func,\n TReturn elseValue = default(TReturn)) where TIn : class\n { return obj != null ? func(obj) : elseValue; }\n\n// versions for CLR 2, which doesn't support optional params\n\npublic static TReturn NullOr<TIn, TReturn>(this TIn obj, Func<TIn, TReturn> func,\n TReturn elseValue) where TIn : class\n { return obj != null ? func(obj) : elseValue; }\npublic static TReturn NullOr<TIn, TReturn>(this TIn obj, Func<TIn, TReturn> func)\n where TIn : class\n { return obj != null ? func(obj) : default(TReturn); }\n"
},
{
"answer_id": 3932311,
"author": "RameshVel",
"author_id": 97572,
"author_profile": "https://Stackoverflow.com/users/97572",
"pm_score": 2,
"selected": false,
"text": "public static bool IsNullOrEmpty<TSource>(this List<TSource> src)\n{ \n return (src == null || src.Count == 0);\n}\n"
},
{
"answer_id": 3935547,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 3,
"selected": false,
"text": "public static IObservable<T> ToAsyncObservable<T>(this IEnumerable<T> @this)\n{\n return Observable.Create<T>(observer =>\n {\n var task = new Task(() =>\n {\n try\n {\n @this.Run(observer.OnNext);\n observer.OnCompleted();\n }\n catch (Exception e)\n {\n observer.OnError(e);\n }\n });\n\n task.Start();\n\n return () => { };\n });\n}\n"
},
{
"answer_id": 3936445,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 2,
"selected": false,
"text": "INotifyPropertyChanged"
},
{
"answer_id": 3940680,
"author": "Will Vousden",
"author_id": 58635,
"author_profile": "https://Stackoverflow.com/users/58635",
"pm_score": 2,
"selected": false,
"text": "public static void Raise(this EventHandler handler, object sender, EventArgs e)\n{\n if (handler != null)\n {\n handler(sender, e);\n }\n}\n\npublic static void Raise<T>(this EventHandler<T> handler, object sender, T e) where T : EventArgs\n{\n if (handler != null)\n {\n handler(sender, e);\n }\n}\n"
},
{
"answer_id": 3944491,
"author": "dejanb",
"author_id": 376044,
"author_profile": "https://Stackoverflow.com/users/376044",
"pm_score": 2,
"selected": false,
"text": "public static class ControlExtenders\n{\n /// <summary>\n /// Advanced version of find control.\n /// </summary>\n /// <typeparam name=\"T\">Type of control to find.</typeparam>\n /// <param name=\"id\">Control id to find.</param>\n /// <returns>Control of given type.</returns>\n /// <remarks>\n /// If the control with the given id is not found\n /// a new control instance of the given type is returned.\n /// </remarks>\n public static T FindControl<T>(this Control control, string id) where T : Control\n {\n // User normal FindControl method to get the control\n Control _control = control.FindControl(id);\n\n // If control was found and is of the correct type we return it\n if (_control != null && _control is T)\n {\n // Return new control\n return (T)_control;\n }\n\n // Create new control instance\n _control = (T)Activator.CreateInstance(typeof(T));\n\n // Add control to source control so the\n // next it is found and the value can be\n // passed on itd, remember to hide it and\n // set an ID so it can be found next time\n if (!(_control is ExtenderControlBase))\n {\n _control.Visible = false;\n }\n _control.ID = id;\n control.Controls.Add(_control);\n\n // Use reflection to create a new instance of the control\n return (T)_control;\n }\n}\n\npublic static class GenericListExtenders\n{\n /// <summary>\n /// Sorts a generic list by items properties.\n /// </summary>\n /// <typeparam name=\"T\">Type of collection.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n /// <param name=\"fieldName\">Field to sort data on.</param>\n /// <param name=\"sortDirection\">Sort direction.</param>\n /// <remarks>\n /// Use this method when a dinamyc sort field is requiered. If the \n /// sorting field is known manual sorting might improve performance.\n /// </remarks>\n public static void SortObjects<T>(this List<T> list, string fieldName, SortDirection sortDirection)\n {\n PropertyInfo propInfo = typeof(T).GetProperty(fieldName);\n if (propInfo != null)\n {\n Comparison<T> compare = delegate(T a, T b)\n {\n bool asc = sortDirection == SortDirection.Ascending;\n object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);\n object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);\n return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;\n };\n list.Sort(compare);\n }\n }\n\n /// <summary>\n /// Creates a pagged collection from generic list.\n /// </summary>\n /// <typeparam name=\"T\">Type of collection.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n /// <param name=\"sortField\">Field to sort data on.</param>\n /// <param name=\"sortDirection\">Sort direction.</param>\n /// <param name=\"from\">Page from item index.</param>\n /// <param name=\"to\">Page to item index.</param>\n /// <param name=\"copy\">Creates a copy and returns a new list instead of changing the current one.</param>\n /// <returns>Pagged list collection.</returns>\n public static List<T> Page<T>(this List<T> list, string sortField, bool sortDirection, int from, int to, bool copy)\n {\n List<T> _pageList = new List<T>();\n\n // Copy list\n if (copy)\n {\n T[] _arrList = new T[list.Count];\n list.CopyTo(_arrList);\n _pageList = new List<T>(_arrList);\n }\n else\n {\n _pageList = list;\n }\n\n // Make sure there are enough items in the list\n if (from > _pageList.Count)\n {\n int diff = Math.Abs(from - to);\n from = _pageList.Count - diff;\n }\n if (to > _pageList.Count)\n {\n to = _pageList.Count;\n }\n\n // Sort items\n if (!string.IsNullOrEmpty(sortField))\n {\n SortDirection sortDir = SortDirection.Descending;\n if (!sortDirection) sortDir = SortDirection.Ascending;\n _pageList.SortObjects(sortField, sortDir);\n }\n\n // Calculate max number of items per page\n int count = to - from;\n if (from + count > _pageList.Count) count -= (from + count) - _pageList.Count;\n\n // Get max number of items per page\n T[] pagged = new T[count];\n _pageList.CopyTo(from, pagged, 0, count);\n\n // Return pagged items\n return new List<T>(pagged);\n }\n\n /// <summary>\n /// Shuffle's list items.\n /// </summary>\n /// <typeparam name=\"T\">List type.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n public static void Shuffle<T>(this List<T> list)\n {\n Random rng = new Random();\n for (int i = list.Count - 1; i > 0; i--)\n {\n int swapIndex = rng.Next(i + 1);\n if (swapIndex != i)\n {\n T tmp = list[swapIndex];\n list[swapIndex] = list[i];\n list[i] = tmp;\n }\n }\n }\n\n /// <summary>\n /// Converts generic List to DataTable.\n /// </summary>\n /// <typeparam name=\"T\">Type.</typeparam>\n /// <param name=\"list\">Generic list.</param>\n /// <param name=\"columns\">Name of the columns to copy to the DataTable.</param>\n /// <returns>DataTable.</returns>\n public static DataTable ToDataTable<T>(this List<T> list, string[] columns)\n {\n List<string> _columns = new List<string>(columns);\n DataTable dt = new DataTable();\n\n foreach (PropertyInfo info in typeof(T).GetProperties())\n {\n if (_columns.Contains(info.Name) || columns == null)\n {\n dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));\n }\n }\n foreach (T t in list)\n {\n DataRow row = dt.NewRow();\n foreach (PropertyInfo info in typeof(T).GetProperties())\n {\n if (_columns.Contains(info.Name) || columns == null)\n {\n row[info.Name] = info.GetValue(t, null);\n }\n }\n dt.Rows.Add(row);\n }\n return dt;\n }\n}\n\npublic static class DateTimeExtenders\n{\n /// <summary>\n /// Returns number of month from a string representation.\n /// </summary>\n /// <returns>Number of month.</returns>\n public static int MonthToNumber(this DateTime datetime, string month)\n {\n month = month.ToLower();\n for (int i = 1; i <= 12; i++)\n {\n DateTime _dt = DateTime.Parse(\"1.\" + i + \".2000\");\n string _month = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i).ToLower();\n if (_month == month)\n {\n return i;\n }\n }\n return 0;\n }\n\n /// <summary>\n /// Returns month name from month number.\n /// </summary>\n /// <returns>Name of month.</returns>\n public static string MonthToName(this DateTime datetime, int month)\n {\n for (int i = 1; i <= 12; i++)\n {\n if (i == month)\n {\n return CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i);\n }\n }\n return \"\";\n }\n}\n\npublic static class ObjectExtender\n{\n public static object CloneBinary<T>(this T originalObject)\n {\n using (var stream = new System.IO.MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter();\n binaryFormatter.Serialize(stream, originalObject);\n stream.Position = 0;\n return (T)binaryFormatter.Deserialize(stream);\n }\n }\n\n public static object CloneObject(this object obj)\n {\n using (MemoryStream memStream = new MemoryStream())\n {\n BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));\n binaryFormatter.Serialize(memStream, obj);\n memStream.Position = 0;\n return binaryFormatter.Deserialize(memStream);\n }\n }\n}\n\npublic static class StringExtenders\n{\n /// <summary>\n /// Returns string as unit.\n /// </summary>\n /// <param name=\"value\">Value.</param>\n /// <returns>Unit</returns>\n public static Unit ToUnit(this string value)\n {\n // Return empty unit\n if (string.IsNullOrEmpty(value))\n return Unit.Empty;\n\n // Trim value\n value = value.Trim();\n\n // Return pixel unit\n if (value.EndsWith(\"px\"))\n {\n // Set unit type\n string _int = value.Replace(\"px\", \"\");\n\n // Try parsing to int\n double _val = 0;\n if (!double.TryParse(_int, out _val))\n {\n // Invalid value\n return Unit.Empty;\n }\n\n // Return unit\n return new Unit(_val, UnitType.Pixel);\n }\n\n // Return percent unit\n if (value.EndsWith(\"%\"))\n {\n // Set unit type\n string _int = value.Replace(\"%\", \"\");\n\n // Try parsing to int\n double _val = 0;\n if (!double.TryParse(_int, out _val))\n {\n // Invalid value\n return Unit.Empty;\n }\n\n // Return unit\n return new Unit(_val, UnitType.Percentage);\n }\n\n // No match found\n return new Unit();\n }\n\n /// <summary>\n /// Returns alternative string if current string is null or empty.\n /// </summary>\n /// <param name=\"str\"></param>\n /// <param name=\"alternative\"></param>\n /// <returns></returns>\n public static string Alternative(this string str, string alternative)\n {\n if (string.IsNullOrEmpty(str)) return alternative;\n return str;\n }\n\n /// <summary>\n /// Removes all HTML tags from string.\n /// </summary>\n /// <param name=\"html\">String containing HTML tags.</param>\n /// <returns>String with no HTML tags.</returns>\n public static string StripHTML(this string html)\n {\n string nohtml = Regex.Replace(html, \"<(.|\\n)*?>\", \"\");\n nohtml = nohtml.Replace(\"\\r\\n\", \"\").Replace(\"\\n\", \"\").Replace(\" \", \"\").Trim();\n return nohtml;\n }\n}\n"
},
{
"answer_id": 3973579,
"author": "KeithS",
"author_id": 436376,
"author_profile": "https://Stackoverflow.com/users/436376",
"pm_score": 2,
"selected": false,
"text": "public static class FluentOrderingExtensions\n public class FluentOrderer<T> : IEnumerable<T>\n {\n internal List<Comparison<T>> Comparers = new List<Comparison<T>>();\n\n internal IEnumerable<T> Source;\n\n public FluentOrderer(IEnumerable<T> source)\n {\n Source = source;\n }\n\n #region Implementation of IEnumerable\n\n public IEnumerator<T> GetEnumerator()\n {\n var workingArray = Source.ToArray();\n Array.Sort(workingArray, IterativeComparison);\n\n foreach(var element in workingArray) yield return element;\n }\n\n private int IterativeComparison(T a, T b)\n {\n foreach (var comparer in Comparers)\n {\n var result = comparer(a,b);\n if(result != 0) return result;\n }\n return 0;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n #endregion\n }\n\n public static FluentOrderer<T> OrderFluentlyBy<T,TResult>(this IEnumerable<T> source, Func<T,TResult> predicate) \n where TResult : IComparable<TResult>\n {\n var result = new FluentOrderer<T>(source);\n result.Comparers.Add((a,b)=>predicate(a).CompareTo(predicate(b)));\n return result;\n }\n\n public static FluentOrderer<T> OrderFluentlyByDescending<T,TResult>(this IEnumerable<T> source, Func<T,TResult> predicate) \n where TResult : IComparable<TResult>\n {\n var result = new FluentOrderer<T>(source);\n result.Comparers.Add((a,b)=>predicate(a).CompareTo(predicate(b)) * -1);\n return result;\n }\n\n public static FluentOrderer<T> ThenBy<T, TResult>(this FluentOrderer<T> source, Func<T, TResult> predicate)\n where TResult : IComparable<TResult>\n {\n source.Comparers.Add((a, b) => predicate(a).CompareTo(predicate(b)));\n return source;\n }\n\n public static FluentOrderer<T> ThenByDescending<T, TResult>(this FluentOrderer<T> source, Func<T, TResult> predicate)\n where TResult : IComparable<TResult>\n {\n source.Comparers.Add((a, b) => predicate(a).CompareTo(predicate(b)) * -1);\n return source;\n }\n}\n"
},
{
"answer_id": 3997753,
"author": "John",
"author_id": 83091,
"author_profile": "https://Stackoverflow.com/users/83091",
"pm_score": 0,
"selected": false,
"text": "public static class TypeExtensions\n{\n public static string GenerateClassDefinition(this Type type)\n {\n var properties = type.GetFields();\n var sb = new StringBuilder();\n var classtext = @\"private class $name\n {\n $props}\";\n\n foreach (var p in GetTypeInfo(type))\n {\n sb.AppendFormat(\" public {0} {1} \", p.Item2, p.Item1).AppendLine(\" { get; set; }\");\n }\n\n return classtext.Replace(\"$name\", type.Name).Replace(\"$props\", sb.ToString());\n }\n\n #region Private Methods\n private static List<Tuple<string, string>> GetTypeInfo(Type type)\n {\n var ret = new List<Tuple<string, string>>();\n var fields = type.GetFields();\n var props = type.GetProperties();\n\n foreach(var p in props) ret.Add(new Tuple<string, string>(p.Name, TranslateType(p.PropertyType))); \n foreach(var f in fields) ret.Add(new Tuple<string, string>(f.Name, TranslateType(f.FieldType)));\n\n return ret;\n }\n\n\n private static string TranslateType(Type input)\n {\n string ret;\n\n if (Nullable.GetUnderlyingType(input) != null)\n {\n ret = string.Format(\"{0}?\", TranslateType(Nullable.GetUnderlyingType(input)));\n }\n else\n {\n switch (input.Name)\n {\n case \"Int32\": ret = \"int\"; break;\n case \"Int64\": ret = \"long\"; break;\n case \"IntPtr\": ret = \"long\"; break;\n case \"Boolean\": ret = \"bool\"; break;\n case \"String\":\n case \"Char\":\n case \"Decimal\":\n ret = input.Name.ToLower(); break;\n default: ret = input.Name; break;\n }\n }\n\n return ret;\n }\n #endregion\n}\n"
},
{
"answer_id": 4001342,
"author": "KeithS",
"author_id": 436376,
"author_profile": "https://Stackoverflow.com/users/436376",
"pm_score": 3,
"selected": false,
"text": "public static T ObjectWithMin<T, TResult>(this IEnumerable<T> sequence, Func<T, TResult> predicate)\n where T : class\n where TResult : IComparable\n{\n if (!sequence.Any()) return null;\n\n //get the first object with its predicate value\n var seed = sequence.Select(x => new {Object = x, Value = predicate(x)}).FirstOrDefault();\n //compare against all others, replacing the accumulator with the lesser value\n //tie goes to first object found\n return\n sequence.Select(x => new {Object = x, Value = predicate(x)})\n .Aggregate(seed,(acc, x) => acc.Value.CompareTo(x.Value) <= 0 ? acc : x).Object;\n}\n\npublic static T ObjectWithMax<T, TResult>(this IEnumerable<T> sequence, Func<T, TResult> predicate)\n where T : class\n where TResult : IComparable\n{\n if (!sequence.Any()) return null;\n\n //get the first object with its predicate value\n var seed = sequence.Select(x => new {Object = x, Value = predicate(x)}).FirstOrDefault();\n //compare against all others, replacing the accumulator with the greater value\n //tie goes to last object found\n return\n sequence.Select(x => new {Object = x, Value = predicate(x)})\n .Aggregate(seed, (acc, x) => acc.Value.CompareTo(x.Value) > 0 ? acc : x).Object;\n}\n"
},
{
"answer_id": 4001549,
"author": "KeithS",
"author_id": 436376,
"author_profile": "https://Stackoverflow.com/users/436376",
"pm_score": 1,
"selected": false,
"text": "public enum ParseFailBehavior\n{\n ReturnNull,\n ReturnDefault,\n ThrowException\n}\n\npublic static T? ParseNullableEnum<T>(this string theValue, ParseFailBehavior desiredBehavior = ParseFailBehavior.ReturnNull) where T:struct\n{\n T output;\n T? result = Enum.TryParse<T>(theValue, out output) \n ? (T?)output\n : desiredBehavior == ParseFailBehavior.ReturnDefault\n ? (T?)default(T)\n : null;\n\n if(result == null && desiredBehavior == ParseFailBehavior.ThrowException)\n throw new ArgumentException(\"Parse Failed for value {0} of enum type {1}\".\n FormatWith(theValue, typeof(T).Name)); \n}\n"
},
{
"answer_id": 4152788,
"author": "Will Vousden",
"author_id": 58635,
"author_profile": "https://Stackoverflow.com/users/58635",
"pm_score": 2,
"selected": false,
"text": "public static T GetAttribute<T>(this ICustomAttributeProvider provider, bool inherit = false, int index = 0) where T : Attribute\n{\n return provider.GetAttribute(typeof(T), inherit, index) as T;\n}\n\npublic static Attribute GetAttribute(this ICustomAttributeProvider provider, Type type, bool inherit = false, int index = 0)\n{\n bool exists = provider.IsDefined(type, inherit);\n if (!exists)\n {\n return null;\n }\n\n object[] attributes = provider.GetCustomAttributes(type, inherit);\n if (attributes != null && attributes.Length != 0)\n {\n return attributes[index] as Attribute;\n }\n else\n {\n return null;\n }\n}\n"
},
{
"answer_id": 4178109,
"author": "Roman A. Taycher",
"author_id": 259130,
"author_profile": "https://Stackoverflow.com/users/259130",
"pm_score": 0,
"selected": false,
"text": "using System;\nnamespace SmalltalkBooleanExtensionMethods\n{\n\n public static class BooleanExtension\n {\n public static T ifTrue<T> (this bool aBoolean, Func<T> method)\n {\n if (aBoolean)\n return (T)method();\n else\n return default(T);\n }\n\n public static void ifTrue (this bool aBoolean, Action method)\n {\n if (aBoolean)\n method();\n }\n\n\n public static T ifFalse<T> (this bool aBoolean, Func<T> method)\n {\n if (!aBoolean)\n return (T)method();\n else\n return default(T);\n }\n\n public static void ifFalse (this bool aBoolean, Action method)\n {\n if (!aBoolean)\n method();\n }\n\n\n public static T ifTrueifFalse<T> (this Boolean aBoolean, Func<T> methodA, Func<T> methodB)\n {\n if (aBoolean)\n return (T)methodA();\n else\n return (T)methodB();\n }\n\n public static void ifTrueifFalse (this Boolean aBoolean, Action methodA, Action methodB)\n {\n if (aBoolean)\n methodA();\n else\n methodB();\n }\n\n }\n\n\n}\n"
},
{
"answer_id": 4339648,
"author": "Nicholas Carey",
"author_id": 467473,
"author_profile": "https://Stackoverflow.com/users/467473",
"pm_score": 1,
"selected": false,
"text": "namespace Extensions.String\n{\n using System.Text.RegularExpressions;\n\n public static class Extensions\n {\n /// <summary>\n /// Normalizes whitespace in a string.\n /// Leading/Trailing whitespace is eliminated and\n /// all sequences of internal whitespace are reduced to\n /// a single SP (ASCII 0x20) character.\n /// </summary>\n /// <param name=\"s\">The string whose whitespace is to be normalized</param>\n /// <returns>a normalized string</returns>\n public static string NormalizeWS( this string @this )\n {\n string src = @this ?? \"\" ;\n string normalized = rxWS.Replace( src , m =>{\n bool isLeadingTrailingWS = ( m.Index == 0 || m.Index+m.Length == src.Length ? true : false ) ;\n string p = ( isLeadingTrailingWS ? \"\" : \" \" ) ;\n return p ;\n }) ;\n\n return normalized ;\n\n }\n private static Regex rxWS = new Regex( @\"\\s+\" ) ;\n }\n}\n"
},
{
"answer_id": 4525903,
"author": "Chris",
"author_id": 553218,
"author_profile": "https://Stackoverflow.com/users/553218",
"pm_score": 0,
"selected": false,
"text": " public static class Utilities\n{\n public enum DropDownListSelectionType\n {\n ByValue,\n ByText\n }\n\n public static void SelectItem(this System.Web.UI.WebControls.DropDownList drp, string selectedValue, DropDownListSelectionType type)\n {\n drp.ClearSelection();\n System.Web.UI.WebControls.ListItem li;\n if (type == DropDownListSelectionType.ByValue)\n li = drp.Items.FindByValue(selectedValue.Trim());\n else\n li = drp.Items.FindByText(selectedValue.Trim());\n if (li != null)\n li.Selected = true;\n }}\n"
},
{
"answer_id": 4689138,
"author": "HuseyinUslu",
"author_id": 170181,
"author_profile": "https://Stackoverflow.com/users/170181",
"pm_score": 3,
"selected": false,
"text": "public static Bitmap GrayScale(this Bitmap bitmap)\n{\n Bitmap newBitmap = new Bitmap(bitmap.Width, bitmap.Height);\n Graphics g = Graphics.FromImage(newBitmap);\n\n //the grayscale ColorMatrix\n ColorMatrix colorMatrix = new ColorMatrix(new float[][] {\n new float[] {.3f, .3f, .3f, 0, 0},\n new float[] {.59f, .59f, .59f, 0, 0},\n new float[] {.11f, .11f, .11f, 0, 0},\n new float[] {0, 0, 0, 1, 0},\n new float[] {0, 0, 0, 0, 1}\n });\n\n ImageAttributes attributes = new ImageAttributes();\n attributes.SetColorMatrix(colorMatrix);\n g.DrawImage(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, attributes);\n g.Dispose();\n return newBitmap;\n}\n"
},
{
"answer_id": 4689170,
"author": "HuseyinUslu",
"author_id": 170181,
"author_profile": "https://Stackoverflow.com/users/170181",
"pm_score": 0,
"selected": false,
"text": "public static class InvokeExtensions\n{\n public static void InvokeHandler(this Control control, MethodInvoker del) // Sync. control-invoke extension.\n {\n if (control.InvokeRequired)\n {\n control.Invoke(del);\n return; \n }\n del(); // run the actual code.\n }\n\n public static void AsyncInvokeHandler(this Control control, MethodInvoker del) // Async. control-invoke extension.\n {\n if (control.InvokeRequired)\n {\n control.BeginInvoke(del);\n return; \n }\n del(); // run the actual code.\n }\n}\n"
},
{
"answer_id": 4690969,
"author": "19WAS85",
"author_id": 79191,
"author_profile": "https://Stackoverflow.com/users/79191",
"pm_score": 1,
"selected": false,
"text": "var names = new[] { \"Wagner\", \"Francine\", \"Arthur\", \"Bernardo\" };\n\nnames.ToString(\"Name: {0}\\n\");\n// Name: Wagner\n// Name: Francine\n// Name: Arthur\n// Name: Bernardo\n\nnames.ToString(name => name.Length > 6 ? String.Format(\"{0} \", name) : String.Empty);\n// Francine Bernardo\n\nnames.Join(\" - \");\n// Wagner - Francine - Arthur - Bernardo\n"
},
{
"answer_id": 4714651,
"author": "Shaul Behr",
"author_id": 7850,
"author_profile": "https://Stackoverflow.com/users/7850",
"pm_score": 2,
"selected": false,
"text": "out"
},
{
"answer_id": 4723915,
"author": "HuseyinUslu",
"author_id": 170181,
"author_profile": "https://Stackoverflow.com/users/170181",
"pm_score": 2,
"selected": false,
"text": "public static class ControlExtensions\n{\n public static void DoubleBuffer(this Control control) \n {\n // http://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form/77233#77233\n // Taxes: Remote Desktop Connection and painting: http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx\n\n if (System.Windows.Forms.SystemInformation.TerminalServerSession) return;\n System.Reflection.PropertyInfo dbProp = typeof(System.Windows.Forms.Control).GetProperty(\"DoubleBuffered\", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);\n dbProp.SetValue(control, true, null);\n }\n}\n"
},
{
"answer_id": 4838802,
"author": "Steve Potter",
"author_id": 574723,
"author_profile": "https://Stackoverflow.com/users/574723",
"pm_score": 2,
"selected": false,
"text": "new[] { \"first\", \"second\", \"third\" }.Each((value, index) =>\n{\n if (value.Contains(\"d\"))\n return false;\n Console.Write(value);\n return true;\n});\n"
},
{
"answer_id": 5569514,
"author": "fre0n",
"author_id": 252004,
"author_profile": "https://Stackoverflow.com/users/252004",
"pm_score": 0,
"selected": false,
"text": "Equals(object)"
},
{
"answer_id": 5709002,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "List<Order> orders = dataContext.Orders.FetchByIds(\n orderIdChunks,\n list => row => list.Contains(row.OrderId)\n);\n\nList<Customer> customers = dataContext.Orders.FetchByIds(\n orderIdChunks,\n list => row => list.Contains(row.OrderId),\n row => row.Customer\n);\n\npublic static List<ResultType> FetchByIds<RecordType, ResultType>(\n this IQueryable<RecordType> querySource,\n List<List<int>> IdChunks,\n Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator,\n Expression<Func<RecordType, ResultType>> projectionExpression\n ) where RecordType : class\n{\n List<ResultType> result = new List<ResultType>();\n foreach (List<int> chunk in IdChunks)\n {\n Expression<Func<RecordType, bool>> filterExpression =\n filterExpressionGenerator(chunk);\n\n IQueryable<ResultType> query = querySource\n .Where(filterExpression)\n .Select(projectionExpression);\n\n List<ResultType> rows = query.ToList();\n result.AddRange(rows);\n }\n\n return result;\n}\n\npublic static List<RecordType> FetchByIds<RecordType>(\n this IQueryable<RecordType> querySource,\n List<List<int>> IdChunks,\n Func<List<int>, Expression<Func<RecordType, bool>>> filterExpressionGenerator\n ) where RecordType : class\n{\n Expression<Func<RecordType, RecordType>> identity = r => r;\n\n return FetchByIds(\n querySource,\n IdChunks,\n filterExpressionGenerator,\n identity\n );\n}\n"
},
{
"answer_id": 5751106,
"author": "Chuck Savage",
"author_id": 353147,
"author_profile": "https://Stackoverflow.com/users/353147",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Open with default 'open' program\n/// </summary>\n/// <param name=\"value\"></param>\npublic static Process Open(this FileInfo value)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n Process p = new Process();\n p.StartInfo.FileName = value.FullName;\n p.StartInfo.Verb = \"Open\";\n p.Start();\n return p;\n}\n\n/// <summary>\n/// Print the file\n/// </summary>\n/// <param name=\"value\"></param>\npublic static void Print(this FileInfo value)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n Process p = new Process();\n p.StartInfo.FileName = value.FullName;\n p.StartInfo.Verb = \"Print\";\n p.Start();\n}\n\n/// <summary>\n/// Send this file to the Recycle Bin\n/// </summary>\n/// <exception cref=\"File doesn't exist\" />\n/// <param name=\"value\"></param>\npublic static void Recycle(this FileInfo value)\n{ \n value.Recycle(false);\n}\n\n/// <summary>\n/// Send this file to the Recycle Bin\n/// On show, if person refuses to send file to the recycle bin, \n/// exception is thrown or otherwise delete fails\n/// </summary>\n/// <exception cref=\"File doesn't exist\" />\n/// <exception cref=\"On show, if user refuses, throws exception 'The operation was canceled.'\" />\n/// <param name=\"value\">File being recycled</param>\n/// <param name=\"showDialog\">true to show pop-up</param>\npublic static void Recycle(this FileInfo value, bool showDialog)\n{\n if (!value.Exists)\n throw new FileNotFoundException(\"File doesn't exist\");\n if( showDialog )\n FileSystem.DeleteFile\n (value.FullName, UIOption.AllDialogs, \n RecycleOption.SendToRecycleBin);\n else\n FileSystem.DeleteFile\n (value.FullName, UIOption.OnlyErrorDialogs, \n RecycleOption.SendToRecycleBin);\n}\n"
},
{
"answer_id": 5913908,
"author": "John",
"author_id": 83091,
"author_profile": "https://Stackoverflow.com/users/83091",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Compares the files to see if they are different. \n/// First checks file size\n/// Then modified if the file is larger than the specified size\n/// Then compares the bytes\n/// </summary>\n/// <param name=\"file1\">The source file</param>\n/// <param name=\"file2\">The destination file</param>\n/// <param name=\"mb\">Skip the smart check if the file is larger than this many megabytes. Default is 10.</param>\n/// <returns></returns>\npublic static bool IsDifferentThan(this FileInfo file1, FileInfo file2, int mb = 10)\n{\n var ret = false;\n\n // different size is a different file\n if(file1.Length != file2.Length) return true;\n\n // if the file times are different and the file is bigger than 10mb flag it for updating\n if(file1.LastWriteTimeUtc > file2.LastWriteTimeUtc && file1.Length > ((mb*1024)*1024)) return true;\n\n var f1 = File.ReadAllBytes(file1.FullName);\n var f2 = File.ReadAllBytes(file2.FullName);\n\n // loop through backwards because if they are different\n // it is more likely that the last few bytes will be different\n // than the first few\n for(var i = file1.Length - 1; i > 0; i--)\n {\n if(f1[i] != f2[i])\n {\n ret = true;\n break;\n }\n }\n\n return ret;\n}\n"
},
{
"answer_id": 6031710,
"author": "takrl",
"author_id": 520044,
"author_profile": "https://Stackoverflow.com/users/520044",
"pm_score": 2,
"selected": false,
"text": "public static class ColorExtensions\n{\n // Gets a color that will be readable on top of a given background color\n public static Color GetForegroundColor(this Color input)\n {\n // Math taken from one of the replies to\n // http://stackoverflow.com/questions/2241447/make-foregroundcolor-black-or-white-depending-on-background\n if (Math.Sqrt(input.R * input.R * .241 + input.G * input.G * .691 + input.B * input.B * .068) > 128)\n return Color.Black;\n else\n return Color.White;\n }\n\n // Converts a given Color to gray\n public static Color ToGray(this Color input)\n {\n int g = (int)(input.R * .299) + (int)(input.G * .587) + (int)(input.B * .114);\n return Color.FromArgb(input.A, g, g, g);\n }\n}\n"
},
{
"answer_id": 6038212,
"author": "Gleno",
"author_id": 427673,
"author_profile": "https://Stackoverflow.com/users/427673",
"pm_score": 1,
"selected": false,
"text": "Convert.ChangeType"
},
{
"answer_id": 7089538,
"author": "NeverFade",
"author_id": 604351,
"author_profile": "https://Stackoverflow.com/users/604351",
"pm_score": 0,
"selected": false,
"text": "static public string ToFaString (this string value)\n {\n // 1728 , 1584\n string result = \"\";\n if (value != null)\n {\n char[] resChar = value.ToCharArray();\n for (int i = 0; i < resChar.Length; i++)\n {\n if (resChar[i] >= '0' && resChar[i] <= '9')\n result += (char)(resChar[i] + 1728);\n else\n result += resChar[i];\n }\n }\n return result;\n }\n"
},
{
"answer_id": 7089576,
"author": "NeverFade",
"author_id": 604351,
"author_profile": "https://Stackoverflow.com/users/604351",
"pm_score": 0,
"selected": false,
"text": " static public bool IsAllZero (this string input)\n {\n if(string.IsNullOrEmpty(input))\n return true;\n foreach (char ch in input)\n {\n if(ch != '0')\n return false;\n }\n return true;\n }\n"
},
{
"answer_id": 7201703,
"author": "sasjaq",
"author_id": 913610,
"author_profile": "https://Stackoverflow.com/users/913610",
"pm_score": 1,
"selected": false,
"text": "public static T Safe<T>(this T obj) where T : new()\n{\n if (obj == null)\n {\n obj = new T();\n }\n\n return obj;\n}\n"
},
{
"answer_id": 7201807,
"author": "sasjaq",
"author_id": 913610,
"author_profile": "https://Stackoverflow.com/users/913610",
"pm_score": 0,
"selected": false,
"text": " public static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0);\n\n public static long ToUnixTimestamp(this DateTime dateTime)\n {\n return (long) (dateTime - Epoch).TotalSeconds;\n }\n\n public static long ToUnixUltraTimestamp(this DateTime dateTime)\n {\n return (long) (dateTime - Epoch).TotalMilliseconds;\n }\n"
},
{
"answer_id": 7926954,
"author": "Otiel",
"author_id": 825024,
"author_profile": "https://Stackoverflow.com/users/825024",
"pm_score": 2,
"selected": false,
"text": "IndexOf"
},
{
"answer_id": 8068261,
"author": "jaekie",
"author_id": 1398964,
"author_profile": "https://Stackoverflow.com/users/1398964",
"pm_score": 1,
"selected": false,
"text": "public static string[] Split(this string value, string regexPattern)\n{\n return value.Split(regexPattern, RegexOptions.None);\n}\n\npublic static string[] Split(this string value, string regexPattern, \n RegexOptions options)\n{\n return Regex.Split(value, regexPattern, options);\n}\n"
},
{
"answer_id": 8472175,
"author": "Otiel",
"author_id": 825024,
"author_profile": "https://Stackoverflow.com/users/825024",
"pm_score": 2,
"selected": false,
"text": "List<MyObject> myObjects = new List<MyObject>() { \n new MyObject() {Name = \"a\", Id = 0}, \n new MyObject() {Name = \"b\", Id = 1}, \n new MyObject() {Name = \"c\", Id = 2} }\ncomboBox.FillDataSource<MyObject>(myObjects, x => x.Name);\n"
},
{
"answer_id": 9593534,
"author": "jerone",
"author_id": 108448,
"author_profile": "https://Stackoverflow.com/users/108448",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// Collection Helper\n/// </summary>\n/// <remarks>\n/// Use IEnumerable by default, but when altering or getting item at index use IList.\n/// </remarks>\npublic static class CollectionHelper\n{\n\n #region Alter;\n\n /// <summary>\n /// Swap item to another place\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"IndexA\">Index a</param>\n /// <param name=\"IndexB\">Index b</param>\n /// <returns>New collection</returns>\n public static IList<T> Swap<T>(this IList<T> @this, Int32 IndexA, Int32 IndexB)\n {\n T Temp = @this[IndexA];\n @this[IndexA] = @this[IndexB];\n @this[IndexB] = Temp;\n return @this;\n }\n\n /// <summary>\n /// Swap item to the left\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index</param>\n /// <returns>New collection</returns>\n public static IList<T> SwapLeft<T>(this IList<T> @this, Int32 Index)\n {\n return @this.Swap(Index, Index - 1);\n }\n\n /// <summary>\n /// Swap item to the right\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index</param>\n /// <returns>New collection</returns>\n public static IList<T> SwapRight<T>(this IList<T> @this, Int32 Index)\n {\n return @this.Swap(Index, Index + 1);\n }\n\n #endregion Alter;\n\n #region Action;\n\n /// <summary>\n /// Execute action at specified index\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index</param>\n /// <param name=\"ActionAt\">Action to execute</param>\n /// <returns>New collection</returns>\n public static IList<T> ActionAt<T>(this IList<T> @this, Int32 Index, Action<T> ActionAt)\n {\n ActionAt(@this[Index]);\n return @this;\n }\n\n #endregion Action;\n\n #region Randomize;\n\n /// <summary>\n /// Take random items\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Count\">Number of items to take</param>\n /// <returns>New collection</returns>\n public static IEnumerable<T> TakeRandom<T>(this IEnumerable<T> @this, Int32 Count)\n {\n return @this.Shuffle().Take(Count);\n }\n\n /// <summary>\n /// Take random item\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <returns>Item</returns>\n public static T TakeRandom<T>(this IEnumerable<T> @this)\n {\n return @this.TakeRandom(1).Single();\n }\n\n /// <summary>\n /// Shuffle list\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <returns>New collection</returns>\n public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> @this)\n {\n return @this.OrderBy(Item => Guid.NewGuid());\n }\n\n #endregion Randomize;\n\n #region Navigate;\n\n /// <summary>\n /// Get next item in collection and give first item, when last item is selected;\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index in collection</param>\n /// <returns>Next item</returns>\n public static T Next<T>(this IList<T> @this, ref Int32 Index)\n {\n Index = ++Index >= 0 && Index < @this.Count ? Index : 0;\n return @this[Index];\n }\n\n /// <summary>\n /// Get previous item in collection and give last item, when first item is selected;\n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Index\">Index in collection</param>\n /// <returns>Previous item</returns>\n public static T Previous<T>(this IList<T> @this, ref Int32 Index)\n {\n Index = --Index >= 0 && Index < @this.Count ? Index : @this.Count - 1;\n return @this[Index];\n }\n\n #endregion Navigate;\n\n #region Clone;\n\n /// <summary>\n /// \n /// </summary>\n /// <typeparam name=\"T\">Collection type</typeparam>\n /// <param name=\"this\">Collection</param>\n /// <returns>Cloned collection</returns>\n public static IEnumerable<T> Clone<T>(this IEnumerable<T> @this) where T : ICloneable\n {\n return @this.Select(Item => (T)Item.Clone());\n }\n\n #endregion Clone;\n\n #region String;\n\n /// <summary>\n /// Joins multiple string with Separator\n /// </summary>\n /// <param name=\"this\">Collection</param>\n /// <param name=\"Separator\">Separator</param>\n /// <returns>Joined string</returns>\n public static String Join(this IEnumerable<String> @this, String Separator = \"\")\n {\n return String.Join(Separator, @this);\n }\n\n #endregion String;\n\n}\n"
},
{
"answer_id": 9839800,
"author": "takrl",
"author_id": 520044,
"author_profile": "https://Stackoverflow.com/users/520044",
"pm_score": 0,
"selected": false,
"text": "public static bool IsWinXPOrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && ((OS.Version.Major > 5) || ((OS.Version.Major == 5) && (OS.Version.Minor >= 1)));\n}\n\npublic static bool IsWinVistaOrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && (OS.Version.Major >= 6);\n}\n\npublic static bool IsWin7OrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && ((OS.Version.Major > 6) || ((OS.Version.Major == 6) && (OS.Version.Minor >= 1)));\n}\n\npublic static bool IsWin8OrHigher(this OperatingSystem OS)\n{\n return (OS.Platform == PlatformID.Win32NT)\n && ((OS.Version.Major > 6) || ((OS.Version.Major == 6) && (OS.Version.Minor >= 2)));\n}\n"
},
{
"answer_id": 10042182,
"author": "Luke Puplett",
"author_id": 107783,
"author_profile": "https://Stackoverflow.com/users/107783",
"pm_score": 0,
"selected": false,
"text": " /// <summary>\n /// Adds the specified query parameter to the URI builder.\n /// </summary>\n /// <param name=\"builder\">The builder.</param>\n /// <param name=\"parameterName\">Name of the parameter.</param>\n /// <param name=\"value\">The URI escaped value.</param>\n /// <returns>The final full query string.</returns>\n public static string AddQueryParam(this UriBuilder builder, string parameterName, string value)\n {\n if (parameterName == null)\n throw new ArgumentNullException(\"parameterName\");\n\n if (parameterName.Length == 0)\n throw new ArgumentException(\"The parameter name is empty.\");\n\n if (value == null)\n throw new ArgumentNullException(\"value\");\n\n if (value.Length == 0)\n throw new ArgumentException(\"The value is empty.\");\n\n if (builder.Query.Length == 0)\n {\n builder.Query = String.Concat(parameterName, \"=\", value);\n }\n else if\n (builder.Query.Contains(String.Concat(\"&\", parameterName, \"=\"))\n || builder.Query.Contains(String.Concat(\"?\", parameterName, \"=\")))\n {\n throw new InvalidOperationException(String.Format(\"The parameter {0} already exists.\", parameterName));\n }\n else\n {\n builder.Query = String.Concat(builder.Query.Substring(1), \"&\", parameterName, \"=\", value);\n }\n\n return builder.Query;\n }\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11135/"
] |
271,406 | <p>I have a table in lua with some data.</p>
<pre><code>sometable = {
{name = "bob", something = "foo"},
{name = "greg", something = "bar"}
}
</code></pre>
<p>I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this.</p>
<pre><code>for i,t in ipairs(sometable) do
t.name = i
end
</code></pre>
<p>I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.</p>
| [
{
"answer_id": 274107,
"author": "Doug Currie",
"author_id": 33252,
"author_profile": "https://Stackoverflow.com/users/33252",
"pm_score": 3,
"selected": true,
"text": "> sometable = {{name = \"bob\", something = \"foo\"},{name = \"greg\", something = \"bar\"}}\n> for i,t in ipairs(sometable) do t[t.name] = i end\n> for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end \nname bob\nsomething foo\nbob 1\ngreg 2\nsomething bar\nname greg\n> return sometable[1].bob\n1>\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18933/"
] |
271,428 | <hr>
<p>Thanks for answers,Actually I am not puzzled about draw 1024*768 pixels is slower than 100* 100 pixels... It is so simple a logic..
Which made me puzzled is that DrawImage's interpolation algorithm may be very slow, while there exists lots of better algorithm, and its decoder seems can decode from a jpg with a certain resolution, it is really cool, I search for sometime but do not find any free lib to do this...</p>
<p>It is really strange!
I add the following code into on Paint method. c:\1.jpg is 5M jpg file, about 4000*3000</p>
<p>//--------------------------------------------------------------</p>
<pre><code>HDC hdc = pDC->GetSafeHdc();
bitmap = Bitmap::FromFile(L"c:\\1.jpg",true);
Graphics graphics(hdc);
graphics.SetInterpolationMode( InterpolationModeNearestNeighbor );
graphics.DrawImage(bitmap,0,0,200,200);
</code></pre>
<p>The above is really fast! even real time! I don't think decode a 5m JPG can be that fast!</p>
<p>//--------------------------------------------------------------</p>
<pre><code>HDC hdc = pDC->GetSafeHdc();
bitmap = Bitmap::FromFile(L"c:\\1.jpg",true);
Graphics graphics(hdc);
graphics.SetInterpolationMode( InterpolationModeNearestNeighbor );
graphics.DrawImage(bitmap,0,0,2000,2000);
</code></pre>
<p>The above code become really slow</p>
<p>//--------------------------------------------------------------</p>
<p>If I add Bitmap = Bitmap::FromFile(L"c:\1.jpg", true); // into construct</p>
<p>leave </p>
<pre><code> Graphics graphics(hdc);
graphics.SetInterpolationMode( InterpolationModeNearestNeighbor );
graphics.DrawImage(bitmap,0,0,2000,2000);
</code></pre>
<p>in OnPaint method,
The code is still a bit slow~~~</p>
<p>//------------------------------------------------------------------</p>
<p>Comparing with decoding, the drawImage Process is really slow...</p>
<p>Why and How did they do that? Did Microsoft pay the men taking charge of decoder double salary than the men taking charge of writing drawingImage?</p>
| [
{
"answer_id": 271463,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 3,
"selected": false,
"text": "graphics.DrawImage(bitmap,0,0,200,200);\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
271,438 | <p>I am having a .cs file, i need to execute that file..
I don't have experience in C#.. Please help.. Do we have to install any software to run it.. </p>
<p>Currently i am using windows XP.. </p>
<p>Please help me... </p>
| [
{
"answer_id": 272151,
"author": "Xiaofu",
"author_id": 31967,
"author_profile": "https://Stackoverflow.com/users/31967",
"pm_score": 0,
"selected": false,
"text": "csc /out:your_app_name.exe your_cs_filename.cs\n"
},
{
"answer_id": 53193120,
"author": "NanoWar",
"author_id": 1436044,
"author_profile": "https://Stackoverflow.com/users/1436044",
"pm_score": 1,
"selected": false,
"text": "@echo off\nIF \"%1\"==\"\" GOTO HELP\n\nREM => copy .net core project file into temp folder\nmkdir _temp 2>NUL\necho ^<Project Sdk=\"Microsoft.NET.Sdk.Web\"^>^<PropertyGroup^>^<TargetFramework^>netcoreapp2.0^</TargetFramework^>^</PropertyGroup^>^</Project^> > _temp\\p.csproj\ncopy %1 _temp 1>NUL\ncd _temp\n\nREM => run program\ndotnet run\n\nREM => clean-up\ncd ..\nrmdir /Q /S _temp 1>NUL\nGOTO EXIT\n\n:HELP\necho Runs any C# file with a static Main() directly\necho Usage: %0 [file.cs]\n\n:EXIT\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,440 | <p>I met an interesting issue about C#. I have code like below.</p>
<pre><code>List<Func<int>> actions = new List<Func<int>>();
int variable = 0;
while (variable < 5)
{
actions.Add(() => variable * 2);
++ variable;
}
foreach (var act in actions)
{
Console.WriteLine(act.Invoke());
}
</code></pre>
<p>I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.</p>
<p>It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.</p>
<p>Is there a way to work round this limit to have each action instance have its own captured variable?</p>
| [
{
"answer_id": 271447,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 9,
"selected": true,
"text": "while (variable < 5)\n{\n int copy = variable;\n actions.Add(() => copy * 2);\n ++ variable;\n}\n"
},
{
"answer_id": 271449,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 3,
"selected": false,
"text": "variable"
},
{
"answer_id": 271450,
"author": "Tyler Levine",
"author_id": 35339,
"author_profile": "https://Stackoverflow.com/users/35339",
"pm_score": 4,
"selected": false,
"text": "while( variable < 5 )\n{\n int copy = variable;\n actions.Add( () => copy * 2 );\n ++variable;\n}\n"
},
{
"answer_id": 4829027,
"author": "Sunil",
"author_id": 593932,
"author_profile": "https://Stackoverflow.com/users/593932",
"pm_score": 3,
"selected": false,
"text": "for (int counter = 1; counter <= 5; counter++)\n{\n new Thread (() => Console.Write (counter)).Start();\n}\n"
},
{
"answer_id": 15707665,
"author": "gerrard00",
"author_id": 1011470,
"author_profile": "https://Stackoverflow.com/users/1011470",
"pm_score": 4,
"selected": false,
"text": "void Main()\n{\n List<Func<int>> actions = new List<Func<int>>();\n\n int variable = 0;\n\n var closure = new CompilerGeneratedClosure();\n\n Func<int> anonymousMethodAction = null;\n\n while (closure.variable < 5)\n {\n if(anonymousMethodAction == null)\n anonymousMethodAction = new Func<int>(closure.YourAnonymousMethod);\n\n //we're re-adding the same function \n actions.Add(anonymousMethodAction);\n\n ++closure.variable;\n }\n\n foreach (var act in actions)\n {\n Console.WriteLine(act.Invoke());\n }\n}\n\nclass CompilerGeneratedClosure\n{\n public int variable;\n\n public int YourAnonymousMethod()\n {\n return this.variable * 2;\n }\n}\n"
},
{
"answer_id": 50837161,
"author": "Maverick Meerkat",
"author_id": 6296435,
"author_profile": "https://Stackoverflow.com/users/6296435",
"pm_score": 3,
"selected": false,
"text": "() => variable * 2"
},
{
"answer_id": 53744561,
"author": "Junaid Pathan",
"author_id": 8304176,
"author_profile": "https://Stackoverflow.com/users/8304176",
"pm_score": -1,
"selected": false,
"text": "List<Func<int>> actions = new List<Func<int>>();\n\nint variable = 0;\nwhile (variable < 5)\n{\n int i = variable;\n actions.Add(() => i * 2);\n ++ variable;\n}\n\nforeach (var act in actions)\n{\n Console.WriteLine(act.Invoke());\n}\n"
},
{
"answer_id": 60474255,
"author": "Nathan Chappell",
"author_id": 6084517,
"author_profile": "https://Stackoverflow.com/users/6084517",
"pm_score": -1,
"selected": false,
"text": "for (for-initializer; for-condition; for-iterator) embedded-statement\n"
},
{
"answer_id": 65439550,
"author": "Arshman Saleem",
"author_id": 6366945,
"author_profile": "https://Stackoverflow.com/users/6366945",
"pm_score": 0,
"selected": false,
"text": "for (int n=0; n < 10; n++) //forloop syntax\nforeach (string item in foo) foreach syntax\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
271,464 | <p>I have a multiline text string (e.g. "Stuff\nMore Stuff\nYet More Stuff"), and I want to paint it, along with a bitmap into a tooltip. Since I am painting the bitmap, I need to set OwnerDraw to true, which I am doing. I am also handling the Popup event, so I can size the tooltip to be large enough to hold the text and the bitmap.</p>
<p>I am calling e.DrawBackground and e.DrawBorder(), and then painting my bitmap on the left side of the tooltip area. </p>
<p>Is there a set of flags I can pass to e.DrawText() in order to left-align the text, but to offset it so that it doesn't get painted over my bitmap? Or do I need to custom draw all the text as well (which will probably involve splitting the string on newlines, etc)?</p>
<p>UPDATED: The final code looks like this:</p>
<pre><code>private void _ItemTip_Draw(object sender, DrawToolTipEventArgs e)
{
e.DrawBackground();
e.DrawBorder();
// Reserve a square of size e.Bounds.Height x e.Bounds.Height
// for the image. Keep a margin around it so that it looks good.
int margin = 2;
Image i = _ItemTip.Tag as Image;
if (i != null)
{
int side = e.Bounds.Height - 2 * margin;
e.Graphics.DrawImage(i, new Rectangle(margin, margin, side, side));
}
// Construct bounding rectangle for text (don't want to paint it over the image).
int textOffset = e.Bounds.Height + 2 * margin;
RectangleF rText = e.Bounds;
rText.Offset(textOffset, 0);
rText.Width -= textOffset;
e.Graphics.DrawString(e.ToolTipText, e.Font, Brushes.Black, rText);
}
</code></pre>
| [
{
"answer_id": 271628,
"author": "Robert Jeppesen",
"author_id": 9436,
"author_profile": "https://Stackoverflow.com/users/9436",
"pm_score": 3,
"selected": true,
"text": " RectangleF rect = new RectangleF(100,100,100,100);\n e.Graphics.DrawString(myString, myFont, myBrush, rect);\n"
},
{
"answer_id": 271658,
"author": "tamberg",
"author_id": 3588,
"author_profile": "https://Stackoverflow.com/users/3588",
"pm_score": 0,
"selected": false,
"text": "double MeasureStringHeight (Graphics g, string s, Font f, int w) {\n double result = 0;\n int n = s.Length;\n int i = 0;\n while (i < n) {\n StringBuilder line = new StringBuilder();\n int iLineStart = i;\n int iSpace = -1;\n SizeF sLine = new SizeF(0, 0);\n while ((i < n) && (sLine.Width <= w)) {\n char ch = s[i];\n if ((ch == ' ') || (ch == '-')) {\n iSpace = i;\n }\n line.Append(ch);\n sLine = g.MeasureString(line.ToString(), f);\n i++;\n }\n if (sLine.Width > w) {\n if (iSpace >= 0) {\n i = iSpace + 1;\n } else {\n i--;\n }\n // Assert(w > largest ch in line)\n }\n result += sLine.Height;\n }\n return result;\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2683/"
] |
271,485 | <p>whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#</p>
<p>cheers.. </p>
| [
{
"answer_id": 271487,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<table><tr><td>...</td></tr>...</table>"
},
{
"answer_id": 271496,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "private void ExportButton_Click(object sender, System.EventArgs e)\n{\n Response.Clear();\n Response.Buffer = true;\n Response.ContentType = \"application/vnd.ms-excel\";\n Response.Charset = \"\";\n this.EnableViewState = false;\n System.IO.StringWriter oStringWriter = new System.IO.StringWriter();\n System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);\n this.ClearControls(dataGrid);\n dataGrid.RenderControl(oHtmlTextWriter);\n Response.Write(oStringWriter.ToString());\n Response.End();\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23491/"
] |
271,488 | <p>I asked <a href="https://stackoverflow.com/questions/269417/which-language-should-i-use">a question</a> earlier about which language to use for an AI prototype. The consensus seemed to be that if I want it to be fast, I need to use a language like Java or C++, but that Python / Perl / Ruby would be good for the interface bits. </p>
<p>So, this leads me on to another question. How easy is it to link these languages together? And which combination works best? So, if I wanted to have a Ruby CGI-type program calling C++ or Java AI functions, is that easy to do? Any pointers for where I look for information on doing that kind of thing? Or would a different combination be better?</p>
<p>My main experience with writing web applications started with C++ CGI and then moved on to Java servlets (about 10 years ago) and then after a long gap away from programming I did some PHP. But I've not had experience of writing a web application in a scripting language which then calls out to a compiled language for the speed-critical bits. So any advice will be welcome!</p>
| [
{
"answer_id": 271494,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "require \"java\"\n# The next line exposes Java's String as JString\ninclude_class(\"java.lang.String\") { |pkg, name| \"J\" + name }\ns = JString.new(\"f\")\n"
},
{
"answer_id": 271642,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 5,
"selected": true,
"text": "char const* greet()\n{\n return \"hello, world\";\n}\n"
},
{
"answer_id": 272363,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "use Inline C => <<'END_C';\n\n void greet() {\n printf(\"Hello, world\\n\");\n }\nEND_C\n\ngreet;\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11522/"
] |
271,506 | <p>I am refering to the <a href="https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java#252905">question</a> on changing the classpath programmatically.</p>
<p>I read and found out that there is some function under <strong>System</strong> class as getproperties where we can retrieve the properties and then also can set it using setProperties().</p>
<p>The answers however I got was that It Wont work. I have not tried this myself, however, i am taking the call.</p>
<p>Just to clarify, then why these setProperty() and getProperty() methods are there if they cannot alter it at run time. Or is this specific to the classpath property only ?</p>
<p>I will appreciate if someone can present a scenario where they are really helpful?</p>
| [
{
"answer_id": 271522,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "/*\nAdd the URL handler to the handler property. This informs \nIBMJSSE what URL handler to use to handle the safkeyring \nsupport. In this case IBMJCE.\n*/\nSystem.setProperty(\"java.protocol.handler.pkgs\", \"com.ibm.crypto.provider\");\n"
},
{
"answer_id": 272049,
"author": "Martin Probst",
"author_id": 22227,
"author_profile": "https://Stackoverflow.com/users/22227",
"pm_score": 0,
"selected": false,
"text": "getProperty()"
},
{
"answer_id": 1198693,
"author": "Dave Jarvis",
"author_id": 59087,
"author_profile": "https://Stackoverflow.com/users/59087",
"pm_score": 4,
"selected": false,
"text": "addURL"
},
{
"answer_id": 8598258,
"author": "Zorkus",
"author_id": 1965110,
"author_profile": "https://Stackoverflow.com/users/1965110",
"pm_score": 2,
"selected": false,
"text": "System.setProperty( \"java.library.path\", newPath);\nField fieldSysPath = ClassLoader.class.getDeclaredField(\"sys_paths\");\nfieldSysPath.setAccessible(true);\nfieldSysPath.set(null, null); // that's the key.\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11614/"
] |
271,520 | <p>I could do this in C#..</p>
<pre><code>int number = 2;
string str = "Hello " + number + " world";
</code></pre>
<p>..and str ends up as "Hello 2 world".</p>
<p>In VB.NET i could do this..</p>
<pre><code>Dim number As Integer = 2
Dim str As String = "Hello " + number + " world"
</code></pre>
<p>..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."</p>
<p>I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?</p>
| [
{
"answer_id": 271529,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "Dim number As Integer = 2\nDim str As String = \"Hello \" & number & \" world\"\n"
},
{
"answer_id": 271531,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 3,
"selected": false,
"text": "+"
},
{
"answer_id": 271532,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 1,
"selected": false,
"text": "Dim str = 1 + \"2\"\n"
},
{
"answer_id": 271585,
"author": "Loris",
"author_id": 23824,
"author_profile": "https://Stackoverflow.com/users/23824",
"pm_score": 2,
"selected": false,
"text": "str = String.Format(\"Hello {0} workd\", Number)\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15233/"
] |
271,521 | <p>Sometimes when I am debugging code in Eclipse it happens that although I can see and inspect class member variables without any difficulty I am unable to inspect the values of variables declared locally within functions. As an aside, any parameters to the current function lose their 'real' names and instead one sees their values listed in the Variables window as arg0, arg1, arg2, etc but at least the values are visible.</p>
<p>This is occurring at present in relation to classes defined within the core JDK. I have verified that the installed and current JRE is a JDK.</p>
<p>Is anybody able to shed some light on this behaviour?</p>
| [
{
"answer_id": 940988,
"author": "Geoffrey Zheng",
"author_id": 62479,
"author_profile": "https://Stackoverflow.com/users/62479",
"pm_score": 4,
"selected": false,
"text": "mkdir \\tmp; mkdir \\tmp\\out"
},
{
"answer_id": 31980261,
"author": "Naresh",
"author_id": 3359659,
"author_profile": "https://Stackoverflow.com/users/3359659",
"pm_score": 0,
"selected": false,
"text": "<compilerarg line=\"-g\" />"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35138/"
] |
271,526 | <p>I use <code>x != null</code> to avoid <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html" rel="noreferrer"><code>NullPointerException</code></a>. Is there an alternative?</p>
<pre class="lang-java prettyprint-override"><code>if (x != null) {
// ...
}
</code></pre>
| [
{
"answer_id": 271576,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 6,
"selected": false,
"text": "a.f(b); <-> b.f(a);\n"
},
{
"answer_id": 271587,
"author": "javamonkey79",
"author_id": 27657,
"author_profile": "https://Stackoverflow.com/users/27657",
"pm_score": 7,
"selected": false,
"text": "String foo;\n...\nif( StringUtils.isBlank( foo ) ) {\n ///do something\n}\n"
},
{
"answer_id": 271616,
"author": "myplacedk",
"author_id": 28683,
"author_profile": "https://Stackoverflow.com/users/28683",
"pm_score": 8,
"selected": false,
"text": "public void method(Object object) {\n if (object == null) {\n throw new IllegalArgumentException(\"...\");\n }\n"
},
{
"answer_id": 271617,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 5,
"selected": false,
"text": "if( o == null ) handleNull()"
},
{
"answer_id": 271735,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public class NonNullThing {\n\n Vector vectorField = new Vector();\n\n int[] arrayField = new int[0];\n\n public NonNullThing() {\n\n // etc\n\n }\n\n}\n"
},
{
"answer_id": 271874,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 12,
"selected": true,
"text": "Objects.requireNonNull(foo)"
},
{
"answer_id": 275869,
"author": "echox",
"author_id": 35915,
"author_profile": "https://Stackoverflow.com/users/35915",
"pm_score": 8,
"selected": false,
"text": "if ( foo.equals(\"bar\") ) {\n // ...\n}\n"
},
{
"answer_id": 288524,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": false,
"text": "NullObjectPattern"
},
{
"answer_id": 397740,
"author": "user2427",
"author_id": 1356709,
"author_profile": "https://Stackoverflow.com/users/1356709",
"pm_score": 6,
"selected": false,
"text": "static <T> T checkNotNull(T e) {\n if (e == null) {\n throw new NullPointerException();\n }\n return e;\n}\n"
},
{
"answer_id": 452820,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 8,
"selected": false,
"text": "NullObject pattern"
},
{
"answer_id": 1202969,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 6,
"selected": false,
"text": "nil"
},
{
"answer_id": 2064441,
"author": "thSoft",
"author_id": 90874,
"author_profile": "https://Stackoverflow.com/users/90874",
"pm_score": 8,
"selected": false,
"text": "Optional"
},
{
"answer_id": 2386013,
"author": "Luca Molteni",
"author_id": 4206,
"author_profile": "https://Stackoverflow.com/users/4206",
"pm_score": 9,
"selected": false,
"text": "@Nullable"
},
{
"answer_id": 3499225,
"author": "fastcodejava",
"author_id": 184730,
"author_profile": "https://Stackoverflow.com/users/184730",
"pm_score": 5,
"selected": false,
"text": "assert"
},
{
"answer_id": 3925191,
"author": "tltester",
"author_id": 474659,
"author_profile": "https://Stackoverflow.com/users/474659",
"pm_score": 4,
"selected": false,
"text": "public static <T> T ifNull(T toCheck, T ifNull) {\n if (toCheck == null) {\n return ifNull;\n }\n return toCheck;\n}\n"
},
{
"answer_id": 5311857,
"author": "Oleg",
"author_id": 634475,
"author_profile": "https://Stackoverflow.com/users/634475",
"pm_score": 5,
"selected": false,
"text": "ValidationUtils.getNullValidator().addParam(plans, \"plans\").addParam(persons, \"persons\").validate();\n"
},
{
"answer_id": 6101200,
"author": "Alex Worden",
"author_id": 181551,
"author_profile": "https://Stackoverflow.com/users/181551",
"pm_score": 7,
"selected": false,
"text": "NullPointerException"
},
{
"answer_id": 7847199,
"author": "jeha",
"author_id": 571271,
"author_profile": "https://Stackoverflow.com/users/571271",
"pm_score": 3,
"selected": false,
"text": "public static <T> boolean isNull(T argument) {\n return (argument == null);\n}\n"
},
{
"answer_id": 8212184,
"author": "Mike",
"author_id": 448078,
"author_profile": "https://Stackoverflow.com/users/448078",
"pm_score": 6,
"selected": false,
"text": "public Photo getPhotoOfThePerson(Person person) {\n if (person == null)\n return null;\n // Grabbing some resources or intensive calculation\n // using person object anyhow.\n}\n"
},
{
"answer_id": 9845966,
"author": "Murat Derya Özen",
"author_id": 396216,
"author_profile": "https://Stackoverflow.com/users/396216",
"pm_score": 5,
"selected": false,
"text": "Optional<T>"
},
{
"answer_id": 11896966,
"author": "Stuart Marks",
"author_id": 1441122,
"author_profile": "https://Stackoverflow.com/users/1441122",
"pm_score": 6,
"selected": false,
"text": "java.util.Objects"
},
{
"answer_id": 12390983,
"author": "drzymala",
"author_id": 1391568,
"author_profile": "https://Stackoverflow.com/users/1391568",
"pm_score": 1,
"selected": false,
"text": "public void simpleFunc(SomeObject someObject){\n someObject = someObject != null ? someObject : new SomeObject(null);\n someObject.doSomething();\n}\n"
},
{
"answer_id": 12946734,
"author": "ianpojman",
"author_id": 1342121,
"author_profile": "https://Stackoverflow.com/users/1342121",
"pm_score": 5,
"selected": false,
"text": "if = null else"
},
{
"answer_id": 13676682,
"author": "abishkar bhattarai",
"author_id": 1564766,
"author_profile": "https://Stackoverflow.com/users/1564766",
"pm_score": 2,
"selected": false,
"text": "M2(Object test2)"
},
{
"answer_id": 14253016,
"author": "Vinay Lodha",
"author_id": 212665,
"author_profile": "https://Stackoverflow.com/users/212665",
"pm_score": 2,
"selected": false,
"text": "@NotNull"
},
{
"answer_id": 16218718,
"author": "Pierre Henry",
"author_id": 315677,
"author_profile": "https://Stackoverflow.com/users/315677",
"pm_score": 8,
"selected": false,
"text": "java.util.Optional"
},
{
"answer_id": 17109182,
"author": "Stuart Axon",
"author_id": 62709,
"author_profile": "https://Stackoverflow.com/users/62709",
"pm_score": 4,
"selected": false,
"text": "// Bad\nArrayList<String> lemmings;\nString[] names;\n\nvoid checkLemmings() {\n if (lemmings != null) for(lemming: lemmings) {\n // do something\n }\n}\n\n\n\n// Good\nArrayList<String> lemmings = new ArrayList<String>();\nString[] names = {};\n\nvoid checkLemmings() {\n for(lemming: lemmings) {\n // do something\n }\n}\n"
},
{
"answer_id": 19714883,
"author": "iowatiger08",
"author_id": 552782,
"author_profile": "https://Stackoverflow.com/users/552782",
"pm_score": 1,
"selected": false,
"text": "ObjectUtils.equals(object, null)\n"
},
{
"answer_id": 21391466,
"author": "Tobb",
"author_id": 1054021,
"author_profile": "https://Stackoverflow.com/users/1054021",
"pm_score": 2,
"selected": false,
"text": "null-checks"
},
{
"answer_id": 21726959,
"author": "Alireza Fattahi",
"author_id": 2648077,
"author_profile": "https://Stackoverflow.com/users/2648077",
"pm_score": 4,
"selected": false,
"text": "if(object == null){\n //you called my method badly!\n"
},
{
"answer_id": 22211014,
"author": "Gal Morad",
"author_id": 1940722,
"author_profile": "https://Stackoverflow.com/users/1940722",
"pm_score": 3,
"selected": false,
"text": "Preconditions.checkNotNull(paramVal, \"Method foo received null paramVal\");\n"
},
{
"answer_id": 23021801,
"author": "Sireesh Yarlagadda",
"author_id": 2057902,
"author_profile": "https://Stackoverflow.com/users/2057902",
"pm_score": 4,
"selected": false,
"text": "org.apache.commons.lang.Validate //using apache framework\n"
},
{
"answer_id": 29887121,
"author": "Yogesh Devatraj",
"author_id": 1646333,
"author_profile": "https://Stackoverflow.com/users/1646333",
"pm_score": 5,
"selected": false,
"text": "java.util.Optional<T>"
},
{
"answer_id": 33763493,
"author": "Lii",
"author_id": 452775,
"author_profile": "https://Stackoverflow.com/users/452775",
"pm_score": 1,
"selected": false,
"text": "void example() {\n Entry entry = new Entry();\n // This is the same as H-MANs solution \n Person person = getNullsafe(entry, e -> e.getPerson()); \n // Get object in several steps\n String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());\n // Call void methods\n doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt()); \n}\n\n/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */\npublic static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {\n if (o1 != null) return f1.apply(o1);\n return null; \n}\n\npublic static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {\n return getNullsafe(getNullsafe(o0, f1), f2);\n}\n\npublic static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {\n return getNullsafe(getNullsafe(o0, f1, f2), f3);\n}\n\n\n/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */\npublic static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {\n if (o1 != null) f1.accept(o1);\n}\n\npublic static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {\n doNullsafe(getNullsafe(o0, f1), f2);\n}\n\npublic static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {\n doNullsafe(getNullsafe(o0, f1, f2), f3);\n}\n\n\nclass Entry {\n Person getPerson() { return null; }\n}\n\nclass Person {\n Name getName() { return null; }\n}\n\nclass Name {\n void nameIt() {}\n String getGivenName() { return null; }\n}\n"
},
{
"answer_id": 34996504,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 3,
"selected": false,
"text": "final"
},
{
"answer_id": 36167495,
"author": "Raghu K Nair",
"author_id": 2194364,
"author_profile": "https://Stackoverflow.com/users/2194364",
"pm_score": 5,
"selected": false,
"text": "Optional"
},
{
"answer_id": 38207227,
"author": "Ivan Golovach",
"author_id": 6546993,
"author_profile": "https://Stackoverflow.com/users/6546993",
"pm_score": 3,
"selected": false,
"text": "T"
},
{
"answer_id": 39848137,
"author": "Vidura Mudalige",
"author_id": 3719179,
"author_profile": "https://Stackoverflow.com/users/3719179",
"pm_score": -1,
"selected": false,
"text": "public abstract class SomeObject {\n public abstract boolean isNil();\n}\n\npublic class NullObject extends SomeObject {\n @Override\n public boolean isNil() {\n return true;\n }\n}\npublic class RealObject extends SomeObject {\n @Override\n public boolean isNil() {\n return false;\n }\n}\n"
},
{
"answer_id": 40840957,
"author": "Philip John",
"author_id": 4256410,
"author_profile": "https://Stackoverflow.com/users/4256410",
"pm_score": 3,
"selected": false,
"text": "Java 7"
},
{
"answer_id": 44902405,
"author": "Jobin",
"author_id": 2893693,
"author_profile": "https://Stackoverflow.com/users/2893693",
"pm_score": 3,
"selected": false,
"text": "isNull(yourObject)"
},
{
"answer_id": 47285263,
"author": "yanefedor",
"author_id": 4545552,
"author_profile": "https://Stackoverflow.com/users/4545552",
"pm_score": 4,
"selected": false,
"text": "if (object != null) {\n ....\n}\n"
},
{
"answer_id": 47986378,
"author": "Binod Pant",
"author_id": 1119386,
"author_profile": "https://Stackoverflow.com/users/1119386",
"pm_score": 1,
"selected": false,
"text": "@RequiresNonNull(value = { \"#1\" })\nstatic void check( Boolean x) {\n if (x) System.out.println(\"true\");\n else System.out.println(\"false\");\n}\n\npublic static void main(String[] args) {\n\n\n check(null);\n\n}\n"
},
{
"answer_id": 48671389,
"author": "nilesh",
"author_id": 503804,
"author_profile": "https://Stackoverflow.com/users/503804",
"pm_score": 2,
"selected": false,
"text": "if(CommonUtil.resolve(()-> a.b().c()).isPresent()) {\n\n}\n"
},
{
"answer_id": 51311500,
"author": "Mukesh A",
"author_id": 4014678,
"author_profile": "https://Stackoverflow.com/users/4014678",
"pm_score": 3,
"selected": false,
"text": "NullPointerException"
},
{
"answer_id": 54017256,
"author": "Ramprabhu",
"author_id": 7236932,
"author_profile": "https://Stackoverflow.com/users/7236932",
"pm_score": 0,
"selected": false,
"text": " BiConsumer<Object, Consumer<Object>> consumeIfPresent = (s,f) ->{\n if(s!=null) {\n f.accept(s);\n }\n };\n\n consumeIfPresent.accept(null, (s)-> System.out.println(s) );\n consumeIfPresent.accept(\"test\", (s)-> System.out.println(s));\n\n BiFunction<Object, Function<Object,Object>,Object> executeIfPresent = (a,b) ->{\n if(a!=null) {\n return b.apply(a);\n }\n return null;\n };\n executeIfPresent.apply(null, (s)-> {System.out.println(s);return s;} );\n executeIfPresent.apply(\"test\", (s)-> {System.out.println(s);return s;} );\n"
},
{
"answer_id": 56145630,
"author": "Sebastian3000",
"author_id": 2785025,
"author_profile": "https://Stackoverflow.com/users/2785025",
"pm_score": 2,
"selected": false,
"text": "Optional.ofNullable(someobject).ifPresent(someobject -> someobject.doCalc());\n"
},
{
"answer_id": 56543966,
"author": "rohit prakash",
"author_id": 6024604,
"author_profile": "https://Stackoverflow.com/users/6024604",
"pm_score": 3,
"selected": false,
"text": "java.util"
},
{
"answer_id": 63325067,
"author": "Satish Hawalppagol",
"author_id": 12079719,
"author_profile": "https://Stackoverflow.com/users/12079719",
"pm_score": 0,
"selected": false,
"text": "public static String getNullString(Object someobject)\n{\n if(null==someobject )\n return null;\n\n else if(someobject.getClass().isInstance(\"\") && \n (((String)someobject).trim().equalsIgnoreCase(\"null\")|| \n ((String)someobject).trim().equalsIgnoreCase(\"\")))\n return null;\n\n else if(someobject.getClass().isInstance(\"\"))\n return (String)someobject;\n\n else\n return someobject.toString().trim();\n}\n"
},
{
"answer_id": 64437815,
"author": "Dan Chase",
"author_id": 3152516,
"author_profile": "https://Stackoverflow.com/users/3152516",
"pm_score": 0,
"selected": false,
"text": "try\n{\n myvar = get_user_supplied_value(); \n if (myvar == null || myvar.length() == 0) { alert_the_user_somehow(); return; };\n\n process_user_input(myvar);\n} catch (Exception ex) {\n handle_exception(ex);\n}\n"
},
{
"answer_id": 64455793,
"author": "Allen",
"author_id": 12716256,
"author_profile": "https://Stackoverflow.com/users/12716256",
"pm_score": 2,
"selected": false,
"text": " /**\n * Returns an {@code Optional} describing the specified value, if non-null,\n * otherwise returns an empty {@code Optional}.\n *\n * @param <T> the class of the value\n * @param value the possibly-null value to describe\n * @return an {@code Optional} with a present value if the specified value\n * is non-null, otherwise an empty {@code Optional}\n */\n public static <T> Optional<T> ofNullable(T value) {\n return value == null ? empty() : of(value);\n }\n"
},
{
"answer_id": 64747393,
"author": "vidy",
"author_id": 9993935,
"author_profile": "https://Stackoverflow.com/users/9993935",
"pm_score": 2,
"selected": false,
"text": "public class Null {\n\npublic static void main(String[] args) {\n String str1 = null;\n String str2 = \"\";\n\n if(isNullOrEmpty(str1))\n System.out.println(\"First string is null or empty.\");\n else\n System.out.println(\"First string is not null or empty.\");\n\n if(isNullOrEmpty(str2))\n System.out.println(\"Second string is null or empty.\");\n else\n System.out.println(\"Second string is not null or empty.\");\n}\n\npublic static boolean isNullOrEmpty(String str) {\n if(str != null && !str.isEmpty())\n return false;\n return true;\n}\n}\n"
},
{
"answer_id": 69973748,
"author": "Premakumar Tatireddy",
"author_id": 5671333,
"author_profile": "https://Stackoverflow.com/users/5671333",
"pm_score": 1,
"selected": false,
"text": "Objects.isNull(null)"
},
{
"answer_id": 72436784,
"author": "Greg7000",
"author_id": 6210975,
"author_profile": "https://Stackoverflow.com/users/6210975",
"pm_score": 0,
"selected": false,
"text": "import lombok.NonNull;\n\npublic class NonNullExample extends Something {\n private String name;\n \n public NonNullExample(@NonNull Person person) {\n super(\"Hello\");\n this.name = person.getName();\n }\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34856/"
] |
271,530 | <p>There is an application with an extensive object graph. This graph mainly consists of a set of subgraphs which are connected to the rest of the graph through the only reference. But internally each such subgraph has some number of cross-references among objects. Once in a while such a sub graph needs to be thrown away. Would it be enough just to set to null the only referece which points to that subgraph to make it eligible for garbage collection?</p>
<p>My concern is that internal cross-references may "protect" the entire subgraph from garbage collection. In other words, is the garbage collector wise enough to figure out that all references in a subgraph do not leave the boundaries of the subgraph and therefore entire subgraph can be purged.</p>
| [
{
"answer_id": 271556,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "public void buidDog() {\n Dog newDog = new Dog();\n Tail newTail = new Tail();\n newDog.tail = newTail;\n newTail.dog = newDog;\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31993/"
] |
271,546 | <p>I have an object instance which I access with the ME as it accesses the instantiated object. I have a method that gets a collection of these objects and I wish to assign the first one to the instantiated object. </p>
<p>This is some of the code</p>
<pre><code>Dim Books As New BookCollection(True)
Books.ListByThemeFeatured(ThemeID, 1) ' Fills the collection
If Books.Count > 0 Then
Me = Books(0) ' Should set the first item to the current object
End If
</code></pre>
<p>Is this possible?</p>
<p>EDIT: Me refers to the class that was instantiated. In this case it is a BookEntity Class. THis method would have been called using the following code</p>
<pre><code> Dim Book As New BookEntity
Book.FeaturedBook() ' Should fill the book entity with a featured book
</code></pre>
| [
{
"answer_id": 271556,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "public void buidDog() {\n Dog newDog = new Dog();\n Tail newTail = new Tail();\n newDog.tail = newTail;\n newTail.dog = newDog;\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23230/"
] |
271,561 | <p>In c#, is there any difference in the excecution speed for the order in which you state the condition?</p>
<pre><code>if (null != variable) ...
if (variable != null) ...
</code></pre>
<p>Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.</p>
<p>If there is no difference, what is the advantage of the first one?</p>
| [
{
"answer_id": 271573,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "int i = 0;\nif (i = 1)\n{\n ...\n}\n"
},
{
"answer_id": 271575,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "// Probably wrong\nif (x = 5)\n"
},
{
"answer_id": 970563,
"author": "Gad",
"author_id": 25152,
"author_profile": "https://Stackoverflow.com/users/25152",
"pm_score": -1,
"selected": false,
"text": "int i;\nif(i==1){ // Exception raised: i is not initialized. (C/C++)\n doThis();\n}\n"
},
{
"answer_id": 10741601,
"author": "DanW",
"author_id": 1415586,
"author_profile": "https://Stackoverflow.com/users/1415586",
"pm_score": 4,
"selected": false,
"text": "if(null == myDuck)"
},
{
"answer_id": 14622883,
"author": "Oliver",
"author_id": 1838048,
"author_profile": "https://Stackoverflow.com/users/1838048",
"pm_score": 4,
"selected": false,
"text": "if(someVariableThatShouldBeChecked != null\n && anotherOne != null\n && justAnotherCheckThatIsNeededForTestingNullity != null\n && allTheseChecksAreReallyBoring != null\n && thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded != null)\n{\n // ToDo: Everything is checked, do something...\n}\n"
},
{
"answer_id": 26175819,
"author": "Gokkula Sudan R",
"author_id": 4089930,
"author_profile": "https://Stackoverflow.com/users/4089930",
"pm_score": 2,
"selected": false,
"text": "if( 5 == variable)\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26070/"
] |
271,588 | <p>Is there a way to pass null arguments to C# methods (something like null arguments in c++)?</p>
<p>For example:</p>
<p>Is it possible to translate the following c++ function to C# method:</p>
<pre><code>private void Example(int* arg1, int* arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
</code></pre>
| [
{
"answer_id": 271593,
"author": "Marcin K",
"author_id": 28722,
"author_profile": "https://Stackoverflow.com/users/28722",
"pm_score": 3,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n{\n if(arg1 == null)\n {\n //do something\n }\n if(arg2 == null)\n {\n //do something else\n }\n}\n"
},
{
"answer_id": 271594,
"author": "MADMap",
"author_id": 17558,
"author_profile": "https://Stackoverflow.com/users/17558",
"pm_score": 3,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n{\n if(!arg1.HasValue)\n {\n //do something\n }\n if(!arg2.HasValue)\n {\n //do something else\n }\n}\n"
},
{
"answer_id": 271597,
"author": "user35412",
"author_id": 35412,
"author_profile": "https://Stackoverflow.com/users/35412",
"pm_score": 2,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n{\n if(arg1 == null)\n {\n //do something\n }\n if(arg2 == null)\n {\n //do something else\n }\n}\n"
},
{
"answer_id": 271600,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 7,
"selected": true,
"text": "// Both of these types mean the same thing, the ? is just C# shorthand.\nprivate void Example(int? arg1, Nullable<int> arg2)\n{\n if (arg1.HasValue)\n DoSomething();\n\n arg1 = null; // Valid.\n arg1 = 123; // Also valid.\n\n DoSomethingWithInt(arg1); // NOT valid!\n DoSomethingWithInt(arg1.Value); // Valid.\n}\n"
},
{
"answer_id": 271667,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 3,
"selected": false,
"text": "int*"
},
{
"answer_id": 13724965,
"author": "ruffin",
"author_id": 1028230,
"author_profile": "https://Stackoverflow.com/users/1028230",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace consolePlay\n{\n class Program\n {\n static void Main(string[] args)\n {\n Program.test(new DateTime());\n Program.test(null);\n //Program.test(); // <<< Error. \n // \"No overload for method 'test' takes 0 arguments\" \n // So don't mistake nullable to be optional.\n\n Console.WriteLine(\"Done. Return to quit\");\n Console.Read();\n }\n\n static public void test(DateTime? dteIn)\n {\n Console.WriteLine(\"#\" + dteIn.ToString() + \"#\");\n }\n }\n}\n"
},
{
"answer_id": 31465371,
"author": "juancalbarran",
"author_id": 3119676,
"author_profile": "https://Stackoverflow.com/users/3119676",
"pm_score": 2,
"selected": false,
"text": "private void Example(int? arg1, int? arg2)\n {\n if (arg1.HasValue)\n {\n //do something\n }\n if (arg1.HasValue)\n {\n //do something else\n }\n }\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22996/"
] |
271,595 | <p>I need to get all the dates present in the date range using SQL Server 2005</p>
| [
{
"answer_id": 271607,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 3,
"selected": false,
"text": "select * from yourTable where yourDate between date1 and date2\n"
},
{
"answer_id": 271775,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": -1,
"selected": false,
"text": "if object_id ('ods.uf_DateHierarchy') is not null\n drop function ods.uf_DateHierarchy\ngo\n\ncreate function ods.uf_DateHierarchy (\n @DateFrom datetime\n ,@DateTo datetime\n) returns @DateHierarchy table (\n DateKey datetime\n) as begin\n declare @today datetime \n set @today = @Datefrom\n\n while @today <= @DateTo begin\n insert @DateHierarchy (DateKey) values (@today)\n set @today = dateadd (dd, 1, @today)\n end\n\n return\nend\n\ngo\n"
},
{
"answer_id": 271878,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 6,
"selected": false,
"text": "DECLARE @DateFrom smalldatetime, @DateTo smalldatetime;\nSET @DateFrom='20000101';\nSET @DateTo='20081231';\n-------------------------------\nWITH T(date)\nAS\n( \nSELECT @DateFrom \nUNION ALL\nSELECT DateAdd(day,1,T.date) FROM T WHERE T.date < @DateTo\n)\nSELECT date FROM T OPTION (MAXRECURSION 32767);\n"
},
{
"answer_id": 271910,
"author": "Soraz",
"author_id": 24610,
"author_profile": "https://Stackoverflow.com/users/24610",
"pm_score": -1,
"selected": false,
"text": "select distinct(orderPlacedDate) \nfrom orders \nwhere orderPlacedDate between '2008-07-01' and 2008-09-30' \norder by orderPlacedDate\n"
},
{
"answer_id": 272568,
"author": "user34850",
"author_id": 34850,
"author_profile": "https://Stackoverflow.com/users/34850",
"pm_score": 1,
"selected": false,
"text": "SELECT TO_DATE ('01-OCT-2008') + ROWNUM - 1 g_date\n FROM all_objects\n WHERE ROWNUM <= 15\n"
},
{
"answer_id": 1271024,
"author": "Chris Moutray",
"author_id": 81053,
"author_profile": "https://Stackoverflow.com/users/81053",
"pm_score": 0,
"selected": false,
"text": "/* holds a sequential set of number ie 0 to max */\n/* where max is the total number of rows expected */\ndeclare @Numbers table ( Number int )\n\ndeclare @max int \ndeclare @cnt int\n\nset @cnt = 0\n/* this value could be limited if you knew the total rows expected */\nset @max = 999 \n\n/* we are building the NUMBERS table on the fly */\n/* but this could be a proper table in the database */\n/* created at the point of first deployment */\nwhile (@cnt <= @max)\nbegin\n insert into @Numbers select @cnt\n set @cnt = @cnt + 1\nend\n\n/* EXAMPLE of creating dates with different intervals */\n\ndeclare @DateRanges table ( \n StartDateTime datetime, EndDateTime datetime, Interval int )\n\n/* example set of date ranges */\ninsert into @DateRanges\nselect '01 Jan 2009', '10 Jan 2009', 1 /* 1 day interval */\nunion select '01 Feb 2009', '10 Feb 2009', 2 /* 2 day interval */\n\n/* heres the important bit generate the dates */\nselect\n StartDateTime\nfrom\n(\n select\n d.StartDateTime as RangeStart,\n d.EndDateTime as RangeEnd,\n dateadd(DAY, d.Interval * n.Number, d.StartDateTime) as StartDateTime\n from \n @DateRanges d, @Numbers n\n) as dates\nwhere\n StartDateTime between RangeStart and RangeEnd\norder by StartDateTime\n"
},
{
"answer_id": 40958788,
"author": "Surinder Singh",
"author_id": 6892711,
"author_profile": "https://Stackoverflow.com/users/6892711",
"pm_score": 3,
"selected": false,
"text": "DECLARE @Date1 DATE='2016-12-21', @Date2 DATE='2016-12-25'\nSELECT DATEADD(DAY,number,@Date1) [Date] FROM master..spt_values WHERE type = 'P' AND DATEADD(DAY,number,@Date1) <= @Date2\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,596 | <p>I've got a Java application that I'm writing an installer for. We're using the AdvancedInstaller program to create our installer (well, we're evaluating it currently, but will definitely purchase a license soon), and although it has special support for Java applications, it is geared more towards repackaging them as desktop-type apps, and our software is a series of Java services and other utilities which doesn't make sense to distribute in EXE-wrappers. The target audience for this software is very specific, and we know that our software will probably be automatically distributed on freshly-imaged Windows 2003 Server machines. So requiring Java as a prerequisite basically makes more work for some poor sysadmin, and I'd rather avoid that if at all possible by repackaging the JRE's installer inside of our own.</p>
<p>I discovered that if I tried to execute the JRE's installer as a pre-install step from my MSI, it complains that another installer is already running (mine, of course), so it bails out. When I try to add the JRE installer as a software prerequisite in the AdvancedInstaller project (as a bundled EXE, not a URL link), it never seems to actually get installed, despite me trying to force-install it.</p>
<p>What's the best way to repackage the JRE? I'm not really a Java guy, so I don't know too much about how other developers deal with this same problem, short of requiring their users to hunt out and install the JRE on their own. The ideal solution here would be for us to find a EXE installer which can be executed from inside of another MSI installer, or if it's possible, to just package all of the files inside of the JRE and then create the appropriate registry and environment variables. How should I go about doing this?</p>
| [
{
"answer_id": 271622,
"author": "bdumitriu",
"author_id": 35415,
"author_profile": "https://Stackoverflow.com/users/35415",
"pm_score": 2,
"selected": false,
"text": "java ..."
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
] |
271,598 | <p>How do I save a Tlistviews layout in Delphi 2007?</p>
<p>I have been asked to write some code to allow users to re-order columns in a TListview (well all TListviews in our application), I have the code working (by manipulating the columns index and setting width to zero to hide columns not needed) but now I need a way to save the state of the view when to form exits.</p>
<p>What is the best way to do this? I thought about serialization, but I dont need the data or sort order so that seamed a bit overkill to me.</p>
<p>Some things to ponder
It needs to be on a per user basis
It needs to be flexible, in-case we add a new column in the middle of the listview
There is no garantee that the Column headding will be unique
The listview name may not be unique across the application</p>
<p>Any ideas?</p>
| [
{
"answer_id": 271619,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "[Settings]\n\n[Col_1]\nposition=1\nwidth=500\ntitle=hello world\nalign=left\nsort=ascending\n\n.. etc for more fields and more columns.\n"
},
{
"answer_id": 44900707,
"author": "C. MARIN",
"author_id": 8237709,
"author_profile": "https://Stackoverflow.com/users/8237709",
"pm_score": 0,
"selected": false,
"text": "Name | First name | Age | Job title\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] |
271,609 | <p>We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows? </p>
<p>Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used to run that particular application?</p>
| [
{
"answer_id": 271623,
"author": "reallyinsane",
"author_id": 35407,
"author_profile": "https://Stackoverflow.com/users/35407",
"pm_score": 7,
"selected": true,
"text": "java ...\n"
},
{
"answer_id": 271630,
"author": "Ruben",
"author_id": 26919,
"author_profile": "https://Stackoverflow.com/users/26919",
"pm_score": 2,
"selected": false,
"text": "set JAVA_HOME=C:\\...\\j2dskXXX"
},
{
"answer_id": 49688921,
"author": "Felipe Ferreira",
"author_id": 6489237,
"author_profile": "https://Stackoverflow.com/users/6489237",
"pm_score": 2,
"selected": false,
"text": "setlocal\nset JAVA_HOME=\"c:\\java8\"\nset PATH=%JAVA_HOME%\\bin;%PATH%;\njava -version\n"
},
{
"answer_id": 55476231,
"author": "Naresh Joshi",
"author_id": 2078093,
"author_profile": "https://Stackoverflow.com/users/2078093",
"pm_score": 3,
"selected": false,
"text": "_HOME"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35061/"
] |
271,612 | <p>I have the following file/line:</p>
<pre><code>pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200
pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200
</code></pre>
<p>and so on.
I wish to parse this and take the key value pairs and put them in a structure:</p>
<pre><code>struct pky
{
pky() :
a_id(0),
sz_id(0),
cr_id(0),
cp_id(0),
cv_id(0),
ct_id(0),
fr(0),
g('U'),
a(0),
pc(0),
p_id(0)
{ }
};
</code></pre>
<p>wherein either all the structure fields are used or some might be omitted.</p>
<p>How do I create a C++ class, which will do the same? I am new to C++ and not aware of any functions or library which would do this work.</p>
<p>Each line is to be processed, and the structure will be populated with one line each time and used, before it is flushed. The structure is later used as a parameter to a function.</p>
| [
{
"answer_id": 271654,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "std::string line;\nstd::map<std::string, std::string> props;\nstd::ifstream file(\"foo.txt\");\nwhile(std::getline(file, line)) {\n std::string token;\n std::istringstream tokens(line);\n while(tokens >> token) {\n std::size_t pos = token.find('=');\n if(pos != std::string::npos) {\n props[token.substr(0, pos)] = token.substr(pos + 1);\n }\n }\n\n /* work with those keys/values by doing properties[\"name\"] */\n Line l(props[\"pc\"], props[\"ct\"], ...);\n\n /* clear the map for the next line */\n props.clear();\n}\n"
},
{
"answer_id": 271670,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 2,
"selected": false,
"text": "#include <sstream>\n#include <string>\n#include <vector>\n#include <map>\n\nusing namespace std;\n\nvector<string> Tokenize(const string &str, const string &delim)\n{\n vector<string> tokens;\n\n size_t p0 = 0, p1 = string::npos;\n while(p0 != string::npos)\n {\n p1 = str.find_first_of(delim, p0);\n if(p1 != p0)\n {\n string token = str.substr(p0, p1 - p0);\n tokens.push_back(token);\n }\n p0 = str.find_first_not_of(delim, p1);\n }\n\n return tokens;\n}\n\nint main()\n{\n string data = \"pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200 pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200\";\n vector<string> entries = Tokenize(data, \" \");\n map<string, int> items;\n\n for (size_t i = 0; i < entries.size(); ++i)\n {\n string item = entries[i];\n\n size_t pos = item.find_first_of('=');\n if(pos == string::npos)\n continue;\n\n string key = item.substr(0, pos);\n int value;\n stringstream stream(item.substr(pos + 1));\n stream >> value;\n items.insert (pair<string, int>(key, value));\n }\n\n}\n"
},
{
"answer_id": 272265,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "#include <string>\n#include <fstream>\n#include <sstream>\n#include <istream>\n#include <vector>\n#include <algorithm>\n#include <iterator>\n\nstd::istream& operator>> (std::istream& str,pky& value)\n{\n std::string line;\n std::getline(str,line);\n\n std::stringstream dataStr(line);\n\n static const std::streamsize max = std::numeric_limits<std::streamsize>::max();\n\n // Code assumes the ordering is always as follows\n // pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200\n dataStr.ignore(max,'=') >> value.pc;\n dataStr.ignore(max,'=') >> value.ct_id;\n dataStr.ignore(max,'=') >> value.a; // Guessing av=\n dataStr.ignore(max,'=') >> value.cv_id;\n dataStr.ignore(max,'=') >> value.cp_id;\n dataStr.ignore(max,'=') >> value.fr; // Guessing rec=\n dataStr.ignore(max,'=') >> value.p_id;\n dataStr.ignore(max,'=') >> value.g;\n dataStr.ignore(max,'=') >> value.a_id;\n dataStr.ignore(max,'=') >> value.sz_id;\n dataStr.ignore(max,'=') >> value.cr_id;\n\n return str;\n}\n\nint main()\n{\n std::ifstream file(\"plop\");\n\n std::vector<pky> v;\n pky data;\n\n while(file >> data)\n {\n // Do Somthing with data\n v.push_back(data);\n }\n\n // Even use the istream_iterators\n std::ifstream file2(\"plop2\");\n std::vector<pky> v2;\n\n std::copy(std::istream_iterator<pky>(file2),\n std::istream_iterator<pky>(),\n std::back_inserter(v2)\n );\n}\n"
},
{
"answer_id": 1727555,
"author": "3yE",
"author_id": 207427,
"author_profile": "https://Stackoverflow.com/users/207427",
"pm_score": 1,
"selected": false,
"text": "std::tr1::regex"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35416/"
] |
271,613 | <p>I was reading <em><a href="http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html" rel="nofollow noreferrer">Java Platform Performance</a></em> (sadly the link seems to have disappeared from the internet since I originally posed this question) and section A.3.3 worried me.</p>
<p>I had been working on the assumption that a variable that dropped out of scope would no longer be considered a GC root, but this paper appears to contradict that.</p>
<p>Do recent JVMs, in particular Sun's 1.6.0_07 version, still have this limitation? If so, then I have a lot of code to analyse...</p>
<p>I ask the question because the paper is from 1999 - sometimes things change, particularly in the world of GC.</p>
<hr/>
<p>As the paper is no longer available, I'd like to paraphrase the concern. The paper implied that variables that were defined inside a method would be considered a GC root until the method exited, and not until the code block ended. Therefore setting the variable to null was necessary to permit the Object referenced to be garbage collected.</p>
<p>This meant that a local variable defined in a conditional block in the main() method (or similar method that contained an infinite loop) would cause a one-off memory leak unless you nulled a variable just before it dropped out of scope.</p>
<p>The code from the <a href="https://stackoverflow.com/a/271824/7938">chosen answer</a> illustrates the issue well. On the version of the JVM referenced in the document, the foo object can not be garbage collected when it drops out of scope at the end of the try block. Instead, the JVM will hold open the reference until the end of the main() method, even though it is impossible for anything to use that reference.</p>
<p>This appears to be the origin of the idea that nulling a variable reference would help the garbage collector out, even if the variable was just about to drop out of scope.</p>
| [
{
"answer_id": 271824,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 4,
"selected": true,
"text": "public class TestInvisibleObject{\n public static class PrintWhenFinalized{\n private String s;\n public PrintWhenFinalized(String s){\n System.out.println(\"Constructing from \"+s);\n this.s = s;\n }\n protected void finalize() throws Throwable {\n System.out.println(\"Finalizing from \"+s);\n } \n }\n public static void main(String[] args) {\n try {\n PrintWhenFinalized foo = new PrintWhenFinalized(\"main\");\n } catch (Exception e) {\n // whatever\n }\n while (true) {\n // Provoke garbage-collection by allocating lots of memory\n byte[] o = new byte[1024];\n } \n }\n}\n"
},
{
"answer_id": 271932,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 2,
"selected": false,
"text": "public void doSomething() { \n for(int i = 0; i < 10 ; i++) {\n String s = new String(\"boo\");\n System.out.println(s);\n }\n}\n"
},
{
"answer_id": 18406054,
"author": "Holger",
"author_id": 2711488,
"author_profile": "https://Stackoverflow.com/users/2711488",
"pm_score": 2,
"selected": false,
"text": "import java.lang.ref.*;\n\npublic class Test {\n static final ReferenceQueue<Object> RQ=new ReferenceQueue<>();\n static Reference<Object> A, B;\n public static void main(String[] s) {\n {\n Object a=new Object();\n A=new PhantomReference<>(a, RQ);\n }\n {\n Object b=new Object();\n B=new PhantomReference<>(b, RQ);\n }\n forceGC();\n checkGC();\n }\n\n private static void forceGC() {\n try {\n for(int i=100000;;i+=i) {\n byte[] b=new byte[i];\n }\n } catch(OutOfMemoryError err){ err.printStackTrace();}\n }\n\n private static void checkGC() {\n for(;;) {\n Reference<?> r=RQ.poll();\n if(r==null) break;\n if(r==A) System.out.println(\"Object a collected\");\n if(r==B) System.out.println(\"Object b collected\");\n }\n }\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7938/"
] |
271,615 | <p>I have two lists of custom objects and want to update a field for all objects in one list if there is an object in the other list which matches on another pair of fields.</p>
<p>This code explains the problem better and produces the results I want. However for larger lists 20k, and a 20k list with matching objects, this takes a considerable time (31s). I can improve this with ~50% by using the generic lists Find(Predicate) method.</p>
<pre><code>using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace ExperimentFW3
{
public class PropValue
{
public string Name;
public decimal Val;
public decimal Total;
}
public class Adjustment
{
public string PropName;
public decimal AdjVal;
}
class Program
{
static List<PropValue> propList;
static List<Adjustment> adjList;
public static void Main()
{
propList = new List<PropValue>{
new PropValue{Name = "Alfa", Val=2.1M},
new PropValue{Name = "Beta", Val=1.0M},
new PropValue{Name = "Gamma", Val=8.0M}
};
adjList = new List<Adjustment>{
new Adjustment{PropName = "Alfa", AdjVal=-0.1M},
new Adjustment{PropName = "Beta", AdjVal=3M}
};
foreach (var p in propList)
{
Adjustment a = adjList.SingleOrDefault(
av => av.PropName.Equals(p.Name)
);
if (a != null)
p.Total = p.Val + a.AdjVal;
else
p.Total = p.Val;
}
}
}
}
</code></pre>
<p>The desired result is: Alfa total=2,Beta total=4,Gamma total=8</p>
<p>But I wonder if this is possible to do even faster. Inner joining the two lists takes very little time, even when looping over 20k items in the resultset.</p>
<pre><code>var joined = from p in propList
join a in adjList on p.Name equals a.PropName
select new { p.Name, p.Val, p.Total, a.AdjVal };
</code></pre>
<p>So my question is if it's possible to do something like I would do with T-SQL? An UPDATE from a left join using ISNULL(val,0) on the adjustment value.</p>
| [
{
"answer_id": 271645,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "adjList"
},
{
"answer_id": 272155,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "Dictionary<string, decimal> adjDictionary = adjList\n .GroupBy(a => a.PropName)\n .ToDictionary(g => g.Key, g => g.Sum(a => a.AdjVal))\n\npropList.ForEach(p => \n {\n decimal a;\n adjDictionary.TryGetValue(p.Name, out a);\n p.Total = p.Val + a;\n });\n"
},
{
"answer_id": 2093104,
"author": "DRBlaise",
"author_id": 234720,
"author_profile": "https://Stackoverflow.com/users/234720",
"pm_score": 0,
"selected": false,
"text": "var adjLookUp = adjList.ToLookUp(a => a.PropName);\nforeach (var p in propList) \n p.Total = p.Val + adjLookUp[p.Name].Sum(a => a.AdjVal);\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2006748/"
] |
271,657 | <p>I have many emails coming in from different sources.
they all have attachments, many of them have attachment names in chinese, so these
names are converted to base64 by their email clients.</p>
<p>When I receive these emails, I wish to decode the name. but there are other names which are
not base64. How can I differentiate whether a string is base64 or not, using the <strong>jython</strong> programming language?</p>
<p>Ie. </p>
<p>First attachment: </p>
<pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860
Content-Type: application/vnd.ms-excel;
name="Copy of Book1.xls"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="Copy of Book1.xls"
</code></pre>
<p>second attachment:</p>
<pre><code>------=_NextPart_000_0091_01C940CC.EF5AC860
Content-Type: application/vnd.ms-excel;
name="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?="
</code></pre>
<p>Please note both "<strong>Content-Transfer-Encoding</strong>" have base64</p>
| [
{
"answer_id": 271832,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 5,
"selected": true,
"text": "Content-Transfer-Encoding"
},
{
"answer_id": 1687765,
"author": "Ringding",
"author_id": 135811,
"author_profile": "https://Stackoverflow.com/users/135811",
"pm_score": 2,
"selected": false,
"text": "decode_header"
},
{
"answer_id": 2955981,
"author": "John Machin",
"author_id": 84270,
"author_profile": "https://Stackoverflow.com/users/84270",
"pm_score": 0,
"selected": false,
"text": "Content-Type: application/vnd.ms-excel;\n name=\"=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=\"\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
271,661 | <p>I have a problem with Lucene.NET. During an index, I receive the error 'Access to the path segments is denied'. Or sometimes 'Access to the path deletable is denied'. I eventually gave 'Everyone' full security rights to the index directory, but the problem still existed.</p>
<p>I then found out that during the index run, lucene renames the segments file to 'segments.new', and <em>then</em> this error happens. I guess some process still tries to read from the old segments file after it has been renamed? I have no clue as to why this happens, or how to fix this. Strangely enough, my co-developers can run the index on their computer without a problem.</p>
<p>The error happens at happens in Lucene.Net.Index.IndexModifier.AddDocument(Document).</p>
<p>Any ideas would be much appreciated.</p>
| [
{
"answer_id": 1325676,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " doc.Add(new Field(\"URL\", \"C:/Users/blabla/(convert-csharp)/IMssg\", Field.Store.YES, Field.Index.TOKENIZED));\n\n writer.AddDocument(doc);\n"
},
{
"answer_id": 1885765,
"author": "msr",
"author_id": 229350,
"author_profile": "https://Stackoverflow.com/users/229350",
"pm_score": 1,
"selected": false,
"text": " int attemptNo = 0;\n while (attemptNo < 2)\n {\n try\n {\n writer.AddDocument(doc);\n break;\n }\n catch (Exception e)\n {\n String ErrMsg = String.Format(\"{0} ({1}): While adding Document {2}/{3}, caught {4}\", DateTime.Now, attemptNo, doc.GetField(\"kanji\").StringValue(), doc.GetField(\"kana\").StringValue(), e.Message);\n attemptNo++;\n System.Threading.Thread.Sleep(30);\n Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)delegate()\n {\n ViewModel.Log.Add(ErrMsg);\n });\n }\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,665 | <p>I have a client sending me requests without HTTP chunking (they use content-length). When my server responds, chunking is enabled, and the client can't handle this - even though they should be able to as they are using HTTP 1.1..... </p>
<p>I have tried to disable chunking by removing the entry below from the axis2 config file (axis2.xml) but the response is still going back chunked.</p>
<p>chunked</p>
<p>So the question is, is there somewhere else that the chunking is being enabled that is over-riding the axis2 setting? In tomcat setting perhaps?</p>
<p>Webserver details - tomcat 6.0.16, axis2 2.1.3</p>
<p>Thanks
Mike</p>
| [
{
"answer_id": 1394439,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 2,
"selected": false,
"text": "myStub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,668 | <p>Is there a way of converting special folder paths to a full file name (and back) or do I need to code my own (not hard I know, but no point if it exists)</p>
<p>e.g. I want to store the file name of a template for an application, which the user can then change, it exists in the LocalApplicationData folder.</p>
<p>what I would like to store is the location of the file in the format:</p>
<p>%LOCALAPPDATA%\MyApp\Templates\Report Template.xls</p>
<p>so that this application file can be used by many users, each user when they open it will get the Report Template from their own local app directory.</p>
<p>I can write</p>
<pre><code>replace("%LOCALAPPDATA%", _
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.LocalApplicationData))
and vice versa
</code></pre>
<p>when I come to save the file location, however is there a System.IO (or similar) call to do this for me, rather than having to go through every possible special folder?</p>
| [
{
"answer_id": 271683,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": true,
"text": "static void Main(string[] args)\n{\n var values = Enum.GetValues(typeof(Environment.SpecialFolder));\n\n foreach (Environment.SpecialFolder value in values)\n Console.WriteLine(value + \" : \" + Environment.GetFolderPath(value));\n\n Console.ReadKey();\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6684/"
] |
271,672 | <p>I tried this on J2ME</p>
<pre><code>try {
Image immutableThumb = Image.createImage( temp, 0, temp.length);
} catch (Exception ex) {
System.out.println(ex);
}
</code></pre>
<p>I hit this error:
<code>java.lang.IllegalArgumentException:</code></p>
<p>How do I solve this?</p>
| [
{
"answer_id": 2461625,
"author": "Cipi",
"author_id": 191164,
"author_profile": "https://Stackoverflow.com/users/191164",
"pm_score": 0,
"selected": false,
"text": "FFD8"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,675 | <p>I have a binded DataGridView where depending on some BoundItem property value that line will be read only. What is the best way to implement this?
Thanks</p>
| [
{
"answer_id": 271679,
"author": "CestLaGalere",
"author_id": 6684,
"author_profile": "https://Stackoverflow.com/users/6684",
"pm_score": 0,
"selected": false,
"text": "private sub MyView_RowEnter(...) handles MyView.RowEnter\n MyView.Rows(e.Rowindex).ReadOnly = (condition)\nend sub\n"
},
{
"answer_id": 3176471,
"author": "x77",
"author_id": 494800,
"author_profile": "https://Stackoverflow.com/users/494800",
"pm_score": 2,
"selected": false,
"text": "Private Sub Dgv_CellBeginEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles Dgv.CellBeginEdit\n If YourCondition(BoundItem.Property) then e.cancel = true\nEnd Sub\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,688 | <p><a href="http://dl.getdropbox.com/u/240752/stars.gif" rel="nofollow noreferrer">My screenshot http://dl.getdropbox.com/u/240752/stars.gif</a></p>
<p>I want to have it so that only the text is underlined. The only way I can see of doing this is this:</p>
<pre><code>.no-underline {
text-decoration:none;
}
.underline {
text-decoration:underline;
}
<a href="#" class="no-underline"><span class="underline">Average customer review rating</span><img src="img/five-stars.gif" alt="five stars" width="78" height="16" title="5 star review rating" /></a>
</code></pre>
<p>Is this the best way? or does someone know a leaner way? Thanks.</p>
| [
{
"answer_id": 271697,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 4,
"selected": true,
"text": "<a href=\"#\" class=\"imgLink\"><span>Link Text</span> <img src=\"...\"></a>\n\na.imgLink { text-decoration: none; }\na.imgLink span { text-decoration: underline; }\n"
},
{
"answer_id": 271732,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 0,
"selected": false,
"text": "<a class=\"imgLink\" href=\"\">some text<img src=\"\" /></a>"
},
{
"answer_id": 1915596,
"author": "elliott",
"author_id": 230861,
"author_profile": "https://Stackoverflow.com/users/230861",
"pm_score": 0,
"selected": false,
"text": "a.externalLink{\n padding-right: 15px;\n background: transparent url('badge.png') no-repeat center right;\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
271,699 | <p>Is there any way to (unit) test my own HtmlHelpers? In case when I'd like to have custom control (rendered by HtmlHelper) and I know requierements for that control how could I write tests first - and then write code? Is there a specific (nice) way to do that? </p>
<p>Is it worth?</p>
| [
{
"answer_id": 747186,
"author": "Marc Climent",
"author_id": 58791,
"author_profile": "https://Stackoverflow.com/users/58791",
"pm_score": 6,
"selected": true,
"text": " public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData)\n {\n var mocks = new MockRepository();\n\n var cc = mocks.DynamicMock<ControllerContext>(\n mocks.DynamicMock<HttpContextBase>(),\n new RouteData(),\n mocks.DynamicMock<ControllerBase>());\n\n var mockViewContext = mocks.DynamicMock<ViewContext>(\n cc,\n mocks.DynamicMock<IView>(),\n viewData,\n new TempDataDictionary());\n\n var mockViewDataContainer = mocks.DynamicMock<IViewDataContainer>();\n\n mockViewDataContainer.Expect(v => v.ViewData).Return(viewData);\n\n return new HtmlHelper(mockViewContext, mockViewDataContainer);\n }\n"
},
{
"answer_id": 5957990,
"author": "CRice",
"author_id": 55693,
"author_profile": "https://Stackoverflow.com/users/55693",
"pm_score": 3,
"selected": false,
"text": "HtmlHelper<T>"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] |
271,700 | <p>As far as i know the EAP editions of JBoss Application Server (AS) are just a bunch of community edition JBoss projects with some sugar.</p>
<p>So, what is the <strong>community edition</strong> of the JBoss Application Server that <strong>JBoss EAP 4.3.0</strong> corresponds to?</p>
| [
{
"answer_id": 17274131,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 1,
"selected": false,
"text": "settings.xml"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23428/"
] |
271,706 | <p>I basically have a page which shows a "processing" screen which has been flushed to the browser. Later on I need to redirect this page, currently we use meta refresh and this normally works fine. </p>
<p>With a new payment system, which includes 3D secure, we potentially end up within an iframe being directed back to our site from a third party.</p>
<p>I need to be able to redirect from this page, either using javascript or meta-refresh, and bust out of the iframe if it exists.</p>
<p>Cheers!</p>
<p>(I have done busting out of iframes before but can't find my old code and a google search was useless, thought it was the perfect time to try Stackoverflow out!)</p>
| [
{
"answer_id": 271902,
"author": "Ben Lynch",
"author_id": 15363,
"author_profile": "https://Stackoverflow.com/users/15363",
"pm_score": 3,
"selected": true,
"text": "<script type=\"text/javascript\" language=\"javascript\">\n if (top.frames.length>0)\n setTimeout(\"top.location = window.location;\",100);\n</script>\n"
},
{
"answer_id": 272218,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 0,
"selected": false,
"text": "<SCRIPT TYPE=\"text/JavaScript\">\n if (window == top){top.location.replace(\"/foo.html\");}\n</SCRIPT>\n"
},
{
"answer_id": 11338554,
"author": "Devaroop",
"author_id": 909297,
"author_profile": "https://Stackoverflow.com/users/909297",
"pm_score": 0,
"selected": false,
"text": "parent.document.location = \"http://www.google.com\"\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15363/"
] |
271,710 | <p>The code looks like below:</p>
<pre><code>namespace Test
{
public interface IMyClass
{
List<IMyClass> GetList();
}
public class MyClass : IMyClass
{
public List<IMyClass> GetList()
{
return new List<IMyClass>();
}
}
}
</code></pre>
<p>When I Run Code Analysis i get the following recommendation.</p>
<blockquote>
<p>Warning 3 CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection</p>
</blockquote>
<p>How should I fix this and what is good practice here?</p>
| [
{
"answer_id": 271711,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "IList<T>"
},
{
"answer_id": 271719,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": -1,
"selected": false,
"text": "//using System.Collections.ObjectModel;\n\nCollection<MyClass> myCollection = new Collection<MyClass>(myList);\n"
},
{
"answer_id": 271726,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "Collection<T>"
},
{
"answer_id": 271842,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 9,
"selected": true,
"text": "List<T>"
},
{
"answer_id": 8859865,
"author": "Konstantin Isaev",
"author_id": 1026676,
"author_profile": "https://Stackoverflow.com/users/1026676",
"pm_score": 0,
"selected": false,
"text": "this.InternalData.Filter(crteria).ToList();\n"
},
{
"answer_id": 33654749,
"author": "NullReference",
"author_id": 2170850,
"author_profile": "https://Stackoverflow.com/users/2170850",
"pm_score": 1,
"selected": false,
"text": "List<T>"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11135/"
] |
271,718 | <p>In a detailsview, how can I prepopulate one of the textboxes on the insertcommand (When the user clicks insert and the view is insert).</p>
<p>I think this would work for codebehind:</p>
<p>Dim txtBox As TextBox = FormView1.FindControl("txtbox")</p>
<p>txtbox.Text = "Whatever I want"</p>
<p>Is this right? What do I need in the aspx (not as sure)? Also, I'm assuming the server-side code will go in the itemcommand or insertcreating event.</p>
<p>I have typed this in VB.NET but I am using C# (I can do both so on a language agnostic forum I might type the problem in another language). I am also using a SqlDataSource, with my parameters and insert/delete/edit commands all created.</p>
<p>I am trying to generate a random GUID (using the GUID object), which will be prepopulated in the textbox.</p>
<p>Also, is the postbackurl property of a button not another way of preserving form state?</p>
<p>Thanks</p>
| [
{
"answer_id": 684039,
"author": "Anthony K",
"author_id": 1682,
"author_profile": "https://Stackoverflow.com/users/1682",
"pm_score": 0,
"selected": false,
"text": "dvDetails.ChangeMode(DetailsViewMode.Insert)\npnlDetailMenu.Visible = True\nDim ColumnTextBox As TextBox\nColumnTextBox = dvDetails.Rows(0).Cells(1).Controls(0)\nIf Not ColumnTextBox Is Nothing Then\n ColumnTextBox.Text = \"Initial Value\"\nEnd If\n"
},
{
"answer_id": 696436,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 1,
"selected": false,
"text": "<asp:TemplateField>\n <InsertItemTemplate>\n <asp:TextBox ID=\"txtField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </InsertItemTemplate>\n <ItemTemplate>\n <asp:Label ID=\"lblField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </ItemTemplate>\n</asp:TemplateField>\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32484/"
] |
271,724 | <p>I am playing around with ASP.NET MVC for the first time, so I apologize in advance if this sounds academic. </p>
<p>I have created a simple content management system using ASP.NET MVC. The url to retrieve a list of content, in this case, announcements, looks like:</p>
<pre><code>http://www.mydomain.com/announcements/list/10
</code></pre>
<p>This will return the top ten most recent announcements.</p>
<p>My questions are as follows:</p>
<ol>
<li><p>Is it possible for any website to consume this service? Or would I also have to expose it using something like WCF?</p></li>
<li><p>What are some examples, of how to consume this service to display this data on another website? I'm primarily programming in the .NET world, but I'm thinking if I could consume the service using javascript, or do something with Json, it could really work for any technology.</p></li>
</ol>
<p>I am looking to dynamically generate something like the following output:</p>
<pre><code><div class="announcement">
<h1>Title</h1>
<h2>Posted Date</h3>
<p>Teaser</p>
<a href="www.someotherdomain.com">More</a>
</div>
</code></pre>
<hr>
<p>For now ... is it possible to return an Html representation and display it in a webpage? Is this possible using just Javascript?</p>
| [
{
"answer_id": 684039,
"author": "Anthony K",
"author_id": 1682,
"author_profile": "https://Stackoverflow.com/users/1682",
"pm_score": 0,
"selected": false,
"text": "dvDetails.ChangeMode(DetailsViewMode.Insert)\npnlDetailMenu.Visible = True\nDim ColumnTextBox As TextBox\nColumnTextBox = dvDetails.Rows(0).Cells(1).Controls(0)\nIf Not ColumnTextBox Is Nothing Then\n ColumnTextBox.Text = \"Initial Value\"\nEnd If\n"
},
{
"answer_id": 696436,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 1,
"selected": false,
"text": "<asp:TemplateField>\n <InsertItemTemplate>\n <asp:TextBox ID=\"txtField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </InsertItemTemplate>\n <ItemTemplate>\n <asp:Label ID=\"lblField\" runat=\"server\" Text='<%# Bind(\"GUID\") %>'/>\n </ItemTemplate>\n</asp:TemplateField>\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
271,725 | <p>I'm working on a search module that searches in text columns that contains html code. The queries are constructed like: WHERE htmlcolumn LIKE '% searchterm %';</p>
<p>Default the modules searches with spaces at both end of the searchterms, with wildcards at the beginning and/or the end of the searchterms these spaces are removed (*searchterm -> LIKE '%searchterm %'; Also i've added the possibility to exclude results with certain words (-searchterm -> NOT LIKE '% searchterm %'). So far so good.</p>
<p>The problem is that words that that are preceded by an html-tag are not found (<code><br/></code>searchterm is not found when searching on LIKE '% searchterm.., also words that come after a comma or end with a period etc.).
What i would like to do is search for words that are not preceded or followed by the characters A-Z and a-z. Every other characters are ok.</p>
<p>Any ideas how i should achieve this? Thanks!</p>
| [
{
"answer_id": 272043,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM `t` WHERE `htmlcolumn` REGEXP '[[:<:]]term[[:>:]]'\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21238/"
] |
271,730 | <p>I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database. </p>
<p>I want to query for the last ten posted items BUT with the constraint of a maximum of 3 items can come from any single user. </p>
<p>What is the best way of doing it? My preferred solution is a constraint that is put on the SQL query requesting the last ten items. But ideas on how to set up the database design is very welcome.</p>
<p>Thanks in advance!</p>
<p>BR</p>
| [
{
"answer_id": 271768,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "SELECT\n i.UserId,\n i.ImageId\nFROM\n UserSuppliedImages i\nWHERE\n /* second valid ImageId */\n ImageId = (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n )\n OR\n /* second valid ImageId */\n ImageId = (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n AND ImageId < (\n SELECT MAX(ImageId)\n FROM UserSuppliedImages\n WHERE UserId = i.UserId\n )\n )\n /* you get the picture... \n the more \"per user\" images you want, the more complex this will get */\nLIMIT 10;\n"
},
{
"answer_id": 271996,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 4,
"selected": true,
"text": "SELECT `img`.`id` , `img`.`userid`\nFROM `img`\nWHERE 3 > (\nSELECT count( * )\nFROM `img` AS `img1`\nWHERE `img`.`userid` = `img1`.`userid`\nAND `img`.`id` > `img1`.`id` )\nORDER BY `img`.`id` DESC\nLIMIT 10 \n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103373/"
] |
271,736 | <p>Given a html document, what is the most correct and concise regular expression pattern to remove the query strings from each url in the document?</p>
| [
{
"answer_id": 271778,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "/href=\"([^\\?\"]*?)\\?[^\\\"]*\"/\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6691/"
] |
271,741 | <p>I'm trying to parse a html page and extract 2 values from a table row.
The html for the table row is as follows: -</p>
<pre><code><tr>
<td title="Associated temperature in (ºC)" class="TABLEDATACELL" nowrap="nowrap" align="Left" colspan="1" rowspan="1">Max Temperature (ºC)</td>
<td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1">6</td>
<td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1"> 13:41:30</td>
</tr>
</code></pre>
<p>and the expression I have at the moment is:</p>
<pre><code><tr>[\s]<td[^<]+?>Max Temperature[\w\s]*</td>[\s]
<td[^<]+?>(?<value>([\d]+))</td>[\s]
<td[^<]+?>(?<time>([\d\:]+))</td>[\s]</tr>
</code></pre>
<p>However I don't seem to be able to extract any matches.
Could anyone point me in the right direction, thanks.</p>
| [
{
"answer_id": 271748,
"author": "siukurnin",
"author_id": 35273,
"author_profile": "https://Stackoverflow.com/users/35273",
"pm_score": 0,
"selected": false,
"text": "<td[^<]+?>"
},
{
"answer_id": 271750,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 0,
"selected": false,
"text": "<tr>[\\s]<td[^<]+?>Max Temperature[\\w\\s]*</td>[\\s]\n"
},
{
"answer_id": 271751,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 2,
"selected": true,
"text": "<tr>\\s*\n<td[^>]*>.*?</td>\\s*\n<td[^>]*>\\s*(?<value>\\d+)\\s*</td>\\s*\n<td[^>]*>\\s*(?<time>\\d{2}:\\d{2}:\\d{2})\\s*</td>\\s*\n</tr>\\s*\n"
},
{
"answer_id": 271754,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "<tr>[\\s]<td[^<]+?>Max Temperature[^<]*</td>[\\s]\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,742 | <p>What are the advantages of rendering a control like this:</p>
<pre><code><% Html.RenderPartial("MyControl") %> or
<%=Html.TextBox("txtName", Model.Name) %>
</code></pre>
<p>over the web Forms style:</p>
<pre><code><uc1:MyControl ID=MyControl runat=server />
</code></pre>
<p>I understand that performance can be one reason because no object needs to be created but having the possibility of calling it from the codebehing just to do some basic rendering logic can be very useful. </p>
<p>If this is discouraged then how you are suposed to deal with this scenarios:</p>
<ul>
<li><p>You need to make the control visible conditionally and you dont want to fill your HTML with rendering logic.</p></li>
<li><p>You have <code><input type="text" value="<%= Model.Name %>" /></code> but you need to check if Model is null because otherways a NullPointerException will raise.</p></li>
</ul>
<p><strong>[EDIT]</strong> I asked this when I was beginning with ASP MVC, now I see the advantages of the MVC way like in Cristian answer.</p>
| [
{
"answer_id": 272531,
"author": "Santiago Corredoira",
"author_id": 4264,
"author_profile": "https://Stackoverflow.com/users/4264",
"pm_score": 0,
"selected": false,
"text": "<custom:HtmlTextBox ID=\"txtName\" runat=\"server\" />\n"
},
{
"answer_id": 272737,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 3,
"selected": true,
"text": "<%= Html.BindTextBox(\"txtName\", Model, \"Person.Name\") %>\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4264/"
] |
271,743 | <p>What's the difference between <code><b></code> and <code><strong></code>, <code><i></code> and <code><em></code> in HTML/XHTML? When should you use each?</p>
| [
{
"answer_id": 271755,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 8,
"selected": false,
"text": "<b>"
},
{
"answer_id": 271756,
"author": "James",
"author_id": 7837,
"author_profile": "https://Stackoverflow.com/users/7837",
"pm_score": 5,
"selected": false,
"text": "<strong>"
},
{
"answer_id": 271761,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<b>"
},
{
"answer_id": 271763,
"author": "Antonio Louro",
"author_id": 15528,
"author_profile": "https://Stackoverflow.com/users/15528",
"pm_score": 0,
"selected": false,
"text": "<strong>"
},
{
"answer_id": 271776,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 11,
"selected": true,
"text": "<b>"
},
{
"answer_id": 271788,
"author": "Kariem",
"author_id": 12039,
"author_profile": "https://Stackoverflow.com/users/12039",
"pm_score": 3,
"selected": false,
"text": "<b>"
},
{
"answer_id": 271798,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "<b>"
},
{
"answer_id": 275515,
"author": "mwiik",
"author_id": 35863,
"author_profile": "https://Stackoverflow.com/users/35863",
"pm_score": 3,
"selected": false,
"text": "<strong>"
},
{
"answer_id": 275576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<b>"
},
{
"answer_id": 5576545,
"author": "ritakriti",
"author_id": 696155,
"author_profile": "https://Stackoverflow.com/users/696155",
"pm_score": -1,
"selected": false,
"text": "<strong>"
},
{
"answer_id": 8521088,
"author": "Danubian Sailor",
"author_id": 531954,
"author_profile": "https://Stackoverflow.com/users/531954",
"pm_score": 1,
"selected": false,
"text": "<b>"
},
{
"answer_id": 19988223,
"author": "Rick Westera",
"author_id": 672086,
"author_profile": "https://Stackoverflow.com/users/672086",
"pm_score": 3,
"selected": false,
"text": "<b>"
},
{
"answer_id": 25671886,
"author": "Thomas Eding",
"author_id": 239916,
"author_profile": "https://Stackoverflow.com/users/239916",
"pm_score": 3,
"selected": false,
"text": "<em>"
},
{
"answer_id": 32511723,
"author": "ahnbizcad",
"author_id": 2951835,
"author_profile": "https://Stackoverflow.com/users/2951835",
"pm_score": -1,
"selected": false,
"text": "<strong>"
},
{
"answer_id": 37764775,
"author": "Muhammad Awais",
"author_id": 3901944,
"author_profile": "https://Stackoverflow.com/users/3901944",
"pm_score": 0,
"selected": false,
"text": "<b>This text is bold</b>\n"
},
{
"answer_id": 43477006,
"author": "adnan2nd",
"author_id": 985754,
"author_profile": "https://Stackoverflow.com/users/985754",
"pm_score": 2,
"selected": false,
"text": "<i>"
},
{
"answer_id": 60089299,
"author": "Touhidur Rahaman",
"author_id": 12098890,
"author_profile": "https://Stackoverflow.com/users/12098890",
"pm_score": 1,
"selected": false,
"text": "<b>"
},
{
"answer_id": 62904344,
"author": "squarecandy",
"author_id": 947370,
"author_profile": "https://Stackoverflow.com/users/947370",
"pm_score": 4,
"selected": false,
"text": "<strong>"
},
{
"answer_id": 63466498,
"author": "hammad khan",
"author_id": 5307595,
"author_profile": "https://Stackoverflow.com/users/5307595",
"pm_score": -1,
"selected": false,
"text": "simple text this is test text normal text\n\n\n\nsimple text this is important textwith normal text\n"
},
{
"answer_id": 68564761,
"author": "Junaga",
"author_id": 6655130,
"author_profile": "https://Stackoverflow.com/users/6655130",
"pm_score": 1,
"selected": false,
"text": "<b>"
},
{
"answer_id": 72599307,
"author": "Al Mamun Khan",
"author_id": 15274012,
"author_profile": "https://Stackoverflow.com/users/15274012",
"pm_score": 1,
"selected": false,
"text": "<em>"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
271,747 | <p>I'd like to send mail without bothering with the SMTP-Server which is used for delivery.</p>
<p>So <a href="http://java.sun.com/products/javamail/" rel="noreferrer">JavaMail API</a> doesn't work for me because I have to specify a SMTP server to connect to.</p>
<p>I'd like the library to find out on its own which SMTP server is responsible for which email address by querying the MX record of the mail address domain.</p>
<p>I'm looking for something like <a href="https://aspirin.dev.java.net/" rel="noreferrer">Aspirin</a>. Unfortunately I can't use Aspirin itself because the development stopped 2004 and the library fails to communicate with modern spam hardened servers correctly.</p>
<p>An embeddable version of <a href="http://james.apache.org/" rel="noreferrer">James</a> would do the task. But I haven't found documentation concerning whether this is possible.</p>
<p>Or does anyone know about other libraries I could use?</p>
| [
{
"answer_id": 271829,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 4,
"selected": false,
"text": "<dependency>\n <groupId>dnsjava</groupId>\n <artifactId>dnsjava</artifactId>\n <version>2.0.1</version>\n</dependency>\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17428/"
] |
271,762 | <p>Can someone supply me with a regex to match a search term that is not preceded or followed by <code>[a-z]</code> and <code>[A-Z]</code>? (Other characters are OK.) I.e., when searching for <code>key</code>, I don't want <code>keyboard</code> in my search results, but <code>key.</code> is okay.</p>
| [
{
"answer_id": 271769,
"author": "siukurnin",
"author_id": 35273,
"author_profile": "https://Stackoverflow.com/users/35273",
"pm_score": 1,
"selected": false,
"text": "\\b"
},
{
"answer_id": 271770,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "\\bkey\\b"
},
{
"answer_id": 271801,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "[^A-Za-z]key[^A-Za-z]"
},
{
"answer_id": 271883,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "[^\\w]key[^\\w]"
},
{
"answer_id": 271898,
"author": "Anders Waldenborg",
"author_id": 24082,
"author_profile": "https://Stackoverflow.com/users/24082",
"pm_score": 2,
"selected": false,
"text": "[[:<:]]key[[:>:]]"
},
{
"answer_id": 1639703,
"author": "davew",
"author_id": 198408,
"author_profile": "https://Stackoverflow.com/users/198408",
"pm_score": 0,
"selected": false,
"text": "OR"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21238/"
] |
271,767 | <p>I have in my Form constructor, after the InitializeComponent the following code:</p>
<pre><code>using (WebClient client = new WebClient())
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync("http://example.com/version.txt");
}
</code></pre>
<p>When I start my form, the UI doesn't appears till client_DownloadDataCompleted is raised.
The client_DownloadDataCompleted method is empty, so there's no problem there.</p>
<p>What I'm doing wrong?
How is supposed to do this without freezing the UI?</p>
<p>Thanks for your time.<br>
Best regards.</p>
<p><strong>FULL CODE:</strong> </p>
<p><strong>Program.cs</strong></p>
<pre><code>using System;
using System.Windows.Forms;
namespace Lala
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
</code></pre>
<p><strong>Form1.cs</strong></p>
<pre><code>using System;
using System.Net;
using System.Windows.Forms;
namespace Lala
{
public partial class Form1 : Form
{
WebClient client = new WebClient();
public Form1()
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(new Uri("http://www.google.com"));
InitializeComponent();
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
textBox1.Text += "A";
}
}
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 12);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(12, 41);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(468, 213);
this.textBox1.TabIndex = 1;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 266);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
}
}
</code></pre>
| [
{
"answer_id": 271790,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 0,
"selected": false,
"text": " int a, b;\n ThreadPool.GetMaxThreads(out a, out b);\n"
},
{
"answer_id": 5544274,
"author": "Roman Pushkin",
"author_id": 337085,
"author_profile": "https://Stackoverflow.com/users/337085",
"pm_score": 1,
"selected": false,
"text": "client.Proxy = GlobalProxySelection.GetEmptyProxy();\n"
},
{
"answer_id": 22886642,
"author": "Wiseman",
"author_id": 125264,
"author_profile": "https://Stackoverflow.com/users/125264",
"pm_score": 3,
"selected": false,
"text": "WebClient webClient = new WebClient();\nwebClient.Proxy = null;\n... Do whatever else ...\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
271,815 | <p>Is there a better way to write this code? </p>
<p>I want to show a default value ('No data') for any empty fields returned by the query:</p>
<pre><code>$archivalie_id = $_GET['archivalie_id'];
$query = "SELECT
a.*,
ip.description AS internal_project,
o.description AS origin,
to_char(ad.origin_date,'YYYY') AS origin_date
FROM archivalie AS a
LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id
LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id
LEFT JOIN origin AS o ON a.origin_id = o.id
WHERE a.id = $archivalie_id";
$result = pg_query($db, $query);
while ($row = pg_fetch_object($result))
{
$no_data = '<span class="no-data">No data</span>';
$internal_project = ($row->internal_project != '') ? $row->internal_project : $no_data;
$incoming_date = ($row->incoming_date != '') ? $row->incoming_date : $no_data;
$origin = ($row->origin != '') ? $row->origin : $no_data;
}
</code></pre>
| [
{
"answer_id": 271826,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 3,
"selected": true,
"text": "function dbValue($value, $default=null)\n{\n if ($default===null) {\n $default='<span class=\"no-data\">No data</span>';\n }\n if (!empty($value)) {\n return $value;\n } else {\n return $default;\n }\n}\n"
},
{
"answer_id": 271844,
"author": "markus",
"author_id": 11995,
"author_profile": "https://Stackoverflow.com/users/11995",
"pm_score": 1,
"selected": false,
"text": "$archivalie_id = pg_escape_string($_GET['archivalie_id']);\n"
},
{
"answer_id": 271887,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "SELECT \n IFNULL(NULLIF(a.field1, ''), 'No data') AS field1, \n IFNULL(NULLIF(a.field2, ''), 'No data') AS field2, \n IFNULL(NULLIF(ip.description, ''), 'No data') AS internal_project,\n IFNULL(NULLIF(o.description, ''), 'No data') AS origin,\n to_char(ad.origin_date,'YYYY') AS origin_date \nFROM \n archivalie AS a \n LEFT JOIN archivalie_dating AS ad ON a.id = ad.archivalie_id \n LEFT JOIN internal_project AS ip ON a.internal_project_id = ip.id\n LEFT JOIN origin AS o ON a.origin_id = o.id \nWHERE \n a.id = $archivalie_id\n"
},
{
"answer_id": 271915,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 0,
"selected": false,
"text": "$query = \"SELECT \n a.*, \n COALESCE(ip.description,'NO_DATA') AS internal_project,\n COALESCE(o.description,'NO_DATA') AS origin,\n COALESCE(to_char(ad.origin_date,'YYYY'),'NO_DATA') AS origin_date \n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
271,821 | <p>I have a site that usually has news items at the top of the homepage, and sometimes (for specific periods) will have one or more 'quicklinks' beneath the news items, to guide users to pages of topical interest. Beneath those is the usual blurb.</p>
<p>We have alternative language versions of these sites, which often don't contain either the news items or the quicklinks, but may do from time to time.</p>
<p>Previously, when the appearance was less dynamic, each section was absolutely positioned, with a top attribute configured appropriately. But as more subtle variations were required, I find myself chopping and changing both the base HTML and the stylesheet rules. </p>
<p>My question is what do people think about the different approaches to this problem, and do they have any suggestions that I haven't considered. Achieving the desired result is easy, but I'm thinking of good coding practice that makes the site easier to read & debug.</p>
<p>I could have separate style classes for each variation of each item:</p>
<pre><code>.news {top: 100px; etc...;}
.news2 {top: 150px; etc...;}
.ql {top: 150px; etc...;}
.ql2 {top: 200px; etc...;}
.main {top: 200px; etc...;}
.main2 {top: 250px; etc...;}
</code></pre>
<p>...which seems a little too verbose.</p>
<p>Or, perhaps:</p>
<pre><code>.news {etc...;}
.ql {etc...;}
.main {etc...;}
.top100 {top: 100px;}
.top150 {top: 150px;}
.top200 {top: 200px;}
.top250 {top: 250px;}
</code></pre>
<p>Somewhat more compact, and it keeps the styling in the stylesheet and away from the HTML.</p>
<p>Or, perhaps even:</p>
<pre><code>.news {etc...;}
.ql {etc...;}
.main {etc...;}
</code></pre>
<p>in HTML:</p>
<pre><code><div class="news" style="top:100px;">
<div class="ql" style="top:150px;">
<div class="main" style="top:200px;">
</code></pre>
<p>This is the most 'direct' solution, but clearly some of the styling is in the HTML which from a purists point of view is a 'no-no'; There are practical reasons for this view, but in this case, this is probably the easiest way to handle the varied and arbitrary changes that will be requested.</p>
<p>Note: The site was (poorly) designed by a 3rd party, although I have tried to rescue it without entirely re-writing it. However, the site will be re-developed, possibly as early as Q3 or Q4 2009. At that stage, I'd hope to be moving away from a absolutely positioned approach, to one that is more fluid - so this question is about what to do in the interim, and also as a general question of style.</p>
| [
{
"answer_id": 271827,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": true,
"text": ".top100 {top: 100px;}\n.top150 {top: 150px;}\n.top200 {top: 200px;}\n.top250 {top: 250px;}\n"
},
{
"answer_id": 275745,
"author": "Lee Kowalkowski",
"author_id": 30945,
"author_profile": "https://Stackoverflow.com/users/30945",
"pm_score": 1,
"selected": false,
"text": "\"<classname>\""
},
{
"answer_id": 281352,
"author": "CJM",
"author_id": 6898,
"author_profile": "https://Stackoverflow.com/users/6898",
"pm_score": 0,
"selected": false,
"text": ".news, .news2 {top: 100px; etc...;}\n.news2 {top: 150px;}\n.ql, .ql2 {top: 150px; etc...;}\n.ql2 {top: 200px;}\n.main, .main2 {top: 200px; etc...;}\n.main2 {top: 250px;}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6898/"
] |
271,843 | <p>Does that mean that I can't share a Form between delphi 2007 and 2009?</p>
| [
{
"answer_id": 275156,
"author": "Ondrej Kelle",
"author_id": 11480,
"author_profile": "https://Stackoverflow.com/users/11480",
"pm_score": 4,
"selected": false,
"text": "unit Delphi2009Form;\n\ninterface\n\nuses\n Windows, Classes, SysUtils, Controls, Forms;\n\ntype\n{$IFDEF VER200}\n TDelphi2009Form = class(TForm);\n{$ELSE}\n TDelphi2009Form = class(TForm)\n private\n procedure ReaderError(Reader: TReader; const Message: string; var Handled: Boolean);\n protected\n procedure ReadState(Reader: TReader); override;\n end;\n\n TReaderErrorProc = procedure(const Message: string);\n\nvar\n ReaderErrorProc: TReaderErrorProc = nil;\n{$ENDIF}\n\nimplementation\n\n{$IFNDEF VER200}\ntype\n THackReader = class(TReader);\n\nprocedure TDelphi2009Form.ReaderError(Reader: TReader; const Message: string; var Handled: Boolean);\nbegin\n with THackReader(Reader) do\n Handled := AnsiSameText(PropName, 'DoubleBuffered') or AnsiSameText(PropName, 'ParentDoubleBuffered');\n if Handled and Assigned(ReaderErrorProc) then\n ReaderErrorProc(Message);\nend;\n\nprocedure TDelphi2009Form.ReadState(Reader: TReader);\nbegin\n Reader.OnError := ReaderError;\n inherited ReadState(Reader);\nend;\n{$ENDIF}\n\nend.\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
271,850 | <p>After upgrading a project from Delphi 2007 to Delphi 2009 I'm getting an Unknown memory leak, so far I've been tryin to track it down using fastMM, here is what fastMM stack trace reports:</p>
<pre><code>A memory block has been leaked. The size is: 20
This block was allocated by thread 0x111C, and the stack trace (return addresses)
at the time was:
40339E [System.pas][System][@GetMem][3412] 534873 [crtl][_malloc]
56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918]
56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
562D48 [DBCommon.pas][DBCommon][TFilterExpr.PutExprNode][1583]
408E46 [System.pas][System][DynArraySetLength][20464]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
408E92 [System.pas][System][@DynArraySetLength][20486]
528C1B [Forms.pas][Forms][TCustomForm.DoCreate][3260]
171A1A [GetRawStackTrace]
The block is currently used for an object of class: Unknown
The allocation number is: 302844
</code></pre>
<p>And sometimes I get this:</p>
<pre><code>A memory block has been leaked. The size is: 20
This block was allocated by thread 0x111C, and the stack trace (return addresses)
at the time was:
40339E [System.pas][System][@GetMem][3412]
534873 [crtl][_malloc]
56D1C4 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3918]
56D316 [canex.cpp][MidasLib][DllGetDataSnapClassObject][3961]
77DC921A [RtlAnsiStringToUnicodeString]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
7726B8F5 [GetProcAddress]
7726B907 [GetProcAddress]
589B1E [ossrv.cpp][MidasLib][DllGetDataSnapClassObject][3163]
56D5EE [canex.cpp][MidasLib][DllGetDataSnapClassObject][4085]
408E92 [System.pas][System][@DynArraySetLength][20486]
The block is currently used for an object of class: Unknown
</code></pre>
<p>Is there some better way to figure out what really is causing the Memory leak?</p>
| [
{
"answer_id": 272370,
"author": "zendar",
"author_id": 25732,
"author_profile": "https://Stackoverflow.com/users/25732",
"pm_score": 1,
"selected": false,
"text": "@DynArraySetLength"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
271,870 | <p>I have a form whose controls I want to enable/disable depending on the values in a ComboBox control. This ComboBox control is linked, like all the other controls in the form, to a table. Inside the ComboBox's Change event, I placed the code that enables/disables the other controls.</p>
<p>The problem I have is that when I open the form, the controls are not enabled/disabled. I have to re-choose the ComboBox value to make all other controls enable or disable.</p>
<p>One thing I noticed is that the RecordSet control inside the ComboBox often does not change to the value shown in the value property of the ComboBox.</p>
<p>I tried using <br>
<code>combobox.recordset.filter = "Key = " & combobox.value</code><br>
but I get the error <br>
<code>Operation is not supported for this type of object.</code></p>
<hr>
<h2>Update</h2>
<p>I think my problem has to do more in how I'm accessing the values in the combobox.recordset. I was under the impression that combobox.recordset held the value received from the table. But, it seems to hold the first record from the recordsource.</p>
<p>I'm guessing that I will need to search those values I need by using another recordset object.</p>
| [
{
"answer_id": 274294,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 1,
"selected": false,
"text": " Private Sub cmbComboBox1_AfterUpdate()\n Dim strRowsource As String\n\n strRowsource = \"SELECT * FROM MyTable\"\n If Not IsNull(Me!cmbComboBox1) Then\n strRowsource = strRowsource & \" WHERE MyField = \" & Me!cmbComboBox1\n End If\n Me!cmbComboBox2.Rowsource = strRowsource\n End Sub\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
271,881 | <p>I am using a JEditorPane as an editor to write comments in my application. The content type is set "text/plain". When I am writing text in it and the text fills the available space and I go on typing, the text is not moving upward to show the cursor. So I dont know where I am typing and what I am typing since it would be visible.</p>
<p>Could you tell me how to always show the caret by moving the above text upwards?</p>
<p>Instead, it could be better if I can auto-resize the editor as I am typing. The JEditorPane is inside a JPanel, so I have to resize that too. any Ideas?</p>
| [
{
"answer_id": 5837644,
"author": "Raze",
"author_id": 142716,
"author_profile": "https://Stackoverflow.com/users/142716",
"pm_score": 1,
"selected": false,
"text": "scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);\nscrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22550/"
] |
271,888 | <p>In my database application I sometimes have to deal with <code>null</code> strings in the database. In most cases this is fine, but when it comes do displaying data in a form the Swing components - using <code>JTextField</code> for example - cannot handle null strings. (<code>.setText(null)</code> fails)</p>
<p>(<strong>EDIT:</strong> I just noticed that <code>JTextField</code> actually accepts a <code>null</code> string, but the question remains for all other cases where unexpected <code>null</code> values can lead to problems.)</p>
<p>The null values have no special meaning, they can (must) be treated as empty strings. </p>
<p>What is the best practice to deal with this problem? <em>Unfortunatly I cannot change the database</em>.</p>
<ul>
<li>Checking every value if it is <code>null</code> before calling <code>setText()</code>?</li>
<li>Adding a try-catch handler to every <code>setText()</code> call?</li>
<li>Introducing a static method which filters all <code>null</code> strings?</li>
<li>Replace all <code>null</code> values to empty strings immediatly after reading from the database?</li>
<li>... [your suggestions]</li>
</ul>
| [
{
"answer_id": 271921,
"author": "Ron Tuffin",
"author_id": 939,
"author_profile": "https://Stackoverflow.com/users/939",
"pm_score": 2,
"selected": false,
"text": "select ISNULL(column_name,'') from ...\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
271,892 | <p>I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option. The option may or may not be selected.</p>
<p>Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes).</p>
<p>Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.</p>
| [
{
"answer_id": 271903,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": -1,
"selected": false,
"text": "$(\"#idselect option[value='yourval']\")\n"
},
{
"answer_id": 271906,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 0,
"selected": false,
"text": "myOptions[valueImLookingFor]"
},
{
"answer_id": 271911,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "// first, build a reverse lookup\nvar optCount = mySelect.options.length;\nvar reverseLookup = {};\nfor (var i = 0; i < optCount; i++)\n{\n var option = mySelect.options[i];\n if (!reverseLookup[option.value])\n {\n // use an array to account for multiple options with the same value\n reverseLookup[option.value] = [];\n }\n // store a reference to the DOM element\n reverseLookup[option.value].push(option);\n}\n\n// then, use it to find the option\nvar foundOptions = reverseLookup[\"Value that you are looking for\"];\nif (foundOptions && foundOptions.length)\n{\n alert(foundOptions[0].id);\n}\n"
},
{
"answer_id": 273448,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 1,
"selected": false,
"text": "var i = mySelect.options.length - 1;\nvar reverseLookup = {};\nwhile ( i >= 0 )\n{\n var option = mySelect.options[i];\n if (!reverseLookup[option.value])\n {\n // use an array to account for multiple options with the same value\n reverseLookup[option.value] = [];\n }\n // store a reference to the DOM element\n reverseLookup[option.value].push(option);\n i--;\n}\n\n// then, use it to find the option\nvar foundOptions = reverseLookup[\"Value that you are looking for\"];\nif (foundOptions && foundOptions.length)\n{\n alert(foundOptions[0].id);\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4641/"
] |
271,904 | <p>Say you have a class declaration, e.g.:</p>
<pre><code>
class MyClass
{
int myInt=7;
int myOtherInt;
}
</code></pre>
<p>Now, is there a way in generic code, using reflection (or any other means, for that matter), that I can deduce that myInt has a default value assigned, whereas myOtherInt does not?
Note the difference between being initialised with an explicit default value, and being left to it's implicit default value (myOtherInt will be initialised to 0, by default).</p>
<p>From my own research it looks like there is no way to do this - but I thought I'd ask here before giving up.</p>
<p>[Edit]</p>
<p>Even with nullable and reference types I want to distingush between those that have been left as null, and those that have been explicitly initialised to null. This is so that I can say that fields with an initialiser are "optional" and other fields are "mandatory". At the moment I'm having to do this using attributes - which niggles me with their redundancy of information in this case.</p>
| [
{
"answer_id": 271919,
"author": "John Lemp",
"author_id": 12915,
"author_profile": "https://Stackoverflow.com/users/12915",
"pm_score": 2,
"selected": false,
"text": "class MyClass\n{\n int? myInt = 7;\n int? myOtherInt = null;\n}\n"
},
{
"answer_id": 271925,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 2,
"selected": false,
"text": "int explicitly = 0;\nint implicitly;\n"
},
{
"answer_id": 271929,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 5,
"selected": true,
"text": ".method public hidebysig specialname rtspecialname \n instance void .ctor() cil managed\n{\n // Code size 15 (0xf)\n .maxstack 8\n IL_0000: ldarg.0\n IL_0001: ldc.i4.7\n IL_0002: stfld int32 dummyCSharp.MyClass::myInt\n IL_0007: ldarg.0\n IL_0008: call instance void [mscorlib]System.Object::.ctor()\n IL_000d: nop\n IL_000e: ret\n} // end of method MyClass::.ctor\n"
},
{
"answer_id": 271935,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": -1,
"selected": false,
"text": "bool isAssigned = (myOtherInt == default(int));\n"
},
{
"answer_id": 271951,
"author": "Jack Ryan",
"author_id": 28882,
"author_profile": "https://Stackoverflow.com/users/28882",
"pm_score": 1,
"selected": false,
"text": "int mandatoryInt;\nint? optionalInt;\n"
},
{
"answer_id": 272020,
"author": "Doug L.",
"author_id": 19179,
"author_profile": "https://Stackoverflow.com/users/19179",
"pm_score": 0,
"selected": false,
"text": " class myClass\n {\n #region Property: MyInt\n private int _myIntDefault = 7;\n private bool _myIntChanged = false;\n private int _myInt;\n private int MyInt\n {\n get\n {\n if (_myIntChanged)\n {\n return _myInt;\n }\n else\n {\n return _myIntDefault;\n }\n }\n set\n {\n _myInt = value;\n _myIntChanged = true;\n }\n }\n\n private bool MyIntIsDefault\n {\n get\n {\n if (_myIntChanged)\n {\n return (_myInt == _myIntDefault);\n }\n else\n {\n return true;\n }\n }\n }\n #endregion\n }\n"
},
{
"answer_id": 272074,
"author": "Javier Suero Santos",
"author_id": 34432,
"author_profile": "https://Stackoverflow.com/users/34432",
"pm_score": 1,
"selected": false,
"text": "private int myNumber = 3;\n[System.ComponentModel.DefaultValue(3)]\npublic int MyNumber\n{\n get\n {\n return myNumber;\n }\n set\n {\n myNumber = value;\n }\n}\n"
},
{
"answer_id": 272359,
"author": "dviljoen",
"author_id": 29021,
"author_profile": "https://Stackoverflow.com/users/29021",
"pm_score": 0,
"selected": false,
"text": "class MyClass\n{\n\n public MyClass()\n {\n myInt = 7;\n }\n\n int? _myInt;\n protected int myInt\n {\n set { _myInt = value; }\n get { return _myInt ?? 0; }\n }\n\n int? _myOtherInt;\n protected int myOtherInt\n {\n set { _myOtherInt = value; }\n get { return _myOtherInt ?? 0; }\n }\n}\n"
},
{
"answer_id": 272422,
"author": "Edward Kmett",
"author_id": 34707,
"author_profile": "https://Stackoverflow.com/users/34707",
"pm_score": 1,
"selected": false,
"text": "public struct InitializationKnown<T> {\n private T m_value;\n private bool m_initialized;\n\n // the default constructor leaves m_initialized = false, m_value = default(T)\n // InitializationKnown() {}\n\n InitializationKnown(T value) : m_value(value), m_initialized(true) {}\n\n public bool initialized { \n get { return m_initialized; }\n }\n public static operator T (InitializationKnown that) {\n return that.m_value;\n }\n // ... other operators including assignment go here\n}\n"
},
{
"answer_id": 272516,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Reflection;\nusing System.Linq;\nusing System.Data;\n\n\nnamespace FieldAttribute\n{\n [global::System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]\n sealed class DefaultValueAttribute : Attribute\n {\n public DefaultValueAttribute(int i)\n {\n IntVal = i;\n }\n\n public DefaultValueAttribute(bool b)\n {\n BoolVal = b;\n }\n\n public int IntVal { get; set; }\n public bool BoolVal { get; set; }\n\n private static FieldInfo[] GetAttributedFields(object o, string matchName)\n {\n Type t = o.GetType();\n FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);\n\n return fields.Where(fi => ((matchName != null && fi.Name == matchName) || matchName == null) &&\n (fi.GetCustomAttributes(false).Where(attr => attr is DefaultValueAttribute)).Count() > 0).ToArray();\n }\n\n public static void SetDefaultFieldValues(object o)\n {\n FieldInfo[] fields = GetAttributedFields(o, null);\n foreach (FieldInfo fi in fields)\n {\n IEnumerable<object> attrs = fi.GetCustomAttributes(false).Where(attr => attr is DefaultValueAttribute);\n foreach (Attribute attr in attrs)\n {\n DefaultValueAttribute def = attr as DefaultValueAttribute;\n Type fieldType = fi.FieldType;\n if (fieldType == typeof(Boolean))\n {\n fi.SetValue(o, def.BoolVal);\n }\n if (fieldType == typeof(Int32))\n {\n fi.SetValue(o, def.IntVal);\n }\n }\n }\n }\n\n public static bool HasDefaultValue(object o, string fieldName)\n {\n FieldInfo[] fields = GetAttributedFields(o, null);\n foreach (FieldInfo fi in fields)\n {\n IEnumerable<object> attrs = fi.GetCustomAttributes(false).Where(attr => attr is DefaultValueAttribute);\n foreach (Attribute attr in attrs)\n {\n DefaultValueAttribute def = attr as DefaultValueAttribute;\n Type fieldType = fi.FieldType;\n if (fieldType == typeof(Boolean))\n {\n return (Boolean)fi.GetValue(o) == def.BoolVal;\n }\n if (fieldType == typeof(Int32))\n {\n return (Int32)fi.GetValue(o) == def.IntVal;\n }\n }\n }\n return false;\n }\n }\n\n class Program\n {\n [DefaultValue(3)]\n int foo;\n\n [DefaultValue(true)]\n bool b;\n\n public Program()\n {\n DefaultValueAttribute.SetDefaultFieldValues(this);\n Console.WriteLine(b + \" \" + foo);\n Console.WriteLine(\"b has default value? \" + DefaultValueAttribute.HasDefaultValue(this, \"b\"));\n foo = 2;\n Console.WriteLine(\"foo has default value? \" + DefaultValueAttribute.HasDefaultValue(this, \"foo\"));\n }\n\n static void Main(string[] args)\n {\n Program p = new Program();\n }\n }\n}\n"
},
{
"answer_id": 272843,
"author": "Robert Giesecke",
"author_id": 35443,
"author_profile": "https://Stackoverflow.com/users/35443",
"pm_score": 0,
"selected": false,
"text": "\nvar inst1 := new Sample();\nvar inst2 := new Sample(X := 2);\n\nvar test1 := new DefaultValueInspector<Sample>(true);\nvar test2 := new DefaultValueInspector<Sample>(inst2, true);\n\nvar d := test1.DefaultValueByName[\"X\"];\n\nvar inst1HasDefault := test1.HasDefaultValue(inst1, \"X\");\nvar inst2HasDefault := test1.HasDefaultValue(inst2, \"X\");\n\nConsole.WriteLine(\"Value: {0}; inst1HasDefault: {1}; inst2HasDefault {2}\",\n d, inst1HasDefault, inst2HasDefault);\n\nd := test2.DefaultValueByName[\"X\"];\n\ninst1HasDefault := test2.HasDefaultValue(inst1, \"X\");\ninst2HasDefault := test2.HasDefaultValue(inst2, \"X\");\n\nConsole.WriteLine(\"Value: {0}; inst1HasDefault: {1}; inst2HasDefault {2}\",\n d, inst1HasDefault, inst2HasDefault);\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32136/"
] |
271,907 | <p>Is there a way to find out when in a LAN anyone plugs in a pendrive to the USB port?
Programatically (in C# preferably) or through some tool. Basically I'd imagine a client application sits on each terminal and monitors the USB ports and sends the information to the server. </p>
<p>a.) Can I get the details of the file(s) being copied?
b.) Is there a way to do this without a client application? </p>
<p>EDIT</p>
<p>I dont want to disable the USB port entirely. its to be on a need to have basis. Basically just want the users on the LAN to share data responsibly and know that whatever data is tranfered is monitored and logged and can be questioned later.</p>
| [
{
"answer_id": 272005,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 5,
"selected": true,
"text": "DEV_BROADCAST_DEVICEINTERFACE"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20358/"
] |
271,938 | <p>Background: I have a kubuntu laptop right now that I can't use wirelessly, i.e. I haven't got wireless assistant installed. But I have a windows laptop that I can download the debian packages seperately on a USB memory stick.</p>
<p>How do I install a debian package on the computer locally?</p>
| [
{
"answer_id": 271952,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 3,
"selected": true,
"text": "dpkg --install /path/to/foo_VVV-RRR.deb\n"
},
{
"answer_id": 271989,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 2,
"selected": false,
"text": "dpkg -i"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713/"
] |
271,944 | <p>I have a scenario where users of my ASP.NET web application submit testimonials consisting of text info and images. The submit process has the following steps:</p>
<ul>
<li>First the user inputs the content and chooses a path to an image</li>
<li>When he clicks preview, the info is once again shown so that he can confirm</li>
<li>Once confirmed the info is persisted in the database</li>
</ul>
<p>The problem with this is that I don't want to store uploaded images in the DB before the user actually confirms. Instead I store them as temporary files and put them in DB only after final confirmation.</p>
<p>Since I also want my application to run in medium trust, I have write permissions only to the application directory and nowhere outside. I even want to limit write permissions for the ASPNET / NETWORK SERVICE user to the ~/App_Data folder. The problem with my scenario is that once a temporary file is created in this folder, the application pool is recycled and I don't want that on every testimonial submit.</p>
<p>How do you advise I keep these temp files instead? The pool is not restarted if I update a file - only on create or rename. But I don't think I can store whole images in a single file for all users. What do you think?</p>
<p><b>UPDATE</b>: I should note that I'm using a third party control for upload. It gives me programmatic access to the binary stream of the file contents after upload, but I cannot keep this after a second postback (the first step and postback actually does the upload).</p>
| [
{
"answer_id": 271994,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 4,
"selected": true,
"text": "IsolatedStorageFileStream stream = \n new IsolatedStorageFileStream(ISOLATED_FILE_NAME, \n FileMode.Create, isoStore);\n\nStreamWriter writer = new StreamWriter( stream );\nwriter.WriteLine( \"This is my first line in the isolated storage file.\" );\nwriter.WriteLine( \"This is second line.\" );\nwriter.Close();\n"
},
{
"answer_id": 275563,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 2,
"selected": false,
"text": " <IPermission\n class=\"FileIOPermission\"\n version=\"1\"\n Read=\"$AppDir$\"\n Write=\"$AppDir$\"\n Append=\"$AppDir$\"\n PathDiscovery=\"$AppDir$\"\n />\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801/"
] |
271,953 | <p>Got into a situation where in a schema i have a table, say table ACTION , while i got a synonym called ACTION as well which refers to another table to another schema.</p>
<p>Now, when i run the query</p>
<p>select * from ACTION</p>
<p>it will select the records from the table, but not the synonym.</p>
<p>Anyway for me to select from the synonym AND the table both together?</p>
<p>Thanx</p>
| [
{
"answer_id": 271997,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 2,
"selected": false,
"text": "SELECT * from LOCAL_ACTION\nUNION\nSELECT * from otheruser.LOCAL_ACTION\n"
},
{
"answer_id": 272051,
"author": "Salamander2007",
"author_id": 10629,
"author_profile": "https://Stackoverflow.com/users/10629",
"pm_score": 3,
"selected": false,
"text": "select * from ACTION\nunion \nselect * from public.ACTION\n"
},
{
"answer_id": 277877,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 1,
"selected": false,
"text": "select * from ACTION\nunion all\nselect * from public.ACTION\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
271,954 | <p>I never use Access 2007 - until today.</p>
<p>I want to connect to an existing SQL Server 2008 database. I have tried using:</p>
<ul>
<li>External Data ODBC option - but get DSN errror</li>
<li>Upsizing wizard with ODBC - get an error</li>
<li>Upsizing wizard with SNAC - get ODBC error. So that one seems a none starter :-)</li>
</ul>
<p>I have done some searching and only found others with same issue. About to do some more... but hoping one of you has the answer OTTOYH. Thanks.</p>
| [
{
"answer_id": 271984,
"author": "Eric Nelson",
"author_id": 5636,
"author_profile": "https://Stackoverflow.com/users/5636",
"pm_score": 0,
"selected": false,
"text": "[ODBC]\nDRIVER=SQL Server\nUID=ericnel\nDATABASE=AccessTest\nWSID=ERICNEL1\nAPP=2007 Microsoft Office system\nTrusted_Connection=Yes\nSERVER=ericnel1\nDescription=test\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5636/"
] |
271,957 | <p>I got a row structure looks like ID bigint, ScanRept XML</p>
<p>I want to wind up with a file named 4.xml containing just the xml from the ScanRept column where the ID number is 4.</p>
<p>I don't want to do it interactively (by going into Manager Studio, finding the row, right-clicking the field and doing Save AS) - that's what I'll do if I can't figure out a better way. </p>
<p>I do have C# available; if this is doable with sqlcmd, that's my preference (cause there will probably be a lot of variations I can't anticipate right now).</p>
| [
{
"answer_id": 271984,
"author": "Eric Nelson",
"author_id": 5636,
"author_profile": "https://Stackoverflow.com/users/5636",
"pm_score": 0,
"selected": false,
"text": "[ODBC]\nDRIVER=SQL Server\nUID=ericnel\nDATABASE=AccessTest\nWSID=ERICNEL1\nAPP=2007 Microsoft Office system\nTrusted_Connection=Yes\nSERVER=ericnel1\nDescription=test\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35458/"
] |
271,965 | <p>Is there a function in glut which moves the mouse to a specific position?
There is a similar function in SDL (SDL_WarpMouse) but I want to stick to glut.</p>
| [
{
"answer_id": 271975,
"author": "Alexander Stolz",
"author_id": 2450,
"author_profile": "https://Stackoverflow.com/users/2450",
"pm_score": 4,
"selected": true,
"text": "glutWarpPointer(middleX, middleY)"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2450/"
] |
271,966 | <p>There are no builtin matrix functions in C#, but there are in the F# powerpack.</p>
<p>Rather than using a third party or open source C# library, I wonder about rolling my own in F#, and exposing the useful bits to C#. </p>
<p>Wondered if anybody has already thought of this, or tried it, and whether it's a good idea.</p>
<p>Should I expose it as a class, or a load of static functions?</p>
<p>Or should I create a C# wrapper class, and have that call down to F#? Or have the F# use the C# class as input and output?</p>
<p>Any thoughts?</p>
<p>Answer thanks to <a href="https://stackoverflow.com/questions/271966/about-using-f-to-create-a-matrix-assembly-usable-from-c#272250">Hath</a> below: you can use the F# library directly in C# (operators as well!):</p>
<pre><code>using System;
using System.Text;
using Microsoft.FSharp.Math;
namespace CSharp
{
class Program
{
static void Main(string[] args)
{
double[,] x = { { 1.0, 2.0 }, { 4.0, 5.0 } };
double[,] y = { { 1.0, 2.0 }, { 7.0, 8.0 } };
Matrix<double> m1 = MatrixModule.of_array2(x);
Matrix<double> m2 = MatrixModule.of_array2(y);
var mp = m1 * m2;
var output = mp.ToArray2();
Console.WriteLine(output.StringIt());
Console.ReadKey();
}
}
public static class Extensions
{
public static string StringIt(this double[,] array)
{
var sb = new StringBuilder();
for (int r = 0; r < array.Length / array.Rank; r++)
{
for (int c = 0; c < array.Rank; c++)
{
if (c > 0) sb.Append("\t");
sb.Append(array[r, c].ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
}
}
</code></pre>
| [
{
"answer_id": 272250,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 4,
"selected": true,
"text": "Microsoft.FSharp.Math.BigInt class.\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
271,971 | <p>Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields?</p>
<pre><code>SYSTEMTIME sysTime;
GetLocalTime( &sysTime );
char buf[80];
for (int i = 0; i < 100000; i++)
{
sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d",
sysTime.wYear, sysTime.wMonth, sysTime.wDay,
sysTime.wHour, sysTime.wMinute, sysTime.wSecond);
}
</code></pre>
<hr>
<p>Note: The OP explains in the comments that this is a stripped-down example. The "real" loop contains additional code that uses varying time values from a database. Profiling has pinpointed <code>sprintf()</code> as the offender.</p>
| [
{
"answer_id": 271993,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 3,
"selected": false,
"text": "buf[0] = (sysTime.wYear / 1000) % 10 + '0' ;\nbuf[1] = (sysTime.wYear / 100) % 10 + '0';\nbuf[2] = (sysTime.wYear / 10) % 10 + '0';\nbuf[3] = sysTime.wYear % 10 + '0';\nbuf[4] = '-';\n"
},
{
"answer_id": 272016,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "sprintf()"
},
{
"answer_id": 272021,
"author": "Jaywalker",
"author_id": 382974,
"author_profile": "https://Stackoverflow.com/users/382974",
"pm_score": 2,
"selected": false,
"text": "SYSTEMTIME sysTime, oldSysTime;\n"
},
{
"answer_id": 272024,
"author": "John Carter",
"author_id": 8331,
"author_profile": "https://Stackoverflow.com/users/8331",
"pm_score": 5,
"selected": true,
"text": "strftime()"
},
{
"answer_id": 272113,
"author": "Tom Barta",
"author_id": 29839,
"author_profile": "https://Stackoverflow.com/users/29839",
"pm_score": 2,
"selected": false,
"text": "printf"
},
{
"answer_id": 272146,
"author": "shank",
"author_id": 24697,
"author_profile": "https://Stackoverflow.com/users/24697",
"pm_score": 2,
"selected": false,
"text": "\nstatic char fbuf[80];\nstatic SYSTEMTIME lastSysTime = {0, ..., 0}; // initialize to all zeros.\n\nfor (int i = 0; i < 100000; i++)\n{\n if ((lastSysTime.wHour != sysTime.wHour)\n || (lastSysTime.wDay != sysTime.wDay)\n || (lastSysTime.wMonth != sysTime.wMonth)\n || (lastSysTime.wYear != sysTime.wYear))\n {\n sprintf(fbuf, \"%4d-%02s-%02s %02s:%%02s:%%02s\",\n sysTime.wYear, n2s[sysTime.wMonth],\n n2s[sysTime.wDay], n2s[sysTime.wHour]);\n\n lastSysTime.wHour = sysTime.wHour;\n lastSysTime.wDay = sysTime.wDay;\n lastSysTime.wMonth = sysTime.wMonth;\n lastSysTime.wYear = sysTime.wYear;\n }\n\n sprintf(buf, fbuf, n2s[sysTime.wMinute], n2s[sysTime.wSecond]);\n\n}\n"
},
{
"answer_id": 814222,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "void log(int channel, char *filename, int lineno, format, ...)"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9328/"
] |
271,979 | <p>I need to pull some BLOB data from a SQL Server 2005 database and generate a SQL script to insert this same data in another database, in another server.</p>
<p>I am only allowed to do this using SQL scripts, I can't use any other utility or write a program in Java or .NET to do it.</p>
<p>The other big restriction I have is that I don't have access to the original database (where the original BLOB data is) when I run the script, to copy the BLOB data to the target database, so the data should already be encoded within the SQL script file.</p>
<p>Summing up: is there a way to encode the BLOB data into text so that I can dump it into a SQL INSERT command within a script text file and run it?</p>
<p>I am able to run special T-SQL statements and stored procedures if needed to.</p>
| [
{
"answer_id": 271999,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "CREATE PROCEDURE sp_textcopy (\n @srvname varchar (30),\n @login varchar (30),\n @password varchar (30),\n @dbname varchar (30),\n @tbname varchar (30),\n @colname varchar (30),\n @filename varchar (30),\n @whereclause varchar (40),\n @direction char(1))\n\nAS\n\nDECLARE @exec_str varchar (255)\nSELECT @exec_str =\n 'textcopy /S ' + @srvname +\n ' /U ' + @login +\n ' /P ' + @password +\n ' /D ' + @dbname +\n ' /T ' + @tbname +\n ' /C ' + @colname +\n ' /W \"' + @whereclause +\n '\" /F ' + @filename +\n ' /' + @direction\nEXEC master..xp_cmdshell @exec_str\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/271979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407003/"
] |
272,003 | <p>I have a MS-access database. But it is on the shared drive. And it is required that only some selected number of people can use it. Is there a way to authenticate the user?</p>
| [
{
"answer_id": 417801,
"author": "Mike",
"author_id": 51350,
"author_profile": "https://Stackoverflow.com/users/51350",
"pm_score": 0,
"selected": false,
"text": "AuthorizedUser = True\nSelect Case user\n Case \"USER_A\":\n Case \"USER_B\":\n Case \"USER_C\": \n Case Else: AuthorizedUser = False\nEnd Select\n\nIf AuthorizedUser = True Then\n MsgBox \"Welcome authorized user \" & user\nElse\n MsgBox user & \"is not Authorized. For access to this database contact User_A\"\n DoCmd.Quit\nEnd If\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] |
272,007 | <p>I am using jQuery to try and trigger a method when an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> (2.0) dropdown list's change event is handled by jQuery. The problem is that the drop down list is located inside a gridview and even then only when a user has decided to edit a row within that gridview.</p>
<p>I think I have it picking up the object using an ASP code block, but the problem with that is that when the page first loads the edit index of the row does not exist and it throws an error. Putting the block inside a <code>IF</code> statement also does not work.</p>
<pre><code>$(document).ready(function() //when DOM is ready, run containing code
{
<% if (grvTimeSheets.EditIndex > -1) {%>
$(#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>).change(function() {
$(#<%= grvTimeSheets.ClientID %>).block({ message: null }
});
}
);
<% } %>
</code></pre>
<p>It is one attempt I made, and I also tried putting the IF statement ASP code outside the JavaScript block. It doesn't work either.</p>
<p>How could I apply the jQuery event to the drop drop box? Ideally as concise as possible.</p>
<hr>
<p>Thanks for the answer but nope, it doesn't work :(. The JavaScript code seems not to be outputted... Confusing...</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.js"></script>
<script type="text/javascript" src="jquery.blockUI.js"></script>
<script type="text/javascript">
$(document).ready(function() //When DOM is ready, run the containing code
{
}
);
</script>
</code></pre>
<p>Is the output. Even though this is the code:</p>
<pre><code><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.tablesorter.js"></script>
<script type="text/javascript" src="jquery.blockUI.js"></script>
<script type="text/javascript">
$(document).ready(function() //when DOM is ready, run containing code
{<% if (grvTimeSheets.EditIndex > -1) {%>
var id = '#<%=grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients").ClientID %>';
$(id).change(function() {
$(id).block({ message: null }
});
<% } %>
}
);
</script>
</code></pre>
<p>It was doing that before as well, driving me CRAZY.</p>
<hr>
<p>Sorry, could you make that slightly clearer. I tried defining the entire thing in code behind like so:</p>
<pre><code>DropDownList ddl (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl("ddlClients");
if (ddl != null)
{
ClientScriptManager csm = Page.ClientScript;
Type cstype = this.GetType();
String csname1 = "PopupScript";
string script = @"
<script language='javascript' type='text/javascript'>
$(#" + ddl.ClientID + ").change(function() { $(" + grvTimeSheets.ClientID + ").blockUI({ message: null }});} </script>";
csm.RegisterStartupScript(cstype, csname1, script, true);
}
</code></pre>
<p>Is that what you meant?</p>
<p>BTW, the above didn't work. No errors, just no events worked.</p>
| [
{
"answer_id": 272311,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 3,
"selected": true,
"text": "$()"
},
{
"answer_id": 272752,
"author": "OutOFTouch",
"author_id": 35166,
"author_profile": "https://Stackoverflow.com/users/35166",
"pm_score": 1,
"selected": false,
"text": "var myFancySelector = '#' + myControlId;\nselectedValue = $(myFancySelector).val();\n"
},
{
"answer_id": 272788,
"author": "OutOFTouch",
"author_id": 35166,
"author_profile": "https://Stackoverflow.com/users/35166",
"pm_score": 1,
"selected": false,
"text": "cs.RegisterClientScriptBlock(cstype, csname, cstext2.ToString(), False)\n"
},
{
"answer_id": 272853,
"author": "Damien",
"author_id": 35454,
"author_profile": "https://Stackoverflow.com/users/35454",
"pm_score": 0,
"selected": false,
"text": "DropDownList ddl = (DropDownList)grvTimeSheets.Rows[grvTimeSheets.EditIndex].FindControl(\"ddlClients\");\nif (ddl != null)\n{\n ClientScriptManager csm = Page.ClientScript;\n Type cstype = this.GetType();\n String csname1 = \"PopupScript\";\n\n string script = @\"\n <script language='javascript' type='text/javascript'>\n jQuery(#\" + ddl.ClientID + \").change(function() { $(\" + grvTimeSheets.ClientID + \").blockUI({ message: null }});} </script>\";\n csm.RegisterStartupScript(cstype, csname1, script, false);\n"
},
{
"answer_id": 272871,
"author": "OutOFTouch",
"author_id": 35166,
"author_profile": "https://Stackoverflow.com/users/35166",
"pm_score": 1,
"selected": false,
"text": "string script = @\"<script type=text/javascript> var myControlId = '\" + ddl.ClientId \"';\") + \"</script>\"\n"
},
{
"answer_id": 272883,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "$(function() {\n $(\"select.yourMarkerClass\").change(....);\n});\n"
},
{
"answer_id": 272884,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 1,
"selected": false,
"text": "$('[id$=ddlClients]')\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35454/"
] |
272,010 | <p>I'm looking for a PHP (with MYSQL) nested sets class with all needed functions.
For example:</p>
<p>createLeftNode, createRightNode,createRootNode, createSubNode,deleteNode and <strong>moveTree</strong>. Not only 1 left, 1 right, 1 up and 1 down but also a part of a tree in a nother tree.</p>
<p>Thanks!</p>
| [
{
"answer_id": 42076840,
"author": "Kim Pepper",
"author_id": 668727,
"author_profile": "https://Stackoverflow.com/users/668727",
"pm_score": 0,
"selected": false,
"text": "revision_id"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35459/"
] |
272,013 | <p>Why is it called a single in VB.net? I'm sure there is a good reason but it doesn't seem intuitive to a non formally trained programmer like me.</p>
| [
{
"answer_id": 272023,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "shorthand"
},
{
"answer_id": 272186,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "System.Single"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2763/"
] |
272,030 | <p>I have a VS 2005 C# project that uses a special Plugin folder to load extra DLLs (for use as nodes in an asset conversion process).</p>
<p>I have a mixture of C# and C++ DLLs in this folder.</p>
<p>The issue I have is that when Shadow Copying is enabled, the C++ DLLs refuse to load using Assembly.LoadFrom. I have attempted to create a custom app domain, and used Load, but this also failed.</p>
<p>Finally, I tried reading the DLL in as byte[] data and using Load on that - again, only the C# DLLs would work this way, with an error "Additional information: Unverifiable code failed policy check. (Exception from HRESULT: 0x80131402)".</p>
<p>An article on the net prompted me to attempt to use /clr:safe when building that particular DLL, but then it simply failed to build due to thousands of errors in Microsoft code... (apparently)</p>
<p>With Shadow Copying disabled, LoadFrom works fine for all DLLs. The app is itself a plugin for Maya, and this used to work with Maya 8.5 but fails with 2008 / 2009 (if Shadow Copying is enabled).</p>
<p>We really would prefer to use Shadow Copying, because it prevents DLL file locks when the app is running (the Plugins folder is stored in a location that Perforce can update while the app is running).</p>
<p>Any ideas as to how I can persuade Shadow Copying to work with a custom folder AND a mix of C# / C++ DLLs without these problems?</p>
| [
{
"answer_id": 272307,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 1,
"selected": false,
"text": "/clr:safe"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35444/"
] |
272,035 | <p>I have a form that displays file information in a TabControl, and I'd like the pages to have the file's icon in their tab. How do I get the icon associated with a file type?</p>
<p>I'd prefer solutions that don't involve looking things up in the registry, but if that's the only way then so be it.</p>
| [
{
"answer_id": 272044,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": true,
"text": "FileAssociationInfo"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15371/"
] |
272,036 | <p>I've accidentally removed Win2K compatibility from an application by using <a href="http://msdn.microsoft.com/en-us/library/ms683215(VS.85).aspx" rel="nofollow noreferrer">GetProcessID</a>.</p>
<p>I use it like this, to get the main HWND for the launched application.</p>
<pre><code>ShellExecuteEx(&info); // Launch application
HANDLE han = info.hProcess; // Get process
cbinfo.han = han;
//Call EnumWindows to enumerate windows....
//with this as the callback
static BOOL CALLBACK enumproc(HWND hwnd, LPARAM lParam)
{
DWORD id;
GetWIndowThreadProcessID(hwnd, &id);
if (id == GetProcessID(cbinfo.han))
setResult(hwnd)
...
}
</code></pre>
<p>Any ideas how the same function could be acheived on Win2K?</p>
| [
{
"answer_id": 280533,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 2,
"selected": false,
"text": "#include \"Winternl.h\"\n\ntypedef DWORD (WINAPI* pfnGetProcID)(HANDLE h);\n\ntypedef NTSTATUS (WINAPI* pfnQueryInformationProcess)(\n HANDLE ProcessHandle,\n PROCESSINFOCLASS ProcessInformationClass,\n PVOID ProcessInformation,\n ULONG ProcessInformationLength,\n PULONG ReturnLength);\n\nDWORD MyGetProcessId(HANDLE h)\n{\n static pfnQueryInformationProcess ntQIP = (pfnQueryInformationProcess) GetProcAddress(GetModuleHandle(\"NTDLL.DLL\"),\"NtQueryInformationProcess\");\n static pfnGetProcID getPId = (pfnGetProcID) GetProcAddress(GetModuleHandle(\"KERNEL32.DLL\"),\"GetProcessId\");\n\n if ((ntQIP == NULL) && (getPId == NULL))\n throw Exception(\"Can't retrieve process ID : GetProcessID not supported\");\n\n if (getPId != NULL)\n return getPId(h);\n else\n {\n PROCESS_BASIC_INFORMATION info;\n ULONG returnSize;\n ntQIP(h, ProcessBasicInformation, &info, sizeof(info), &returnSize); // Get basic information.\n return info.UniqueProcessId;\n }\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
272,038 | <p>In my Seam application, I have a Seam component that returns a (<code>@Datamodel</code>) list of items I want to transform into a set of <code><li></code> HTML elements. I have this working without a problem. </p>
<p>But now, I want to split up the list according to an EL expression. So the EL expression determines if a new <code><ul></code> element should be started. I tried the following:</p>
<pre><code><s:fragment rendered="#{action.isNewList(index)}">
<ul>
</s:fragment>
<!-- stuff that does the <li>'s goes here -->
<s:fragment rendered="#{action.isNewList(index)}">
</ul>
</s:fragment>
</code></pre>
<p>But that's invalid, because the nesting for <code><ul></code> is wrong.</p>
<p>How should I do this?</p>
| [
{
"answer_id": 483930,
"author": "phloopy",
"author_id": 8507,
"author_profile": "https://Stackoverflow.com/users/8507",
"pm_score": 0,
"selected": false,
"text": "<!-- before your loop, open your first <ul> if the (@Datamodel) is not empty -->\n\n<s:fragment rendered=\"#{action.isNewList(index)}\">\n </ul>\n <ul>\n</s:fragment>\n<!-- stuff that does the <li>'s goes here -->\n\n<!-- after your loop, close your last </ul> if the (@Datamodel) is not empty -->\n"
},
{
"answer_id": 485578,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 0,
"selected": false,
"text": "<ul>\n <s:for items=\"itemList\" ...>\n\n <s:fragment rendered=\"#{action.isNewList(index) && index > 0}\">\n </ul>\n <ul>\n </s:fragment>\n <li>\n <!-- stuff that does the <li>'s goes here -->\n </li>\n\n </s:for>\n</ul>\n"
},
{
"answer_id": 487676,
"author": "Peter Hilton",
"author_id": 2670,
"author_profile": "https://Stackoverflow.com/users/2670",
"pm_score": 2,
"selected": true,
"text": "<f:verbatim>"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6400/"
] |
272,045 | <p>I have two tables A and B. I would like to delete all the records from table A that are returned in the following query:</p>
<pre><code>SELECT A.*
FROM A , B
WHERE A.id = B.a_id AND
b.date < '2008-10-10'
</code></pre>
<p>I have tried:</p>
<pre><code>DELETE A
WHERE id in (
SELECT a_id
FROM B
WHERE date < '2008-10-10')
</code></pre>
<p>but that only works if the inner select actually returns a value (not if the result set is empty)</p>
<p><strong>NB:</strong> this has to work on <strong>both SQLServer AND MySQL</strong></p>
<p>EDIT: More information</p>
<p>The above delete works 100% on SQLServer</p>
<p>When running it on MySQL I get an "error in you SQL syntax" message which points to the start of the SELECT as the problem. if I substitute the inner select with (1,2) then it works. </p>
<p><em>@Kibbee You are right it actually makes no difference if the inner select returns rows or not.</em></p>
<p><em>@Fred I get a "not unique table.alias: a" message</em></p>
| [
{
"answer_id": 272056,
"author": "Fred",
"author_id": 33630,
"author_profile": "https://Stackoverflow.com/users/33630",
"pm_score": 1,
"selected": false,
"text": "DELETE FROM A\nWHERE A.id in (\n SELECT B.a_id \n FROM B\n WHERE B.date < '2008-10-10');\n"
},
{
"answer_id": 272083,
"author": "lmop",
"author_id": 22260,
"author_profile": "https://Stackoverflow.com/users/22260",
"pm_score": 4,
"selected": true,
"text": "DELETE a.* FROM A a JOIN B b ON b.id = a.id WHERE b.date < '2008-10-10';\n"
},
{
"answer_id": 272156,
"author": "Shawn",
"author_id": 26,
"author_profile": "https://Stackoverflow.com/users/26",
"pm_score": 0,
"selected": false,
"text": "delete from a inner join b on a.id = b.a_id and b.date < '2008-10-10'\n"
},
{
"answer_id": 272221,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": "Delete A \nFrom A\nWhere Exists \n (Select * From B \n Where B.Id = A.Id\n And B.date < '2008-10-10');\n"
},
{
"answer_id": 277377,
"author": "EJ.",
"author_id": 35109,
"author_profile": "https://Stackoverflow.com/users/35109",
"pm_score": 0,
"selected": false,
"text": "select b.ID\ninto #T\nfrom \n [Table b] with (nolock) \nwhere \n b.date > '2008-10-10'\n\nif exists (select * from #T with (nolock))\n delete from [Table a] where a.id in (select id from #T with (nolock))\n drop table #T\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939/"
] |
272,097 | <p>How do I dynamically reload the app.config in a .net Windows application? I need to turn logging on and off dynamically and not just based upon the value at application start.</p>
<p>ConfigurationManager.RefreshSection("appSettings") does not work and I've also tried explicitly opening the config file using OpenExeConfiguration but I always get the cached value at application startup and not the current value. </p>
<p>I've accepted the answer of creating a custom configuration section. As a side note and foolish mistake - if you're running from the IDE there's no point in updating the app.config file and expecting changes. Yuo have to modify the .exe.config file in the bin\debug folder. Doh!</p>
| [
{
"answer_id": 272114,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 6,
"selected": true,
"text": "ConfigurationManager.RefreshSection(\"yoursection/subsection\");\n"
},
{
"answer_id": 272120,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 3,
"selected": false,
"text": "app.config"
},
{
"answer_id": 748467,
"author": "foson",
"author_id": 22539,
"author_profile": "https://Stackoverflow.com/users/22539",
"pm_score": 2,
"selected": false,
"text": "Application.Start(new Form1())"
},
{
"answer_id": 3607822,
"author": "Ruchir",
"author_id": 435781,
"author_profile": "https://Stackoverflow.com/users/435781",
"pm_score": 3,
"selected": false,
"text": "ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Save(ConfigurationSaveMode.Modified);\n ConfigurationManager.RefreshSection(\"appSettings\");\n"
},
{
"answer_id": 6841134,
"author": "froeschli",
"author_id": 431657,
"author_profile": "https://Stackoverflow.com/users/431657",
"pm_score": 1,
"selected": false,
"text": "internal interface ILoggingConfiguration\n{\n void SetLogLevel(string level);\n\n string GetLogLevel();\n}\n"
},
{
"answer_id": 11425940,
"author": "Sudhanshu Mishra",
"author_id": 190476,
"author_profile": "https://Stackoverflow.com/users/190476",
"pm_score": 0,
"selected": false,
"text": "class Program\n {\n static void Main(string[] args)\n {\n string value = string.Empty, key = \"mySetting\";\n Program program = new Program();\n\n program.GetValue(program, key);\n Console.WriteLine(\"--------------------------------------------------------------\");\n Console.WriteLine(\"Press any key to exit...\");\n Console.ReadLine();\n }\n\n /// <summary>\n /// Gets the value of the specified key from app.config file.\n /// </summary>\n /// <param name=\"program\">The instance of the program.</param>\n /// <param name=\"key\">The key.</param>\n private void GetValue(Program program, string key)\n {\n string value;\n if (ConfigurationManager.AppSettings.AllKeys.Contains(key))\n {\n Console.WriteLine(\"--------------------------------------------------------------\");\n Console.WriteLine(\"Key found, evaluating value...\");\n value = ConfigurationManager.AppSettings[key];\n Console.WriteLine(\"Value read from app.confg for Key = {0} is {1}\", key, value);\n Console.WriteLine(\"--------------------------------------------------------------\");\n\n //// Update the value\n program.UpdateAppSettings(key, \"newValue\");\n //// Re-read from config file\n value = ConfigurationManager.AppSettings[key];\n Console.WriteLine(\"New Value read from app.confg for Key = {0} is {1}\", key, value);\n }\n else\n {\n Console.WriteLine(\"Specified key not found in app.config\");\n }\n }\n\n /// <summary>\n /// Updates the app settings.\n /// </summary>\n /// <param name=\"key\">The key.</param>\n /// <param name=\"value\">The value.</param>\n public void UpdateAppSettings(string key, string value)\n {\n Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n\n if (configuration.AppSettings.Settings.AllKeys.Contains(key))\n {\n configuration.AppSettings.Settings[key].Value = value;\n }\n\n configuration.Save(ConfigurationSaveMode.Modified);\n ConfigurationManager.RefreshSection(\"appSettings\");\n }\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
272,109 | <p>I have a csv file of the format:</p>
<pre><code>270291014011 ED HARDY - TRUE TO MY LOVE - Cap NEU 2008 NEU 0,00 € 0,00 € 0 1 0 22.10.2008 03:37:10 21.11.2008 02:37:10 21.11.2008 02:42:10 50 0 0 0 39,99 € http://i7.ebayimg.com/02/i/001/16/0d/68af_1.JPG?set_id=800005007 0 2 8.10.2008 13:40:20 8.10.2008 13:40:20 80587 0 <table bordercolordark="#999900" bordercolorlight="#666666" bgcolor="#ffffff" border="10" bordercolor="#666666" width="100%">
<tbody>
<tr>
<td><b><font color="#990000" face="arial" size="5"><br>
</font></b><blockquote>
<div align="center"><b><font color="#990000" face="arial" size="5"><font color="#ff0000">
</font></font></b><h1><font size="6"><b><font color="#990000" face="arial"><font color="#ff0000">100% ORGINAL MARKENWARE AUS DEN USA</font></font></b></font></h1>
<p style="color: rgb(0, 0, 0);"><font size="6"><b><font face="arial">ED HARDY</font></b></font></p><p style="color: rgb(0, 0, 0);"><b><font face="arial" size="5">CAP<br></font></b></p></div><div style="text-align: center;"><font size="5"><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Style: TRUE ROSE<br></font></b></font></font></b><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"><br></font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Die Kollektion von der trend Marke Ed Hardy kreiert sportlich, hipe Mode die bei den Stars in Hollywood der absolute Renner ist. In diesem super Trucker Cap fallen Sie auf !!&nbsp; </font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Dieses Cap ist nagelneu mit Etikett und</font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"> 100% orginal.</font></b></font></font></b></font><font size="5"><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial"><br><br></font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Wir tragen die ebay Kosten und der Kaeufer die Versandkosten.</font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Versandkosten nach Europa sind folgend:</font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">fuer unversicherten Versand 6,00 Euro<br></font></b></font></font></b></font><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">fuer versicherten Versand 12,00 Euro</font></b></font></font></b></font><br>
<font size="5"><span style="font-family: arial;"><span style="font-weight: bold;">Bei paypal Bezahlungen akzeptieren wir nur noch versicherten Versand!</span></span></font><br><font size="5"><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Auf Ihren Wunsch versenden wir die Ware auch versichert. Ansonsten trägt das Risiko beim Versand der Käufer. </font></b></font></font></b><br><b><font color="#990000" face="arial"><font color="#ff0000"><b><font color="black" face="arial">Wir bitten um Ihre Zahlung innerhalb 10 Tage nach Auktionsende.</font></b></font></font></b><br></font></div><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><br>
</font></b></font></font></b><div align="center"><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><font color="#ff0000">
</font></font></b></font></font></b><marquee width="70%" bgcolor="#ffffff">
<h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><b><font color="black" face="arial" size="3"><font color="#ff0000">Schauen Sie unbedingt bei unserem Shop "cheap-and-hip" vorbei!!!</font></font></b></font></font></b></h2></marquee><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><br><b><font color="black" face="arial" size="5"><br>
</font></b></font></font></font></b><blockquote>
<div align="center">
<center>
<h1><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><b><font color="black" face="arial" size="5">Abwicklung Ihres Einkaufs bei uns</font></b></font></font></font></b></h1><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><b><font color="black" face="arial" size="5"><br></font></b></font></font></font></b></center><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><br></font></font></font></b></div><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Jeder Käufer erhält innerhalb von 24 Stunden nach Auktionsende eine e-mail mit allen für die Kaufabwicklung relevanten Informationen. Sollten Sie nach 24 Stunden noch keine e-mail erhalten haben, setzen Sie sich bitte mit uns per e-mail in Verbindung. <br><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Kauf von mehreren Artikeln</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Da das Porto aus den USA nach Gewicht berechnet wird, werden die Versandkosten beim Einkauf von mehreren Artikeln neu berechnet. Bitte teilen Sie uns per e-mail mit, wenn Sie mehrere Artikel ersteigert/gekauft haben, bzw. noch ersteigern/kaufen moechten, Sie erhalten von uns dann die kompletten Versandkosten. Die Kosten fuer den Versand werden von dem Kaeufer getragen. Die Versanddauer betraegt bei Luftversand zirka 5-10 Tage.<br><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Versand</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Der Versand erfolgt innerhalb von 2-3 Werktagen nach Zahlungseingang (Gutschrift der Überweisung auf unserem Konto bei der Postbank oder bei paypal). Bitte beachten Sie, dass es je nach Kreditinstitut 2-4 Werktage dauern kann, bis Ihre Überweisung auf unserem Konto gutgeschrieben wird. Kreditkarten Gutbuchung ueber paypal erfolgt noch am gleichen Tag.<br>Als Betreff einer Ueberweisung muß unbedingt die eBay-Artikelnummer der Auktion angegeben werden. Ohne diese Information ist eine Zuordnung der Überweisung leider fast nicht möglich! <br>ZOLL: Bitte beachten Sie das Zollgebuehren anfallen koennen auch wenn es nur selten vorkommt sollten Sie sich mit den Einfuhrbestimmungen Ihres Landes vertraut machen. <br></font></font></font></font></b><br><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Umtausch</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Wir tauschen gerne Ihren Artikel um sofern Sie die Ware innerhalb von 14 Tagen nach erhalt den Artikel uns wieder zuschicken. Wir nehmen nur ungetragene Ware zurueck und alle Etiketten muessen noch an dem Artikel befestigt sein<br><br>
</font></font></font></font></b><h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Falls Sie Reklamationen haben</font></font></font></font></b></h2><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3">Wir bitten bei Beanstandungen der Ware sich erst mit uns in Verbindung zu setzten. Wir pruefen unsere Ware immer auf Defekte aber es kann vorkommen das uns etwas entgeht und bevor Sie eine "negative Bewertung" abgeben moechten wir die Chance bekommen Sie zufrieden zustellen.
</font></font></font></font></b><p><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5">
</font></b></font></font></font></font></b></p><center><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5">Vielen Dank fuer Ihr Intresse!</font></b></font></font></font></font></b></center><p><b><font color="#990000" face="arial" size="5"><font color="#ff0000"><font color="black" face="arial" size="3"><font color="black" face="arial" size="3"><b><font color="#ff0000" face="arial" size="5"><br></font></b></font></font></font></font></b></p></blockquote></div></blockquote></td></tr></tbody></table><br><br> 1 Baltimore 1 0 1 0 0 0,10 € 0,00 € 0,00 € 0 0 1 77
</code></pre>
<p>I would like to know if there is an easy way with sed or awk to remove the HTML tags except for <code><p></code> tags. I would also like to know if it is possible for any link html embedding a Flash SWF file, to change the HTML automatically to link to this file.</p>
<p>So, in essence, to replace any code such as</p>
<pre><code><embed src="http://backend.supremeauction.com/app/gallery/loader.swf">
</code></pre>
<p>with something like <code><a href="http://backend.supremeauction.com/app/gallery/loader.swf">Click here for external description</a></code> and then remove all other HTML tags except for <code><p></code></p>
<p>Is this even possible?</p>
| [
{
"answer_id": 272353,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 2,
"selected": true,
"text": "perl -pe 's/<\\/?(?>[^p]|p\\w+)[^>]*>//ig'\n"
},
{
"answer_id": 272376,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 1,
"selected": false,
"text": "sed -e 's/[<][/][^Pp][^>]*[>]//g' -e 's/[<][^/Pp][^>]*[>]//g' file\n"
},
{
"answer_id": 272478,
"author": "Charles Duffy",
"author_id": 14122,
"author_profile": "https://Stackoverflow.com/users/14122",
"pm_score": 0,
"selected": false,
"text": "&"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
272,118 | <p>I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.</p>
<p>Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.</p>
<p>So, what are your experiences, what works best?</p>
| [
{
"answer_id": 272506,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 3,
"selected": false,
"text": "@Controller\npublic class MyController {\n @RequestMapping(\"/viewPosts\")\n public void doViewPosts(HttpRequest r, HttpResponse res) {\n //...\n }\n}\n"
},
{
"answer_id": 272651,
"author": "alex",
"author_id": 26787,
"author_profile": "https://Stackoverflow.com/users/26787",
"pm_score": 2,
"selected": false,
"text": "for(Handler handler : handlers) {\n if(handler.handle(request, response)) {\n return;\n }\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
272,124 | <p>since JTree & TreeModel don't provide tooltips straight out-of-the-box, what do you think, what would be the best way to have item-specific tooltips for JTree?</p>
<p>Edit: (Answering my own question afterwards.) </p>
<p>@Zarkonnen: Thanks for the getTooltipText idea. </p>
<p>I found out another (maybe still a bit nicer) way with overriding DefaultTreeCellRenderer and thought to share it:</p>
<pre><code>public class JTreeWithToolTips {
private static class OwnRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean sel, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
setToolTipText("foobar" + row);
return super.getTreeCellRendererComponent(tree, value, sel,
expanded, leaf, row, hasFocus);
}
}
public static void main(String[] args) {
JTree tree = new JTree(new Object[] { "foo", "bar", "foobar" });
tree.setCellRenderer(new OwnRenderer());
ToolTipManager.sharedInstance().registerComponent(tree);
JFrame frame = new JFrame();
frame.getContentPane().add(tree);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
</code></pre>
| [
{
"answer_id": 1774609,
"author": "Agustin",
"author_id": 215965,
"author_profile": "https://Stackoverflow.com/users/215965",
"pm_score": 1,
"selected": false,
"text": "onMouseMoved"
},
{
"answer_id": 46084789,
"author": "Matthieu",
"author_id": 1098603,
"author_profile": "https://Stackoverflow.com/users/1098603",
"pm_score": 1,
"selected": false,
"text": "TreeNode"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28482/"
] |
272,131 | <h2>Setup</h2>
<p>I have a website that draws RSS feeds and displays them on the page. Currently, I use percentages on the divs that contain each feed, so that multiples can appear next to each other.</p>
<p>However, I only have two next to each other, and if the window resizes, there can be some ugly empty space on the screen.</p>
<h2>Desire</h2>
<p>What I'd like to be able to do, but have not figured out a way yet, is to put all the feeds linearly into the page, and have:</p>
<ul>
<li>a 'pre-built' multicolumn view where the feeds would "balance" themselves into the columns</li>
</ul>
<p>which leads me to:</p>
<ul>
<li>the number of columns change depending on how wide the screen is currently\</li>
</ul>
<p>This is akin to how word processing applications handle columnar layouts.</p>
<h2>Question</h2>
<p>I presume that I will need to implement some form of AJAXy happiness, but currently know very little about Javascript.</p>
<p>Is there a way to do this with <strong><em>just</em></strong> CSS/HTML/PHP?</p>
<p>If not, how should I go about solving this?</p>
<p><br/></p>
<h3>final solution:</h3>
<p>(based on <a href="https://stackoverflow.com/a/272183/4418">@warpr</a>'s and <a href="https://stackoverflow.com/a/272229/4418">@joh6nn</a>'s answers)</p>
<pre><code>#rss
{min-width: 10em;
max-width: 25em;
min-height: 15em;
max-height: 25em;
font-size: .97em;
float: left;
}
</code></pre>
| [
{
"answer_id": 272351,
"author": "Raithlin",
"author_id": 6528,
"author_profile": "https://Stackoverflow.com/users/6528",
"pm_score": 0,
"selected": false,
"text": "var columns = $(\".feed\").size();\nvar size = 100/columns;\n$(\".feed\").css(\"width\",size+\"%\");\n"
},
{
"answer_id": 274595,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 0,
"selected": false,
"text": "var docwidth = $(document).width();\nvar numOfCollums = $('.feed').length;\nvar colWidth = docwidth/numOfCollums;\n$('.feed').each( function() {\n $(this).width(colWidth);\n});\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4418/"
] |
272,152 | <p>What do I have to do to convert a DIB to a BMP?</p>
| [
{
"answer_id": 18292271,
"author": "Jeff Barnes",
"author_id": 1919288,
"author_profile": "https://Stackoverflow.com/users/1919288",
"pm_score": 2,
"selected": false,
"text": "BITMAPFILEHEADER *bmp = ...;\nchar * bmpBytes = reinterpret_cast<char *>(bmp);\nvoid * myDib = (void *)bmpBytes + BMP_HEADER_LENGTH; /* (14 bytes) */\n/* cast and do something with myDib */\n...\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
272,153 | <p>If I define a struct in C# using automatic properties like this:</p>
<pre><code>public struct Address
{
public Address(string line1, string line2, string city, string state, string zip)
{
Line1 = line1;
Line2 = line2;
City = city;
State = state;
Zip = zip;
}
public string Line1 { get; protected set; }
public string Line2 { get; protected set; }
public string City { get; protected set; }
public string State { get; protected set; }
public string Zip { get; protected set; }
}
</code></pre>
<p>When I attempt to build the file, I get a compilation error saying <code>The 'this' object cannot be used before all of its fields are assigned to</code>. This can be solved by changing the constructor to make a chained call to the default constructor like this:</p>
<pre><code>public Address(string line1, string line2, string city, string state, string zip): this()
{
Line1 = line1;
Line2 = line2;
City = city;
State = state;
Zip = zip;
}
</code></pre>
<p>My question is, why does this work, and what is happening? I have a guess, and I tried to prove it by looking at IL, but I'm only kidding myself if I think I can break down IL. But my guess is, auto properties work by having the compiler generate fields for your properties behind the scenes. Those fields cannot be accessed through code, all setting and getting must be done through the properties. When creating a struct, a default constructor cannot be explicitly defined. So behind the scenes, the compiler must be generating a default constructor that sets the values of the fields that the developer can't see.</p>
<p>Any and all IL wizards are welcome to prove or disprove my theory.</p>
| [
{
"answer_id": 272164,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "this()"
},
{
"answer_id": 12676594,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "Get"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6146/"
] |
272,157 | <p>I have a triangle mesh that has no texture, but a set color (sort of blue) and alpha (0.7f). This mesh is run time generated and the normals are correct. I find that with lighting on, the color of my object changes as it moves around the level. Also, the lighting doesn't look right. When I draw this object, this is the code:</p>
<pre><code>glEnable( GL_COLOR_MATERIAL );
float matColor[] = { cur->GetRed(), cur->GetGreen(), cur->GetBlue(), cur->GetAlpha() };
float white[] = { 0.3f, 0.3f, 0.3f, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, matColor);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
</code></pre>
<p>Another odd thing I noticed is that the lighting fails, when I disable <code>GL_FRONT_AND_BACK</code> and use just <code>GL_FRONT</code> or <code>GL_BACK</code>.
Here is my lighting setup (done once at beginning of renderer):</p>
<pre><code>m_lightAmbient[] = { 0.2f, 0.2f, 0.2f, 1.0f };
m_lightSpecular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
m_lightPosition[] = { 0.0f, 1200.0f, 0.0f, 1.0f };
glLightfv(GL_LIGHT0, GL_AMBIENT, m_lightAmbient);
glLightfv(GL_LIGHT0, GL_SPECULAR, m_lightSpecular);
glLightfv(GL_LIGHT0, GL_POSITION, m_lightPosition);
</code></pre>
<p>EDIT: I've done a lot to make the normals "more" correct (since I am generating the surface myself), but the objects color still changes depending where it is. Why is this? Does openGL have some special environment blending I don't know about?</p>
<p>EDIT: Turns out the color changing was because a previous texture was on the texture stack, and even though it wasn't being drawn, <code>glMaterialfv</code> was blending with it.</p>
| [
{
"answer_id": 277381,
"author": "DavidG",
"author_id": 25893,
"author_profile": "https://Stackoverflow.com/users/25893",
"pm_score": 0,
"selected": false,
"text": "// Vertices!\nglEnableClientState(GL_VERTEX_ARRAY);\n\n// Depth func\nglEnable(GL_DEPTH_TEST);\nglDepthFunc( GL_LESS );\n\n// Enable alpha blending\nglEnable(GL_BLEND);\nglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n// Lighting\nglEnable(GL_LIGHTING);\nglEnable(GL_LIGHT0);\nglLightfv(GL_LIGHT0, GL_AMBIENT, m_lightAmbient);\nglLightfv(GL_LIGHT0, GL_SPECULAR, m_lightSpecular);\nglLightfv(GL_LIGHT0, GL_POSITION, m_lightPosition);\n\n// Culling\nglDisable( GL_CULL_FACE );\n// Smooth Shading\nglShadeModel(GL_SMOOTH);\n\nm_glSetupDone = true;\n"
},
{
"answer_id": 277421,
"author": "korona",
"author_id": 25731,
"author_profile": "https://Stackoverflow.com/users/25731",
"pm_score": 1,
"selected": false,
"text": " /\\ /\\\n / \\ / \\\n / \\/ \\\n / /\\ \\\n/_____/__\\_____\\\n"
},
{
"answer_id": 413184,
"author": "Manuel",
"author_id": 50770,
"author_profile": "https://Stackoverflow.com/users/50770",
"pm_score": 0,
"selected": false,
"text": "glEnable(GL_NORMALIZE);\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25893/"
] |
272,159 | <p>I have the following one route, registered in my global.asax.</p>
<pre><code>routes.MapRoute(
"Home", // Unique name
"", // Root url
new { controller = "Home", action = "Index",
tag = string.Empty, page = 1 }
);
</code></pre>
<p>kewl. when I start the site, it correctly picks up this route.</p>
<p>Now, when I try to programmatically do the following, it returns NULL.</p>
<pre><code>var pageLinkValueDictionary =
new RouteValueDictionar(linkWithoutPageValuesDictionary)
{{"page", 2}};
VirtualPathData virtualPathData =
RouteTable.Routes.GetVirtualPath(viewContext, "Home"
pageLinkValueDictionary);
// NOTE: pageLinkValueDictionary ==
// Key: Action, Value: Index; Key: page, Value: 2
</code></pre>
<p>Why would this be happening?</p>
<p>I was under the impression that it would find the Home route but append any values not found as query string items?</p>
<h2>Update</h2>
<p>Still no luck with this. Also, using the <a href="https://www.microsoft.com/downloads/details.aspx?FamilyID=f4e4ee26-4bc5-41ed-80c9-261336b2a5b6&displaylang=en" rel="nofollow noreferrer">MVC RC</a>, I now need to change the viewContext to veiwContext.RequestContext .. which compiles but I'm still getting a null result.</p>
<h2>Update 2</h2>
<p>When I have the route without the <code>page=1</code> default item, the route <em>IS FOUND</em>.
eg.</p>
<pre><code>routes.MapRoute(
"Home",
"",
new { controller = "Post", action = "Index", tags = string.Empty }
);
</code></pre>
<p>.. and <code>RouteTable.Routes.GetVirtualPath</code> returns a <code>VirtualPathData</code> instance. When I add the <code>page=1</code> (default value) back in, the <code>VirtualPathData</code> instance returned is null?</p>
| [
{
"answer_id": 272527,
"author": "Torkel",
"author_id": 24425,
"author_profile": "https://Stackoverflow.com/users/24425",
"pm_score": 2,
"selected": true,
"text": "return RedirectToRoute(\"IndexDefault\", new {page = \"2\"}); \n"
},
{
"answer_id": 272917,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 1,
"selected": false,
"text": "route.MapRoute(\"theRoute\", \"{controller}/{action}/{tag}/{page}\",\n new { controller=\"Post\", action=\"Index\", tag=\"\", page=1 });\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
272,161 | <p>When I write code like this in VS 2008:<br><br></p>
<pre><code>.h
struct Patterns {
string ptCreate;
string ptDelete;
string ptDrop;
string ptUpdate;
string ptInsert;
string ptSelect;
};
class QueryValidate {
string query;
string pattern;
static Patterns pts;
public:
friend class Query;
QueryValidate(const string& qr, const string& ptn):
query(qr), pattern(ptn) {}
bool validate() {
boost::regex rg(pattern);
return boost::regex_match(query, rg);
}
virtual ~QueryValidate() {}
};
</code></pre>
<p>I then initialize my structure like this: </p>
<pre><code>.cpp
string QueryValidate::pts::ptCreate = "something";
string QueryValidate::pts::ptDelete = "something";
//...
</code></pre>
<p>The compiler gives the following errors: </p>
<blockquote>
<p>'Patterns': the symbol to the left of a '::' must be a type 'ptSelect'
: is not a member of 'QueryValidate'</p>
</blockquote>
<p>What am I doing wrong? Is this a problem with Visual Studio or with my code? I know that static members except for const ones must be defined outside the class they were declared in.</p>
| [
{
"answer_id": 272240,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 4,
"selected": true,
"text": "Patterns QueryValidate::pts = {\"CREATE\", \"DELETE\"}; // etc. for every string\n"
},
{
"answer_id": 272295,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 2,
"selected": false,
"text": "Patterns QueryValidate::pts = { \"something\", \"something\", ... };\n"
},
{
"answer_id": 272336,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 0,
"selected": false,
"text": "Patterns QueryValidate::pts;\n\nvoid foo () {\n QueryValidate::pts.ptCreate = \"something\";\n QueryValidate::pts.ptDelete = \"something\";\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
272,188 | <p>I have already visited <a href="https://stackoverflow.com/questions/191673/preferred-python-unit-testing-framework">Preferred Python unit-testing framework</a>. I am not just looking at Python Unit Testing Framework, but also code coverage with respect to unit tests. So far I have only come across <a href="http://nedbatchelder.com/code/modules/coverage.html" rel="nofollow noreferrer">coverage.py</a>. Is there any better option?</p>
<p>An interesting option for me is to integrate <a href="http://www.python.org/" rel="nofollow noreferrer">cpython</a>, unit testing of Python code and code coverage of Python code with Visual Studio 2008 through plugins (something similar to <a href="http://www.codeplex.com/IronPythonStudio" rel="nofollow noreferrer">IronPython Studio</a>). What can be done to achieve this? I look forward to suggestions.</p>
| [
{
"answer_id": 288711,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 0,
"selected": false,
"text": "--coverage"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30289/"
] |
272,190 | <p>I basically created some tables to play around with: I have Two main tables, and a Many-Many join table. Here is the DDL: (I am using HSQLDB)</p>
<pre><code>CREATE TABLE PERSON
(
PERSON_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
NAME VARCHAR(50), MAIN_PERSON_ID INTEGER
)
CREATE TABLE JOB
(
JOB_ID INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
NAME VARCHAR(50)
)
CREATE TABLE JOB_PERSON
(
PERSON_ID INTEGER,
JOB_ID INTEGER
)
ALTER TABLE JOB_PERSON ADD
CONSTRAINT FK_PERSON_JOB FOREIGN KEY(PERSON_ID)
REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE JOB_PERSON ADD
CONSTRAINT FK_JOB_PERSON FOREIGN KEY(JOB_ID)
REFERENCES JOB ON DELETE CASCADE ON UPDATE CASCADE
ALTER TABLE PERSON ADD
CONSTRAINT FK_PERSON_PERSON FOREIGN KEY(MAIN_PERSON_ID)
REFERENCES PERSON ON DELETE CASCADE ON UPDATE CASCADE
insert into person values(null,'Arthur', null);
insert into person values(null,'James',0);
insert into job values(null, 'Programmer')
insert into job values(null, 'Manager')
insert into job_person values(0,0);
insert into job_person values(0,1);
insert into job_person values(1,1);
</code></pre>
<p>I want to create a delete statement that deletes orphans from JOB (if there exists only one entry in the join table for a specific job) based on the PERSON.PERSON_ID. </p>
<p>In pseudo language: </p>
<pre><code>delete from job where job_person.job_id=job.job_id
AND count(job_person.job_id)=1 AND job_person.person_id=X
</code></pre>
<p>Where X is some person_id. I have tried a lot of different ways; I think it is the "COUNT" part that is causing problems. I am an SQL rookie, so any help would be much appreciated.</p>
| [
{
"answer_id": 272243,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": true,
"text": "JOB"
},
{
"answer_id": 272251,
"author": "Fred",
"author_id": 33630,
"author_profile": "https://Stackoverflow.com/users/33630",
"pm_score": 1,
"selected": false,
"text": "DELETE FROM JOB\nWHERE JOB_ID NOT IN (\n SELECT JOB_ID\n FROM JOB_PERSON\n)\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33863/"
] |
272,194 | <p>My webapp is part of a larger EAR that is deployed into a websphere server. The server hosts number of other apps on the same virtual server. My webapp has some initialisation/health checks in a servletContextListener->contextInitialized method. I want to make the webapp unavailable if initialisation/health checks fail. What is a realiable way of doing this? Will throwing a RuntimeException from within contextInitialized suffice? Is the rest of the EAR still expected to be available? Thank you.</p>
| [
{
"answer_id": 272747,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "RuntimeException"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33434/"
] |
272,199 | <p>I have a solution which contains many class libraries and an ASP .NET website which references those assemblies.</p>
<p>When I build the solution from within the IDE, all assemblies referenced by the website end up in the bin directory. Great!</p>
<p>When I use MsBuild from the command line, all the referenced assemblies are not copied to the bin directory. Why?</p>
<p>My command line is simply:</p>
<pre><code>msbuild.exe d:\myproject\mysolution.sln
</code></pre>
| [
{
"answer_id": 287900,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "%windir%\\Microsoft.Net\\framework\\v2.0.50727\\aspnet_compiler -v \\%~n1 -f -p .\\%1 .\\Website\n"
},
{
"answer_id": 2315626,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "md \"$(SolutionDir)Assemblies\"\ndel \"$(SolutionDir)Assemblies\\$(TargetFileName)\"\ncopy \"$(TargetPath)\" \"$(SolutionDir)Assemblies\" /y\n"
},
{
"answer_id": 11551469,
"author": "vangorra",
"author_id": 1267536,
"author_profile": "https://Stackoverflow.com/users/1267536",
"pm_score": 1,
"selected": false,
"text": "msbuild.exe myproject.vbproj /T:Rebuild\nmsbuild.exe myproject.vbproj /T:Package\n"
},
{
"answer_id": 21729974,
"author": "Henry Aloni",
"author_id": 938982,
"author_profile": "https://Stackoverflow.com/users/938982",
"pm_score": 0,
"selected": false,
"text": " c:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\MSBuild.exe <yourSolutionFile>.sln\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5449/"
] |
272,203 | <p>I'm thinking of using PDO in all of my future webapp. Currently (using what I've learned from SO so far), what I have in my site to handle database connection is a Singleton class like this :</p>
<pre><code>class DB {
private static $instance = NULL;
private static $dsn = "mysql:host=localhost;dbname=mydatabase;";
private static $db_user = 'root';
private static $db_pass = '0O0ooIl1';
private function __construct()
{
}
private function __clone()
{
}
public static function getInstance() {
if (!self::$instance)
{
self::$instance = new PDO(self::$dsn, self::$db_user, self::$db_pass);
self::$instance-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$instance;
}
}
</code></pre>
<p>and another file (functions.php) with content-specific functions looking exactly like this one :</p>
<pre><code>function get_recent_activities ()
{
try
{
$db = DB::getInstance();
// --prepare and execute query here, fetch the result--
return $my_list_of_recent_activities;
}
catch (PDOException $e)
{
return "some fail-messages";
}
}
...
</code></pre>
<p>meaning that I have to repeat the <code>try .. catch</code> part in all of the functions.</p>
<p>My questions are :</p>
<ol>
<li>How should I make that more efficient ? (eg. not having to repeat <code>try..catch</code> in all functions, and yet still able to return different "fail-message" on each one)</li>
<li>Is this already a good practice ? I'm still new at PDO and OOP (still a lot more to learn), so (as of now), I can't really see any disadvantages or things that can be improved in there.</li>
</ol>
<p>I'm sorry if that seems unclear or too long. Thanks in advance.</p>
| [
{
"answer_id": 272274,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 2,
"selected": false,
"text": "class DB extends PDO \n{\n // Allows implementation of the singleton pattern -- ndg 5/24/2008\n private static $instance;\n\n // Public static variables for configuring the DB class for a particular database -- ndg 6/16/2008\n public static $error_table;\n public static $host_name;\n public static $db_name;\n public static $username;\n public static $password;\n public static $driver_options;\n public static $db_config_path;\n\n\n\n function __construct($dsn=\"\", $username=\"\", $password=\"\", $driver_options=array()) \n {\n if(isset(self::$db_config_path))\n {\n try \n {\n if(!require_once self::$db_config_path)\n {\n throw new error('Failed to require file: ' . self::$db_config_path); \n }\n } \n catch(error $e) \n {\n $e->emailAdmin();\n }\n }\n elseif(isset($_ENV['DB']))\n {\n self::$db_config_path = 'config.db.php';\n\n try \n {\n if(!require_once self::$db_config_path)\n {\n throw new error('Failed to require file: ' . self::$db_config_path); \n }\n } \n catch(error $e) \n {\n $e->emailAdmin();\n }\n }\n\n parent::__construct(\"mysql:host=\" . self::$host_name . \";dbname=\" .self::$db_name, self::$username, self::$password, self::$driver_options);\n $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('QueryStatement', array($this)));\n\n if(!isset(self::$error_table))\n {\n self::$error_table = 'errorlog_rtab';\n }\n }\n\n /**\n * Return a DB Connection Object\n *\n * @return DB\n */\n public static function connect()\n {\n\n // New PDO Connection to be used in NEW development and MAINTENANCE development\n try \n {\n if(!isset(self::$instance))\n { \n if(!self::$instance = new DB())\n {\n throw new error('PDO DB Connection failed with error: ' . self::errorInfo());\n }\n }\n\n return self::$instance;\n }\n catch(error $e)\n {\n $e->printErrMsg();\n }\n }\n\n /**\n * Returns a QueryBuilder object which can be used to build dynamic queries\n *\n * @return QueryBuilder\n * \n */\n public function createQuery()\n {\n return new QueryBuilder();\n }\n\n public function executeStatement($statement, $params = null, $FETCH_MODE = null)\n {\n if($FETCH_MODE == 'scalar')\n {\n return $this->executeScalar($statement, $params); \n }\n\n\n try {\n try {\n if(!empty($params))\n {\n $stmt = $this->prepare($statement);\n $stmt->execute($params);\n }\n else \n {\n $stmt = $this->query($statement);\n }\n }\n catch(PDOException $pdo_error)\n {\n throw new error(\"Failed to execute query:\\n\" . $statement . \"\\nUsing Parameters:\\n\" . print_r($params, true) . \"\\nWith Error:\\n\" . $pdo_error->getMessage());\n }\n }\n catch(error $e)\n {\n $this->logDBError($e);\n $e->emailAdmin();\n return false;\n }\n\n try \n {\n if($FETCH_MODE == 'all')\n {\n $tmp = $stmt->fetchAll();\n }\n elseif($FETCH_MODE == 'column')\n {\n $arr = $stmt->fetchAll();\n\n foreach($arr as $key => $val)\n {\n foreach($val as $var => $value)\n {\n $tmp[] = $value;\n }\n } \n }\n elseif($FETCH_MODE == 'row') \n {\n $tmp = $stmt->fetch();\n }\n elseif(empty($FETCH_MODE))\n {\n return true;\n }\n }\n catch(PDOException $pdoError)\n {\n return true;\n }\n\n $stmt->closeCursor();\n\n return $tmp;\n\n }\n\n public function executeScalar($statement, $params = null)\n {\n $stmt = $this->prepare($statement);\n\n if(!empty($this->bound_params) && empty($params))\n {\n $params = $this->bound_params;\n }\n\n try {\n try {\n if(!empty($params))\n {\n $stmt->execute($params);\n }\n else \n {\n $stmt = $this->query($statement);\n }\n }\n catch(PDOException $pdo_error)\n {\n throw new error(\"Failed to execute query:\\n\" . $statement . \"\\nUsing Parameters:\\n\" . print_r($params, true) . \"\\nWith Error:\\n\" . $pdo_error->getMessage());\n }\n }\n catch(error $e)\n {\n $this->logDBError($e);\n $e->emailAdmin();\n }\n\n $count = $stmt->fetchColumn();\n\n $stmt->closeCursor();\n\n //echo $count;\n return $count; \n }\n\n protected function logDBError($e)\n {\n $error = $e->getErrorReport();\n\n $sql = \"\n INSERT INTO \" . self::$error_table . \" (message, time_date) \n VALUES (:error, NOW())\";\n\n $this->executeStatement($sql, array(':error' => $error));\n }\n}\n\nclass QueryStatement extends PDOStatement \n{\n public $conn;\n\n protected function __construct() \n {\n $this->conn = DB::connect();\n $this->setFetchMode(PDO::FETCH_ASSOC);\n }\n\n public function execute($bound_params = null)\n {\n return parent::execute($bound_params); \n }\n}\n"
},
{
"answer_id": 273090,
"author": "pd.",
"author_id": 19066,
"author_profile": "https://Stackoverflow.com/users/19066",
"pm_score": 7,
"selected": true,
"text": "try {\n $rs = $db->prepare('SELECT * FROM foo');\n $rs->execute();\n $foo = $rs->fetchAll();\n} catch (Exception $e) {\n die(\"Oh noes! There's an error in the query!\");\n}\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26721/"
] |
272,207 | <p>I have a weird issue. I had a web service that was compiled under the 2.0 framework that was being consumed by a windows app that was compiled with the 1.1 framework. This worked just fine. Now, after upgrading the web service to the 3.5 framework, the windows app is no longer able to call it.</p>
<p>Creating a little windows app in 3.5 as a test is able to call the web service without problems so I know it still works.</p>
<p>Nothing has changed in the code at all, it's just compiled as a 3.5 project instead of a 2.0 project.</p>
<p>For those who care what error I get back, it's this:</p>
<blockquote>
<p>An unhandled exception of type
'System.Net.WebException' occurred in
system.web.services.dll</p>
<p>Additional information: The underlying connection was closed: An
unexpected error occurred on a
receive.</p>
</blockquote>
<p>Is there anything I can do to the web service to make it backwards compatible (if that's even the issue)?</p>
<p>[Edit] Responses to answers below (so far): Re-Discovering did not work, nor did removing and re-adding the webservice. I don't believe it's a SOAP issue becuase the WSDLs are identical (both show SOAP 1.2). Browsing to the webservice from the server works just fine.</p>
| [
{
"answer_id": 274277,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 1,
"selected": false,
"text": " // Put this override in the generated Reference.cs of the client proxy\n protected override System.Net.WebRequest GetWebRequest(Uri uri)\n {\n HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);\n\n webRequest.KeepAlive = false;\n webRequest.ProtocolVersion = HttpVersion.Version10;\n return webRequest;\n }\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2849/"
] |
272,210 | <p>What is the accepted practice for indenting SQL statements? For example, consider the following SQL statement:</p>
<pre><code>SELECT column1, column2
FROM table1
WHERE column3 IN
(
SELECT TOP(1) column4
FROM table2
INNER JOIN table3
ON table2.column1 = table3.column1
)
</code></pre>
<p>How should this be indented? Many thanks.</p>
| [
{
"answer_id": 272227,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 4,
"selected": false,
"text": "SELECT\n column1,\n column2\nFROM\n table1\nWHERE\n column3 IN ( \n SELECT TOP(1)\n column4\n FROM\n table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n )\n\n\nSELECT\n column1,\n column2\nFROM\n table1\nWHERE\n column3 IN ( \n SELECT TOP(1)\n column4\n FROM\n table2\n INNER JOIN table3\n ON table2.column1 = table3.column1 -- for long ones\n )\n"
},
{
"answer_id": 272228,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": false,
"text": "SELECT column1, column2\nFROM table\nWHERE column3 IN (\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 272231,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 5,
"selected": false,
"text": "SELECT \n column1, \n column2 \nFROM \n table1 \nWHERE \n column3 IN \n ( \n SELECT TOP(1) \n column4 \n FROM \n table2 \n INNER JOIN \n table3 \n ON table2.column1 = table3.column1 \n )\n"
},
{
"answer_id": 272232,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 7,
"selected": true,
"text": "SELECT column1\n , column2\nFROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 272236,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "print(\"SELECT column1, column2\n FROM table1\n WHERE column3 IN (SELECT TOP(1) column4\n FROM table2 INNER JOIN \n table3 ON table2.column1 = table3.column1)\");\n"
},
{
"answer_id": 272238,
"author": "Bullines",
"author_id": 27870,
"author_profile": "https://Stackoverflow.com/users/27870",
"pm_score": 2,
"selected": false,
"text": "SELECT column1, column2\nFROM table1\nWHERE column3 IN(SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3 ON\n table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 272242,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": "SELECT\n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN (SELECT TOP(1) \n column4 \n FROM \n table2 \n INNER JOIN table3 ON table2.column1 = table3.column1)\n"
},
{
"answer_id": 272245,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 1,
"selected": false,
"text": "SELECT column1, column2\n FROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 272264,
"author": "jalbert",
"author_id": 1360388,
"author_profile": "https://Stackoverflow.com/users/1360388",
"pm_score": 4,
"selected": false,
"text": "SELECT column1,\n column2\n FROM table1\n WHERE column3 IN (SELECT column4\n FROM table2\n JOIN table3\n ON table2.column1 = table3.column1);\n"
},
{
"answer_id": 272267,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": " SELECT column1\n ,column2\n FROM table1\n WHERE column3 IN (\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 272278,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "SELECT \n column1\n ,column2\nFROM\n table1\nWHERE column3 IN (\n SELECT TOP(1) column4\n FROM \n table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 272282,
"author": "Jack Ryan",
"author_id": 28882,
"author_profile": "https://Stackoverflow.com/users/28882",
"pm_score": 3,
"selected": false,
"text": "SELECT column1, \n column2\nFROM table1\nWHERE column3 IN\n(\n SELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 272305,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": false,
"text": "SELECT\n Column1,\n Column2\nFROM Table1\nWHERE \n Column3 IN (\n SELECT Column4\n FROM Table2\n JOIN Table3 ON\n Table2.Column1 = Table3.Column1\n )\n"
},
{
"answer_id": 272339,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "Select column1, column2\nFrom table1 T1\nWhere column3 In (Select Top(1) column4\n From table2 T2\n Join table3 T3\n On T2.column1 = T3.column1)\n"
},
{
"answer_id": 272344,
"author": "Slapout",
"author_id": 19072,
"author_profile": "https://Stackoverflow.com/users/19072",
"pm_score": 4,
"selected": false,
"text": "\nSELECT column1, \n column2 \n FROM table1, table2 \n WHERE table1.column1 = table2.column4 \n AND table1.col5 = \"hi\" \n OR table2.myfield = 678 \n"
},
{
"answer_id": 272391,
"author": "Mike Burton",
"author_id": 22225,
"author_profile": "https://Stackoverflow.com/users/22225",
"pm_score": 3,
"selected": false,
"text": "SELECT \n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN\n (\n SELECT TOP(1) \n column4\n FROM \n table2\n INNER JOIN table3 ON table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 272655,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT column1, column2\nFROM table1\nWHERE column3 IN\n(\nSELECT TOP(1) column4\n FROM table2\n INNER JOIN table3\n ON table2.column1 = table3.column1\n)\n"
},
{
"answer_id": 3535810,
"author": "José Américo Antoine Jr",
"author_id": 426870,
"author_profile": "https://Stackoverflow.com/users/426870",
"pm_score": 3,
"selected": false,
"text": "SELECT \n produtos_cesta.cod_produtos_cesta, \n produtos.nome_pequeno,\n tab_contagem.cont,\n produtos_cesta.sku, \n produtos_kits.sku_r AS sku_kit, \n sku_final = CASE\n WHEN produtos_kits.sku_r IS NOT NULL THEN produtos_kits.sku_r\n ELSE produtos_cesta.sku\n END,\n estoque = CASE\n WHEN produtos2.estoque IS NOT NULL THEN produtos2.estoque\n ELSE produtos.estoque\n END,\n produtos_cesta.unidades as unidades1, \n unidades_x_quantidade = CASE\n WHEN produtos.cod_produtos_kits_tipo = 1 THEN CAST(produtos_cesta.quantidade * (produtos_cesta.unidades / tab_contagem.cont) * produtos_kits.quantidade AS int)\n ELSE CAST(produtos_cesta.quantidade * produtos_cesta.unidades AS int)\n END,\n unidades = CASE\n WHEN produtos.cod_produtos_kits_tipo = 1 THEN produtos_cesta.unidades / tab_contagem.cont * produtos_kits.quantidade\n ELSE produtos_cesta.unidades\n END,\n unidades_parent = produtos_cesta.unidades,\n produtos_cesta.quantidade,\n produtos.controla_estoque, \n produtos.status\nFROM \n produtos_cesta \nINNER JOIN produtos \n ON (produtos_cesta.sku = produtos.sku) \nINNER JOIN produtos_pacotes \n ON (produtos_cesta.sku = produtos_pacotes.sku) \nINNER JOIN (\n SELECT \n produtos_cesta.cod_produtos_cesta,\n cont = SUM(\n CASE\n WHEN produtos_kits.quantidade IS NOT NULL THEN produtos_kits.quantidade\n ELSE 1\n END\n )\n FROM \n produtos_cesta \n LEFT JOIN produtos_kits \n ON (produtos_cesta.sku = produtos_kits.sku) \n LEFT JOIN produtos \n ON (produtos_cesta.sku = produtos.sku) \n WHERE \n shopper_id = '\" + mscsShopperId + @\"' \n GROUP BY \n produtos_cesta.cod_produtos_cesta, \n produtos_cesta.sku, \n produtos_cesta.unidades \n) \nAS tab_contagem\n ON (produtos_cesta.cod_produtos_cesta = tab_contagem.cod_produtos_cesta)\nLEFT JOIN produtos_kits \n ON (produtos.sku = produtos_kits.sku) \nLEFT JOIN produtos as produtos2\n ON (produtos_kits.sku_r = produtos2.sku) \nWHERE \n shopper_id = '\" + mscsShopperId + @\"' \nGROUP BY \n produtos_cesta.cod_produtos_cesta, \n tab_contagem.cont,\n produtos_cesta.sku, \n produtos_kits.sku_r, \n produtos.cod_produtos_kits_tipo, \n produtos2.estoque,\n produtos.controla_estoque, \n produtos.estoque, \n produtos.status, \n produtos.nome_pequeno, \n produtos_cesta.unidades, \n produtos_cesta.quantidade,\n produtos_kits.quantidade\nORDER BY \n produtos_cesta.sku, \n produtos_cesta.unidades DESC\n"
},
{
"answer_id": 4582352,
"author": "S. Goldberg",
"author_id": 560893,
"author_profile": "https://Stackoverflow.com/users/560893",
"pm_score": 1,
"selected": false,
"text": "SELECT\n Column1,\n Column2\nFROM\n Table1\nWHERE\n Column3 IN\n (\n SELECT TOP (1)\n Column4\n FROM \n Table2\n INNER JOIN \n Table3\n ON\n Table2.Column1 = Table3.Column1\n )\n"
},
{
"answer_id": 9910379,
"author": "Jens Frandsen",
"author_id": 1298535,
"author_profile": "https://Stackoverflow.com/users/1298535",
"pm_score": 3,
"selected": false,
"text": "SELECT \n column1, \n column2\nFROM \n table1\nWHERE \n column3 IN\n (\n SELECT TOP(1) \n column4\n FROM \n table2 INNER JOIN \n table3 ON table2.column1 = table3.column1\n )\n"
},
{
"answer_id": 18098922,
"author": "John Doe",
"author_id": 2659987,
"author_profile": "https://Stackoverflow.com/users/2659987",
"pm_score": 3,
"selected": false,
"text": "select column1, column2\n from table1\n where (column3 in (\n select top(1) column4\n from table2\n inner join table3\n on (table2.column1 = table3.column1)\n ))\n;\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35483/"
] |
272,270 | <pre><code> <object height="25" width="75" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
<param value="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK" name="movie"/>
<param value="high" name="quality"/>
<param value="#FFFFFF" name="bgcolor"/>
<param value="opaque" name="wmode"/>
<embed height="25" width="75" wmode="opaque" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" bgcolor="#FFFFFF" quality="high" src="http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK"/>
</object>
</code></pre>
<p>I am having to insert this legacy markup into a new site that I'm building. Problem is its using an <code><embed></code> tag. </p>
<p>Would I just do away with the <code><embed></code> and put some content in as an alternative, for those that do not have flash? Basically I'm just trying to bring this piece of html into the 21st century.</p>
| [
{
"answer_id": 272308,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<P> <!-- First, try the Python applet -->\n<OBJECT title=\"The Earth as seen from space\" \n classid=\"http://www.observer.mars/TheEarth.py\">\n <!-- Else, try the MPEG video -->\n <OBJECT data=\"TheEarth.mpeg\" type=\"application/mpeg\">\n <!-- Else, try the GIF image -->\n <OBJECT data=\"TheEarth.gif\" type=\"image/gif\">\n <!-- Else render the text -->\n The <STRONG>Earth</STRONG> as seen from space.\n </OBJECT>\n </OBJECT>\n</OBJECT>\n"
},
{
"answer_id": 272328,
"author": "Raithlin",
"author_id": 6528,
"author_profile": "https://Stackoverflow.com/users/6528",
"pm_score": 1,
"selected": false,
"text": "<!--[if !IE]> -->\n<object type=\"application/x-shockwave-flash\" data=\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\" width=\"75\" height=\"25\">\n<!-- <![endif]-->\n\n<!--[if IE]>\n<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0\" width=\"75\" height=\"25\">\n <param name=\"movie\" value=\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\" />\n<!--><!--dgx-->\n <param name=\"loop\" value=\"false\">\n <param name=\"menu\" value=\"false\">\n <param name=\"quality\" value=\"high\">\n</object>\n<!-- <![endif]-->\n"
},
{
"answer_id": 272362,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"swfobject.js\"></script>\n<script type=\"text/javascript\">\n swfobject.embedSWF(\"http://click-here-to-listen.com/players/iaPlay13.swf?x=1058286910FTRZGK\", \n \"myContent\", \"25\", \"75\", \"9.0.0\");\n</script>\n<div id=\"myContent\">\n <p>Alternative content</p>\n</div>\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
272,313 | <p>I have the requirement to support different Master pages on my application (ASP.NET MVC).
What is the recommended way to:</p>
<ol>
<li>Pass the master page name to the view from.</li>
<li>Store the master page (in session, or something) so it sticks during a user's visit.</li>
</ol>
| [
{
"answer_id": 460828,
"author": "Slee",
"author_id": 34548,
"author_profile": "https://Stackoverflow.com/users/34548",
"pm_score": 4,
"selected": true,
"text": "Public Class CustomBaseController\n Inherits System.Web.Mvc.Controller\n\n Protected Overrides Function View(ByVal viewName As String, ByVal masterName As String, ByVal model As Object) As System.Web.Mvc.ViewResult\n\n Return MyBase.View(viewName, Session(\"MasterPage\"), model)\n\n End Function\n\nEnd Class\n"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7277/"
] |
272,360 | <p>If so, does it effectively deprecate the <code>visibility</code> property?</p>
<p>(I realize that Internet Explorer does not yet support this CSS2 property.)
<br/>
<a href="http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(CSS)#Properties" rel="noreferrer">Comparisons of layout engines</a></p>
<p><a href="https://stackoverflow.com/questions/133051/what-is-the-difference-between-visibilityhidden-and-displaynone">See also: What is the difference between visibility:hidden and display:none</a></p>
| [
{
"answer_id": 272380,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 2,
"selected": false,
"text": "opacity: 0.6;\n-moz-opacity: 0.6;\nfilter: alpha(opacity=60);\n"
},
{
"answer_id": 272381,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "filter:alpha(opacity=0);\n"
},
{
"answer_id": 742324,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "opacity:0"
},
{
"answer_id": 43482222,
"author": "MalcolmOcean",
"author_id": 985026,
"author_profile": "https://Stackoverflow.com/users/985026",
"pm_score": 2,
"selected": false,
"text": "contenteditable"
},
{
"answer_id": 50027026,
"author": "Mr Lister",
"author_id": 1016716,
"author_profile": "https://Stackoverflow.com/users/1016716",
"pm_score": 3,
"selected": false,
"text": "visibility"
}
] | 2008/11/07 | [
"https://Stackoverflow.com/questions/272360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.