qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
13,599 | <p>Does anyone know how to transform a enum value to a human readable value?</p>
<p>For example:</p>
<blockquote>
<p>ThisIsValueA should be "This is Value A".</p>
</blockquote>
| [
{
"answer_id": 13602,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 3,
"selected": false,
"text": "<p>Most examples of this that I've seen involve marking your enum values up with [Description] attributes and using reflection to do the "conversion" between the value and the description. Here's an old blog post about it:</p>\n<p><<a href=\"https://web.archive.org/web/20201125032118/http://geekswithblogs.net/rakker/archive/2006/05/19/78952.aspx\" rel=\"nofollow noreferrer\">Link</a>></p>\n"
},
{
"answer_id": 13610,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>You can also take a look at this article: <a href=\"http://www.codeproject.com/KB/cs/enumdatabinding.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/enumdatabinding.aspx</a></p>\n\n<p>It's specifically about data binding, but shows how to use an attribute to decorate the enum values and provides a \"GetDescription\" method to retrieve the text of the attribute. The problem with using the built-in description attribute is that there are other uses/users of that attribute so there is a possibility that the description appears where you don't want it to. The custom attribute solves that issue.</p>\n"
},
{
"answer_id": 13611,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 2,
"selected": false,
"text": "<p>You can inherit from the \"Attribute\" class of System.Reflection to create your own \"Description\" class. Like this (from <a href=\"http://blogs.msdn.com/abhinaba/archive/2005/10/20/483000.aspx\" rel=\"nofollow noreferrer\">here</a>):</p>\n\n<pre><code>using System;\nusing System.Reflection;\nnamespace FunWithEnum\n{\n enum Coolness : byte\n {\n [Description(\"Not so cool\")]\n NotSoCool = 5,\n Cool, // since description same as ToString no attr are used\n [Description(\"Very cool\")]\n VeryCool = NotSoCool + 7,\n [Description(\"Super cool\")]\n SuperCool\n }\n class Description : Attribute\n {\n public string Text;\n public Description(string text)\n {\n Text = text;\n }\n }\n class Program\n {\n static string GetDescription(Enum en)\n {\n Type type = en.GetType();\n MemberInfo[] memInfo = type.GetMember(en.ToString());\n if (memInfo != null && memInfo.Length > 0)\n {\n object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description), false);\n if (attrs != null && attrs.Length > 0)\n return ((Description)attrs[0]).Text;\n }\n return en.ToString();\n }\n static void Main(string[] args)\n {\n Coolness coolType1 = Coolness.Cool;\n Coolness coolType2 = Coolness.NotSoCool;\n Console.WriteLine(GetDescription(coolType1));\n Console.WriteLine(GetDescription(coolType2));\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 13613,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 5,
"selected": true,
"text": "<p>Converting this from a vb code snippet that a certain Ian Horwill left at a <a href=\"http://secretgeek.net/progr_purga.asp\" rel=\"noreferrer\">blog post long ago</a>... i've since used this in production successfully.</p>\n\n<pre><code> /// <summary>\n /// Add spaces to separate the capitalized words in the string, \n /// i.e. insert a space before each uppercase letter that is \n /// either preceded by a lowercase letter or followed by a \n /// lowercase letter (but not for the first char in string). \n /// This keeps groups of uppercase letters - e.g. acronyms - together.\n /// </summary>\n /// <param name=\"pascalCaseString\">A string in PascalCase</param>\n /// <returns></returns>\n public static string Wordify(string pascalCaseString)\n { \n Regex r = new Regex(\"(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])\");\n return r.Replace(pascalCaseString, \" ${x}\");\n }\n</code></pre>\n\n<p>(requires, 'using System.Text.RegularExpressions;')</p>\n\n<p>Thus:</p>\n\n<pre><code>Console.WriteLine(Wordify(ThisIsValueA.ToString()));\n</code></pre>\n\n<p>Would return, </p>\n\n<pre><code>\"This Is Value A\".\n</code></pre>\n\n<p>It's much simpler, and less redundant than providing Description attributes.</p>\n\n<p>Attributes are useful here only if you need to provide a layer of indirection (which the question didn't ask for).</p>\n"
},
{
"answer_id": 13641,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 0,
"selected": false,
"text": "<p>I found it best to define your enum values with an under score so ThisIsValueA would be This_Is_Value_A then you can just do a enumValue.toString().Replace(\"_\",\" \") where enumValue is your varible.</p>\n"
},
{
"answer_id": 13697,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>The .ToString on Enums is relatively slow in C#, comparable with GetType().Name (it might even use that under the covers).</p>\n\n<p>If your solution needs to be very quick or highly efficient you may be best of caching your conversions in a static dictionary, and looking them up from there.</p>\n\n<hr>\n\n<p>A small adaptation of @Leon's code to take advantage of C#3. This does make sense as an extension of enums - you could limit this to the specific type if you didn't want to clutter up all of them.</p>\n\n<pre><code>public static string Wordify(this Enum input)\n{ \n Regex r = new Regex(\"(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])\");\n return r.Replace( input.ToString() , \" ${x}\");\n}\n\n//then your calling syntax is down to:\nMyEnum.ThisIsA.Wordify();\n</code></pre>\n"
},
{
"answer_id": 52067663,
"author": "Matt Williams",
"author_id": 3905343,
"author_profile": "https://Stackoverflow.com/users/3905343",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative to adding <code>Description</code> attributes to each enumeration is to create an extension method. To re-use Adam's \"Coolness\" enum:</p>\n\n<pre><code>public enum Coolness\n{\n NotSoCool,\n Cool,\n VeryCool,\n SuperCool\n}\n\npublic static class CoolnessExtensions\n{\n public static string ToString(this Coolness coolness)\n {\n switch (coolness)\n {\n case Coolness.NotSoCool:\n return \"Not so cool\";\n case Coolness.Cool:\n return \"Cool\";\n case Coolness.VeryCool:\n return \"Very cool\";\n case Coolness.SuperCool:\n return Properties.Settings.Default[\"SuperCoolDescription\"].ToString();\n default:\n throw new ArgumentException(\"Unknown amount of coolness\", nameof(coolness));\n }\n }\n}\n</code></pre>\n\n<p>Although this means that the descriptions are further away from the actual values, it allows you to use localisation to print different strings for each language, such as in my <code>VeryCool</code> example.</p>\n"
},
{
"answer_id": 68849180,
"author": "osynavets",
"author_id": 9547346,
"author_profile": "https://Stackoverflow.com/users/9547346",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Enum.GetName(typeof(EnumFoo), EnumFoo.BarValue)\n</code></pre>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | Does anyone know how to transform a enum value to a human readable value?
For example:
>
> ThisIsValueA should be "This is Value A".
>
>
> | Converting this from a vb code snippet that a certain Ian Horwill left at a [blog post long ago](http://secretgeek.net/progr_purga.asp)... i've since used this in production successfully.
```
/// <summary>
/// Add spaces to separate the capitalized words in the string,
/// i.e. insert a space before each uppercase letter that is
/// either preceded by a lowercase letter or followed by a
/// lowercase letter (but not for the first char in string).
/// This keeps groups of uppercase letters - e.g. acronyms - together.
/// </summary>
/// <param name="pascalCaseString">A string in PascalCase</param>
/// <returns></returns>
public static string Wordify(string pascalCaseString)
{
Regex r = new Regex("(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])");
return r.Replace(pascalCaseString, " ${x}");
}
```
(requires, 'using System.Text.RegularExpressions;')
Thus:
```
Console.WriteLine(Wordify(ThisIsValueA.ToString()));
```
Would return,
```
"This Is Value A".
```
It's much simpler, and less redundant than providing Description attributes.
Attributes are useful here only if you need to provide a layer of indirection (which the question didn't ask for). |
13,615 | <p>I need to validate an integer to know if is a valid enum value.</p>
<p>What is the best way to do this in C#?</p>
| [
{
"answer_id": 13635,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>Brad Abrams specifically warns against <strong><code>Enum.IsDefined</code></strong> in his post <a href=\"https://learn.microsoft.com/en-us/archive/blogs/brada/the-danger-of-over-simplification-enum-isdefined\" rel=\"nofollow noreferrer\">The Danger of Oversimplification</a>. </p>\n\n<p>The best way to get rid of this requirement (that is, the need to validate enums) is to remove ways where users can get it wrong, e.g., an input box of some sort. Use enums with drop downs, for example, to enforce only valid enums.</p>\n"
},
{
"answer_id": 13651,
"author": "Mike Polen",
"author_id": 212,
"author_profile": "https://Stackoverflow.com/users/212",
"pm_score": 0,
"selected": false,
"text": "<p>I found this <a href=\"http://www.cambiaresearch.com/c4/52a7e5fe-c7fc-49ab-b21d-37e6194687f3/Convert-Integer-To-Enum-Instance-in-csharp.aspx\" rel=\"nofollow noreferrer\">link</a> that answers it quite well. It uses:</p>\n\n<pre><code>(ENUMTYPE)Enum.ToObject(typeof(ENUMTYPE), INT)\n</code></pre>\n"
},
{
"answer_id": 4807469,
"author": "Vman",
"author_id": 299529,
"author_profile": "https://Stackoverflow.com/users/299529",
"pm_score": 8,
"selected": true,
"text": "<p>You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!</p>\n\n<p><code>IsDefined</code> is fine for most scenarios, you could start with:</p>\n\n<pre><code>public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)\n{\n retVal = default(TEnum);\n bool success = Enum.IsDefined(typeof(TEnum), enumValue);\n if (success)\n {\n retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);\n }\n return success;\n}\n</code></pre>\n\n<p>(Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension)</p>\n"
},
{
"answer_id": 15752719,
"author": "deegee",
"author_id": 1655625,
"author_profile": "https://Stackoverflow.com/users/1655625",
"pm_score": 5,
"selected": false,
"text": "<p>IMHO the post marked as the answer is incorrect.<br>\nParameter and data validation is one of the things that was drilled into me decades ago.</p>\n\n<p><strong>WHY</strong></p>\n\n<p>Validation is required because essentially any integer value can be assigned to an enum without throwing an error.<br>\nI spent many days researching C# enum validation because it is a necessary function in many cases.</p>\n\n<p><strong>WHERE</strong></p>\n\n<p>The main purpose in enum validation for me is in validating data read from a file: you never know if the file has been corrupted, or was modified externally, or was hacked on purpose.<br>\nAnd with enum validation of application data pasted from the clipboard: you never know if the user has edited the clipboard contents.</p>\n\n<p>That said, I spent days researching and testing many methods including profiling the performance of every method I could find or design.</p>\n\n<p>Making calls into anything in System.Enum is so slow that it was a noticeable performance penalty on functions that contained hundreds or thousands of objects that had one or more enums in their properties that had to be validated for bounds.</p>\n\n<p>Bottom line, stay away from <em>everything</em> in the System.Enum class when validating enum values, it is dreadfully slow.</p>\n\n<p><strong>RESULT</strong></p>\n\n<p>The method that I currently use for enum validation will probably draw rolling eyes from many programmers here, but it is imho the least evil for my specific application design.</p>\n\n<p>I define one or two constants that are the upper and (optionally) lower bounds of the enum, and use them in a pair of if() statements for validation.<br>\nOne downside is that you must be sure to update the constants if you change the enum.<br>\nThis method also only works if the enum is an \"auto\" style where each enum element is an incremental integer value such as 0,1,2,3,4,.... It won't work properly with Flags or enums that have values that are not incremental.</p>\n\n<p>Also note that this method is almost as fast as regular if \"<\" \">\" on regular int32s (which scored 38,000 ticks on my tests).</p>\n\n<p>For example:</p>\n\n<pre><code>public const MyEnum MYENUM_MINIMUM = MyEnum.One;\npublic const MyEnum MYENUM_MAXIMUM = MyEnum.Four;\n\npublic enum MyEnum\n{\n One,\n Two,\n Three,\n Four\n};\n\npublic static MyEnum Validate(MyEnum value)\n{\n if (value < MYENUM_MINIMUM) { return MYENUM_MINIMUM; }\n if (value > MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }\n return value;\n}\n</code></pre>\n\n<p><strong>PERFORMANCE</strong></p>\n\n<p>For those who are interested, I profiled the following variations on an enum validation, and here are the results.</p>\n\n<p>The profiling was performed on release compile in a loop of one million times on each method with a random integer input value. Each test was ran more than 10 times and averaged. The tick results include the total time to execute which will include the random number generation etc. but those will be constant across the tests. 1 tick = 10ns.</p>\n\n<p>Note that the code here isn't the complete test code, it is only the basic enum validation method. There were also a lot of additional variations on these that were tested, and all of them with results similar to those shown here that benched 1,800,000 ticks.</p>\n\n<p>Listed slowest to fastest with rounded results, hopefully no typos.</p>\n\n<p><strong>Bounds determined in Method</strong> = 13,600,000 ticks</p>\n\n<pre><code>public static T Clamp<T>(T value)\n{\n int minimum = Enum.GetValues(typeof(T)).GetLowerBound(0);\n int maximum = Enum.GetValues(typeof(T)).GetUpperBound(0);\n\n if (Convert.ToInt32(value) < minimum) { return (T)Enum.ToObject(typeof(T), minimum); }\n if (Convert.ToInt32(value) > maximum) { return (T)Enum.ToObject(typeof(T), maximum); }\n return value;\n}\n</code></pre>\n\n<p><strong>Enum.IsDefined</strong> = 1,800,000 ticks<br>\nNote: this code version doesn't clamp to Min/Max but returns Default if out of bounds.</p>\n\n<pre><code>public static T ValidateItem<T>(T eEnumItem)\n{\n if (Enum.IsDefined(typeof(T), eEnumItem) == true)\n return eEnumItem;\n else\n return default(T);\n}\n</code></pre>\n\n<p><strong>System.Enum Convert Int32 with casts</strong> = 1,800,000 ticks</p>\n\n<pre><code>public static Enum Clamp(this Enum value, Enum minimum, Enum maximum)\n{\n if (Convert.ToInt32(value) < Convert.ToInt32(minimum)) { return minimum; }\n if (Convert.ToInt32(value) > Convert.ToInt32(maximum)) { return maximum; }\n return value;\n}\n</code></pre>\n\n<p><strong>if() Min/Max Constants</strong> = 43,000 ticks = the winner by 42x and 316x faster.</p>\n\n<pre><code>public static MyEnum Clamp(MyEnum value)\n{\n if (value < MYENUM_MINIMUM) { return MYENUM_MINIMUM; }\n if (value > MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }\n return value;\n}\n</code></pre>\n\n<p>-eol-</p>\n"
},
{
"answer_id": 19036239,
"author": "Schultz9999",
"author_id": 494343,
"author_profile": "https://Stackoverflow.com/users/494343",
"pm_score": 1,
"selected": false,
"text": "<p>This is how I do it based on multiple posts online. The reason for doing this is to make sure enums marked with <code>Flags</code> attribute can also be successfully validated.</p>\n\n<pre><code>public static TEnum ParseEnum<TEnum>(string valueString, string parameterName = null)\n{\n var parsed = (TEnum)Enum.Parse(typeof(TEnum), valueString, true);\n decimal d;\n if (!decimal.TryParse(parsed.ToString(), out d))\n {\n return parsed;\n }\n\n if (!string.IsNullOrEmpty(parameterName))\n {\n throw new ArgumentException(string.Format(\"Bad parameter value. Name: {0}, value: {1}\", parameterName, valueString), parameterName);\n }\n else\n {\n throw new ArgumentException(\"Bad value. Value: \" + valueString);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 21990178,
"author": "Vman",
"author_id": 299529,
"author_profile": "https://Stackoverflow.com/users/299529",
"pm_score": 3,
"selected": false,
"text": "<p>This answer is in response to deegee's answer which raises the performance issues of System.Enum so should not be taken as my preferred generic answer, more addressing enum validation in tight performance scenarios.</p>\n\n<p>If you have a mission critical performance issue where slow but functional code is being run in a tight loop then I personally would look at moving that code out of the loop if possible instead of solving by reducing functionality. Constraining the code to only support contiguous enums could be a nightmare to find a bug if, for example, somebody in the future decides to deprecate some enum values. Simplistically you could just call Enum.GetValues once, right at the start to avoid triggering all the reflection, etc thousands of times. That should give you an immediate performance increase. If you need more performance and you know that a lot of your enums are contiguous (but you still want to support 'gappy' enums) you could go a stage further and do something like:</p>\n\n<pre><code>public abstract class EnumValidator<TEnum> where TEnum : struct, IConvertible\n{\n protected static bool IsContiguous\n {\n get\n {\n int[] enumVals = Enum.GetValues(typeof(TEnum)).Cast<int>().ToArray();\n\n int lowest = enumVals.OrderBy(i => i).First();\n int highest = enumVals.OrderByDescending(i => i).First();\n\n return !Enumerable.Range(lowest, highest).Except(enumVals).Any();\n }\n }\n\n public static EnumValidator<TEnum> Create()\n {\n if (!typeof(TEnum).IsEnum)\n {\n throw new ArgumentException(\"Please use an enum!\");\n }\n\n return IsContiguous ? (EnumValidator<TEnum>)new ContiguousEnumValidator<TEnum>() : new JumbledEnumValidator<TEnum>();\n }\n\n public abstract bool IsValid(int value);\n}\n\npublic class JumbledEnumValidator<TEnum> : EnumValidator<TEnum> where TEnum : struct, IConvertible\n{\n private readonly int[] _values;\n\n public JumbledEnumValidator()\n {\n _values = Enum.GetValues(typeof (TEnum)).Cast<int>().ToArray();\n }\n\n public override bool IsValid(int value)\n {\n return _values.Contains(value);\n }\n}\n\npublic class ContiguousEnumValidator<TEnum> : EnumValidator<TEnum> where TEnum : struct, IConvertible\n{\n private readonly int _highest;\n private readonly int _lowest;\n\n public ContiguousEnumValidator()\n {\n List<int> enumVals = Enum.GetValues(typeof (TEnum)).Cast<int>().ToList();\n\n _lowest = enumVals.OrderBy(i => i).First();\n _highest = enumVals.OrderByDescending(i => i).First();\n }\n\n public override bool IsValid(int value)\n {\n return value >= _lowest && value <= _highest;\n }\n}\n</code></pre>\n\n<p>Where your loop becomes something like:</p>\n\n<pre><code>//Pre import-loop\nEnumValidator< MyEnum > enumValidator = EnumValidator< MyEnum >.Create();\nwhile(import) //Tight RT loop.\n{\n bool isValid = enumValidator.IsValid(theValue);\n}\n</code></pre>\n\n<p>I'm sure the EnumValidator classes could written more efficiently (it’s just a quick hack to demonstrate) but quite frankly who cares what happens outside the import loop? The only bit that needs to be super-fast is within the loop. This was the reason for taking the abstract class route, to avoid an unnecessary if-enumContiguous-then-else in the loop (the factory Create essentially does this upfront).\nYou will note a bit of hypocrisy, for brevity this code constrains functionality to int-enums. I should be making use of IConvertible rather than using int's directly but this answer is already wordy enough!</p>\n"
},
{
"answer_id": 27305198,
"author": "Doug S",
"author_id": 1145177,
"author_profile": "https://Stackoverflow.com/users/1145177",
"pm_score": 4,
"selected": false,
"text": "<p>As others have mentioned, <code>Enum.IsDefined</code> is slow, something you have to be aware of if it's in a loop.</p>\n\n<p>When doing multiple comparisons, a speedier method is to first put the values into a <code>HashSet</code>. Then simply use <code>Contains</code> to check whether the value is valid, like so:</p>\n\n<pre><code>int userInput = 4;\n// below, Enum.GetValues converts enum to array. We then convert the array to hashset.\nHashSet<int> validVals = new HashSet<int>((int[])Enum.GetValues(typeof(MyEnum)));\n// the following could be in a loop, or do multiple comparisons, etc.\nif (validVals.Contains(userInput))\n{\n // is valid\n}\n</code></pre>\n"
},
{
"answer_id": 38331283,
"author": "Juan Carlos Velez",
"author_id": 391895,
"author_profile": "https://Stackoverflow.com/users/391895",
"pm_score": 0,
"selected": false,
"text": "<p>To validate if a value is a valid value in an enumeration, you only need to call the static method <a href=\"https://msdn.microsoft.com/en-us/library/system.enum.isdefined(v=vs.110).aspx\" rel=\"nofollow\">Enum.IsDefined</a>.</p>\n\n<pre><code>int value = 99;//Your int value\nif (Enum.IsDefined(typeof(your_enum_type), value))\n{\n //Todo when value is valid\n}else{\n //Todo when value is not valid\n}\n</code></pre>\n"
},
{
"answer_id": 55028274,
"author": "Timo",
"author_id": 543814,
"author_profile": "https://Stackoverflow.com/users/543814",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Update 2022-09-27</strong></p>\n<p>As of .NET 5, a fast, <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?#system-enum-isdefined-1(-0)\" rel=\"nofollow noreferrer\">generic overload</a> is available: <code>Enum.IsDefined<TEnum>(TEnum value)</code>.</p>\n<p>The generic overload alleviates the performance issues of the non-generic one.</p>\n<p><strong>Original Answer</strong></p>\n<p>Here is a fast generic solution, using a statically-constucted <code>HashSet<T></code>.</p>\n<p>You can define this once in your toolbox, and then use it for all your enum validation.</p>\n<pre><code>public static class EnumHelpers\n{\n /// <summary>\n /// Returns whether the given enum value is a defined value for its type.\n /// Throws if the type parameter is not an enum type.\n /// </summary>\n public static bool IsDefined<T>(T enumValue)\n {\n if (typeof(T).BaseType != typeof(System.Enum)) throw new ArgumentException($"{nameof(T)} must be an enum type.");\n\n return EnumValueCache<T>.DefinedValues.Contains(enumValue);\n }\n\n /// <summary>\n /// Statically caches each defined value for each enum type for which this class is accessed.\n /// Uses the fact that static things exist separately for each distinct type parameter.\n /// </summary>\n internal static class EnumValueCache<T>\n {\n public static HashSet<T> DefinedValues { get; }\n\n static EnumValueCache()\n {\n if (typeof(T).BaseType != typeof(System.Enum)) throw new Exception($"{nameof(T)} must be an enum type.");\n\n DefinedValues = new HashSet<T>((T[])System.Enum.GetValues(typeof(T)));\n }\n }\n}\n</code></pre>\n<p>Note that this approach is easily extended to enum parsing as well, by using a dictionary with string keys (minding case-insensitivity and numeric string representations).</p>\n"
},
{
"answer_id": 56796430,
"author": "Matt Jenkins",
"author_id": 251200,
"author_profile": "https://Stackoverflow.com/users/251200",
"pm_score": 2,
"selected": false,
"text": "<p>Building upon Timo's answer, here is an even faster, safer and simpler solution, provided as an extension method.</p>\n<pre><code>public static class EnumExtensions\n{\n /// <summary>Whether the given value is defined on its enum type.</summary>\n public static bool IsDefined<T>(this T enumValue) where T : Enum\n {\n return EnumValueCache<T>.DefinedValues.Contains(enumValue);\n }\n \n private static class EnumValueCache<T> where T : Enum\n {\n public static readonly HashSet<T> DefinedValues = new HashSet<T>((T[])Enum.GetValues(typeof(T)));\n }\n}\n</code></pre>\n<p><strong>Usage:</strong></p>\n<pre><code>if (myEnumValue.IsDefined()) { ... }\n</code></pre>\n<p><strong>Update - it's even now cleaner in .NET 5:</strong></p>\n<pre><code>public static class EnumExtensions\n{\n /// <summary>Whether the given value is defined on its enum type.</summary>\n public static bool IsDefined<T>(this T enumValue) where T : struct, Enum\n {\n return EnumValueCache<T>.DefinedValues.Contains(enumValue);\n }\n\n private static class EnumValueCache<T> where T : struct, Enum\n {\n public static readonly HashSet<T> DefinedValues = new(Enum.GetValues<T>());\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59470338,
"author": "Cemal",
"author_id": 12493422,
"author_profile": "https://Stackoverflow.com/users/12493422",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the FluentValidation for your project. Here is a simple example for the \"Enum Validation\"</p>\n\n<p>Let's create a EnumValidator class with using FluentValidation;</p>\n\n<pre><code>public class EnumValidator<TEnum> : AbstractValidator<TEnum> where TEnum : struct, IConvertible, IComparable, IFormattable\n{\n public EnumValidator(string message)\n {\n RuleFor(a => a).Must(a => typeof(TEnum).IsEnum).IsInEnum().WithMessage(message);\n }\n\n}\n</code></pre>\n\n<p>Now we created the our enumvalidator class; let's create the a class to call enumvalidor class;</p>\n\n<pre><code> public class Customer \n{\n public string Name { get; set; }\n public Address address{ get; set; }\n public AddressType type {get; set;}\n}\npublic class Address \n{\n public string Line1 { get; set; }\n public string Line2 { get; set; }\n public string Town { get; set; }\n public string County { get; set; }\n public string Postcode { get; set; }\n</code></pre>\n\n<p>}</p>\n\n<pre><code>public enum AddressType\n{\n HOME,\n WORK\n}\n</code></pre>\n\n<p>Its time to call our enum validor for the address type in customer class.</p>\n\n<pre><code>public class CustomerValidator : AbstractValidator<Customer>\n{\n public CustomerValidator()\n {\n RuleFor(x => x.type).SetValidator(new EnumValidator<AddressType>(\"errormessage\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71877470,
"author": "Christopher Eberle",
"author_id": 15324778,
"author_profile": "https://Stackoverflow.com/users/15324778",
"pm_score": 1,
"selected": false,
"text": "<p>To expound on the performance scaling specifically regarding Timo/Matt Jenkins method:\nConsider the following code:</p>\n<pre><code>//System.Diagnostics - Stopwatch\n//System - ConsoleColor\n//System.Linq - Enumerable\nStopwatch myTimer = Stopwatch.StartNew();\nint myCyclesMin = 0;\nint myCyclesCount = 10000000;\nlong myExt_IsDefinedTicks;\nlong myEnum_IsDefinedTicks;\nforeach (int lCycles in Enumerable.Range(myCyclesMin, myCyclesMax))\n{\n Console.WriteLine(string.Format("Cycles: {0}", lCycles));\n\n myTimer.Restart();\n foreach (int _ in Enumerable.Range(0, lCycles)) { ConsoleColor.Green.IsDefined(); }\n myExt_IsDefinedTicks = myTimer.ElapsedTicks;\n\n myTimer.Restart();\n foreach (int _ in Enumerable.Range(0, lCycles)) { Enum.IsDefined(typeof(ConsoleColor), ConsoleColor.Green); }\n myEnum_IsDefinedTicks = myTimer.E\n\n Console.WriteLine(string.Format("object.IsDefined() Extension Elapsed: {0}", myExt_IsDefinedTicks.ToString()));\n Console.WriteLine(string.Format("Enum.IsDefined(Type, object): {0}", myEnum_IsDefinedTicks.ToString()));\n if (myExt_IsDefinedTicks == myEnum_IsDefinedTicks) { Console.WriteLine("Same"); }\n else if (myExt_IsDefinedTicks < myEnum_IsDefinedTicks) { Console.WriteLine("Extension"); }\n else if (myExt_IsDefinedTicks > myEnum_IsDefinedTicks) { Console.WriteLine("Enum"); }\n}\n</code></pre>\n<p>Output starts out like the following:</p>\n<pre><code>Cycles: 0\nobject.IsDefined() Extension Elapsed: 399\nEnum.IsDefined(Type, object): 31\nEnum\nCycles: 1\nobject.IsDefined() Extension Elapsed: 213654\nEnum.IsDefined(Type, object): 1077\nEnum\nCycles: 2\nobject.IsDefined() Extension Elapsed: 108\nEnum.IsDefined(Type, object): 112\nExtension\nCycles: 3\nobject.IsDefined() Extension Elapsed: 9\nEnum.IsDefined(Type, object): 30\nExtension\nCycles: 4\nobject.IsDefined() Extension Elapsed: 9\nEnum.IsDefined(Type, object): 35\nExtension\n</code></pre>\n<p>This seems to indicate there is a steep setup cost for the static hashset object (in my environment, approximately 15-20ms.\nReversing which method is called first doesn't change that the first call to the extension method (to set up the static hashset) is quite lengthy. <code>Enum.IsDefined(typeof(T), object)</code> is also longer than normal for the first cycle, but, interestingly, much less so.</p>\n<p>Based on this, it appears <code>Enum.IsDefined(typeof(T), object)</code> is actually faster until <code>lCycles = 50000</code> or so.</p>\n<p>I'm unsure why <code>Enum.IsDefined(typeof(T), object)</code> gets faster at both 2 and 3 lookups before it starts rising. Clearly there's some process going on internally as <code>object.IsDefined()</code> also takes markedly longer for the first 2 lookups before settling in to be bleeding fast.</p>\n<p>Another way to phrase this is that if you need to lots of lookups with any other remotely long activity (perhaps a file operation like an open) that will add a few milliseconds, the initial setup for <code>object.IsDefined()</code> will be swallowed up (especially if async) and become mostly unnoticeable. At that point, <code>Enum.IsDefined(typeof(T), object)</code> takes roughly 5x longer to execute.</p>\n<p>Basically, if you don't have literally thousands of calls to make for the same Enum, I'm not sure how hashing the contents is going to save you time over your program execution. <code>Enum.IsDefined(typeof(T), object)</code> may have conceptual performance problems, but ultimately, it's fast enough until you need it thousands of times for the same enum.</p>\n<p>As an interesting side note, implementing the ValueCache as a hybrid dictionary yields a startup time that reaches parity with <code>Enum.IsDefined(typeof(T), object)</code> within ~1500 iterations. Of course, using a HashSet passes both at ~50k.</p>\n<p>So, my advice: If your entire program is validating the same enum (validating different enums causes the same level of startup delay, once for each different enum) less than 1500 times, use <code>Enum.IsDefined(typeof(T), object)</code>. If you're between 1500 and 50k, use a HybridDictionary for your hashset, the initial cache populate is roughly 10x faster. Anything over 50k iterations, HashSet is a pretty clear winner.</p>\n<p>Also keep in mind that we are talking in Ticks. In .Net a 10,000 ticks is 1 ms.</p>\n<p>For full disclosure I also tested List as a cache, and it's about 1/3 the populate time as hashset, however, for any enum over 9 or so elements, it's way slower than any other method. If all your enums are less than 9 elements, (or smaller yet) it may be the fastest approach.</p>\n<p>The cache defined as a HybridDictionary (yes, the keys and values are the same. Yes, it's quite a bit harder to read than the simpler answers referenced above):</p>\n<pre><code>//System.Collections.Specialized - HybridDictionary\nprivate static class EnumHybridDictionaryValueCache<T> where T : Enum\n {\n static T[] enumValues = (T[])Enum.GetValues(typeof(T));\n\n static HybridDictionary PopulateDefinedValues()\n {\n HybridDictionary myDictionary = new HybridDictionary(enumValues.Length);\n foreach (T lEnumValue in enumValues)\n {\n //Has to be unique, values are actually based on the int value. Enums with multiple aliases for one value will fail without checking.\n //Check implicitly by using assignment.\n myDictionary[lEnumValue] = lEnumValue;\n }\n return myDictionary;\n }\n\n public static readonly HybridDictionary DefinedValues = PopulateDefinedValues();\n }\n\n</code></pre>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | I need to validate an integer to know if is a valid enum value.
What is the best way to do this in C#? | You got to love these folk who assume that data not only always comes from a UI, but a UI within your control!
`IsDefined` is fine for most scenarios, you could start with:
```
public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)
{
retVal = default(TEnum);
bool success = Enum.IsDefined(typeof(TEnum), enumValue);
if (success)
{
retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);
}
return success;
}
```
(Obviously just drop the ‘this’ if you don’t think it’s a suitable int extension) |
13,620 | <p>(assume php5) consider</p>
<pre><code><?php
$foo = 'some words';
//case 1
print "these are $foo";
//case 2
print "these are {$foo}";
//case 3
print 'these are ' . $foo;
?>
</code></pre>
<p>Is there much of a difference between 1 and 2?</p>
<p>If not, what about between 1/2 and 3?</p>
| [
{
"answer_id": 13665,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 7,
"selected": true,
"text": "<p>Well, as with all \"What might be faster in real life\" questions, you can't beat a real life test.</p>\n\n<pre><code>function timeFunc($function, $runs)\n{\n $times = array();\n\n for ($i = 0; $i < $runs; $i++)\n {\n $time = microtime();\n call_user_func($function);\n $times[$i] = microtime() - $time;\n }\n\n return array_sum($times) / $runs;\n}\n\nfunction Method1()\n{ \n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are $foo\";\n}\n\nfunction Method2()\n{\n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are {$foo}\";\n}\n\nfunction Method3()\n {\n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are \" . $foo;\n}\n\nprint timeFunc('Method1', 10) . \"\\n\";\nprint timeFunc('Method2', 10) . \"\\n\";\nprint timeFunc('Method3', 10) . \"\\n\";\n</code></pre>\n\n<p>Give it a few runs to page everything in, then...</p>\n\n<p>0.0035568</p>\n\n<p>0.0035388</p>\n\n<p>0.0025394</p>\n\n<p>So, as expected, the interpolation are virtually identical (noise level differences, probably due to the extra characters the interpolation engine needs to handle). Straight up concatenation is about 66% of the speed, which is no great shock. The interpolation parser will look, find nothing to do, then finish with a simple internal string concat. Even if the concat were expensive, the interpolator will still have to do it, <strong>after</strong> all the work to parse out the variable and trim/copy up the original string.</p>\n\n<p><strong>Updates By Somnath:</strong></p>\n\n<p>I added Method4() to above real time logic.</p>\n\n<pre><code>function Method4()\n {\n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = 'these are ' . $foo;\n}\n\nprint timeFunc('Method4', 10) . \"\\n\";\n\nResults were:\n\n0.0014739\n0.0015574\n0.0011955\n0.001169\n</code></pre>\n\n<p>When you are just declaring a string only and no need to parse that string too, then why to confuse PHP debugger to parse. I hope you got my point.</p>\n"
},
{
"answer_id": 13680,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 4,
"selected": false,
"text": "<p>@Adam's test used</p>\n\n<pre><code>\"these are \" . $foo\n</code></pre>\n\n<p>note that the following is even faster:</p>\n\n<pre><code>'these are ' . $foo;\n</code></pre>\n\n<p>this is due to the fact, that a double quoted \"string\" gets evaluated, where a single quoted 'string' is just taken as is...</p>\n"
},
{
"answer_id": 16128,
"author": "Jake McGraw",
"author_id": 302,
"author_profile": "https://Stackoverflow.com/users/302",
"pm_score": 4,
"selected": false,
"text": "<p>Don't get too caught up on trying to optimize string operations in PHP. Concatenation vs. interpolation is meaningless (in real world performance) if your database queries are poorly written or you aren't using any kind of caching scheme. Write your string operations in such a way that debugging your code later will be easy, the performance differences are negligible.</p>\n\n<p>@uberfuzzy Assuming this is just a question about language minutia, I suppose it's fine. I'm just trying to add to the conversation that comparing performance between single-quote, double-quote and heredoc in real world applications in meaningless when compared to the real performance sinks, such as poor database queries.</p>\n"
},
{
"answer_id": 482204,
"author": "Paolo Bergantino",
"author_id": 16417,
"author_profile": "https://Stackoverflow.com/users/16417",
"pm_score": 7,
"selected": false,
"text": "<p>The performance difference has been <a href=\"http://nikic.github.com/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html\" rel=\"noreferrer\">irrelevant</a> since at least January 2012, and likely earlier:</p>\n\n<pre><code>Single quotes: 0.061846971511841 seconds\nDouble quotes: 0.061599016189575 seconds\n</code></pre>\n\n<p>Earlier versions of PHP may have had a difference - I personally prefer single quotes to double quotes, so it was a convenient difference. The conclusion of the article makes an excellent point:</p>\n\n<blockquote>\n <p>Never trust a statistic you didn’t forge yourself.</p>\n</blockquote>\n\n<p>(Although the article quotes the phrase, the original quip was likely falsely <a href=\"http://www.statistik.baden-wuerttemberg.de/Service/Veroeff/Monatshefte/20041111.mha\" rel=\"noreferrer\">attributed</a> to Winston Churchill, invented by Joseph Goebbels' propaganda ministry to portray Churchill as a liar:</p>\n\n<blockquote>\n <p>Ich traue keiner Statistik, die ich nicht selbst gefälscht habe.</p>\n</blockquote>\n\n<p>This loosely translates to, \"I do not trust a statistic that I did not fake myself.\")</p>\n"
},
{
"answer_id": 482239,
"author": "navitronic",
"author_id": 46264,
"author_profile": "https://Stackoverflow.com/users/46264",
"pm_score": 2,
"selected": false,
"text": "<p>I seem to remember that the developer of the forum software, Vanilla replaced all the double quotes in his code with single quotes and noticed a reasonable amount of performance increase. </p>\n\n<p>I can't seem to track down a link to the discussion at the moment though.</p>\n"
},
{
"answer_id": 482291,
"author": "Mike B",
"author_id": 46675,
"author_profile": "https://Stackoverflow.com/users/46675",
"pm_score": 5,
"selected": false,
"text": "<p>Live benchmarks:</p>\n\n<p><a href=\"http://phpbench.com/\" rel=\"noreferrer\">http://phpbench.com/</a></p>\n\n<p>There is actually a subtle difference when concatenating variables with single vs double quotes. </p>\n"
},
{
"answer_id": 482318,
"author": "kimsk",
"author_id": 58905,
"author_profile": "https://Stackoverflow.com/users/58905",
"pm_score": 1,
"selected": false,
"text": "<p>Double quotes can be much slower. I read from several places that that it is better to do this</p>\n\n<pre><code>'parse me '.$i.' times'\n</code></pre>\n\n<p>than</p>\n\n<pre><code>\"parse me $i times\"\n</code></pre>\n\n<p>Although I'd say the second one gave you more readable code.</p>\n"
},
{
"answer_id": 1435564,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>there is a difference when concatenating variables... and what you are doing with the result... and if what you are doing is dumping it to output, is or isn't output buffering on.</p>\n\n<p>also, what is the memory situation of the server? typically memory management on a higher level platform is worse than that at lower platforms... </p>\n\n<pre><code>$a = 'parse' . $this; \n</code></pre>\n\n<p>is managing memory at the user code platform level...</p>\n\n<pre><code>$a = \"parse $this\";\n</code></pre>\n\n<p>is managing memory at the php system code platform level...</p>\n\n<p>so these benchmarks as related to CPU don't tell the full story. </p>\n\n<p>running the benchmark 1000 times vs running the benchmark 1000 times on a server that is attempting to run that same simulation 1000 times concurrently... you might get drastically different results depending on the scope of the application.</p>\n"
},
{
"answer_id": 6158187,
"author": "Klerk",
"author_id": 773811,
"author_profile": "https://Stackoverflow.com/users/773811",
"pm_score": 0,
"selected": false,
"text": "<p>Practically there is no difference at all! See the timings: <a href=\"http://micro-optimization.com/single-vs-double-quotes\" rel=\"nofollow\">http://micro-optimization.com/single-vs-double-quotes</a> </p>\n"
},
{
"answer_id": 11107091,
"author": "Gordon",
"author_id": 208809,
"author_profile": "https://Stackoverflow.com/users/208809",
"pm_score": 3,
"selected": false,
"text": "<p>Any differences in execution time are completely negligible.</p>\n\n<p>Please see</p>\n\n<ul>\n<li><a href=\"http://nikic.github.com/2012/01/09/Disproving-the-Single-Quotes-Performance-Myth.html\" rel=\"noreferrer\">NikiC's Blog: Disproving the Single Quotes Performance Myth</a> for a technical explanation how interpolation and concatenation works in PHP and why it is absolutely pointless to care about their speed.</li>\n</ul>\n\n<p>Don't waste time on micro-optimizations like this. Use a profiler to measure the performance of your application in a real world scenario and then optimize where it is really needed. Optimising a single sloppy DB query is likely to make a bigger performance improvement than applying micro-optimisations all over your code.</p>\n"
},
{
"answer_id": 12856650,
"author": "Rob Forrest",
"author_id": 236755,
"author_profile": "https://Stackoverflow.com/users/236755",
"pm_score": 2,
"selected": false,
"text": "<p>Just to add something else to the mix, if you are using a variable inside a double quoted string syntax:</p>\n\n<pre><code>$foo = \"hello {$bar}\";\n</code></pre>\n\n<p>is faster than</p>\n\n<pre><code>$foo = \"hello $bar\";\n</code></pre>\n\n<p>and both of these are faster than</p>\n\n<pre><code>$foo = 'hello' . $bar; \n</code></pre>\n"
},
{
"answer_id": 43625364,
"author": "ywarnier",
"author_id": 6499848,
"author_profile": "https://Stackoverflow.com/users/6499848",
"pm_score": 0,
"selected": false,
"text": "<p>It should be noted that, when using a modified version of the example by Adam Wright with 3 variables, the results are reversed and the first two functions are actually faster, consistently. This is with PHP 7.1 on CLI:</p>\n\n<pre><code>function timeFunc($function, $runs)\n{\n $times = array();\n\n for ($i = 0; $i < $runs; $i++)\n {\n $time = microtime();\n call_user_func($function);\n @$times[$i] = microtime() - $time;\n }\n\n return array_sum($times) / $runs;\n}\n\nfunction Method1()\n{ \n $foo = 'some words';\n $bar = 'other words';\n $bas = 3;\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are $foo, $bar and $bas\";\n}\n\nfunction Method2()\n{\n $foo = 'some words';\n $bar = 'other words';\n $bas = 3;\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are {$foo}, {$bar} and {$bas}\";\n}\n\nfunction Method3()\n{\n $foo = 'some words';\n $bar = 'other words';\n $bas = 3;\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are \" . $foo . \", \" . $bar . \" and \" .$bas;\n}\n\nprint timeFunc('Method1', 10) . \"\\n\";\nprint timeFunc('Method2', 10) . \"\\n\";\nprint timeFunc('Method3', 10) . \"\\n\";\n</code></pre>\n\n<p>I've also tried with '3' instead of just the integer 3, but I get the same kind of results.</p>\n\n<p>With $bas = 3:</p>\n\n<pre><code>0.0016254\n0.0015719\n0.0019806\n</code></pre>\n\n<p>With $bas = '3':</p>\n\n<pre><code>0.0016495\n0.0015608\n0.0022755\n</code></pre>\n\n<p>It should be noted that these results vary highly (I get variations of about 300%), but the averages seem relatively steady and almost (9 out of 10 cases) always show a faster execution for the 2 first methods, with Method 2 always being slightly faster than method 1.</p>\n\n<p>In conclusion: what is true for 1 single operation (be it interpolation or concatenation) is not always true for combined operations.</p>\n"
},
{
"answer_id": 62986215,
"author": "Stackoverflow",
"author_id": 7180968,
"author_profile": "https://Stackoverflow.com/users/7180968",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, originally this is about PHP5, however in few months arrive PHP8 and today the best option tested over my <strong>PHP 7.4.5</strong> is use <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc\" rel=\"nofollow noreferrer\">PHP - Nowdoc</a> (tested over WIN 10 + Apache and CentOs 7 + Apache):</p>\n<pre><code>function Method6(){\n $k1 = 'AAA';\n for($i = 0; $i < 10000; $i ++)$t = <<<'EOF'\nK1= \nEOF\n.$k1.\n<<<'EOF'\nK2=\nEOF\n.$k1;\n }\n</code></pre>\n<p>here the method #5 (using <strong>Heredoc</strong> to concatenat):</p>\n<pre><code>function Method5(){\n $k1 = 'AAA';\n for($i = 0; $i < 10000; $i ++)$t = <<<EOF\nK1= $k1\nEOF\n.<<<EOF\nK2=$k1 \nEOF;\n }\n</code></pre>\n<p>the methods 1 to 4 is in beginning of this post</p>\n<p>In all my tests the "winner" is method #6 (Newdoc), no't very easy to read, but very fast in CPU and ever using the function <code>function timeFunc($function)</code> by <strong>@Adam Wright</strong>.</p>\n"
},
{
"answer_id": 68206483,
"author": "Rinshan Kolayil",
"author_id": 11543253,
"author_profile": "https://Stackoverflow.com/users/11543253",
"pm_score": 0,
"selected": false,
"text": "<p>I have tested php 7.4 and php 5.4 with following test cases, It was little still confusing to me.</p>\n<pre><code><?php\n$start_time = microtime(true);\n$result = "";\nfor ($i = 0; $i < 700000; $i++) {\n $result .= "THE STRING APPENDED IS " . $i;\n // AND $result .= 'THE STRING APPENDED IS ' . $i;\n // AND $result .= "THE STRING APPENDED IS $i";\n}\necho $result;\n$end_time = microtime(true);\necho "<br><br>";\necho ($end_time - $start_time) . " Seconds";\n</code></pre>\n<p>PHP 7.4 Outputs</p>\n<pre><code> 1. "THE STRING APPENDED IS " . $i = 0.16744208335876\n 2. 'THE STRING APPENDED IS ' . $i = 0.16724419593811\n 3. "THE STRING APPENDED IS $i" = 0.16815495491028\n</code></pre>\n<p>PHP 5.3 Outputs</p>\n<pre><code> 1. "THE STRING APPENDED IS " . $i = 0.27664494514465\n 2. 'THE STRING APPENDED IS ' . $i = 0.27818703651428\n 3. "THE STRING APPENDED IS $i" = 0.28839707374573\n</code></pre>\n<p>I have tested so many times, In php 7.4 it seems to be all 3 test cases got same result many times but still concatenation have little bittle advantage in performance.</p>\n"
},
{
"answer_id": 68391660,
"author": "Meloman",
"author_id": 2282880,
"author_profile": "https://Stackoverflow.com/users/2282880",
"pm_score": 0,
"selected": false,
"text": "<p>Based on @adam-wright answer, I wanted to know if speed difference happens without no concataining / no vars in a string.</p>\n<p><strong>== My questions...</strong></p>\n<ul>\n<li>is <code>$array['key']</code> call or set faster than <code>$array["key"]</code> !?</li>\n<li>is <code>$var = "some text";</code> slower than <code>$var = 'some text';</code> ?</li>\n</ul>\n<p><strong>== My tests</strong> with new vars every time to avoid use same memory address :</p>\n<pre><code>function getArrDblQuote() { \n $start1 = microtime(true);\n $array1 = array("key" => "value");\n for ($i = 0; $i < 10000000; $i++)\n $t1 = $array1["key"];\n echo microtime(true) - $start1;\n}\nfunction getArrSplQuote() {\n $start2 = microtime(true);\n $array2 = array('key' => 'value');\n for ($j = 0; $j < 10000000; $j++)\n $t2 = $array2['key'];\n echo microtime(true) - $start2;\n}\n\nfunction setArrDblQuote() { \n $start3 = microtime(true);\n for ($k = 0; $k < 10000000; $k++)\n $array3 = array("key" => "value");\n echo microtime(true) - $start3;\n}\nfunction setArrSplQuote() {\n $start4 = microtime(true);\n for ($l = 0; $l < 10000000; $l++)\n $array4 = array('key' => 'value');\n echo microtime(true) - $start4;\n}\n\nfunction setStrDblQuote() { \n $start5 = microtime(true);\n for ($m = 0; $m < 10000000; $m++)\n $var1 = "value";\n echo microtime(true) - $start5;\n}\nfunction setStrSplQuote() {\n $start6 = microtime(true);\n for ($n = 0; $n < 10000000; $n++)\n $var2 = 'value';\n echo microtime(true) - $start6;\n}\n\nprint getArrDblQuote() . "\\n<br>";\nprint getArrSplQuote() . "\\n<br>";\nprint setArrDblQuote() . "\\n<br>";\nprint setArrSplQuote() . "\\n<br>";\nprint setStrDblQuote() . "\\n<br>";\nprint setStrSplQuote() . "\\n<br>";\n</code></pre>\n<p><strong>== My Results :</strong></p>\n<p>array get <strong>double</strong> quote <strong>2.1978828907013</strong></p>\n<p>array get <strong>single</strong> quote <strong>2.0163490772247</strong></p>\n<p>array set <strong>double</strong> quote <strong>1.9173440933228</strong></p>\n<p>array get <strong>single</strong> quote <strong>1.4982950687408</strong></p>\n<p>var set <strong>double</strong> quote <strong>1.485809803009</strong></p>\n<p>var set <strong>single</strong> quote <strong>1.3026781082153</strong></p>\n<p><strong>== My conclusion !</strong></p>\n<p>So, result is that difference is not very significant. However, on a big project, I think it can make the difference !</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/314/"
] | (assume php5) consider
```
<?php
$foo = 'some words';
//case 1
print "these are $foo";
//case 2
print "these are {$foo}";
//case 3
print 'these are ' . $foo;
?>
```
Is there much of a difference between 1 and 2?
If not, what about between 1/2 and 3? | Well, as with all "What might be faster in real life" questions, you can't beat a real life test.
```
function timeFunc($function, $runs)
{
$times = array();
for ($i = 0; $i < $runs; $i++)
{
$time = microtime();
call_user_func($function);
$times[$i] = microtime() - $time;
}
return array_sum($times) / $runs;
}
function Method1()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are $foo";
}
function Method2()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are {$foo}";
}
function Method3()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = "these are " . $foo;
}
print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";
```
Give it a few runs to page everything in, then...
0.0035568
0.0035388
0.0025394
So, as expected, the interpolation are virtually identical (noise level differences, probably due to the extra characters the interpolation engine needs to handle). Straight up concatenation is about 66% of the speed, which is no great shock. The interpolation parser will look, find nothing to do, then finish with a simple internal string concat. Even if the concat were expensive, the interpolator will still have to do it, **after** all the work to parse out the variable and trim/copy up the original string.
**Updates By Somnath:**
I added Method4() to above real time logic.
```
function Method4()
{
$foo = 'some words';
for ($i = 0; $i < 10000; $i++)
$t = 'these are ' . $foo;
}
print timeFunc('Method4', 10) . "\n";
Results were:
0.0014739
0.0015574
0.0011955
0.001169
```
When you are just declaring a string only and no need to parse that string too, then why to confuse PHP debugger to parse. I hope you got my point. |
13,753 | <p>I'm missing something here:</p>
<pre><code>$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher.Filter = ("(objectclass=computer)")
$computers = $objSearcher.findall()
</code></pre>
<p>So the question is why do the two following outputs differ?</p>
<pre><code>$computers | %{
"Server name in quotes $_.properties.name"
"Server name not in quotes " + $_.properties.name
}
PS> $computers[0] | %{"$_.properties.name"; $_.properties.name}
System.DirectoryServices.SearchResult.properties.name
GORILLA
</code></pre>
| [
{
"answer_id": 13760,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>I believe it has to do with the way that PS interpolates information in the \"\". Try this:</p>\n\n<p>\"Server name in quotes $($_.properties).name\" </p>\n\n<p>Or you may even need one more set of $(). I'm not somewhere that I can test it at right now.</p>\n"
},
{
"answer_id": 13878,
"author": "slipsec",
"author_id": 1635,
"author_profile": "https://Stackoverflow.com/users/1635",
"pm_score": 0,
"selected": false,
"text": "<p>Close-- The below works correctly, but I'd be interested if anyone has a deeper explanation.</p>\n\n<pre><code>PS C:\\> $computers[0] | %{ \"$_.properties.name\"; \"$($_.properties.name)\" }\nSystem.DirectoryServices.SearchResult.properties.name\nGORILLA\n</code></pre>\n\n<p>So it would seem that $_.properties.name doesn't deference like I expected it to. If I'm visualizing properly, the fact that the name property is multivalued causes it to return an array. Which (I think) would explain why the following works:</p>\n\n<pre><code>$computers[0] | %{ $_.properties.name[0]}\n</code></pre>\n\n<p>If \"name\" were a string this should return the first character, but because it's an array it returns the first string. </p>\n"
},
{
"answer_id": 13972,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": true,
"text": "<p>When you included $_.properties.name in the string, it was returning the type name of the property. When a variable is included in a string and the string is evaluated, it calls the ToString method on that object referenced by the variable (not including the members specified after). </p>\n\n<p>In this case, the ToString method is returning the <strong>type name</strong>. You can force the evaluation of the variable and members similar to what EBGreen suggested, but by using </p>\n\n<pre><code>\"Server name in quotes $($_.properties.name)\" \n</code></pre>\n\n<p>In the other scenario <strong>PowerShell</strong> is evaluating the variable and members specified first and then adding it to the previous string.</p>\n\n<p>You are right that you are getting back a collection of properties. If you pipe <strong>$computer[0].properties</strong> to get-member, you can explore the object model right from the command line. </p>\n\n<p>The important part is below.</p>\n\n<blockquote>\n <p>TypeName: System.DirectoryServices.ResultPropertyCollection</p>\n \n <p>Name MemberType Definition</p>\n \n <hr>\n \n <p>Values Property System.Collections.ICollection Values {get;}</p>\n</blockquote>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1635/"
] | I'm missing something here:
```
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher.Filter = ("(objectclass=computer)")
$computers = $objSearcher.findall()
```
So the question is why do the two following outputs differ?
```
$computers | %{
"Server name in quotes $_.properties.name"
"Server name not in quotes " + $_.properties.name
}
PS> $computers[0] | %{"$_.properties.name"; $_.properties.name}
System.DirectoryServices.SearchResult.properties.name
GORILLA
``` | When you included $\_.properties.name in the string, it was returning the type name of the property. When a variable is included in a string and the string is evaluated, it calls the ToString method on that object referenced by the variable (not including the members specified after).
In this case, the ToString method is returning the **type name**. You can force the evaluation of the variable and members similar to what EBGreen suggested, but by using
```
"Server name in quotes $($_.properties.name)"
```
In the other scenario **PowerShell** is evaluating the variable and members specified first and then adding it to the previous string.
You are right that you are getting back a collection of properties. If you pipe **$computer[0].properties** to get-member, you can explore the object model right from the command line.
The important part is below.
>
> TypeName: System.DirectoryServices.ResultPropertyCollection
>
>
> Name MemberType Definition
>
>
>
>
> ---
>
>
> Values Property System.Collections.ICollection Values {get;}
>
>
> |
13,763 | <p>Is there a function like <code>document.getElementById("FirstDiv").clear()</code>?</p>
| [
{
"answer_id": 13766,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to use the .RemoveNode method of the node or the .RemoveChild method of the parent node.</p>\n"
},
{
"answer_id": 13769,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 6,
"selected": false,
"text": "<p>If you want to clear the div and remove all child nodes, you could put:</p>\n\n<pre><code>var mydiv = document.getElementById('FirstDiv');\nwhile(mydiv.firstChild) {\n mydiv.removeChild(mydiv.firstChild);\n}\n</code></pre>\n"
},
{
"answer_id": 13773,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>You should probably use a JavaScript library to do things like this.</p>\n\n<p>For example, MochiKit has a function <a href=\"http://mochikit.com/doc/html/MochiKit/DOM.html#fn-removeelement\" rel=\"nofollow noreferrer\">removeElement</a>, and jQuery has <a href=\"http://docs.jquery.com/Manipulation/remove#expr\" rel=\"nofollow noreferrer\">remove</a>.</p>\n"
},
{
"answer_id": 13779,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 2,
"selected": false,
"text": "<p>You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE</p>\n"
},
{
"answer_id": 14782,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 8,
"selected": true,
"text": "<p>To answer the original question - there are various ways to do this, but the following would be the simplest.</p>\n\n<p>If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:</p>\n\n<pre><code>myChildNode.parentNode.removeChild(myChildNode);\n</code></pre>\n\n<p>Obviously, if you are not using one of the numerous libraries that already do this, you would want to create a function to abstract this out:</p>\n\n<pre><code>function removeElement(node) {\n node.parentNode.removeChild(node);\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: As has been mentioned by others: if you have any event handlers wired up to the node you are removing, you will want to make sure you disconnect those before the last reference to the node being removed goes out of scope, lest poor implementations of the JavaScript interpreter leak memory.</p>\n"
},
{
"answer_id": 3388480,
"author": "Chris Jacob",
"author_id": 114140,
"author_profile": "https://Stackoverflow.com/users/114140",
"pm_score": 2,
"selected": false,
"text": "<p>A jQuery solution</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><select id=\"foo\">\n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n</select>\n</code></pre>\n\n<p><strong>Javascript</strong></p>\n\n<pre><code>// remove child \"option\" element with a \"value\" attribute equal to \"2\"\n$(\"#foo > option[value='2']\").remove();\n\n// remove all child \"option\" elements\n$(\"#foo > option\").remove();\n</code></pre>\n\n<p>References:</p>\n\n<p><a href=\"http://api.jquery.com/attribute-equals-selector/\" rel=\"nofollow noreferrer\" title=\"Attribute Equals Selector [name=value]\">Attribute Equals Selector [name=value]</a></p>\n\n<blockquote>\n <p>Selects elements that have the\n specified attribute with a value\n exactly equal to a certain value.</p>\n</blockquote>\n\n<p><a href=\"http://api.jquery.com/child-selector/\" rel=\"nofollow noreferrer\">Child Selector (“parent > child”)</a></p>\n\n<blockquote>\n <p>Selects all direct child elements\n specified by \"child\" of elements\n specified by \"parent\"</p>\n</blockquote>\n\n<p><a href=\"http://api.jquery.com/remove/\" rel=\"nofollow noreferrer\">.remove()</a></p>\n\n<blockquote>\n <p>Similar to .empty(), the .remove()\n method takes elements out of the DOM.\n We use .remove() when we want to\n remove the element itself, as well as\n everything inside it. In addition to\n the elements themselves, all bound\n events and jQuery data associated with\n the elements are removed.</p>\n</blockquote>\n"
},
{
"answer_id": 7750327,
"author": "eagle",
"author_id": 961780,
"author_profile": "https://Stackoverflow.com/users/961780",
"pm_score": 2,
"selected": false,
"text": "<p>Use the following code:</p>\n\n<pre><code>//for Internet Explorer\ndocument.getElementById(\"FirstDiv\").removeNode(true);\n\n//for other browsers\nvar fDiv = document.getElementById(\"FirstDiv\");\nfDiv.removeChild(fDiv.childNodes[0]); //first check on which node your required node exists, if it is on [0] use this, otherwise use where it exists.\n</code></pre>\n"
},
{
"answer_id": 40543830,
"author": "Gibolt",
"author_id": 974045,
"author_profile": "https://Stackoverflow.com/users/974045",
"pm_score": 4,
"selected": false,
"text": "<h1>Modern Solution - <code>child.remove()</code></h1>\n<p>For your use case:</p>\n<pre><code>document.getElementById("FirstDiv").remove()\n</code></pre>\n<p>This is recommended by W3C since late 2015, and is <strong>vanilla JS</strong>. All major browsers support it.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove\" rel=\"noreferrer\">Mozilla Docs</a></p>\n<p><a href=\"https://caniuse.com/#feat=childnode-remove\" rel=\"noreferrer\">Supported Browsers</a> - 96% May 2020</p>\n"
},
{
"answer_id": 44698638,
"author": "Vivek Tiwari",
"author_id": 7921020,
"author_profile": "https://Stackoverflow.com/users/7921020",
"pm_score": 1,
"selected": false,
"text": "<pre><code> var p=document.getElementById('childId').parentNode;\n var c=document.getElementById('childId');\n p.removeChild(c);\n alert('Deleted');\n</code></pre>\n\n<p>p is parent node and c is child node<br>\nparentNode is a JavaScript variable which contains parent reference<br>\n<br>\nEasy to understand</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] | Is there a function like `document.getElementById("FirstDiv").clear()`? | To answer the original question - there are various ways to do this, but the following would be the simplest.
If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:
```
myChildNode.parentNode.removeChild(myChildNode);
```
Obviously, if you are not using one of the numerous libraries that already do this, you would want to create a function to abstract this out:
```
function removeElement(node) {
node.parentNode.removeChild(node);
}
```
---
EDIT: As has been mentioned by others: if you have any event handlers wired up to the node you are removing, you will want to make sure you disconnect those before the last reference to the node being removed goes out of scope, lest poor implementations of the JavaScript interpreter leak memory. |
13,775 | <p>I have a .net web application that has a Flex application embedded within a page. This flex application calls a .net webservice. I can trace the execution proccess through the debugger and all looks great until I get the response:</p>
<pre><code>
soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was unable to process request
. ---> System.Xml.XmlException: Root element is missing.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest
request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---
</code>
</pre>
<p>The call from flex looks good, the execution through the webservice is good, but this is the response I capture via wireshark, what is going on here?</p>
<p>I have tried several web methods, from "Hello World" to paramatized methods...all comeback with the same response...</p>
<p>I thought it may have something to do with encoding with the "---&gt", but I'm unsure how to control what .net renders as the response.</p>
| [
{
"answer_id": 15292,
"author": "James Avery",
"author_id": 537,
"author_profile": "https://Stackoverflow.com/users/537",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like you might be sending a poorly formed XML document to the service. Can you use Fiddler or something like that to get a copy of the actual call that is going to the web service? That would be a huge help in figured out what the issue is.</p>\n"
},
{
"answer_id": 78733,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using Flex 3? If so, you can set a breakpoint when the webservice is executed and actually step through the Flex framework as it encodes your request. Look in mx.rpc.soap.SoapEncoder and you'll be able to see exactly what is going to be sent over the wire. </p>\n"
},
{
"answer_id": 145239,
"author": "Brandon",
"author_id": 23133,
"author_profile": "https://Stackoverflow.com/users/23133",
"pm_score": 1,
"selected": false,
"text": "<p>I recently used a .NET REST interface which I consumed using a Flex app. I got some strange exceptions as well and my issue was that I forgot to include in xmlns (the namespace) in the root element when sending requests. This is a wild guess but I hope it helps.</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] | I have a .net web application that has a Flex application embedded within a page. This flex application calls a .net webservice. I can trace the execution proccess through the debugger and all looks great until I get the response:
```
soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was unable to process request
. ---> System.Xml.XmlException: Root element is missing.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ThrowWithoutLineInfo(String res)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlTextReader.Read()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage message)
at System.Web.Services.Protocols.SoapServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest
request, HttpResponse response, Boolean& abortProcessing)
--- End of inner exception stack trace ---
```
The call from flex looks good, the execution through the webservice is good, but this is the response I capture via wireshark, what is going on here?
I have tried several web methods, from "Hello World" to paramatized methods...all comeback with the same response...
I thought it may have something to do with encoding with the "--->", but I'm unsure how to control what .net renders as the response. | It looks like you might be sending a poorly formed XML document to the service. Can you use Fiddler or something like that to get a copy of the actual call that is going to the web service? That would be a huge help in figured out what the issue is. |
13,791 | <p>I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p>
<pre><code>>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This is n a test r'
>>> p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
>>> p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'
</code></pre>
<p>I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light?</p>
| [
{
"answer_id": 13844,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I think you might have missed the r or miscounted the backslashes...</p>\n\n<pre><code>\"\\\\n\" == r\"\\n\"\n\n>>> import re\n>>> mystring = r\"This is \\\\n a test \\\\r\"\n>>> p = re.compile( r\"[\\\\][\\\\](.)\" )\n>>> print p.sub( r\"\\\\\\1\", mystring )\nThis is \\n a test \\r\n>>>\n</code></pre>\n\n<p>Which, if I understood is what was requested.</p>\n\n<p>I suspect the more common request is this:</p>\n\n<pre><code>>>> d = {'n':'\\n', 'r':'\\r', 'f':'\\f'}\n>>> p = re.compile(r\"[\\\\]([nrfv])\")\n>>> print p.sub(lambda mo: d[mo.group(1)], mystring)\nThis is \\\n a test \\\n>>>\n</code></pre>\n\n<p>The interested student should also read Ken Thompson's <a href=\"http://cm.bell-labs.com/who/ken/trust.html\" rel=\"nofollow noreferrer\">Reflections on Trusting Trust\"</a>, wherein our hero uses a similar example to explain the perils of trusting compilers you haven't bootstrapped from machine code yourself.</p>\n"
},
{
"answer_id": 13869,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>You are being tricked by Python's representation of the result string. The Python expression:</p>\n\n<pre><code>'This is \\\\n a test \\\\r'\n</code></pre>\n\n<p>represents the string</p>\n\n<pre><code>This is \\n a test \\r\n</code></pre>\n\n<p>which is I think what you wanted. Try adding 'print' in front of each of your p.sub() calls to print the actual string returned instead of a Python representation of the string.</p>\n\n<pre><code>>>> mystring = r\"This is \\n a test \\r\"\n>>> mystring\n'This is \\\\n a test \\\\r'\n>>> print mystring\nThis is \\n a test \\r\n</code></pre>\n"
},
{
"answer_id": 13882,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 1,
"selected": false,
"text": "<p>The idea is that I'll read in an escaped string, and unescape it (a feature notably lacking from Python, which you shouldn't need to resort to regular expressions for in the first place). Unfortunately I'm not being tricked by the backslashes...</p>\n\n<p>Another illustrative example:</p>\n\n<pre><code>>>> mystring = r\"This is \\n ridiculous\"\n>>> print mystring\nThis is \\n ridiculous\n>>> p = re.compile( r\"\\\\(\\S)\" )\n>>> print p.sub( 'bloody', mystring )\nThis is bloody ridiculous\n>>> print p.sub( r'\\1', mystring )\nThis is n ridiculous\n>>> print p.sub( r'\\\\1', mystring )\nThis is \\1 ridiculous\n>>> print p.sub( r'\\\\\\1', mystring )\nThis is \\n ridiculous\n</code></pre>\n\n<p>What I'd like it to print is</p>\n\n<pre><code>This is \nridiculous\n</code></pre>\n"
},
{
"answer_id": 13943,
"author": "markpasc",
"author_id": 1472,
"author_profile": "https://Stackoverflow.com/users/1472",
"pm_score": 4,
"selected": true,
"text": "<p>Isn't that what Anders' second example does?</p>\n\n<p>In 2.5 there's also a <code>string-escape</code> encoding you can apply:</p>\n\n<pre><code>>>> mystring = r\"This is \\n a test \\r\"\n>>> mystring.decode('string-escape')\n'This is \\n a test \\r'\n>>> print mystring.decode('string-escape')\nThis is \n a test \n>>> \n</code></pre>\n"
},
{
"answer_id": 13958,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 0,
"selected": false,
"text": "<p>Mark; his second example requires every escaped character thrown into an array initially, which generates a KeyError if the escape sequence happens not to be in the array. It will die on anything but the three characters provided (give \\v a try), and enumerating every possible escape sequence every time you want to unescape a string (or keeping a global array) is a really bad solution. Analogous to PHP, that's using <code>preg_replace_callback()</code> with a lambda instead of <code>preg_replace()</code>, which is utterly unnecessary in this situation.</p>\n\n<p>I'm sorry if I'm coming off as a dick about it, I'm just utterly frustrated with Python. This is supported by every other regular expression engine I've ever used, and I can't understand why this wouldn't work.</p>\n\n<p>Thank you for responding; the <code>string.decode('string-escape')</code> function is precisely what i was looking for initially. If someone has a general solution to the regex backreference problem, feel free to post it and I'll accept that as an answer as well.</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1370/"
] | I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...
```
>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This is n a test r'
>>> p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
>>> p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'
```
I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light? | Isn't that what Anders' second example does?
In 2.5 there's also a `string-escape` encoding you can apply:
```
>>> mystring = r"This is \n a test \r"
>>> mystring.decode('string-escape')
'This is \n a test \r'
>>> print mystring.decode('string-escape')
This is
a test
>>>
``` |
13,851 | <p>I am having trouble with IE7. I have a header, which is an IMG. Under it I have a div that represents a menu, they have to be attached to each other without space in between. Both are 1000px width. In Opera and FireFox the header and the menu are neatly attached to each other. However, in IE7, there is a small space between the menu DIV and the IMG. I have tried explicitly defining padding and margin on the IMG, however it does not work. I have had this problem before, so it seems to be a IE7 quirk.</p>
<p>My HTML Code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="middle">
<img id="ctl00_headerHolder_headerImage" src="pictures/headers/header_home.jpg" style="border-width:0px;" />
<div id="ctl00_menuPanel" class="menu">
<a id="ctl00_home" href="Default.aspx" style="color:#FFCC33;">Home</a> |
<a id="ctl00_leden" href="Leden.aspx">Leden</a> |
<a id="ctl00_agenda" href="Agenda.aspx">Agenda</a> |
<a id="ctl00_fotos" href="Fotos.aspx">Foto's</a> |
<a id="ctl00_geschiedenis" href="Geschiedenis.aspx">Geschiedenis</a> |
<a id="ctl00_gastenboek" href="Gastenboek.aspx">Gastenboek</a>
</div>
</div></code></pre>
</div>
</div>
</p>
| [
{
"answer_id": 13854,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 3,
"selected": true,
"text": "<p>Try the IE Developer Toolbar, which will let you inspect what is going on with the elements and give you outlines of the areas covered. It might give you a better understanding of the problem.</p>\n"
},
{
"answer_id": 13855,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The solution: </p>\n\n<pre><code>img {\npadding: 0px;\nmargin: 0px;\ndisplay: block;\n}\n</code></pre>\n\n<p>display: block</p>\n"
},
{
"answer_id": 13860,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I run into this a lot. Rather than hunting down the specific behavior, try sanity checking by explicity setting padding and margin properties for img/div/etc selectors to 0, set border-style: none border-width: 0px border=\"0\" etc.</p>\n\n<p>IE Dev Toolbar is a must-have but whether it helps you with figuring out single-pixel issues is unlikely.</p>\n"
},
{
"answer_id": 13866,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of resorting to display block, note that IE7 does some seriously odd things with whitespace; try removing the whitespace between the image and the div, and see what happens.</p>\n"
},
{
"answer_id": 13868,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 0,
"selected": false,
"text": "<p>CSS Resets (like the <a href=\"http://developer.yahoo.com/yui/reset/\" rel=\"nofollow noreferrer\">YUI Reset CSS</a>) are great for this kind of thing. They reset paddings, margins, and other display properties on a lot of HTML elements to minimize the display differences.</p>\n"
},
{
"answer_id": 13903,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <blockquote>\n <p>The solution...display: block</p>\n </blockquote>\n</blockquote>\n\n<p>That question couldn't be answered properly without knowing the rendering mode that the browser was in; you need to tell people what doctype you have if you have CSS rendering issues. The image behaviour you refer to is different in quirks mode as opposed to standards mode. A minimal test case must include a full HTML document and the CSS to reproduce the problem. Please don't ask people for help without giving them the information they need to answer easily without wasting their time...</p>\n"
},
{
"answer_id": 14183,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 0,
"selected": false,
"text": "<p>The real solution:</p>\n\n<pre><code>#middle { font-size: 0; line-height: 0; }\n</code></pre>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I am having trouble with IE7. I have a header, which is an IMG. Under it I have a div that represents a menu, they have to be attached to each other without space in between. Both are 1000px width. In Opera and FireFox the header and the menu are neatly attached to each other. However, in IE7, there is a small space between the menu DIV and the IMG. I have tried explicitly defining padding and margin on the IMG, however it does not work. I have had this problem before, so it seems to be a IE7 quirk.
My HTML Code:
```html
<div id="middle">
<img id="ctl00_headerHolder_headerImage" src="pictures/headers/header_home.jpg" style="border-width:0px;" />
<div id="ctl00_menuPanel" class="menu">
<a id="ctl00_home" href="Default.aspx" style="color:#FFCC33;">Home</a> |
<a id="ctl00_leden" href="Leden.aspx">Leden</a> |
<a id="ctl00_agenda" href="Agenda.aspx">Agenda</a> |
<a id="ctl00_fotos" href="Fotos.aspx">Foto's</a> |
<a id="ctl00_geschiedenis" href="Geschiedenis.aspx">Geschiedenis</a> |
<a id="ctl00_gastenboek" href="Gastenboek.aspx">Gastenboek</a>
</div>
</div>
``` | Try the IE Developer Toolbar, which will let you inspect what is going on with the elements and give you outlines of the areas covered. It might give you a better understanding of the problem. |
13,857 | <p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>
| [
{
"answer_id": 13875,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 6,
"selected": false,
"text": "<p>It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:</p>\n\n<pre><code>>>> def makeConstantAdder(x):\n... constant = x\n... def adder(y):\n... return y + constant\n... return adder\n... \n>>> f = makeConstantAdder(12)\n>>> f(3)\n15\n>>> g = makeConstantAdder(4)\n>>> g(3)\n7\n</code></pre>\n\n<p>Note that 12 and 4 have \"disappeared\" inside f and g, respectively, this feature is what make f and g proper closures.</p>\n"
},
{
"answer_id": 13902,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p>I've never heard of transactions being used in the same context as explaining what a closure is and there really aren't any transaction semantics here.</p>\n\n<p>It's called a closure because it \"closes over\" the outside variable (constant)--i.e., it's not just a function but an enclosure of the environment where the function was created. </p>\n\n<p>In the following example, calling the closure g after changing x will also change the value of x within g, since g closes over x:</p>\n\n<pre><code>x = 0\n\ndef f():\n def g(): \n return x * 2\n return g\n\n\nclosure = f()\nprint(closure()) # 0\nx = 2\nprint(closure()) # 4\n</code></pre>\n"
},
{
"answer_id": 13906,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 4,
"selected": false,
"text": "<p>I like <a href=\"http://effbot.org/zone/closure.htm\" rel=\"noreferrer\">this rough, succinct definition</a>:</p>\n\n<blockquote>\n <p>A function that can refer to environments that are no longer active.</p>\n</blockquote>\n\n<p>I'd add</p>\n\n<blockquote>\n <p>A closure allows you to bind variables into a function <em>without passing them as parameters</em>.</p>\n</blockquote>\n\n<p>Decorators which accept parameters are a common use for closures. Closures are a common implementation mechanism for that sort of \"function factory\". I frequently choose to use closures in the <a href=\"http://c2.com/cgi/wiki?StrategyPattern\" rel=\"noreferrer\">Strategy Pattern</a> when the strategy is modified by data at run-time.</p>\n\n<p>In a language that allows anonymous block definition -- e.g., Ruby, C# -- closures can be used to implement (what amount to) novel new control structures. The lack of anonymous blocks is among <a href=\"http://ivan.truemesh.com/archives/000411.html\" rel=\"noreferrer\">the limitations of closures in Python</a>.</p>\n"
},
{
"answer_id": 24061,
"author": "Jegschemesch",
"author_id": 1586,
"author_profile": "https://Stackoverflow.com/users/1586",
"pm_score": 4,
"selected": false,
"text": "<p>To be honest, I understand closures perfectly well except I've never been clear about what exactly is the thing which is the \"closure\" and what's so \"closure\" about it. I recommend you give up looking for any logic behind the choice of term.</p>\n\n<p>Anyway, here's my explanation:</p>\n\n<pre><code>def foo():\n x = 3\n def bar():\n print x\n x = 5\n return bar\n\nbar = foo()\nbar() # print 5\n</code></pre>\n\n<p>A key idea here is that the function object returned from foo retains a hook to the local var 'x' even though 'x' has gone out of scope and should be defunct. This hook is to the var itself, not just the value that var had at the time, so when bar is called, it prints 5, not 3.</p>\n\n<p>Also be clear that Python 2.x has limited closure: there's no way I can modify 'x' inside 'bar' because writing 'x = bla' would declare a local 'x' in bar, not assign to 'x' of foo. This is a side-effect of Python's assignment=declaration. To get around this, Python 3.0 introduces the nonlocal keyword:</p>\n\n<pre><code>def foo():\n x = 3\n def bar():\n print x\n def ack():\n nonlocal x\n x = 7\n x = 5\n return (bar, ack)\n\nbar, ack = foo()\nack() # modify x of the call to foo\nbar() # print 7\n</code></pre>\n"
},
{
"answer_id": 94543,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": -1,
"selected": false,
"text": "<p>The best explanation I ever saw of a closure was to explain the mechanism. It went something like this:</p>\n\n<p>Imagine your program stack as a degenerate tree where each node has only one child and the single leaf node is the context of your currently executing procedure.</p>\n\n<p>Now relax the constraint that each node can have only one child.</p>\n\n<p>If you do this, you can have a construct ('yield') that can return from a procedure without discarding the local context (i.e. it doesn't pop it off the stack when you return). The next time the procedure is invoked, the invocation picks up the old stack (tree) frame and continues executing where it left off.</p>\n"
},
{
"answer_id": 141426,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 8,
"selected": true,
"text": "<p><a href=\"http://mrevelle.blogspot.com/2006/10/closure-on-closures.html\" rel=\"noreferrer\">Closure on closures</a></p>\n\n<blockquote>\n <p>Objects are data with methods\n attached, closures are functions with\n data attached.</p>\n</blockquote>\n\n<pre><code>def make_counter():\n i = 0\n def counter(): # counter() is a closure\n nonlocal i\n i += 1\n return i\n return counter\n\nc1 = make_counter()\nc2 = make_counter()\n\nprint (c1(), c1(), c2(), c2())\n# -> 1 2 1 2\n</code></pre>\n"
},
{
"answer_id": 473491,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a typical use case for closures - callbacks for GUI elements (this would be an alternative to subclassing the button class). For example, you can construct a function that will be called in response to a button press, and \"close\" over the relevant variables in the parent scope that are necessary for processing the click. This way you can wire up pretty complicated interfaces from the same initialization function, building all the dependencies into the closure.</p>\n"
},
{
"answer_id": 18918261,
"author": "Ricardo Avila",
"author_id": 2799405,
"author_profile": "https://Stackoverflow.com/users/2799405",
"pm_score": 0,
"selected": false,
"text": "<p>For me, \"closures\" are functions which are capable to remember the environment they were created. This functionality, allows you to use variables or methods within the closure wich, in other way,you wouldn't be able to use either because they don't exist anymore or they are out of reach due to scope. Let's look at this code in ruby:</p>\n\n<pre><code>def makefunction (x)\n def multiply (a,b)\n puts a*b\n end\n return lambda {|n| multiply(n,x)} # => returning a closure\nend\n\nfunc = makefunction(2) # => we capture the closure\nfunc.call(6) # => Result equal \"12\" \n</code></pre>\n\n<p>it works even when both, \"multiply\" method and \"x\" variable,not longer exist. All because the closure capability to remember.</p>\n"
},
{
"answer_id": 24816814,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 2,
"selected": false,
"text": "<p>In Python, a closure is an instance of a function that has variables bound to it immutably.</p>\n\n<p>In fact, the <a href=\"https://docs.python.org/3.3/reference/datamodel.html#the-standard-type-hierarchy\" rel=\"nofollow\">data model explains this</a> in its description of functions' <code>__closure__</code> attribute: </p>\n\n<blockquote>\n <p>None or a <strong>tuple of cells</strong> that contain bindings for the function’s free variables. Read-only</p>\n</blockquote>\n\n<p>To demonstrate this:</p>\n\n<pre><code>def enclosure(foo):\n def closure(bar):\n print(foo, bar)\n return closure\n\nclosure_instance = enclosure('foo')\n</code></pre>\n\n<p>Clearly, we know that we now have a function pointed at from the variable name <code>closure_instance</code>. Ostensibly, if we call it with an object, <code>bar</code>, it should print the string, <code>'foo'</code> and whatever the string representation of <code>bar</code> is.</p>\n\n<p>In fact, the string 'foo' <em>is</em> bound to the instance of the function, and we can directly read it here, by accessing the <code>cell_contents</code> attribute of the first (and only) cell in the tuple of the <code>__closure__</code> attribute:</p>\n\n<pre><code>>>> closure_instance.__closure__[0].cell_contents\n'foo'\n</code></pre>\n\n<p>As an aside, cell objects are described in the C API documentation:</p>\n\n<blockquote>\n <p><a href=\"https://docs.python.org/2/c-api/cell.html\" rel=\"nofollow\">\"Cell\" objects are used to implement variables referenced by multiple\n scopes</a></p>\n</blockquote>\n\n<p>And we can demonstrate our closure's usage, noting that <code>'foo'</code> is stuck in the function and doesn't change:</p>\n\n<pre><code>>>> closure_instance('bar')\nfoo bar\n>>> closure_instance('baz')\nfoo baz\n>>> closure_instance('quux')\nfoo quux\n</code></pre>\n\n<p>And nothing can change it:</p>\n\n<pre><code>>>> closure_instance.__closure__ = None\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: readonly attribute\n</code></pre>\n\n<h3>Partial Functions</h3>\n\n<p>The example given uses the closure as a partial function, but if this is our only goal, the same goal can be accomplished with <code>functools.partial</code></p>\n\n<pre><code>>>> from __future__ import print_function # use this if you're in Python 2.\n>>> partial_function = functools.partial(print, 'foo')\n>>> partial_function('bar')\nfoo bar\n>>> partial_function('baz')\nfoo baz\n>>> partial_function('quux')\nfoo quux\n</code></pre>\n\n<p>There are more complicated closures as well that would not fit the partial function example, and I'll demonstrate them further as time allows.</p>\n"
},
{
"answer_id": 32726068,
"author": "thiagoh",
"author_id": 889213,
"author_profile": "https://Stackoverflow.com/users/889213",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an example of Python3 closures </p>\n\n<pre><code>def closure(x):\n def counter():\n nonlocal x\n x += 1\n return x\n return counter;\n\ncounter1 = closure(100);\ncounter2 = closure(200);\n\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 2 \" + str(counter2()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 2 \" + str(counter2()))\n\n# result\n\ni from closure 1 101\ni from closure 1 102\ni from closure 2 201\ni from closure 1 103\ni from closure 1 104\ni from closure 1 105\ni from closure 2 202\n</code></pre>\n"
},
{
"answer_id": 47981346,
"author": "Dinesh Sonachalam",
"author_id": 5674391,
"author_profile": "https://Stackoverflow.com/users/5674391",
"pm_score": 3,
"selected": false,
"text": "<pre><code># A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.\n\n# Defining a closure\n\n# This is an outer function.\ndef outer_function(message):\n # This is an inner nested function.\n def inner_function():\n print(message)\n return inner_function\n\n# Now lets call the outer function and return value bound to name 'temp'\ntemp = outer_function(\"Hello\")\n# On calling temp, 'message' will be still be remembered although we had finished executing outer_function()\ntemp()\n# Technique by which some data('message') that remembers values in enclosing scopes \n# even if they are not present in memory is called closures\n\n# Output: Hello\n</code></pre>\n\n<p><strong>Criteria to met by Closures are:</strong></p>\n\n<ol>\n<li>We must have nested function.</li>\n<li>Nested function must refer to the value defined in the enclosing function.</li>\n<li>Enclosing function must return the nested function.</li>\n</ol>\n\n<hr>\n\n<pre><code># Example 2\ndef make_multiplier_of(n): # Outer function\n def multiplier(x): # Inner nested function\n return x * n\n return multiplier\n# Multiplier of 3\ntimes3 = make_multiplier_of(3)\n# Multiplier of 5\ntimes5 = make_multiplier_of(5)\nprint(times5(3)) # 15\nprint(times3(2)) # 6\n</code></pre>\n"
},
{
"answer_id": 49885629,
"author": "Nitish Chauhan",
"author_id": 4708210,
"author_profile": "https://Stackoverflow.com/users/4708210",
"pm_score": 1,
"selected": false,
"text": "<p>we all have used <strong>Decorators</strong> in python. They are nice examples to show what are closure functions in python.</p>\n\n<pre><code>class Test():\n def decorator(func):\n def wrapper(*args):\n b = args[1] + 5\n return func(b)\n return wrapper\n\n@decorator\ndef foo(val):\n print val + 2\n\nobj = Test()\nobj.foo(5)\n</code></pre>\n\n<p>here final value is 12</p>\n\n<p>Here, the wrapper function is able to access func object because wrapper is \"lexical closure\", it can access it's parent attributes.\nThat is why, it is able to access func object.</p>\n"
},
{
"answer_id": 50302797,
"author": "Eunjung Lee",
"author_id": 9779393,
"author_profile": "https://Stackoverflow.com/users/9779393",
"pm_score": 1,
"selected": false,
"text": "<p>I would like to share my example and an explanation about closures. I made a python example, and two figures to demonstrate stack states.</p>\n\n<pre><code>def maker(a, b, n):\n margin_top = 2\n padding = 4\n def message(msg):\n print('\\n’ * margin_top, a * n, \n ' ‘ * padding, msg, ' ‘ * padding, b * n)\n return message\n\nf = maker('*', '#', 5)\ng = maker('', '♥’, 3)\n…\nf('hello')\ng(‘good bye!')\n</code></pre>\n\n<p>The output of this code would be as follows:</p>\n\n<pre><code>***** hello #####\n\n good bye! ♥♥♥\n</code></pre>\n\n<p>Here are two figures to show stacks and the closure attached to the function object.</p>\n\n<p><a href=\"https://i.stack.imgur.com/q34kz.jpg\" rel=\"nofollow noreferrer\">when the function is returned from maker</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Jwssu.jpg\" rel=\"nofollow noreferrer\">when the function is called later</a></p>\n\n<p>When the function is called through a parameter or a nonlocal variable, the code needs local variable bindings such as margin_top, padding as well as a, b, n. In order to ensure the function code to work, the stack frame of the maker function which was gone away long ago should be accessible, which is backed up in the closure we can find along with the 'message's function object.</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1649/"
] | I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them. | [Closure on closures](http://mrevelle.blogspot.com/2006/10/closure-on-closures.html)
>
> Objects are data with methods
> attached, closures are functions with
> data attached.
>
>
>
```
def make_counter():
i = 0
def counter(): # counter() is a closure
nonlocal i
i += 1
return i
return counter
c1 = make_counter()
c2 = make_counter()
print (c1(), c1(), c2(), c2())
# -> 1 2 1 2
``` |
13,938 | <p><img src="https://i.stack.imgur.com/DibJS.jpg" alt="Visual Studio folder structure"></p>
<p>I need some advice as to how I easily can separate test runs for unit tests and integration test in Visual Studio. Often, or always, I structure the solution as presented in the above picture: separate projects for unit tests and integration tests. The unit tests is run very frequently while the integration tests naturally is run when the context is correctly aligned.</p>
<p>My goal is to somehow be able configure which tests (or test folders) to run when I use a keyboard shortcut. The tests should preferably be run by a graphical test runner (ReSharpers). So for example</p>
<ul>
<li>Alt+1 runs the tests in project BLL.Test, </li>
<li>Alt+2 runs the tests in project DAL.Tests, </li>
<li>Alt+3 runs them both (i.e. all the tests in the [Tests] folder, and</li>
<li>Alt+4 runs the tests in folder [Tests.Integration].</li>
</ul>
<p>TestDriven.net have an option of running just the test in the selected folder or project by right-clicking it and select Run Test(s). Being able to do this, but via a keyboard command and with a graphical test runner would be awesome.</p>
<p><img src="https://i.stack.imgur.com/NYnmJ.jpg" alt="TestDriven.net test run output"></p>
<p>Currently I use VS2008, ReSharper 4 and nUnit. But advice for a setup in the general is of course also appreciated.</p>
| [
{
"answer_id": 13953,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 0,
"selected": false,
"text": "<p>This is a bit of fiddly solution, but you could configure some <a href=\"http://blogs.msdn.com/saraford/archive/2008/04/24/did-you-know-you-can-run-external-tools-within-visual-studio-201.aspx\" rel=\"nofollow noreferrer\">external tools</a> for each of group of tests you want to run. I'm not sure if you'll be able to launch the ReSharper test runner this way, but you can run the console version of nunit. Once you have of those tools setup, you can assigned keyboard shortcuts to the commands \"Tools.ExternalCommand1\", \"Tools.ExternalCommand2\", etc.</p>\n\n<p>This wont really scale very well, and it's awkward to change - but it will give you keyboard shortcuts for running your tests. It does feel like there should be a much simpler way of doing this.</p>\n"
},
{
"answer_id": 13969,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 3,
"selected": true,
"text": "<p>I actually found kind of a solution for this on my own by using keyboard command bound to a macro. The macro was recorded from the menu Tools>Macros>Record TemporaryMacro. While recording I selected my [Tests] folder and ran ReSharpers UnitTest.ContextRun. This resulted in the following macro, </p>\n\n<pre><code>Sub TemporaryMacro()\n DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate\n DTE.ActiveWindow.Object.GetItem(\"TestUnitTest\\Tests\").Select(vsUISelectionType.vsUISelectionTypeSelect)\n DTE.ExecuteCommand(\"ReSharper.UnitTest_ContextRun\")\nEnd Sub\n</code></pre>\n\n<p>which was then bound to it's own keyboard command in Tools>Options>Environment>Keyboard.</p>\n\n<p>However, what would be even more awesome is a more general solution where I can configure exactly which projects/folders/classes to run and when. For example by the means of an xml file. This could then easily be checked in to version control and distributed to everyone who works with the project.</p>\n"
},
{
"answer_id": 14090,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>You can use a VS macro to parse the XML file and then call nunit.exe with the /fixture command line argument to specify which classes to run or generate a selection save file and run nunit using that.</p>\n"
},
{
"answer_id": 25640,
"author": "Gern Blanston",
"author_id": 2786,
"author_profile": "https://Stackoverflow.com/users/2786",
"pm_score": 0,
"selected": false,
"text": "<p>I have never used this but maybe it could help....</p>\n\n<p><a href=\"http://www.codeplex.com/VS2008UnitTestGUI\" rel=\"nofollow noreferrer\">http://www.codeplex.com/VS2008UnitTestGUI</a></p>\n\n<p>\"Project Description\nThis project is about running all unit test inside multiple .NET Unit tests assembly coded with Visual Studio 2008.\"</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446/"
] | 
I need some advice as to how I easily can separate test runs for unit tests and integration test in Visual Studio. Often, or always, I structure the solution as presented in the above picture: separate projects for unit tests and integration tests. The unit tests is run very frequently while the integration tests naturally is run when the context is correctly aligned.
My goal is to somehow be able configure which tests (or test folders) to run when I use a keyboard shortcut. The tests should preferably be run by a graphical test runner (ReSharpers). So for example
* Alt+1 runs the tests in project BLL.Test,
* Alt+2 runs the tests in project DAL.Tests,
* Alt+3 runs them both (i.e. all the tests in the [Tests] folder, and
* Alt+4 runs the tests in folder [Tests.Integration].
TestDriven.net have an option of running just the test in the selected folder or project by right-clicking it and select Run Test(s). Being able to do this, but via a keyboard command and with a graphical test runner would be awesome.

Currently I use VS2008, ReSharper 4 and nUnit. But advice for a setup in the general is of course also appreciated. | I actually found kind of a solution for this on my own by using keyboard command bound to a macro. The macro was recorded from the menu Tools>Macros>Record TemporaryMacro. While recording I selected my [Tests] folder and ran ReSharpers UnitTest.ContextRun. This resulted in the following macro,
```
Sub TemporaryMacro()
DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate
DTE.ActiveWindow.Object.GetItem("TestUnitTest\Tests").Select(vsUISelectionType.vsUISelectionTypeSelect)
DTE.ExecuteCommand("ReSharper.UnitTest_ContextRun")
End Sub
```
which was then bound to it's own keyboard command in Tools>Options>Environment>Keyboard.
However, what would be even more awesome is a more general solution where I can configure exactly which projects/folders/classes to run and when. For example by the means of an xml file. This could then easily be checked in to version control and distributed to everyone who works with the project. |
13,941 | <p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say "Process complete". I much rather it be a simple "bell."</p>
<p>I know that there's a function that can be used in <em>Cocoa</em> apps, <code>NSBeep</code>, but I don't think that has much anything to do with this.</p>
<p>I've also tried</p>
<pre class="lang-py prettyprint-override"><code>print(\a)
</code></pre>
<p>but that didn't work.</p>
<p>I'm using a Mac, if you couldn't tell by my <em>Cocoa</em> comment, so that may help.</p>
| [
{
"answer_id": 13949,
"author": "gbc",
"author_id": 1667,
"author_profile": "https://Stackoverflow.com/users/1667",
"pm_score": 7,
"selected": true,
"text": "<p>Have you tried :</p>\n\n<pre><code>import sys\nsys.stdout.write('\\a')\nsys.stdout.flush()\n</code></pre>\n\n<p>That works for me here on Mac OS 10.5</p>\n\n<p>Actually, I think your original attempt works also with a little modification:</p>\n\n<pre><code>print('\\a')\n</code></pre>\n\n<p>(You just need the single quotes around the character sequence).</p>\n"
},
{
"answer_id": 13959,
"author": "markpasc",
"author_id": 1472,
"author_profile": "https://Stackoverflow.com/users/1472",
"pm_score": 3,
"selected": false,
"text": "<p>I had to turn off the \"Silence terminal bell\" option in my active Terminal Profile in iTerm for <code>print('\\a')</code> to work. It seemed to work fine by default in Terminal.</p>\n\n<p>You can also use the Mac module <code>Carbon.Snd</code> to play the system beep:</p>\n\n<pre><code>>>> import Carbon.Snd\n>>> Carbon.Snd.SysBeep(1)\n>>> \n</code></pre>\n\n<p>The Carbon modules don't have any documentation, so I had to use <code>help(Carbon.Snd)</code> to see what functions were available. It seems to be a direct interface onto Carbon, so the docs on Apple Developer Connection probably help.</p>\n"
},
{
"answer_id": 34482,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 4,
"selected": false,
"text": "<p>If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do</p>\n\n<pre><code>from AppKit import NSBeep\nNSBeep()\n</code></pre>\n\n<p>to play the system alert.</p>\n"
},
{
"answer_id": 6110229,
"author": "Abhranil Das",
"author_id": 711017,
"author_profile": "https://Stackoverflow.com/users/711017",
"pm_score": 3,
"selected": false,
"text": "<p>I tried the mixer from the pygame module, and it works fine. First install the module:</p>\n\n<pre><code>$ sudo apt-get install python-pygame\n</code></pre>\n\n<p>Then in the program, write this:</p>\n\n<pre><code>from pygame import mixer\nmixer.init() #you must initialize the mixer\nalert=mixer.Sound('bell.wav')\nalert.play()\n</code></pre>\n\n<p>With pygame you have a lot of customization options, which you may additionally experiment with.</p>\n"
},
{
"answer_id": 46743047,
"author": "Martin Müller",
"author_id": 6488645,
"author_profile": "https://Stackoverflow.com/users/6488645",
"pm_score": 2,
"selected": false,
"text": "<p>Building on Barry Wark's answer...\n<code>NSBeep()</code> from AppKit works fine, but also makes the terminal/app icon in the taskbar jump.\nA few extra lines with <code>NSSound()</code> avoids that and gives the opportunity to use another sound:</p>\n\n<pre><code>from AppKit import NSSound\n#prepare sound:\nsound = NSSound.alloc()\nsound.initWithContentsOfFile_byReference_('/System/Library/Sounds/Ping.aiff', True)\n#rewind and play whenever you need it:\nsound.stop() #rewind\nsound.play()\n</code></pre>\n\n<p>Standard sound files can be found via commandline <code>locate /System/Library/Sounds/*.aiff</code>\nThe file used by <code>NSBeep()</code> seems to be <code>'/System/Library/Sounds/Funk.aiff'</code></p>\n"
},
{
"answer_id": 71458296,
"author": "chrischma",
"author_id": 14157064,
"author_profile": "https://Stackoverflow.com/users/14157064",
"pm_score": 0,
"selected": false,
"text": "<p>By the way: there is a module for that. ;-)</p>\n<p>Just install via pip:</p>\n<pre class=\"lang-py prettyprint-override\"><code>pip3 install mac_alerts\n</code></pre>\n<p>run your sound:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from mac_alerts import alerts\nalerts.play_error() # plays an error sound\n</code></pre>\n"
},
{
"answer_id": 72691776,
"author": "jitheshKuyyalil",
"author_id": 9472425,
"author_profile": "https://Stackoverflow.com/users/9472425",
"pm_score": 0,
"selected": false,
"text": "<p>Play sound worked for me. Install using pip</p>\n<pre><code>pip3 install playsound\n</code></pre>\n<p>To play sound</p>\n<pre><code>from playsound import playsound\nplaysound('beep.wav')\n</code></pre>\n<p>References:\n<a href=\"https://www.geeksforgeeks.org/play-sound-in-python/\" rel=\"nofollow noreferrer\">Found the examples here</a>\n<a href=\"https://www.soundjay.com/beep-sounds-1.html#google_vignette\" rel=\"nofollow noreferrer\">downloaded beep.wav from here</a></p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] | I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use `import os` and then use a command line speech program to say "Process complete". I much rather it be a simple "bell."
I know that there's a function that can be used in *Cocoa* apps, `NSBeep`, but I don't think that has much anything to do with this.
I've also tried
```py
print(\a)
```
but that didn't work.
I'm using a Mac, if you couldn't tell by my *Cocoa* comment, so that may help. | Have you tried :
```
import sys
sys.stdout.write('\a')
sys.stdout.flush()
```
That works for me here on Mac OS 10.5
Actually, I think your original attempt works also with a little modification:
```
print('\a')
```
(You just need the single quotes around the character sequence). |
13,963 | <p>I want to parse a config file sorta thing, like so:</p>
<pre><code>[KEY:Value]
[SUBKEY:SubValue]
</code></pre>
<p>Now I started with a <code>StreamReader</code>, converting lines into character arrays, when I figured there's gotta be a better way. So I ask you, humble reader, to help me.</p>
<p>One restriction is that it has to work in a Linux/Mono environment (1.2.6 to be exact). I don't have the latest 2.0 release (of Mono), so try to restrict language features to C# 2.0 or C# 1.0.</p>
| [
{
"answer_id": 13974,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 0,
"selected": false,
"text": "<p>It looks to me that you would be better off using an XML based config file as there are already .NET classes which can read and store the information for you relatively easily. Is there a reason that this is not possible?</p>\n\n<p>@Bernard: <del>It is true that hand editing XML is tedious, but the structure that you are presenting already looks very similar to XML.</del></p>\n\n<p>Then yes, has a good method there. </p>\n"
},
{
"answer_id": 13975,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use a stack, and use a push/pop algorithm. This one matches open/closing tags.</p>\n\n<pre><code>public string check()\n {\n ArrayList tags = getTags();\n\n\n int stackSize = tags.Count;\n\n Stack stack = new Stack(stackSize);\n\n foreach (string tag in tags)\n {\n if (!tag.Contains('/'))\n {\n stack.push(tag);\n }\n else\n {\n if (!stack.isEmpty())\n {\n string startTag = stack.pop();\n startTag = startTag.Substring(1, startTag.Length - 1);\n string endTag = tag.Substring(2, tag.Length - 2);\n if (!startTag.Equals(endTag))\n {\n return \"Fout: geen matchende eindtag\";\n }\n }\n else\n {\n return \"Fout: geen matchende openeningstag\";\n }\n }\n }\n\n if (!stack.isEmpty())\n {\n return \"Fout: geen matchende eindtag\";\n } \n return \"Xml is valid\";\n }\n</code></pre>\n\n<p>You can probably adapt so you can read the contents of your file. Regular expressions are also a good idea.</p>\n"
},
{
"answer_id": 13983,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 2,
"selected": false,
"text": "<p>I was looking at almost this exact problem the other day: <a href=\"http://trackerrealm.com/blogs/2007/04/tokenize-string-with-c-regular.html\" rel=\"nofollow noreferrer\">this article</a> on string tokenizing is exactly what you need. You'll want to define your tokens as something like:</p>\n\n<pre><code>@\"(?&ltlevel>\\s) | \" +\n@\"(?&ltterm>[^:\\s]) | \" +\n@\"(?&ltseparator>:)\"\n</code></pre>\n\n<p>The article does a pretty good job of explaining it. From there you just start eating up tokens as you see fit.</p>\n\n<p>Protip: For an <a href=\"http://en.wikipedia.org/wiki/LL_parser\" rel=\"nofollow noreferrer\">LL(1) parser</a> (read: easy), tokens cannot share a prefix. If you have <code>abc</code> as a token, you cannot have <code>ace</code> as a token</p>\n\n<p>Note: The article's missing the | characters in its examples, just throw them in.</p>\n"
},
{
"answer_id": 13990,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": true,
"text": "<blockquote>\n <p>I considered it, but I'm not going to use XML. I am going to be writing this stuff by hand, and hand editing XML makes my brain hurt. :')</p>\n</blockquote>\n\n<p>Have you looked at <a href=\"http://www.yaml.org/\" rel=\"noreferrer\">YAML</a>?</p>\n\n<p>You get the benefits of XML without all the pain and suffering. It's used extensively in the ruby community for things like config files, pre-prepared database data, etc</p>\n\n<p>here's an example</p>\n\n<pre><code>customer:\n name: Orion\n age: 26\n addresses:\n - type: Work\n number: 12\n street: Bob Street\n - type: Home\n number: 15\n street: Secret Road\n</code></pre>\n\n<p>There appears to be a <a href=\"http://yaml-net-parser.sourceforge.net/default.html\" rel=\"noreferrer\">C# library here</a>, which I haven't used personally, but yaml is pretty simple, so \"how hard can it be?\" :-)</p>\n\n<p>I'd say it's preferable to inventing your own ad-hoc format (and dealing with parser bugs)</p>\n"
},
{
"answer_id": 14057,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "<p>Using a library is almost always preferably to rolling your own. Here's a quick list of \"Oh I'll never need that/I didn't think about that\" points which will end up coming to bite you later down the line:</p>\n\n<ul>\n<li>Escaping characters. What if you want a : in the key or ] in the value?</li>\n<li>Escaping the escape character.</li>\n<li>Unicode</li>\n<li>Mix of tabs and spaces (see the problems with Python's white space sensitive syntax)</li>\n<li>Handling different return character formats</li>\n<li>Handling syntax error reporting</li>\n</ul>\n\n<p>Like others have suggested, YAML looks like your best bet.</p>\n"
},
{
"answer_id": 14274,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": -1,
"selected": false,
"text": "<p>Regardless of the persisted format, using a Regex would be the fastest way of parsing.\nIn ruby it'd probably be a few lines of code.</p>\n\n<pre><code>\\[KEY:(.*)\\] \n\\[SUBKEY:(.*)\\]\n</code></pre>\n\n<p>These two would get you the Value and SubValue in the first group. Check out MSDN on how to match a regex against a string.</p>\n\n<p>This is something everyone should have in their kitty. Pre-Regex days would seem like the Ice Age.</p>\n"
},
{
"answer_id": 14292,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 0,
"selected": false,
"text": "<p>@Gishu</p>\n\n<p>Actually once I'd accommodated for escaped characters my regex ran slightly slower than my hand written top down recursive parser and that's without the nesting (linking sub-items to their parents) and error reporting the hand written parser had.</p>\n\n<p>The regex was a slightly faster to write (though I do have a bit of experience with hand parsers) but that's without good error reporting. Once you add that it becomes slightly harder and longer to do.</p>\n\n<p>I also find the hand written parser easier to understand the intention of. For instance, here is the a snippet of the code:</p>\n\n<pre><code>private static Node ParseNode(TextReader reader)\n{\n Node node = new Node();\n int indentation = ParseWhitespace(reader);\n Expect(reader, '[');\n node.Key = ParseTerminatedString(reader, ':');\n node.Value = ParseTerminatedString(reader, ']');\n}\n</code></pre>\n"
},
{
"answer_id": 29192,
"author": "Antoine Aubry",
"author_id": 2680,
"author_profile": "https://Stackoverflow.com/users/2680",
"pm_score": 1,
"selected": false,
"text": "<p>There is <a href=\"http://yamldotnet.wiki.sourceforge.net/\" rel=\"nofollow noreferrer\">another YAML library for .NET</a> which is under development. Right now it supports reading YAML streams and has been tested on Windows and Mono. Write support is currently being implemented.</p>\n"
}
] | 2008/08/17 | [
"https://Stackoverflow.com/questions/13963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | I want to parse a config file sorta thing, like so:
```
[KEY:Value]
[SUBKEY:SubValue]
```
Now I started with a `StreamReader`, converting lines into character arrays, when I figured there's gotta be a better way. So I ask you, humble reader, to help me.
One restriction is that it has to work in a Linux/Mono environment (1.2.6 to be exact). I don't have the latest 2.0 release (of Mono), so try to restrict language features to C# 2.0 or C# 1.0. | >
> I considered it, but I'm not going to use XML. I am going to be writing this stuff by hand, and hand editing XML makes my brain hurt. :')
>
>
>
Have you looked at [YAML](http://www.yaml.org/)?
You get the benefits of XML without all the pain and suffering. It's used extensively in the ruby community for things like config files, pre-prepared database data, etc
here's an example
```
customer:
name: Orion
age: 26
addresses:
- type: Work
number: 12
street: Bob Street
- type: Home
number: 15
street: Secret Road
```
There appears to be a [C# library here](http://yaml-net-parser.sourceforge.net/default.html), which I haven't used personally, but yaml is pretty simple, so "how hard can it be?" :-)
I'd say it's preferable to inventing your own ad-hoc format (and dealing with parser bugs) |
14,118 | <p>I'm writing my first Perl app -- an AOL Instant Messenger bot that talks to an Arduino microcontroller, which in turn controls a servo that will push the power button on our sysadmin's server, which freezes randomly every 28 hours or so. </p>
<p>I've gotten all the hard stuff done, I'm just trying to add one last bit of code to break the main loop and log out of AIM when the user types 'quit'.</p>
<p>The problem is, if I try to read from STDIN in the main program loop, it blocks the process until input is entered, essentially rendering the bot inactive. I've tried testing for EOF before reading, but no dice... EOF just always returns false.</p>
<p>Here's below is some sample code I'm working with:</p>
<pre><code>while(1) {
$oscar->do_one_loop();
# Poll to see if any arduino data is coming in over serial port
my $char = $port->lookfor();
# If we get data from arduino, then print it
if ($char) {
print "" . $char ;
}
# reading STDIN blocks until input is received... AAARG!
my $a = <STDIN>;
print $a;
if($a eq "exit" || $a eq "quit" || $a eq 'c' || $a eq 'q') {last;}
}
print "Signing off... ";
$oscar->signoff();
print "Done\n";
print "Closing serial port... ";
$port->close() || warn "close failed";
print "Done\n";
</code></pre>
| [
{
"answer_id": 14124,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 5,
"selected": true,
"text": "<p>The Perl built-in is <a href=\"http://perldoc.perl.org/functions/select.html\" rel=\"noreferrer\"><code>select()</code></a>, which is a pass-through to the <code>select()</code> system call, but for sane people I recommend <a href=\"http://search.cpan.org/dist/IO/lib/IO/Select.pm\" rel=\"noreferrer\"><code>IO::Select</code></a>.</p>\n\n<p>Code sample:</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse IO::Select;\n\n$s = IO::Select->new();\n$s->add(\\*STDIN);\n\nwhile (++$i) {\n print \"Hiya $i!\\n\";\n sleep(5);\n if ($s->can_read(.5)) {\n chomp($foo = <STDIN>);\n print \"Got '$foo' from STDIN\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 54816600,
"author": "Gus Schlachter",
"author_id": 3935928,
"author_profile": "https://Stackoverflow.com/users/3935928",
"pm_score": 2,
"selected": false,
"text": "<p>I found that <a href=\"http://search.cpan.org/dist/IO/lib/IO/Select.pm\" rel=\"nofollow noreferrer\">IO::Select</a> works fine as long as STDOUT gets closed, such as when the upstream process in the pipeline exits, or input is from a file. However, if output is ongoing (such as from \"tail -f\") then any partial data buffered by <code><STDIN></code> will not be displayed. Instead, use the unbuffered <a href=\"https://perldoc.perl.org/functions/sysread.html\" rel=\"nofollow noreferrer\">sysread</a>:</p>\n\n<pre><code>#!/usr/bin/perl\nuse IO::Select;\n$s = IO::Select->new(\\*STDIN);\n\nwhile (++$i) {\n if ($s->can_read(2)) {\n last unless defined($foo=get_unbuf_line());\n print \"Got '$foo'\\n\";\n }\n}\n\nsub get_unbuf_line {\n my $line=\"\";\n while (sysread(STDIN, my $nextbyte, 1)) {\n return $line if $nextbyte eq \"\\n\";\n $line .= $nextbyte;\n }\n return(undef);\n}\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I'm writing my first Perl app -- an AOL Instant Messenger bot that talks to an Arduino microcontroller, which in turn controls a servo that will push the power button on our sysadmin's server, which freezes randomly every 28 hours or so.
I've gotten all the hard stuff done, I'm just trying to add one last bit of code to break the main loop and log out of AIM when the user types 'quit'.
The problem is, if I try to read from STDIN in the main program loop, it blocks the process until input is entered, essentially rendering the bot inactive. I've tried testing for EOF before reading, but no dice... EOF just always returns false.
Here's below is some sample code I'm working with:
```
while(1) {
$oscar->do_one_loop();
# Poll to see if any arduino data is coming in over serial port
my $char = $port->lookfor();
# If we get data from arduino, then print it
if ($char) {
print "" . $char ;
}
# reading STDIN blocks until input is received... AAARG!
my $a = <STDIN>;
print $a;
if($a eq "exit" || $a eq "quit" || $a eq 'c' || $a eq 'q') {last;}
}
print "Signing off... ";
$oscar->signoff();
print "Done\n";
print "Closing serial port... ";
$port->close() || warn "close failed";
print "Done\n";
``` | The Perl built-in is [`select()`](http://perldoc.perl.org/functions/select.html), which is a pass-through to the `select()` system call, but for sane people I recommend [`IO::Select`](http://search.cpan.org/dist/IO/lib/IO/Select.pm).
Code sample:
```
#!/usr/bin/perl
use IO::Select;
$s = IO::Select->new();
$s->add(\*STDIN);
while (++$i) {
print "Hiya $i!\n";
sleep(5);
if ($s->can_read(.5)) {
chomp($foo = <STDIN>);
print "Got '$foo' from STDIN\n";
}
}
``` |
14,165 | <p>I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers.</p>
| [
{
"answer_id": 14169,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 5,
"selected": true,
"text": "<p>Check if your code is including the <strong>windows.h</strong> header file and either your code or other third-party headers have their own <strong>min()</strong>/<strong>max()</strong> definitions. If yes, then prepend your <strong>windows.h</strong> inclusion with a definition of <strong>NOMINMAX</strong> like this:</p>\n\n<pre><code>#define NOMINMAX\n#include <windows.h>\n</code></pre>\n"
},
{
"answer_id": 14177,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 0,
"selected": false,
"text": "<p>Ugh... scope it, dude: <code>std::min()</code>, <code>std::max()</code>.</p>\n"
},
{
"answer_id": 14195,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't used it in years but from memory boost assigns min and max too, possibly?</p>\n"
},
{
"answer_id": 24150,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": 2,
"selected": false,
"text": "<p>Another possibility could be from side effects. Most min/max macros will include the parameters multiple times and may not do what you expect. Errors and warnings could also be generated.\n<PRE>\nmax(a,i++) expands as ((a) > (i++) ? (a) : (i++))</p>\n\n<p>afterwards i is either plus 1 or plus 2\n</PRE>\nThe () in the expansion are to avoid problems if you call it with formulae. Try expanding max(a,b+c)</p>\n"
},
{
"answer_id": 1793313,
"author": "dhorn",
"author_id": 148632,
"author_profile": "https://Stackoverflow.com/users/148632",
"pm_score": -1,
"selected": false,
"text": "<p>Honestly, when it comes to min/max, I find it best to just define my own:</p>\n\n<pre><code>#define min(a,b) ((a) < (b) ? (a) : (b))\n#define max(a,b) ((a) >= (b) ? (a) : (b))\n</code></pre>\n"
},
{
"answer_id": 4783177,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>Since Windows defines this as a function-style macro, the following workaround is available:</p>\n\n<pre><code>int i = std::min<int>(3,5);\n</code></pre>\n\n<p>This works because the macro <code>min()</code> is expanded only when <code>min</code> is followed by <code>(</code>, and not when it's followed by <code><</code>. </p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers. | Check if your code is including the **windows.h** header file and either your code or other third-party headers have their own **min()**/**max()** definitions. If yes, then prepend your **windows.h** inclusion with a definition of **NOMINMAX** like this:
```
#define NOMINMAX
#include <windows.h>
``` |
14,209 | <p><code>System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.</code></p>
<p>Anybody ever get this error and/or have any idea on it's cause and/or solution?</p>
<p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=125227&SiteID=1" rel="nofollow noreferrer">This link may have relevant information.</a></p>
<p><strong>Update</strong></p>
<p>The connection string is <code>=.\SQLEXPRESS;AttachDbFilename=C:\temp\HelloWorldTest.mdf;Integrated Security=True</code></p>
<p>The suggested <code>User Instance=false</code> worked.</p>
| [
{
"answer_id": 14214,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>You should add an explicit User Instance=true/false to your connection string</p>\n"
},
{
"answer_id": 1086442,
"author": "Roboblob",
"author_id": 125718,
"author_profile": "https://Stackoverflow.com/users/125718",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the answer to your problem:</p>\n\n<p>Very often old user instance creates some temp files that prevent a new SQL Express user instance to be created. When those files are deleted everything start working properly.</p>\n\n<p>First of all confirm that user instances are enabled by running the following SQL in SQL Server Management Studio:</p>\n\n<pre><code>exec sp_configure 'user instances enabled', 1.\nGO\nReconfigure\n</code></pre>\n\n<p>After running the query restart your SQL Server instance. Now delete the following folder:</p>\n\n<p><code>C:\\Documents and Settings\\{YOUR_USERNAME}\\Local Settings\\Application Data\\Microsoft\\Microsoft SQL Server Data\\{SQL_INSTANCE_NAME}</code></p>\n\n<p>Make sure that you replace <code>{YOUR_USERNAME}</code> and <code>{SQL_INSTANCE_NAME}</code> with the appropriate names.</p>\n\n<p>Source: <a href=\"http://aspdotnetfaq.com/Faq/fix-error-Failed-to-generate-a-user-instance-of-SQL-Server-due-to-a-failure-in-starting-the-process-for-the-user-instance.aspx\" rel=\"noreferrer\">Fix error \"Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance.\" </a></p>\n"
},
{
"answer_id": 17092076,
"author": "Hamid Shahid",
"author_id": 94897,
"author_profile": "https://Stackoverflow.com/users/94897",
"pm_score": 0,
"selected": false,
"text": "<p>I started getting this error this morning in a test deployment environment. I was using SQL Server Express 2008 and the error I was getting was</p>\n\n<p>\"Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.\"</p>\n\n<p>Unsure about what caused it, I followed the instructions in this post and in other post about deleting the \"C:\\Users\\UserName\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS\" directory, but to no avail.</p>\n\n<p>What did the trick for me was to change the connection string from</p>\n\n<p>\"Data Source=.\\SQLExpress;Initial Catalog=<strong>DBFilePath</strong>;Integrated Security=SSPI;MultipleActiveResultSets=true\"</p>\n\n<p>to</p>\n\n<p>\"Data Source=.\\SQLExpress;Initial Catalog=<strong>DBName</strong>;Integrated Security=SSPI;MultipleActiveResultSets=true\"</p>\n"
},
{
"answer_id": 29869425,
"author": "alketraz",
"author_id": 4832647,
"author_profile": "https://Stackoverflow.com/users/4832647",
"pm_score": 0,
"selected": false,
"text": "<p>I followed all these steps but also had to go into</p>\n\n<ol>\n<li>Control Panel > Administrative Tools > Services</li>\n<li>Right-click on SQL Server (SQLEXPRESS)</li>\n<li>Select the Log On tab</li>\n<li>Select the Local System account and then click OK</li>\n</ol>\n\n<p>Problem solved... thank you</p>\n"
},
{
"answer_id": 33201997,
"author": "mukhtar ghaleb",
"author_id": 5042080,
"author_profile": "https://Stackoverflow.com/users/5042080",
"pm_score": 0,
"selected": false,
"text": "<p>I have windows 8 and I test the solution </p>\n\n<ol>\n<li><p>Enable user instances<br>\nexec sp_configure 'user instances enabled', 1.<br>\nGO<br>\nReconfigure </p></li>\n<li><p>Restart your SQL Server instance.</p></li>\n<li><p>Delete the folder:\n<code>C:\\Users\\Arabic\\{YOUR_USERNAME}\\Local\\Microsoft\\Microsoft SQL Server Data</code><br>\nReplace {YOUR_USERNAME} with the appropriate names.</p></li>\n</ol>\n\n<p>the source from Roboblob</p>\n"
},
{
"answer_id": 68836220,
"author": "user8128167",
"author_id": 351154,
"author_profile": "https://Stackoverflow.com/users/351154",
"pm_score": 0,
"selected": false,
"text": "<p>Please note that I found <a href=\"https://stackoverflow.com/users/372/jon-limjap\">Jon Limjap</a>'s answer helpful except that after I did more research I found that it only applies to database connection strings that contain <code>AttachDBFilename</code>, so I had to change my connection string in <code>web.config</code> from:</p>\n<pre><code>connectionString="data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\aspnetdb.mdf"\n</code></pre>\n<p>To:</p>\n<pre><code>connectionString="data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\aspnetdb.mdf;User Instance=true"\n</code></pre>\n<p>For details please see <a href=\"https://stackoverflow.com/questions/9555659/if-add-user-instances-true-to-connection-string-an-exception-is-thrown/9555870#9555870\">If add [user instances=true] to connection string, an exception is thrown</a></p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] | `System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.`
Anybody ever get this error and/or have any idea on it's cause and/or solution?
[This link may have relevant information.](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=125227&SiteID=1)
**Update**
The connection string is `=.\SQLEXPRESS;AttachDbFilename=C:\temp\HelloWorldTest.mdf;Integrated Security=True`
The suggested `User Instance=false` worked. | Here is the answer to your problem:
Very often old user instance creates some temp files that prevent a new SQL Express user instance to be created. When those files are deleted everything start working properly.
First of all confirm that user instances are enabled by running the following SQL in SQL Server Management Studio:
```
exec sp_configure 'user instances enabled', 1.
GO
Reconfigure
```
After running the query restart your SQL Server instance. Now delete the following folder:
`C:\Documents and Settings\{YOUR_USERNAME}\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\{SQL_INSTANCE_NAME}`
Make sure that you replace `{YOUR_USERNAME}` and `{SQL_INSTANCE_NAME}` with the appropriate names.
Source: [Fix error "Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance."](http://aspdotnetfaq.com/Faq/fix-error-Failed-to-generate-a-user-instance-of-SQL-Server-due-to-a-failure-in-starting-the-process-for-the-user-instance.aspx) |
14,247 | <p>I've only done a bit of Flex development thus far, but I've preferred the approach of creating controls programmatically over mxml files, because (and <em>please</em>, correct me if I'm wrong!) I've gathered that you can't have it both ways -- that is to say, have the class functionality in a separate ActionScript class file but have the contained elements declared in mxml.</p>
<p>There doesn't seem to be much of a difference productivity-wise, but doing data binding programmatically seems somewhat less than trivial. I took a look at how the mxml compiler transforms the data binding expressions. The result is a bunch of generated callbacks and a lot more lines than in the mxml representation. So here's the question: <strong>is there a way to do data binding programmatically that doesn't involve a world of hurt?</strong></p>
| [
{
"answer_id": 14261,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": true,
"text": "<p>Don't be afraid of MXML. It's great for laying out views. If you write your own <em>reusable</em> components then writing them in ActionScript may sometimes give you a little more control, but for non-reusable views MXML is much better. It's more terse, bindings are extemely easy to set up, etc.</p>\n\n<p>However, bindings in pure ActionScript need not be that much of a pain. It will never be as simple as in MXML where a lot of things are done for you, but it can be done with not too much effort.</p>\n\n<p>What you have is <code>BindingUtils</code> and it's methods <code>bindSetter</code> and <code>bindProperty</code>. I almost always use the former, since I usually want to do some work, or call <code>invalidateProperties</code> when values change, I almost never just want to set a property.</p>\n\n<p>What you need to know is that these two return an object of the type <code>ChangeWatcher</code>, if you want to remove the binding for some reason, you have to hold on to this object. This is what makes manual bindings in ActionScript a little less convenient than those in MXML.</p>\n\n<p>Let's start with a simple example:</p>\n\n<pre><code>BindingUtils.bindSetter(nameChanged, selectedEmployee, \"name\");\n</code></pre>\n\n<p>This sets up a binding that will call the method <code>nameChanged</code> when the <code>name</code> property on the object in the variable <code>selectedEmployee</code> changes. The <code>nameChanged</code> method will recieve the new value of the <code>name</code> property as an argument, so it should look like this:</p>\n\n<pre><code>private function nameChanged( newName : String ) : void \n</code></pre>\n\n<p>The problem with this simple example is that once you have set up this binding it will fire each time the property of the specified object changes. The value of the variable <code>selectedEmployee</code> may change, but the binding is still set up for the object that the variable pointed to before.</p>\n\n<p>There are two ways to solve this: either to keep the <code>ChangeWatcher</code> returned by <code>BindingUtils.bindSetter</code> around and call <code>unwatch</code> on it when you want to remove the binding (and then setting up a new binding instead), or bind to yourself. I'll show you the first option first, and then explain what I mean by binding to yourself.</p>\n\n<p>The <code>currentEmployee</code> could be made into a getter/setter pair and implemented like this (only showing the setter):</p>\n\n<pre><code>public function set currentEmployee( employee : Employee ) : void {\n if ( _currentEmployee != employee ) {\n if ( _currentEmployee != null ) {\n currentEmployeeNameCW.unwatch();\n }\n\n _currentEmployee = employee;\n\n if ( _currentEmployee != null ) {\n currentEmployeeNameCW = BindingUtils.bindSetter(currentEmployeeNameChanged, _currentEmployee, \"name\");\n }\n }\n}\n</code></pre>\n\n<p>What happens is that when the <code>currentEmployee</code> property is set it looks to see if there was a previous value, and if so removes the binding for that object (<code>currentEmployeeNameCW.unwatch()</code>), then it sets the private variable, and unless the new value was <code>null</code> sets up a new binding for the <code>name</code> property. Most importantly it saves the <code>ChangeWatcher</code> returned by the binding call.</p>\n\n<p>This is a basic binding pattern and I think it works fine. There is, however, a trick that can be used to make it a bit simpler. You can bind to yourself instead. Instead of setting up and removing bindings each time the <code>currentEmployee</code> property changes you can have the binding system do it for you. In your <code>creationComplete</code> handler (or constructor or at least some time early) you can set up a binding like so:</p>\n\n<pre><code>BindingUtils.bindSetter(currentEmployeeNameChanged, this, [\"currentEmployee\", \"name\"]);\n</code></pre>\n\n<p>This sets up a binding not only to the <code>currentEmployee</code> property on <code>this</code>, but also to the <code>name</code> property on this object. So anytime either changes the method <code>currentEmployeeNameChanged</code> will be called. There's no need to save the <code>ChangeWatcher</code> because the binding will never have to be removed.</p>\n\n<p>The second solution works in many cases, but I've found that the first one is sometimes necessary, especially when working with bindings in non-view classes (since <code>this</code> has to be an event dispatcher and the <code>currentEmployee</code> has to be bindable for it to work).</p>\n"
},
{
"answer_id": 36010,
"author": "Nick Higgs",
"author_id": 3187,
"author_profile": "https://Stackoverflow.com/users/3187",
"pm_score": 2,
"selected": false,
"text": "<p>One way to separate the MXML and ActionScript for a component into separate files is by doing something similar to the ASP.Net 1.x code behind model. In this model the declarative part (the MXML in this case) is a subclass of the imperative part (the ActionScript). So I might declare the code behind for a class like this:</p>\n\n<pre><code>package CustomComponents\n{\n import mx.containers.*;\n import mx.controls.*;\n import flash.events.Event;\n\n public class MyCanvasCode extends Canvas\n {\n public var myLabel : Label;\n\n protected function onInitialize(event : Event):void\n {\n MyLabel.text = \"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\";\n }\n }\n}\n</code></pre>\n\n<p>...and the markup like this:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<MyCanvasCode xmlns=\"CustomComponents.*\" \n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n initialize=\"onInitialize(event)\">\n <mx:Label id=\"myLabel\"/> \n</MyCanvasCode>\n</code></pre>\n\n<p>As you can see from this example, a disadvatage of this approach is that you have to declare controls like <strong>myLabel</strong> in both files.</p>\n"
},
{
"answer_id": 511674,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>there is a way that I usually use to use mxml and action script together: All my mxml components inherit from a action script class where I add the more complex code. Then you can refer to event listeners implemented in this class in the mxml file.</p>\n\n<p>Regards,</p>\n\n<p>Ruth</p>\n"
},
{
"answer_id": 5521481,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": 3,
"selected": false,
"text": "<p>It exists as of today. :)</p>\n\n<p>I just released my ActionScript data binding project as open source: <a href=\"http://code.google.com/p/bindage-tools\" rel=\"noreferrer\">http://code.google.com/p/bindage-tools</a></p>\n\n<p>BindageTools is an alternative to BindingUtils (see the play on words there?) that uses a fluent API where you declare your data bindings in a pipeline style:</p>\n\n<pre><code>Bind.fromProperty(person, \"firstName\")\n .toProperty(firstNameInput, \"text\");\n</code></pre>\n\n<p>Two-way bindings:</p>\n\n<pre><code>Bind.twoWay(\n Bind.fromProperty(person, \"firstName\"),\n Bind.fromProperty(firstNameInput, \"text\"));\n</code></pre>\n\n<p>Explicit data conversion and validation:</p>\n\n<pre><code>Bind.twoWay(\n Bind.fromProperty(person, \"age\")\n .convert(valueToString()),\n Bind.fromProperty(ageInput, \"text\")\n .validate(isNumeric()) // (Hamcrest-as3 matcher)\n .convert(toNumber()));\n</code></pre>\n\n<p>Etc. There are lots more examples on the site. There's lots of other features too-come have a look. --Matthew</p>\n\n<p>Edit: updated APIs</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/266/"
] | I've only done a bit of Flex development thus far, but I've preferred the approach of creating controls programmatically over mxml files, because (and *please*, correct me if I'm wrong!) I've gathered that you can't have it both ways -- that is to say, have the class functionality in a separate ActionScript class file but have the contained elements declared in mxml.
There doesn't seem to be much of a difference productivity-wise, but doing data binding programmatically seems somewhat less than trivial. I took a look at how the mxml compiler transforms the data binding expressions. The result is a bunch of generated callbacks and a lot more lines than in the mxml representation. So here's the question: **is there a way to do data binding programmatically that doesn't involve a world of hurt?** | Don't be afraid of MXML. It's great for laying out views. If you write your own *reusable* components then writing them in ActionScript may sometimes give you a little more control, but for non-reusable views MXML is much better. It's more terse, bindings are extemely easy to set up, etc.
However, bindings in pure ActionScript need not be that much of a pain. It will never be as simple as in MXML where a lot of things are done for you, but it can be done with not too much effort.
What you have is `BindingUtils` and it's methods `bindSetter` and `bindProperty`. I almost always use the former, since I usually want to do some work, or call `invalidateProperties` when values change, I almost never just want to set a property.
What you need to know is that these two return an object of the type `ChangeWatcher`, if you want to remove the binding for some reason, you have to hold on to this object. This is what makes manual bindings in ActionScript a little less convenient than those in MXML.
Let's start with a simple example:
```
BindingUtils.bindSetter(nameChanged, selectedEmployee, "name");
```
This sets up a binding that will call the method `nameChanged` when the `name` property on the object in the variable `selectedEmployee` changes. The `nameChanged` method will recieve the new value of the `name` property as an argument, so it should look like this:
```
private function nameChanged( newName : String ) : void
```
The problem with this simple example is that once you have set up this binding it will fire each time the property of the specified object changes. The value of the variable `selectedEmployee` may change, but the binding is still set up for the object that the variable pointed to before.
There are two ways to solve this: either to keep the `ChangeWatcher` returned by `BindingUtils.bindSetter` around and call `unwatch` on it when you want to remove the binding (and then setting up a new binding instead), or bind to yourself. I'll show you the first option first, and then explain what I mean by binding to yourself.
The `currentEmployee` could be made into a getter/setter pair and implemented like this (only showing the setter):
```
public function set currentEmployee( employee : Employee ) : void {
if ( _currentEmployee != employee ) {
if ( _currentEmployee != null ) {
currentEmployeeNameCW.unwatch();
}
_currentEmployee = employee;
if ( _currentEmployee != null ) {
currentEmployeeNameCW = BindingUtils.bindSetter(currentEmployeeNameChanged, _currentEmployee, "name");
}
}
}
```
What happens is that when the `currentEmployee` property is set it looks to see if there was a previous value, and if so removes the binding for that object (`currentEmployeeNameCW.unwatch()`), then it sets the private variable, and unless the new value was `null` sets up a new binding for the `name` property. Most importantly it saves the `ChangeWatcher` returned by the binding call.
This is a basic binding pattern and I think it works fine. There is, however, a trick that can be used to make it a bit simpler. You can bind to yourself instead. Instead of setting up and removing bindings each time the `currentEmployee` property changes you can have the binding system do it for you. In your `creationComplete` handler (or constructor or at least some time early) you can set up a binding like so:
```
BindingUtils.bindSetter(currentEmployeeNameChanged, this, ["currentEmployee", "name"]);
```
This sets up a binding not only to the `currentEmployee` property on `this`, but also to the `name` property on this object. So anytime either changes the method `currentEmployeeNameChanged` will be called. There's no need to save the `ChangeWatcher` because the binding will never have to be removed.
The second solution works in many cases, but I've found that the first one is sometimes necessary, especially when working with bindings in non-view classes (since `this` has to be an event dispatcher and the `currentEmployee` has to be bindable for it to work). |
14,278 | <p>I'd like to provide some way of creating dynamically loadable plugins in my software.
Typical way to do this is using the <a href="http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx" rel="noreferrer">LoadLibrary</a> WinAPI function to load a dll and calling <a href="http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx" rel="noreferrer">GetProcAddress</a> to get an pointer to a function inside that dll.</p>
<p>My question is how do I dynamically load a plugin in C#/.Net application?</p>
| [
{
"answer_id": 14282,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 5,
"selected": true,
"text": "<p>The following code snippet (C#) constructs an instance of any concrete classes derived from <code>Base</code> found in class libraries (*.dll) in the application path and stores them in a list.</p>\n\n<pre><code>using System.IO;\nusing System.Reflection;\n\nList<Base> objects = new List<Base>();\nDirectoryInfo dir = new DirectoryInfo(Application.StartupPath);\n\nforeach (FileInfo file in dir.GetFiles(\"*.dll\"))\n{\n Assembly assembly = Assembly.LoadFrom(file.FullName);\n foreach (Type type in assembly.GetTypes())\n {\n if (type.IsSubclassOf(typeof(Base)) && type.IsAbstract == false)\n {\n Base b = type.InvokeMember(null,\n BindingFlags.CreateInstance,\n null, null, null) as Base;\n objects.Add(b);\n }\n }\n}\n</code></pre>\n\n<p><strong>Edit:</strong> The classes referred to by <a href=\"https://stackoverflow.com/questions/14278/how-to-load-plugins-in-net#14305\">Matt</a> are probably a better option in .NET 3.5.</p>\n"
},
{
"answer_id": 14286,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 2,
"selected": false,
"text": "<p>Basically you can do it in two ways.</p>\n\n<p>The first is to import kernel32.dll and use LoadLibrary and GetProcAddress as you used it before:</p>\n\n<pre><code>[DllImport(\"kernel32.dll\")]\n\ninternal static extern IntPtr LoadLibrary(String dllname);\n\n[DllImport(\"kernel32.dll\")]\n\ninternal static extern IntPtr GetProcAddress(IntPtr hModule, String procname);\n</code></pre>\n\n<p>The second is to do it in the .NET-way: by using reflection. Check System.Reflection namespace and the following methods: </p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/b61s44e8.aspx\" rel=\"nofollow noreferrer\">Assembly.LoadFile</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettype.aspx\" rel=\"nofollow noreferrer\">Assembly.GetType</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettypes.aspx\" rel=\"nofollow noreferrer\">Assembly.GetTypes</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/8zz808e6.aspx\" rel=\"nofollow noreferrer\">Type.GetMethod</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.methodinfo.invoke.aspx\" rel=\"nofollow noreferrer\">MethodInfo.Invoke</a></li>\n</ul>\n\n<p>First you load the assembly by it's path, then get the type (class) from it by it's name, then get the method of the class by it's name again and finally call the method with the relevant parameters.</p>\n"
},
{
"answer_id": 14305,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": false,
"text": "<p>As of .NET 3.5 there's a formalized, baked-in way to create and load plugins from a .NET application. It's all in the <a href=\"http://msdn.microsoft.com/en-us/library/system.addin.aspx\" rel=\"noreferrer\">System.AddIn</a> namespace. For more information you can check out this article on MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/bb384241.aspx\" rel=\"noreferrer\">Add-ins and Extensibility</a></p>\n"
},
{
"answer_id": 14312,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 3,
"selected": false,
"text": "<p>One tip is to load all plugins and such into an own AppDomain, since the code running can be potentially malicious. An own AppDomain can also be used to \"filter\" assemblies and types that you don't want to load.</p>\n\n<pre><code>AppDomain domain = AppDomain.CreateDomain(\"tempDomain\");\n</code></pre>\n\n<p>And to load an assembly into the application domain:</p>\n\n<pre><code>AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyPath);\nAssembly assembly = domain.Load(assemblyName);\n</code></pre>\n\n<p>To unload the application domain:</p>\n\n<pre><code>AppDomain.Unload(domain);\n</code></pre>\n"
},
{
"answer_id": 15048,
"author": "Brian G Swanson",
"author_id": 1795,
"author_profile": "https://Stackoverflow.com/users/1795",
"pm_score": 2,
"selected": false,
"text": "<p>The article is a bit older, but still applicable for creating an extensibility layer within your application:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/magazine/cc164072.aspx\" rel=\"nofollow noreferrer\">Let Users Add Functionality to Your .NET Applications with Macros and Plug-Ins</a></p>\n"
},
{
"answer_id": 53011,
"author": "Jason Olson",
"author_id": 5418,
"author_profile": "https://Stackoverflow.com/users/5418",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, ++ to Matt and System.AddIn (a two-part MSDN magazine article about System.AddIn are available <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163476.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163460.aspx\" rel=\"nofollow noreferrer\">here</a>). Another technology you might want to look at to get an idea where the .NET Framework might be going in the future is the <a href=\"http://www.codeplex.com/mef\" rel=\"nofollow noreferrer\">Managed Extensibility Framework</a> currently available in CTP form on Codeplex.</p>\n"
},
{
"answer_id": 14185590,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 3,
"selected": false,
"text": "<h2>Dynamically Loading Plug-ins</h2>\n\n<p>For information on how to dynamically load .NET assemblies see <a href=\"https://stackoverflow.com/questions/1137781/c-sharp-correct-way-to-load-assembly-find-class-and-call-run-method/14184863#14184863\">this question</a> (and <a href=\"https://stackoverflow.com/a/14184863/184528\">my answer</a>). Here is some code for loading creating an <code>AppDomain</code> and loading an assembly into it.</p>\n\n<pre><code>var domain = AppDomain.CreateDomain(\"NewDomainName\");\nvar pathToDll = @\"C:\\myDll.dll\"; \nvar t = typeof(TypeIWantToLoad);\nvar runnable = domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName) \n as IRunnable;\nif (runnable == null) throw new Exception(\"broke\");\nrunnable.Run();\n</code></pre>\n\n<h2>Unloading Plug-ins</h2>\n\n<p>A typical requirement of a plugin framework is to unload the plugins. To unload dynamically loaded assemblies (e.g. plug-ins and add-ins) you have to unload the containing <code>AppDomain</code>. For more information see <a href=\"http://msdn.microsoft.com/en-us/library/c5b8a8f9.aspx\" rel=\"nofollow noreferrer\">this article on MSDN on Unloading AppDomains</a>.</p>\n\n<h2>Using WCF</h2>\n\n<p>There is a <a href=\"https://stackoverflow.com/questions/5801406/c-sharp-wcf-plugin-design-and-implementation\">stack overflow question and answer</a> that describe how to use the Windows Communication Framework (WCF) to create a plug-in framework. </p>\n\n<h2>Existing Plug-in Frameworks</h2>\n\n<p>I know of two plug-in frameworks: </p>\n\n<ul>\n<li><a href=\"http://www.mono-project.com/Mono.Addins\" rel=\"nofollow noreferrer\">Mono.Add-ins</a> - As mentioned in <a href=\"https://stackoverflow.com/a/9045372/184528\">this answer to another question</a>.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/bb384200.aspx\" rel=\"nofollow noreferrer\">Managed Add-in Framework (MAF)</a> - This is the <code>System.AddIn</code> namespace as <a href=\"https://stackoverflow.com/a/14305/184528\">mentioned by Matt in his answer</a>.</li>\n</ul>\n\n<p>Some people talk about the <a href=\"http://msdn.microsoft.com/en-us/library/dd460648.aspx\" rel=\"nofollow noreferrer\">Managed Extensibility Framework (MEF)</a> as a plug-in or add-in framework, which it isn't. For more information see <a href=\"https://stackoverflow.com/questions/835182/choosing-between-mef-and-maf-system-addin\">this StackOverflow.com question</a> and <a href=\"https://stackoverflow.com/questions/124040/is-mef-a-replacement-for-system-addin\">this StackOverflow.com question</a>.</p>\n"
},
{
"answer_id": 59571238,
"author": "LeonardoX",
"author_id": 1683040,
"author_profile": "https://Stackoverflow.com/users/1683040",
"pm_score": 0,
"selected": false,
"text": "<p>This is my implementation, Inspired in <a href=\"https://www.codeproject.com/Tips/546639/How-to-create-an-easy-plugin-system-in-Csharp\" rel=\"nofollow noreferrer\">this code</a> avoiding to iterate over all assemblies and all types (or at least filtering with linQ). I just load the library and try to load the class which implemets a common shared interface. Simple and fast :)</p>\n\n<p>Just declare an interface in a separated library and reference it in both, your system and your plugin:</p>\n\n<pre><code>public interface IYourInterface\n{\n Task YourMethod();\n}\n</code></pre>\n\n<p>In your plugin library, declare a class which implements IYourInterface</p>\n\n<pre><code>public class YourClass: IYourInterface\n{\n async Task IYourInterface.YourMethod()\n {\n //.....\n }\n}\n</code></pre>\n\n<p>In your system, declare this method</p>\n\n<pre><code>using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Linq;\n\npublic abstract class ReflectionTool<TSource> where TSource : class\n{\n public static TSource LoadInstanceFromLibrary(string libraryPath)\n {\n TSource pluginclass = null;\n if (!System.IO.File.Exists(libraryPath))\n throw new Exception($\"Library '{libraryPath}' not found\");\n else\n {\n Assembly.LoadFrom(libraryPath);\n\n var fileName = System.IO.Path.GetFileName(libraryPath).Replace(\".dll\", \"\");\n var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(c => c.FullName.StartsWith(fileName));\n var type = assembly.GetTypes().FirstOrDefault(c => c.GetInterface(typeof(TSource).FullName) != null);\n\n try\n {\n pluginclass = Activator.CreateInstance(type) as TSource;\n }\n catch (Exception ex)\n {\n LogError(\"\", ex);\n throw;\n }\n }\n\n return pluginclass;\n }\n}\n</code></pre>\n\n<p>And call it like this way:</p>\n\n<pre><code>IYourInterface instance = ReflectionTool<IYourInterface>.LoadInstanceFromLibrary(\"c:\\pathToYourLibrary.dll\");\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1534/"
] | I'd like to provide some way of creating dynamically loadable plugins in my software.
Typical way to do this is using the [LoadLibrary](http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx) WinAPI function to load a dll and calling [GetProcAddress](http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx) to get an pointer to a function inside that dll.
My question is how do I dynamically load a plugin in C#/.Net application? | The following code snippet (C#) constructs an instance of any concrete classes derived from `Base` found in class libraries (\*.dll) in the application path and stores them in a list.
```
using System.IO;
using System.Reflection;
List<Base> objects = new List<Base>();
DirectoryInfo dir = new DirectoryInfo(Application.StartupPath);
foreach (FileInfo file in dir.GetFiles("*.dll"))
{
Assembly assembly = Assembly.LoadFrom(file.FullName);
foreach (Type type in assembly.GetTypes())
{
if (type.IsSubclassOf(typeof(Base)) && type.IsAbstract == false)
{
Base b = type.InvokeMember(null,
BindingFlags.CreateInstance,
null, null, null) as Base;
objects.Add(b);
}
}
}
```
**Edit:** The classes referred to by [Matt](https://stackoverflow.com/questions/14278/how-to-load-plugins-in-net#14305) are probably a better option in .NET 3.5. |
14,281 | <p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p>
<p>Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way to solve this problem without unzipping?</p>
| [
{
"answer_id": 14304,
"author": "jdd",
"author_id": 242853,
"author_profile": "https://Stackoverflow.com/users/242853",
"pm_score": 0,
"selected": false,
"text": "<p>You could loop through the zip files, reading individual files using the zipfile module and running your regex on those, eliminating to unzip all the files at once. </p>\n\n<p>I'm fairly certain that you can't run a regex over the zipped data, at least not meaningfully.</p>\n"
},
{
"answer_id": 14314,
"author": "Craig.Nicol",
"author_id": 1404,
"author_profile": "https://Stackoverflow.com/users/1404",
"pm_score": 0,
"selected": false,
"text": "<p>To access the contents of a zip file you have to unzip it, although the zipfile package makes this fairly easy, as you can unzip each file within an archive individually.</p>\n\n<p><a href=\"http://docs.python.org/lib/module-zipfile.html\" rel=\"nofollow noreferrer\">Python zipfile module</a></p>\n"
},
{
"answer_id": 14320,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "<p>There's nothing that will automatically do what you want.</p>\n\n<p>However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.</p>\n\n<pre><code>#!/usr/bin/python\n\nimport zipfile\nf = zipfile.ZipFile('myfile.zip')\n\nfor subfile in f.namelist():\n print subfile\n data = f.read(subfile)\n for line in data.split('\\n'):\n print line\n</code></pre>\n"
},
{
"answer_id": 41822,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 0,
"selected": false,
"text": "<p>Isn't it (at least theoretically) possible, to read in the ZIP's Huffman coding and then translate the regexp into the Huffman code? Might this be more efficient than first de-compressing the data, then running the regexp?</p>\n\n<p>(Note: I know it wouldn't be quite that simple: you'd also have to deal with other aspects of the ZIP coding—file layout, block structures, back-references—but one imagines this could be fairly lightweight.)</p>\n\n<p>EDIT: Also note that it's probably much more sensible to just use the <code>zipfile</code> solution.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files.
Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way to solve this problem without unzipping? | There's nothing that will automatically do what you want.
However, there is a python zipfile module that will make this easy to do. Here's how to iterate over the lines in the file.
```
#!/usr/bin/python
import zipfile
f = zipfile.ZipFile('myfile.zip')
for subfile in f.namelist():
print subfile
data = f.read(subfile)
for line in data.split('\n'):
print line
``` |
14,287 | <p>In my C/C++ program, I'm using <a href="http://opencvlibrary.sourceforge.net/" rel="noreferrer">OpenCV</a> to capture images from my webcam. The camera (<a href="http://en.wikipedia.org/wiki/Quickcam" rel="noreferrer">Logitech QuickCam IM</a>) can capture at resolutions <strong>320x240</strong>, <strong>640x480</strong> and <strong>1280x960</strong>. But, for some strange reason, OpenCV gives me images of resolution <strong>320x240</strong> only. Calls to change the resolution using <strong>cvSetCaptureProperty()</strong> with other resolution values just don't work. How do I capture images with the other resolutions possible with my webcam?</p>
| [
{
"answer_id": 14290,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 5,
"selected": true,
"text": "<p>There doesn't seem to be a solution. The resolution can be increased to <strong>640x480</strong> using <a href=\"http://tech.groups.yahoo.com/group/OpenCV/message/28735\" rel=\"noreferrer\">this hack</a> shared by <em>lifebelt77</em>. Here are the details reproduced:</p>\n\n<p>Add to <strong>highgui.h</strong>:</p>\n\n<pre><code>#define CV_CAP_PROP_DIALOG_DISPLAY 8\n#define CV_CAP_PROP_DIALOG_FORMAT 9\n#define CV_CAP_PROP_DIALOG_SOURCE 10\n#define CV_CAP_PROP_DIALOG_COMPRESSION 11\n#define CV_CAP_PROP_FRAME_WIDTH_HEIGHT 12\n</code></pre>\n\n<p>Add the function <strong>icvSetPropertyCAM_VFW</strong> to <strong>cvcap.cpp</strong>:</p>\n\n<pre><code>static int icvSetPropertyCAM_VFW( CvCaptureCAM_VFW* capture, int property_id, double value )\n{\n int result = -1;\n CAPSTATUS capstat;\n CAPTUREPARMS capparam;\n BITMAPINFO btmp;\n\n switch( property_id )\n {\n case CV_CAP_PROP_DIALOG_DISPLAY:\n result = capDlgVideoDisplay(capture->capWnd);\n //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEODISPLAY,0,0);\n break;\n\n case CV_CAP_PROP_DIALOG_FORMAT:\n result = capDlgVideoFormat(capture->capWnd);\n //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOFORMAT,0,0);\n break;\n\n case CV_CAP_PROP_DIALOG_SOURCE:\n result = capDlgVideoSource(capture->capWnd);\n //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOSOURCE,0,0);\n break;\n\n case CV_CAP_PROP_DIALOG_COMPRESSION:\n result = capDlgVideoCompression(capture->capWnd);\n break;\n\n case CV_CAP_PROP_FRAME_WIDTH_HEIGHT:\n capGetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));\n btmp.bmiHeader.biWidth = floor(value/1000);\n btmp.bmiHeader.biHeight = value-floor(value/1000)*1000;\n btmp.bmiHeader.biSizeImage = btmp.bmiHeader.biHeight *\n btmp.bmiHeader.biWidth * btmp.bmiHeader.biPlanes *\n btmp.bmiHeader.biBitCount / 8;\n capSetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));\n break;\n\n default:\n break;\n }\n\n return result;\n}\n</code></pre>\n\n<p>and edit <strong>captureCAM_VFW_vtable</strong> as following:</p>\n\n<pre><code>static CvCaptureVTable captureCAM_VFW_vtable =\n{\n6,\n(CvCaptureCloseFunc)icvCloseCAM_VFW,\n(CvCaptureGrabFrameFunc)icvGrabFrameCAM_VFW,\n(CvCaptureRetrieveFrameFunc)icvRetrieveFrameCAM_VFW,\n(CvCaptureGetPropertyFunc)icvGetPropertyCAM_VFW,\n(CvCaptureSetPropertyFunc)icvSetPropertyCAM_VFW, // was NULL\n(CvCaptureGetDescriptionFunc)0\n};\n</code></pre>\n\n<p>Now rebuilt <strong>highgui.dll</strong>.</p>\n"
},
{
"answer_id": 15422,
"author": "Louis Brandy",
"author_id": 2089740,
"author_profile": "https://Stackoverflow.com/users/2089740",
"pm_score": 3,
"selected": false,
"text": "<p>I've done image processing in linux before and skipped OpenCV's built in camera functionality because it's (as you've discovered) incomplete.</p>\n\n<p>Depending on your OS you may have more luck going straight to the hardware through normal channels as opposed to through openCV. If you are using Linux, video4linux or video4linux2 should give you relatively trivial access to USB webcams and you can use libavc1394 for firewire. Depending on the device and the quality of the example code you follow, you should be able to get the device running with the parameters you want in an hour or two. </p>\n\n<p>Edited to add: You are on your own if its Windows. I imagine it's not much more difficult but I've never done it.</p>\n"
},
{
"answer_id": 38187,
"author": "martjno",
"author_id": 3373,
"author_profile": "https://Stackoverflow.com/users/3373",
"pm_score": 3,
"selected": false,
"text": "<p>I strongly suggest using <a href=\"http://muonics.net/school/spring05/videoInput/\" rel=\"nofollow noreferrer\">VideoInput lib</a>, it supports any DirectShow device (even multiple devices at the same time) and is more configurable. You'll spend five minutes make it play with OpenCV.</p>\n"
},
{
"answer_id": 713742,
"author": "Grifo",
"author_id": 86629,
"author_profile": "https://Stackoverflow.com/users/86629",
"pm_score": 5,
"selected": false,
"text": "<p>I'm using openCV 1.1pre1 under Windows (videoinput library is used by default by this version of openCv under windows).</p>\n\n<p>With these instructions I can set camera resolution. Note that I call the old cvCreateCameraCapture instead of cvCaptureFromCam.</p>\n\n<pre><code>capture = cvCreateCameraCapture(cameraIndex);\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 640 );\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 480 );\n\n\nvideoFrame = cvQueryFrame(capture);\n</code></pre>\n\n<p>I've tested it with Logitech, Trust and Philips webcams</p>\n"
},
{
"answer_id": 3076521,
"author": "mg72",
"author_id": 371133,
"author_profile": "https://Stackoverflow.com/users/371133",
"pm_score": -1,
"selected": false,
"text": "<pre><code>cvQueryFrame(capture);\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, any_supported_size );\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, any_supported_size);\n\ncvQueryFrame(capture);\n</code></pre>\n\n<p>should be just enough!</p>\n"
},
{
"answer_id": 3867859,
"author": "fantom1210",
"author_id": 467332,
"author_profile": "https://Stackoverflow.com/users/467332",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>capture = cvCreateCameraCapture(-1);\n//set resolution\ncvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, frameWidth);\ncvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, frameHeight);\n</code></pre>\n"
},
{
"answer_id": 4041979,
"author": "Yo-L",
"author_id": 310108,
"author_profile": "https://Stackoverflow.com/users/310108",
"pm_score": 3,
"selected": false,
"text": "<p>Check this ticket out:\n<a href=\"https://code.ros.org/trac/opencv/ticket/376\" rel=\"noreferrer\">https://code.ros.org/trac/opencv/ticket/376</a></p>\n\n<p>\"The solution is to use the newer libv4l-based wrapper.</p>\n\n<ol>\n<li><p>install libv4l-dev (this is how it's called in Ubuntu)</p></li>\n<li><p>rerun cmake, you will see \"V4L/V4L2: Using libv4l\"</p></li>\n<li><p>rerun make. now the resolution can be changed. tested with built-in isight on MBP.\"</p></li>\n</ol>\n\n<p>This fixed it for me using Ubuntu and might aswell work for you.</p>\n"
},
{
"answer_id": 4157963,
"author": "Shervin Emami",
"author_id": 199142,
"author_profile": "https://Stackoverflow.com/users/199142",
"pm_score": 0,
"selected": false,
"text": "<p>I find that in Windows (from Win98 to WinXP SP3), OpenCV will often use Microsoft's VFW library for camera access. The problem with this is that it is often very slow (say a max of 15 FPS frame capture) and buggy (hence why cvSetCaptureProperty often doesn't work). Luckily, you can usually change the resolution in other software (particularly \"AMCAP\", which is a demo program that is easily available) and it will effect the resolution that OpenCV will use. For example, you can run AMCAP to set the resolution to 640x480, and then OpenCV will use that by default from that point onwards!</p>\n\n<p>But if you can use a different Windows camera access library such as the \"videoInput\" library <a href=\"http://muonics.net/school/spring05/videoInput/\" rel=\"nofollow\">http://muonics.net/school/spring05/videoInput/</a> that accesses the camera using very efficient DirectShow (part of DirectX). Or if you have a professional quality camera, then often it will come with a custom API that lets you access the camera, and you could use that for fast access with the ability to change resolution and many other things.</p>\n"
},
{
"answer_id": 5379910,
"author": "noonv",
"author_id": 421699,
"author_profile": "https://Stackoverflow.com/users/421699",
"pm_score": 0,
"selected": false,
"text": "<p>Under Windows try to use VideoInput library:\n<a href=\"http://robocraft.ru/blog/computervision/420.html\" rel=\"nofollow\">http://robocraft.ru/blog/computervision/420.html</a></p>\n"
},
{
"answer_id": 5816916,
"author": "evangelos",
"author_id": 729049,
"author_profile": "https://Stackoverflow.com/users/729049",
"pm_score": 2,
"selected": false,
"text": "<p>I am using debian and ubuntu, i had the same problem, i couldn't change the resolution of video input using <strong>CV_CAP_PROP_FRAME_WIDTH</strong> and <strong>CV_CAP_PROP_FRAME_HEIGHT</strong></p>\n\n<p>I turned out that the reason was a missing library.\nI installed <strong>lib4l-dev</strong> through synaptic, <em>rebuilt</em> OpenCV and the problem is SOLVED! </p>\n"
},
{
"answer_id": 5849244,
"author": "CyraX",
"author_id": 727013,
"author_profile": "https://Stackoverflow.com/users/727013",
"pm_score": 2,
"selected": false,
"text": "<p>I am posting this to ensure that no one else wastes time on this setproperty function. I spent 2 days on this to see that nothing seems to be working. So I dug out the code (I had installed the library the first time around). This is what actually happens - cvSetCaptureProperty, calls setProperty inside CvCapture class and lo behold setProperty does nothing. It just returns false.\nInstead I'll pick up using another library to feed OpenCV a capture video/images. I am using OpenCV 2.2</p>\n"
},
{
"answer_id": 6250280,
"author": "William",
"author_id": 785686,
"author_profile": "https://Stackoverflow.com/users/785686",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, WIDTH );</p>\n<p>cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, HEIGHT);</p>\n<p>cvQueryFrame(capture);</p>\n</blockquote>\n<p>That will not work with OpenCV 2.2, but if you use OpenCV 2.1 it will work fine !</p>\n"
},
{
"answer_id": 6321334,
"author": "plan9assembler",
"author_id": 1710672,
"author_profile": "https://Stackoverflow.com/users/1710672",
"pm_score": 0,
"selected": false,
"text": "<p>If you are on windows platform, try DirectShow (IAMStreamConfig).</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/dd319784%28v=vs.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/dd319784%28v=vs.85%29.aspx</a></p>\n"
},
{
"answer_id": 12253652,
"author": "Forrest Erickson",
"author_id": 1644581,
"author_profile": "https://Stackoverflow.com/users/1644581",
"pm_score": 3,
"selected": false,
"text": "<p>Code I finally got working in Python once Aaron Haun pointed out I needed to define the arguments of the set function before using them.</p>\n\n<pre><code>#Camera_Get_Set.py\n#By Forrest L. Erickson of VRX Company Inc. 8-31-12.\n#Opens the camera and reads and reports the settings.\n#Then tries to set for higher resolution.\n#Workes with Logitech C525 for resolutions 960 by 720 and 1600 by 896\n\n\nimport cv2.cv as cv\nimport numpy\n\nCV_CAP_PROP_POS_MSEC = 0\nCV_CAP_PROP_POS_FRAMES = 1\nCV_CAP_PROP_POS_AVI_RATIO = 2\nCV_CAP_PROP_FRAME_WIDTH = 3\nCV_CAP_PROP_FRAME_HEIGHT = 4\nCV_CAP_PROP_FPS = 5\nCV_CAP_PROP_POS_FOURCC = 6\nCV_CAP_PROP_POS_FRAME_COUNT = 7\nCV_CAP_PROP_BRIGHTNESS = 8\nCV_CAP_PROP_CONTRAST = 9\nCV_CAP_PROP_SATURATION = 10\nCV_CAP_PROP_HUE = 11\n\nCV_CAPTURE_PROPERTIES = tuple({\nCV_CAP_PROP_POS_MSEC,\nCV_CAP_PROP_POS_FRAMES,\nCV_CAP_PROP_POS_AVI_RATIO,\nCV_CAP_PROP_FRAME_WIDTH,\nCV_CAP_PROP_FRAME_HEIGHT,\nCV_CAP_PROP_FPS,\nCV_CAP_PROP_POS_FOURCC,\nCV_CAP_PROP_POS_FRAME_COUNT,\nCV_CAP_PROP_BRIGHTNESS,\nCV_CAP_PROP_CONTRAST,\nCV_CAP_PROP_SATURATION,\nCV_CAP_PROP_HUE})\n\nCV_CAPTURE_PROPERTIES_NAMES = [\n\"CV_CAP_PROP_POS_MSEC\",\n\"CV_CAP_PROP_POS_FRAMES\",\n\"CV_CAP_PROP_POS_AVI_RATIO\",\n\"CV_CAP_PROP_FRAME_WIDTH\",\n\"CV_CAP_PROP_FRAME_HEIGHT\",\n\"CV_CAP_PROP_FPS\",\n\"CV_CAP_PROP_POS_FOURCC\",\n\"CV_CAP_PROP_POS_FRAME_COUNT\",\n\"CV_CAP_PROP_BRIGHTNESS\",\n\"CV_CAP_PROP_CONTRAST\",\n\"CV_CAP_PROP_SATURATION\",\n\"CV_CAP_PROP_HUE\"]\n\n\ncapture = cv.CaptureFromCAM(0)\n\nprint (\"\\nCamera properties before query of frame.\")\nfor i in range(len(CV_CAPTURE_PROPERTIES_NAMES)):\n# camera_valeus =[CV_CAPTURE_PROPERTIES_NAMES, foo]\n foo = cv.GetCaptureProperty(capture, CV_CAPTURE_PROPERTIES[i])\n camera_values =[CV_CAPTURE_PROPERTIES_NAMES[i], foo]\n# print str(camera_values)\n print str(CV_CAPTURE_PROPERTIES_NAMES[i]) + \": \" + str(foo)\n\n\nprint (\"\\nOpen a window for display of image\")\ncv.NamedWindow(\"Camera\", 1)\nwhile True:\n img = cv.QueryFrame(capture)\n cv.ShowImage(\"Camera\", img)\n if cv.WaitKey(10) == 27:\n break\ncv.DestroyWindow(\"Camera\")\n\n\n#cv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 1024)\n#cv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 768)\ncv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 1600)\ncv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 896)\n\n\nprint (\"\\nCamera properties after query and display of frame.\")\nfor i in range(len(CV_CAPTURE_PROPERTIES_NAMES)):\n# camera_valeus =[CV_CAPTURE_PROPERTIES_NAMES, foo]\n foo = cv.GetCaptureProperty(capture, CV_CAPTURE_PROPERTIES[i])\n camera_values =[CV_CAPTURE_PROPERTIES_NAMES[i], foo]\n# print str(camera_values)\n print str(CV_CAPTURE_PROPERTIES_NAMES[i]) + \": \" + str(foo)\n\n\nprint (\"/nOpen a window for display of image\")\ncv.NamedWindow(\"Camera\", 1)\nwhile True:\n img = cv.QueryFrame(capture)\n cv.ShowImage(\"Camera\", img)\n if cv.WaitKey(10) == 27:\n break\ncv.DestroyWindow(\"Camera\")\n</code></pre>\n"
},
{
"answer_id": 19108254,
"author": "user2833455",
"author_id": 2833455,
"author_profile": "https://Stackoverflow.com/users/2833455",
"pm_score": 0,
"selected": false,
"text": "<p>Just one information that could be valuable for people having difficulties to change the default capture resolution (640 x 480) ! I experimented myself a such problem with opencv 2.4.x and one Logitech camera ... and found one workaround !</p>\n\n<p>The behaviour I detected is that the default format is setup as initial parameters when camera capture is started (cvCreateCameraCapture), and all request to change height or width :</p>\n\n<pre><code>cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, ... \n</code></pre>\n\n<p>or</p>\n\n<pre><code>cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, ...\n</code></pre>\n\n<p>are not possible afterwards ! Effectively, I discovered with adding return error of ioctl functions that V4l2 driver is returning <strong>EBUSY</strong> for thet requests ! \nTherefore, one workaround should be to change the default value directly in highgui/cap_v4l.cpp :</p>\n\n<pre><code>*#define DEFAULT_V4L_WIDTH 1280 // Originally 640* \n\n*#define DEFAULT_V4L_HEIGHT 720 // Originally 480*\n</code></pre>\n\n<p>After that, I just recompiled <strong>opencv</strong> ... and arrived to get 1280 x 720 without any problem ! Of course, a better fix should be to stop the acquisition, change the parameters, and restart stream after, but I'm not enough familiar with opencv for doing that !</p>\n\n<p>Hope it will help.</p>\n\n<p>Michel BEGEY</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | In my C/C++ program, I'm using [OpenCV](http://opencvlibrary.sourceforge.net/) to capture images from my webcam. The camera ([Logitech QuickCam IM](http://en.wikipedia.org/wiki/Quickcam)) can capture at resolutions **320x240**, **640x480** and **1280x960**. But, for some strange reason, OpenCV gives me images of resolution **320x240** only. Calls to change the resolution using **cvSetCaptureProperty()** with other resolution values just don't work. How do I capture images with the other resolutions possible with my webcam? | There doesn't seem to be a solution. The resolution can be increased to **640x480** using [this hack](http://tech.groups.yahoo.com/group/OpenCV/message/28735) shared by *lifebelt77*. Here are the details reproduced:
Add to **highgui.h**:
```
#define CV_CAP_PROP_DIALOG_DISPLAY 8
#define CV_CAP_PROP_DIALOG_FORMAT 9
#define CV_CAP_PROP_DIALOG_SOURCE 10
#define CV_CAP_PROP_DIALOG_COMPRESSION 11
#define CV_CAP_PROP_FRAME_WIDTH_HEIGHT 12
```
Add the function **icvSetPropertyCAM\_VFW** to **cvcap.cpp**:
```
static int icvSetPropertyCAM_VFW( CvCaptureCAM_VFW* capture, int property_id, double value )
{
int result = -1;
CAPSTATUS capstat;
CAPTUREPARMS capparam;
BITMAPINFO btmp;
switch( property_id )
{
case CV_CAP_PROP_DIALOG_DISPLAY:
result = capDlgVideoDisplay(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEODISPLAY,0,0);
break;
case CV_CAP_PROP_DIALOG_FORMAT:
result = capDlgVideoFormat(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOFORMAT,0,0);
break;
case CV_CAP_PROP_DIALOG_SOURCE:
result = capDlgVideoSource(capture->capWnd);
//SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOSOURCE,0,0);
break;
case CV_CAP_PROP_DIALOG_COMPRESSION:
result = capDlgVideoCompression(capture->capWnd);
break;
case CV_CAP_PROP_FRAME_WIDTH_HEIGHT:
capGetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
btmp.bmiHeader.biWidth = floor(value/1000);
btmp.bmiHeader.biHeight = value-floor(value/1000)*1000;
btmp.bmiHeader.biSizeImage = btmp.bmiHeader.biHeight *
btmp.bmiHeader.biWidth * btmp.bmiHeader.biPlanes *
btmp.bmiHeader.biBitCount / 8;
capSetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));
break;
default:
break;
}
return result;
}
```
and edit **captureCAM\_VFW\_vtable** as following:
```
static CvCaptureVTable captureCAM_VFW_vtable =
{
6,
(CvCaptureCloseFunc)icvCloseCAM_VFW,
(CvCaptureGrabFrameFunc)icvGrabFrameCAM_VFW,
(CvCaptureRetrieveFrameFunc)icvRetrieveFrameCAM_VFW,
(CvCaptureGetPropertyFunc)icvGetPropertyCAM_VFW,
(CvCaptureSetPropertyFunc)icvSetPropertyCAM_VFW, // was NULL
(CvCaptureGetDescriptionFunc)0
};
```
Now rebuilt **highgui.dll**. |
14,300 | <p>For example; with the old command prompt it would be:</p>
<pre><code>cmd.exe /k mybatchfile.bat
</code></pre>
| [
{
"answer_id": 14313,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "<p>Drop into a cmd instance (or indeed PowerShell itself) and type this:</p>\n\n<pre><code>powershell -?\n</code></pre>\n\n<p>You'll see that powershell.exe has a \"-noexit\" parameter which tells it not to exit after executing a \"startup command\".</p>\n"
},
{
"answer_id": 5346936,
"author": "john",
"author_id": 665321,
"author_profile": "https://Stackoverflow.com/users/665321",
"pm_score": -1,
"selected": false,
"text": "<p>I am sure that you already figure this out but I just post it</p>\n\n<pre><code>$CreateDate = (Get-Date -format 'yyyy-MM-dd hh-mm-ss')\n\n$RemoteServerName =\"server name\"\n$process = [WMICLASS]\"\\\\$RemoteServerName\\ROOT\\CIMV2:win32_process\" \n$result = $process.Create(\"C:\\path to a script\\test.bat\") \n$result | out-file -file \"C:\\some path \\Log-$CreatedDate.txt\"\n</code></pre>\n"
},
{
"answer_id": 20060082,
"author": "deadlydog",
"author_id": 602585,
"author_profile": "https://Stackoverflow.com/users/602585",
"pm_score": 4,
"selected": false,
"text": "<p>When running PowerShell.exe just provide the <strong>-NoExit</strong> switch like so:</p>\n\n<pre><code>PowerShell -NoExit -File \"C:\\SomeFolder\\SomePowerShellScript.ps1\"\n\nPowerShell -NoExit -Command \"Write-Host 'This window will stay open.'\"\n</code></pre>\n\n<p>Or if you want to run a file and then run a command and have the window stay open, you can do something like this:</p>\n\n<pre><code>PowerShell -NoExit \"& 'C:\\SomeFolder\\SomePowerShellScript.ps1'; Write-Host 'This window will stay open.'\"\n</code></pre>\n\n<p>The <strong>-Command</strong> parameter is implied if not provided, and here we use the <strong>&</strong> to call the PowerShell script, and the <strong>;</strong> separates the PowerShell commands.</p>\n\n<p>Also, at the bottom of <a href=\"http://blog.danskingdom.com/fix-problem-where-windows-powershell-cannot-run-script-whose-path-contains-spaces/\" rel=\"noreferrer\">my blog post</a> I show a quick registry change you can make in order to always have PowerShell remain open after executing a script/command, so that you don't need to always explicitly provide the -NoExit switch all the time.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/887/"
] | For example; with the old command prompt it would be:
```
cmd.exe /k mybatchfile.bat
``` | Drop into a cmd instance (or indeed PowerShell itself) and type this:
```
powershell -?
```
You'll see that powershell.exe has a "-noexit" parameter which tells it not to exit after executing a "startup command". |
14,330 | <p>How do I convert the RGB values of a pixel to a single monochrome value?</p>
| [
{
"answer_id": 14331,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 6,
"selected": true,
"text": "<p>I found one possible solution in the <a href=\"http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html\" rel=\"noreferrer\">Color FAQ</a>. The <em>luminance component</em> Y (from the <em>CIE XYZ system</em>) captures what is most perceived by humans as color in one channel. So, use those coefficients:</p>\n\n<pre><code>mono = (0.2125 * color.r) + (0.7154 * color.g) + (0.0721 * color.b);\n</code></pre>\n"
},
{
"answer_id": 14339,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/bb332387.aspx#tbconimagecolorizer_grayscaleconversion\" rel=\"nofollow noreferrer\">This MSDN article</a> uses <code>(0.299 * color.R + 0.587 * color.G + 0.114 * color.B);</code></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale\" rel=\"nofollow noreferrer\">This Wikipedia article</a> uses <code>(0.3* color.R + 0.59 * color.G + 0.11 * color.B);</code></p>\n"
},
{
"answer_id": 15119,
"author": "Carl Russmann",
"author_id": 1347,
"author_profile": "https://Stackoverflow.com/users/1347",
"pm_score": 3,
"selected": false,
"text": "<p>This depends on what your motivations are. If you just want to turn an arbitrary image to grayscale and have it look pretty good, the conversions in other answers to this question will do.</p>\n\n<p>If you are converting color photographs to black and white, the process can be both very complicated and subjective, requiring specific tweaking for each image. For an idea what might be involved, take a look at this <a href=\"http://www.adobe.com/designcenter/photoshop/articles/phscs2mrblkwht.html\" rel=\"noreferrer\">tutorial</a> from Adobe for Photoshop.</p>\n\n<p>Replicating this in code would be fairly involved, and would still require user intervention to get the resulting image aesthetically \"perfect\" (whatever that means!).</p>\n"
},
{
"answer_id": 25772,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 3,
"selected": false,
"text": "<p>As mentioned also, a grayscale translation (note that monochromatic images need not to be in grayscale) from an RGB-triplet is subject to taste. </p>\n\n<p>For example, you could cheat, extract only the blue component, by simply throwing the red and green components away, and copying the blue value in their stead. Another simple and generally ok solution would be to take the average of the pixel's RGB-triplet and use that value in all three components.</p>\n\n<p>The fact that there's a considerable market for professional and not-very-cheap-at-all-no-sirree grayscale/monochrome converter plugins for Photoshop alone, tells that the conversion is just as simple or complex as you wish.</p>\n"
},
{
"answer_id": 51262134,
"author": "Sau001",
"author_id": 2989655,
"author_profile": "https://Stackoverflow.com/users/2989655",
"pm_score": 1,
"selected": false,
"text": "<p>The logic behind converting any RGB based picture to monochrome can is not a trivial linear transformation. In my opinion such a problem is better addressed by \"Color Segmentation\" techniques. You could achieve \"Color segmentation\" by k-means clustering.</p>\n\n<p>See reference example from MathWorks site.</p>\n\n<p><a href=\"https://www.mathworks.com/examples/image/mw/images-ex71219044-color-based-segmentation-using-k-means-clustering\" rel=\"nofollow noreferrer\">https://www.mathworks.com/examples/image/mw/images-ex71219044-color-based-segmentation-using-k-means-clustering</a></p>\n\n<p><strong>Original picture in colours.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/EcHkr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EcHkr.png\" alt=\"Picture with colours\"></a></p>\n\n<p><strong>After converting to monochrome using k-means clustering</strong>\n<a href=\"https://i.stack.imgur.com/VaLea.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VaLea.png\" alt=\"Picture after converting to monochrome using k-means clustering\"></a></p>\n\n<p><strong>How does this work?</strong></p>\n\n<p>Collect all pixel values from entire image. From an image which is W pixels wide and H pixels high, you will get W *H color values. Now, using k-means algorithm create 2 clusters (or bins) and throw the colours into the appropriate \"bins\". The 2 clusters represent your black and white shades. </p>\n\n<p><strong>Youtube video demonstrating image segmentation using k-means?</strong>\n<a href=\"https://www.youtube.com/watch?v=yR7k19YBqiw\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=yR7k19YBqiw</a></p>\n\n<p><strong>Challenges with this method</strong></p>\n\n<p>The k-means clustering algorithm is susceptible to outliers. A few random pixels with a color whose RGB distance is far away from the rest of the crowd could easily skew the centroids to produce unexpected results.</p>\n"
},
{
"answer_id": 69980882,
"author": "Myndex",
"author_id": 10315269,
"author_profile": "https://Stackoverflow.com/users/10315269",
"pm_score": 1,
"selected": false,
"text": "<p>Just to point out in the self-selected answer, you have to <em>LINEARIZE</em> the sRGB values before you can apply the coefficients. This means removing the transfer curve.</p>\n<p>To remove the power curve, divide the 8 bit R G and B channels by 255.0, then either use the <a href=\"https://www.myndex.com/WEB/LuminanceContrast\" rel=\"nofollow noreferrer\">sRGB piecewise transform</a>, which is recommended for image procesing, OR you can cheat and raise each channel to the power of 2.2.</p>\n<p>Only after linearizing can you apply the coefficients shown, (which also are not exactly correct in the selected answer).</p>\n<p>The standard is <strong>0.2126 0.7152</strong> and <strong>0.0722</strong>. Multiply each channel by its coefficient and sum them together for Y, the luminance. Then re-apply the gamma to Y and multiply by 255, then copy to all three channels, and boom you have a greyscale (monochrome) image.</p>\n<p>Here it is all at once in one simple line:</p>\n<pre class=\"lang-JS prettyprint-override\"><code>// Andy's Easy Greyscale in one line.\n// Send it sR sG sB channels as 8 bit ints, and\n// it returns three channels sRgrey sGgrey sBgrey\n// as 8 bit ints that display glorious grey.\n\n\n sRgrey = sGgrey = sBgrey = Math.min(Math.pow((Math.pow(sR/255.0,2.2)*0.2126+Math.pow(sG/255.0,2.2)*0.7152+Math.pow(sB/255.0,2.2)*0.0722),0.454545)*255),255);\n</code></pre>\n<p>And that's it. Unless you have to parse hex strings....</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | How do I convert the RGB values of a pixel to a single monochrome value? | I found one possible solution in the [Color FAQ](http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html). The *luminance component* Y (from the *CIE XYZ system*) captures what is most perceived by humans as color in one channel. So, use those coefficients:
```
mono = (0.2125 * color.r) + (0.7154 * color.g) + (0.0721 * color.b);
``` |
14,350 | <p>I have a Flex swf hosted at <a href="http://www.a.com/a.swf" rel="nofollow noreferrer">http://www.a.com/a.swf</a>.
I have a flash code on another doamin that tries loading the SWF:</p>
<pre><code>_loader = new Loader();
var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf");
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish);
_loader.load(req);
</code></pre>
<p>On the onLoaderFinish event I try to load classes from the remote SWF and create them:</p>
<pre><code>_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class
</code></pre>
<p>When this code runs I get the following exception</p>
<pre><code>SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf.
at flash.display::LoaderInfo/get applicationDomain()
at NuconomyLoader/onLoaderFinish()
</code></pre>
<p>Is there any way to get this code working?</p>
| [
{
"answer_id": 14384,
"author": "Rytmis",
"author_id": 266,
"author_profile": "https://Stackoverflow.com/users/266",
"pm_score": 0,
"selected": false,
"text": "<p>Mayhaps <a href=\"http://livedocs.adobe.com/flex/15/flex_docs_en/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Flex_Documentation&file=00001750.htm\" rel=\"nofollow noreferrer\" title=\"Flex Documentation: System.Security.allowDomain\">System.Security.allowDomain</a> is what you need?</p>\n"
},
{
"answer_id": 14404,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": true,
"text": "<p>This is all described in <a href=\"http://livedocs.adobe.com/flex/3/progAS_flex3.pdf\" rel=\"nofollow noreferrer\">The Adobe Flex 3 Programming ActionScript 3 PDF</a> on page 550 (Chapter 27: Flash Player Security / Cross-scripting):</p>\n\n<blockquote>\n <p>If two SWF files written with ActionScript 3.0 are served from different domains—for example, <a href=\"http://siteA.com/swfA.swf\" rel=\"nofollow noreferrer\">http://siteA.com/swfA.swf</a> and <a href=\"http://siteB.com/swfB.swf\" rel=\"nofollow noreferrer\">http://siteB.com/swfB.swf</a>—then, by default, Flash Player does not allow swfA.swf to script swfB.swf, nor swfB.swf to script swfA.swf. A SWF file gives permission to SWF files from other domains by calling Security.allowDomain(). By calling Security.allowDomain(\"siteA.com\"), swfB.swf gives SWF files from siteA.com permission to script it.</p>\n</blockquote>\n\n<p>It goes on in some more detail, with diagrams and all.</p>\n"
},
{
"answer_id": 14409,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need a crossdomain.xml policy file on the server that has the file you load, it should look a something like this:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<!-- http://www.foo.com/crossdomain.xml -->\n<cross-domain-policy>\n <allow-access-from domain=\"www.friendOfFoo.com\" />\n <allow-access-from domain=\"*.foo.com\" />\n <allow-access-from domain=\"105.216.0.40\" />\n</cross-domain-policy>\n</code></pre>\n\n<p>Put it as crossdomain.xml in the root of the domain you're loading from.</p>\n\n<p>Also you need to set the loader to read this file as such:</p>\n\n<pre><code>var loaderContext:LoaderContext = new LoaderContext();\nloaderContext.checkPolicyFile = true;\n\nvar loader:Loader = new Loader();\nloader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );\nloader.load( new URLRequest( \"http://my.domain.com/image.png\" ), loaderContext );\n</code></pre>\n\n<p>code sample yoinked from <a href=\"http://blog.log2e.com/2008/08/15/when-a-cross-domain-policy-file-is-not-enough/\" rel=\"nofollow noreferrer\">http://blog.log2e.com/2008/08/15/when-a-cross-domain-policy-file-is-not-enough/</a></p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1228206/"
] | I have a Flex swf hosted at <http://www.a.com/a.swf>.
I have a flash code on another doamin that tries loading the SWF:
```
_loader = new Loader();
var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf");
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish);
_loader.load(req);
```
On the onLoaderFinish event I try to load classes from the remote SWF and create them:
```
_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class
```
When this code runs I get the following exception
```
SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf.
at flash.display::LoaderInfo/get applicationDomain()
at NuconomyLoader/onLoaderFinish()
```
Is there any way to get this code working? | This is all described in [The Adobe Flex 3 Programming ActionScript 3 PDF](http://livedocs.adobe.com/flex/3/progAS_flex3.pdf) on page 550 (Chapter 27: Flash Player Security / Cross-scripting):
>
> If two SWF files written with ActionScript 3.0 are served from different domains—for example, <http://siteA.com/swfA.swf> and <http://siteB.com/swfB.swf>—then, by default, Flash Player does not allow swfA.swf to script swfB.swf, nor swfB.swf to script swfA.swf. A SWF file gives permission to SWF files from other domains by calling Security.allowDomain(). By calling Security.allowDomain("siteA.com"), swfB.swf gives SWF files from siteA.com permission to script it.
>
>
>
It goes on in some more detail, with diagrams and all. |
14,373 | <p>I am converting from existing CVS repository to SVN repository. CVS repository has few brances and I'd like to rename branches while converting.</p>
<p>Wanted conversion is like this:</p>
<pre><code>CVS branch SVN branch
HEAD -> branches/branchX
branchA -> trunk
branchB -> branches/branchB
branchC -> branches/branchC
</code></pre>
<p>That is, CVS HEAD becomes a normal branch and CVS branchA becomes SVN trunk.</p>
<p>Both CVS and SVN repositories will be on same linux machine.</p>
<p>How could this be done? </p>
<p>Also conversion where CVS branchA becomes SVN trunk and all other CVS branches are ignored might be enough.</p>
| [
{
"answer_id": 14382,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 1,
"selected": false,
"text": "<p>Subversion branches are directories, so you could just move the branches after the import has finished and no history will be lost.</p>\n"
},
{
"answer_id": 14383,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>It's been a while since I've done a CVS -> SVN conversion, and probably even longer since I did one with a nontrivial branch structure. Since SVN can move around directory trees fairly easily, you could do the whole conversion first, then sort out the trunk/branches structure entirely within SVN later.</p>\n\n<p>If you do get to that point and are moving around whole directory trees within SVN, it's probably best if you commit after every tree rename/move step. Just something to keep in mind.</p>\n"
},
{
"answer_id": 14405,
"author": "Juha Syrjälä",
"author_id": 1431,
"author_profile": "https://Stackoverflow.com/users/1431",
"pm_score": 0,
"selected": false,
"text": "<p>I am especially interested in preserving commit history. If I rename and move branches around in SVN after the conversion, will the history be preserved?</p>\n"
},
{
"answer_id": 14411,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 4,
"selected": true,
"text": "<blockquote>I am especially interested in preserving commit history. If I rename and move branches around in SVN after the conversion, will the history be preserved?</blockquote>\n\n<p>Yes. Subversion also keeps track of changes to the directory structure, and all version history is preserved even if a file is moved in the tree. </p>\n\n<p>I recommend converting the repository with <a href=\"http://cvs2svn.tigris.org/\" rel=\"noreferrer\">cvs2svn</a>, including branches and tags. Once the repository is in Subversion you can move the branches and tags around as you wish. This also keeps the history of the actual tags and branches being renamed, which may be interesting in a historical context later.</p>\n"
},
{
"answer_id": 129432,
"author": "Matthew Jaskula",
"author_id": 4356,
"author_profile": "https://Stackoverflow.com/users/4356",
"pm_score": 1,
"selected": false,
"text": "<p>Some additional information to support the accepted answer:</p>\n\n<p>cvs2svn does not allow conversion of from trunk to a branch or the branch to trunk</p>\n\n<p>so moving things once you're converted to svn is the best way to go.</p>\n"
},
{
"answer_id": 211627,
"author": "mhagger",
"author_id": 24478,
"author_profile": "https://Stackoverflow.com/users/24478",
"pm_score": 1,
"selected": false,
"text": "<p>It is possible to move the trunk and branch directories after the conversion, but this would require an explicit post-conversion SVN commit that will remain in your SVN history, making history exploration a bit more complicated.</p>\n\n<p>But you can indeed tell cvs2svn to store the trunk and branches to the SVN paths that you want by using the <code>--symbol-hints=symbol-hints.txt</code> command-line option or (if you are using an options file for your conversion) the <code>SymbolHintsFileRule('symbol-hints.txt')</code> symbol strategy rule, where <code>symbol-hints.txt</code> is a file containing lines like the following:</p>\n\n<pre><code>. .trunk. trunk branches/branchX .\n. branchX branch trunk .\n</code></pre>\n\n<p>Please note that some commit messages that are autogenerated by cvs2svn (for example, for the creation of the branch) will mention the original branch name.</p>\n"
},
{
"answer_id": 338341,
"author": "Ed Thomas",
"author_id": 8256,
"author_profile": "https://Stackoverflow.com/users/8256",
"pm_score": 1,
"selected": false,
"text": "<p>Although moving around branches after the conversion is done is possible, it may be better to setup the cvs2svn configuration file to specify exactly the name you want for each of your existing branches. One of the benefits of this is that FishEye will understand the output a lot better.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
] | I am converting from existing CVS repository to SVN repository. CVS repository has few brances and I'd like to rename branches while converting.
Wanted conversion is like this:
```
CVS branch SVN branch
HEAD -> branches/branchX
branchA -> trunk
branchB -> branches/branchB
branchC -> branches/branchC
```
That is, CVS HEAD becomes a normal branch and CVS branchA becomes SVN trunk.
Both CVS and SVN repositories will be on same linux machine.
How could this be done?
Also conversion where CVS branchA becomes SVN trunk and all other CVS branches are ignored might be enough. | > I am especially interested in preserving commit history. If I rename and move branches around in SVN after the conversion, will the history be preserved?
Yes. Subversion also keeps track of changes to the directory structure, and all version history is preserved even if a file is moved in the tree.
I recommend converting the repository with [cvs2svn](http://cvs2svn.tigris.org/), including branches and tags. Once the repository is in Subversion you can move the branches and tags around as you wish. This also keeps the history of the actual tags and branches being renamed, which may be interesting in a historical context later. |
14,375 | <p>I'm using repository pattern with LINQ, have IRepository.DeleteOnSubmit(T Entity). It works fine, but when my entity class has interface, like this: </p>
<pre><code>public interface IEntity { int ID {get;set;} }
public partial class MyEntity: IEntity {
public int ID {
get { return this.IDfield; }
set { this.IDfield=value; }
}
}
</code></pre>
<p>and then trying to delete some entity like this: </p>
<pre><code>IEntity ie=repository.GetByID(1);
repoitory.DeleteOnSubmit(ie);
</code></pre>
<p>throws<br>
The member 'IEntity.ID' has no supported translation to SQL. </p>
<p>fetching data from DB works, but delete and insert doesn't. How to use interface against DataContext?</p>
<hr>
<p>Here it is:<br>
Exception message:
The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL. </p>
<p>Code: </p>
<pre><code>var d = repContent.GetAll().Where(x => x.idContent.Equals(idContent));
foreach (var tagConnect in d) <- error line
{
repContet.DeleteOnSubmit(tagConnect);
</code></pre>
<p>(it gets all tags from DB, and deletes them)</p>
<p>And stack trace: </p>
<pre><code>[NotSupportedException: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.]
System.Data.Linq.SqlClient.Visitor.VisitMember(SqlMember m) +621763
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +541
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.Visitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +196
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect select) +46
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlProvider.BuildQuery( ...
</code></pre>
<p>When I try do decorate partial class:</p>
<pre><code>[Column(Storage = "_idEvent", DbType = "Int NOT NULL", IsPrimaryKey = true)]
public int idContent
{ get { return this.idEvent; } set { this.idEvent=value; } }
</code></pre>
<p>it throws error "Invalid column name 'idContent'."</p>
| [
{
"answer_id": 14381,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>using System.Data.Linq.Mapping;\n\npublic partial class MyEntity: IEntity \n { [Column(Storage=\"IDfield\", DbType=\"int not null\", IsPrimaryKey=true)]\n public int ID \n { \n get { return this.IDfield; } \n set { this.IDfield=value; } \n } \n }\n</code></pre>\n"
},
{
"answer_id": 2069586,
"author": "Frank Tzanabetis",
"author_id": 251210,
"author_profile": "https://Stackoverflow.com/users/251210",
"pm_score": 2,
"selected": false,
"text": "<p>This works for me - </p>\n\n<pre><code>public partial class MyEntity: IEntity \n { [Column(Name = \"IDfield\", Storage = \"_IDfield\", IsDbGenerated = true)]\n public int ID \n { \n get { return this.IDfield; } \n set { this.IDfield=value; } \n } \n }\n</code></pre>\n"
},
{
"answer_id": 2070758,
"author": "jeroenh",
"author_id": 20047,
"author_profile": "https://Stackoverflow.com/users/20047",
"pm_score": 0,
"selected": false,
"text": "<p>For translating your LINQ query to actual SQL, Linq2SQL inspects the expression you give it. The problem is that you have not supplied enough information for L2S to be able to translate the \"ID\" property to the actual DB column name. You can achieve what you want by making sure that L2S can map \"ID\" to \"IDField\". </p>\n\n<p>This should be possible using the approach provided in answers. </p>\n\n<p>If you use the designer, you can also simply rename the class property \"IDField\" to \"ID\", with the added benefit that you won't have to explicitly implement the \"ID\" property in your partial class anymore, i.e. the partial class definition for MyEntity simply becomes:</p>\n\n<pre><code>public partial class MyEntity: IEntity \n{ \n}\n</code></pre>\n"
},
{
"answer_id": 27485863,
"author": "jahu",
"author_id": 2123652,
"author_profile": "https://Stackoverflow.com/users/2123652",
"pm_score": 3,
"selected": false,
"text": "<p>It appears Microsoft dropped support for <code>==</code> operator in interfaces when using linq-to-sql in MVC4 (or maybe it was never supported). You can however use <code>i.ID.Equals(someId)</code> in place of the <code>==</code> operator.</p>\n\n<p>Casting <code>IQueryable</code> to <code>IEnumerable</code> works but <strong>should not be used!</strong> The reason is: <code>IQueryable</code> has funky implementation of <code>IEnumerable</code>. Whatever linq method you'll use on a <code>IQueryable</code> through the <code>IEnumerable</code> interface will cause the query to be executed first, have all the results fetched to the memory from the DB and eventually running the method localy on the data (normally those methods would be translated to SQL and executed in the DB). Imagine trying to get a single row from a table containing billion rows, fetching all of them only to pick one (and it gets much worse with careless casting of <code>IQueryable</code> to <code>IEnumerable</code> and lazy loading related data).</p>\n\n<p>Apparently Linq has no problem using <code>==</code> operator with interfaces on local data (so only <code>IQueryable</code> is affected) and also with Entity Frameworks (or so I heard).</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1407/"
] | I'm using repository pattern with LINQ, have IRepository.DeleteOnSubmit(T Entity). It works fine, but when my entity class has interface, like this:
```
public interface IEntity { int ID {get;set;} }
public partial class MyEntity: IEntity {
public int ID {
get { return this.IDfield; }
set { this.IDfield=value; }
}
}
```
and then trying to delete some entity like this:
```
IEntity ie=repository.GetByID(1);
repoitory.DeleteOnSubmit(ie);
```
throws
The member 'IEntity.ID' has no supported translation to SQL.
fetching data from DB works, but delete and insert doesn't. How to use interface against DataContext?
---
Here it is:
Exception message:
The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.
Code:
```
var d = repContent.GetAll().Where(x => x.idContent.Equals(idContent));
foreach (var tagConnect in d) <- error line
{
repContet.DeleteOnSubmit(tagConnect);
```
(it gets all tags from DB, and deletes them)
And stack trace:
```
[NotSupportedException: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.]
System.Data.Linq.SqlClient.Visitor.VisitMember(SqlMember m) +621763
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +541
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.Visitor.VisitBinaryOperator(SqlBinary bo) +18
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +196
System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8
System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect select) +46
System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20
System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024
System.Data.Linq.SqlClient.SqlProvider.BuildQuery( ...
```
When I try do decorate partial class:
```
[Column(Storage = "_idEvent", DbType = "Int NOT NULL", IsPrimaryKey = true)]
public int idContent
{ get { return this.idEvent; } set { this.idEvent=value; } }
```
it throws error "Invalid column name 'idContent'." | It appears Microsoft dropped support for `==` operator in interfaces when using linq-to-sql in MVC4 (or maybe it was never supported). You can however use `i.ID.Equals(someId)` in place of the `==` operator.
Casting `IQueryable` to `IEnumerable` works but **should not be used!** The reason is: `IQueryable` has funky implementation of `IEnumerable`. Whatever linq method you'll use on a `IQueryable` through the `IEnumerable` interface will cause the query to be executed first, have all the results fetched to the memory from the DB and eventually running the method localy on the data (normally those methods would be translated to SQL and executed in the DB). Imagine trying to get a single row from a table containing billion rows, fetching all of them only to pick one (and it gets much worse with careless casting of `IQueryable` to `IEnumerable` and lazy loading related data).
Apparently Linq has no problem using `==` operator with interfaces on local data (so only `IQueryable` is affected) and also with Entity Frameworks (or so I heard). |
14,378 | <p>I want to use the mouse scrollwheel in my OpenGL GLUT program to zoom in and out of a scene? How do I do that?</p>
| [
{
"answer_id": 14379,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 6,
"selected": true,
"text": "<p>Note that venerable <a href=\"http://www.xmission.com/~nate/glut.html\" rel=\"noreferrer\">Nate Robin's GLUT</a> library doesn't support the scrollwheel. But, later implementations of GLUT like <a href=\"http://freeglut.sourceforge.net/\" rel=\"noreferrer\">FreeGLUT</a> do.</p>\n\n<p>Using the scroll wheel in FreeGLUT is dead simple. Here is how:</p>\n\n<p>Declare a callback function that shall be called whenever the scroll wheel is scrolled. This is the prototype:</p>\n\n<pre><code>void mouseWheel(int, int, int, int);\n</code></pre>\n\n<p>Register the callback with the (Free)GLUT function <strong>glutMouseWheelFunc()</strong>.</p>\n\n<pre><code>glutMouseWheelFunc(mouseWheel);\n</code></pre>\n\n<p>Define the callback function. The second parameter gives the direction of the scroll. Values of +1 is forward, -1 is backward.</p>\n\n<pre><code>void mouseWheel(int button, int dir, int x, int y)\n{\n if (dir > 0)\n {\n // Zoom in\n }\n else\n {\n // Zoom out\n }\n\n return;\n}\n</code></pre>\n\n<p>That's it!</p>\n"
},
{
"answer_id": 7885789,
"author": "BentFX",
"author_id": 710913,
"author_profile": "https://Stackoverflow.com/users/710913",
"pm_score": 5,
"selected": false,
"text": "<p>Freeglut's glutMouseWheelFunc callback is version dependant and not reliable in X. Use standard mouse function and test for buttons 3 and 4.</p>\n\n<p>The OpenGlut notes on glutMouseWheelFunc state:</p>\n\n<blockquote>\n <p>Due to lack of information about the mouse, it is impossible to\n implement this correctly on X at this time. Use of this function\n limits the portability of your application. (This feature does work on\n X, just not reliably.) You are encouraged to use the standard,\n reliable mouse-button reporting, rather than wheel events.</p>\n</blockquote>\n\n<p>Using standard GLUT mouse reporting:</p>\n\n<pre><code>#include <GL/glut.h>\n\n<snip...>\n\nvoid mouse(int button, int state, int x, int y)\n{\n // Wheel reports as button 3(scroll up) and button 4(scroll down)\n if ((button == 3) || (button == 4)) // It's a wheel event\n {\n // Each wheel event reports like a button click, GLUT_DOWN then GLUT_UP\n if (state == GLUT_UP) return; // Disregard redundant GLUT_UP events\n printf(\"Scroll %s At %d %d\\n\", (button == 3) ? \"Up\" : \"Down\", x, y);\n }else{ // normal button event\n printf(\"Button %s At %d %d\\n\", (state == GLUT_DOWN) ? \"Down\" : \"Up\", x, y);\n }\n}\n\n<snip...>\n\nglutMouseFunc(mouse);\n</code></pre>\n\n<p>As the OP stated, it is \"dead simple\". He was just wrong.</p>\n"
},
{
"answer_id": 53304965,
"author": "StackAttack",
"author_id": 4513646,
"author_profile": "https://Stackoverflow.com/users/4513646",
"pm_score": 2,
"selected": false,
"text": "<p>observe case 3 and 4 in the switch statement below in the mouseClick callback</p>\n\n<pre><code>glutMouseFunc(mouseClick);\n</code></pre>\n\n<p>... </p>\n\n<pre><code>void mouseClick(int btn, int state, int x, int y) {\n if (state == GLUT_DOWN) {\n switch(btn) {\n case GLUT_LEFT_BUTTON:\n std::cout << \"left click at: (\" << x << \", \" << y << \")\\n\";\n break;\n case GLUT_RIGHT_BUTTON:\n std::cout << \"right click at: (\" << x << \", \" << y << \")\\n\";\n break;\n case GLUT_MIDDLE_BUTTON:\n std::cout << \"middle click at: (\" << x << \", \" << y << \")\\n\";\n break;\n case 3: //mouse wheel scrolls\n std::cout << \"mouse wheel scroll up\\n\";\n break;\n case 4:\n std::cout << \"mouse wheel scroll down\\n\";\n break;\n default:\n break;\n }\n }\n glutPostRedisplay();\n}\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | I want to use the mouse scrollwheel in my OpenGL GLUT program to zoom in and out of a scene? How do I do that? | Note that venerable [Nate Robin's GLUT](http://www.xmission.com/~nate/glut.html) library doesn't support the scrollwheel. But, later implementations of GLUT like [FreeGLUT](http://freeglut.sourceforge.net/) do.
Using the scroll wheel in FreeGLUT is dead simple. Here is how:
Declare a callback function that shall be called whenever the scroll wheel is scrolled. This is the prototype:
```
void mouseWheel(int, int, int, int);
```
Register the callback with the (Free)GLUT function **glutMouseWheelFunc()**.
```
glutMouseWheelFunc(mouseWheel);
```
Define the callback function. The second parameter gives the direction of the scroll. Values of +1 is forward, -1 is backward.
```
void mouseWheel(int button, int dir, int x, int y)
{
if (dir > 0)
{
// Zoom in
}
else
{
// Zoom out
}
return;
}
```
That's it! |
14,386 | <p>With the <em>Visual Studio 2005 C++ compiler</em>, I get the following warning when my code uses the <code>fopen()</code> and such calls:</p>
<pre class="lang-none prettyprint-override"><code>1>foo.cpp(5) : warning C4996: 'fopen' was declared deprecated
1> c:\program files\microsoft visual studio 8\vc\include\stdio.h(234) : see declaration of 'fopen'
1> Message: 'This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'
</code></pre>
<p>How do I prevent this?</p>
| [
{
"answer_id": 14387,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 8,
"selected": true,
"text": "<p>It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like <strong>fopen_s</strong>), you need to place a definition of <strong>_CRT_SECURE_NO_DEPRECATE</strong> before your included header files. For example:</p>\n\n<pre><code>#define _CRT_SECURE_NO_DEPRECATE\n#include <stdio.h>\n</code></pre>\n\n<p>The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add <strong>_CRT_SECURE_NO_DEPRECATE</strong> to <em>Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions</em>.</p>\n"
},
{
"answer_id": 14506,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 5,
"selected": false,
"text": "<p>Well you could add a:</p>\n\n<pre><code>#pragma warning (disable : 4996)\n</code></pre>\n\n<p>before you use fopen, but have you considered using fopen_s as the warning suggests? It returns an error code allowing you to check the result of the function call. </p>\n\n<p>The problem with just disabling deprecated function warnings is that Microsoft may remove the function in question in a later version of the CRT, breaking your code (as stated below in the comments, this won't happen in this instance with fopen because it's part of the C & C++ ISO standards).</p>\n"
},
{
"answer_id": 91698,
"author": "Joseph Holsten",
"author_id": 16981,
"author_profile": "https://Stackoverflow.com/users/16981",
"pm_score": 2,
"selected": false,
"text": "<p>Consider using a portability library like <a href=\"http://www.gtk.org/\" rel=\"nofollow noreferrer\">glib</a> or the <a href=\"http://apr.apache.org/\" rel=\"nofollow noreferrer\">apache portable runtime</a>. These usually provide safe, portable alternatives to calls like these. It's a good thing too, because these insecure calls are deprecated in most modern environments.</p>\n"
},
{
"answer_id": 284698,
"author": "tragomaskhalos",
"author_id": 31140,
"author_profile": "https://Stackoverflow.com/users/31140",
"pm_score": 4,
"selected": false,
"text": "<p>This is just Microsoft being cheeky. \"Deprecated\" implies a language feature that may not be provided in future versions of the standard language / standard libraries, as decreed by the standards committee. It does not, or should not mean, \"we, unilaterally, don't think you should use it\", no matter how well-founded that advice is.</p>\n"
},
{
"answer_id": 8069439,
"author": "Denys Yurchenko",
"author_id": 1038233,
"author_profile": "https://Stackoverflow.com/users/1038233",
"pm_score": 3,
"selected": false,
"text": "<p>If you code is intended for a different OS (like Mac OS X, Linux) you may use following:</p>\n\n<pre><code>#ifdef _WIN32\n#define _CRT_SECURE_NO_DEPRECATE\n#endif\n</code></pre>\n"
},
{
"answer_id": 27709586,
"author": "Karthik_elan",
"author_id": 3220295,
"author_profile": "https://Stackoverflow.com/users/3220295",
"pm_score": 0,
"selected": false,
"text": "<p>I also got the same problem. When I try to add the opencv library</p>\n\n<pre><code>#include <opencv\\cv.h>\n</code></pre>\n\n<p>I got not a warning but an error.</p>\n\n<pre><code>error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\\program files (x86)\\opencv\\build\\include\\opencv2\\flann\\logger.h \n</code></pre>\n\n<p>I also used the preprocessor directives as mentioned. But that didn't solve the problem.</p>\n\n<p>I solved it by doing as follows:</p>\n\n<ul>\n<li><strong>Go to Properties -> C/C++ -> Precompiled Headers -> Choose Not Using Precompiled Headers in Precompiled Header.</strong></li>\n</ul>\n"
},
{
"answer_id": 28692707,
"author": "JTIM",
"author_id": 2076775,
"author_profile": "https://Stackoverflow.com/users/2076775",
"pm_score": 1,
"selected": false,
"text": "<p>If you want it to be used on many platforms, you could as commented use defines like:</p>\n\n<pre><code>#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) \\\n || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) \n\n errno_t err = fopen_s(&stream,name, \"w\");\n\n#endif\n\n#if defined(unix) || defined(__unix) || defined(__unix__) \\\n || defined(linux) || defined(__linux) || defined(__linux__) \\\n || defined(sun) || defined(__sun) \\\n || defined(BSD) || defined(__OpenBSD__) || defined(__NetBSD__) \\\n || defined(__FreeBSD__) || defined __DragonFly__ \\\n || defined(sgi) || defined(__sgi) \\\n || defined(__MACOSX__) || defined(__APPLE__) \\\n || defined(__CYGWIN__) \n\n stream = fopen(name, \"w\");\n\n#endif\n</code></pre>\n"
},
{
"answer_id": 35191511,
"author": "riderBill",
"author_id": 4079867,
"author_profile": "https://Stackoverflow.com/users/4079867",
"pm_score": 1,
"selected": false,
"text": "<p>Many of Microsoft's secure functions, including fopen_s(), are part of C11, so they should be portable now. You should realize that the secure functions differ in exception behaviors and sometimes in return values. Additionally you need to be aware that while these functions are standardized, it's an <em>optional</em> part of the standard (Annex K) that at least glibc (default on Linux) and FreeBSD's libc don't implement.</p>\n\n<p>However, I fought this problem for a few years. I posted a larger set of conversion macros <a href=\"https://stackoverflow.com/questions/6234682/need-a-define-for-visual-studio-versions-that-include-secure-string-functions/35191283#35191283\">here.</a>, For your immediate problem, put the following code in an include file, and include it in your source code:</p>\n\n<pre><code>#pragma once\n#if !defined(FCN_S_MACROS_H)\n #define FCN_S_MACROS_H\n\n #include <cstdio>\n #include <string> // Need this for _stricmp\n using namespace std;\n\n // _MSC_VER = 1400 is MSVC 2005. _MSC_VER = 1600 (MSVC 2010) was the current\n // value when I wrote (some of) these macros.\n\n #if (defined(_MSC_VER) && (_MSC_VER >= 1400) )\n\n inline extern\n FILE* fcnSMacro_fopen_s(char *fname, char *mode)\n { FILE *fptr;\n fopen_s(&fptr, fname, mode);\n return fptr;\n }\n #define fopen(fname, mode) fcnSMacro_fopen_s((fname), (mode))\n\n #else\n #define fopen_s(fp, fmt, mode) *(fp)=fopen( (fmt), (mode))\n\n #endif //_MSC_VER\n\n#endif // FCN_S_MACROS_H\n</code></pre>\n\n<p>Of course this approach does not implement the expected exception behavior.</p>\n"
},
{
"answer_id": 42908405,
"author": "Marcelo Coronel",
"author_id": 7642855,
"author_profile": "https://Stackoverflow.com/users/7642855",
"pm_score": 1,
"selected": false,
"text": "<p>For those who are using Visual Studio 2017 version, it seems like the preprocessor definition required to run unsafe operations has changed. Use instead:</p>\n\n<pre><code>#define _CRT_SECURE_NO_WARNINGS\n</code></pre>\n\n<p>It will compile then.</p>\n"
},
{
"answer_id": 45114212,
"author": "Bryant",
"author_id": 7666772,
"author_profile": "https://Stackoverflow.com/users/7666772",
"pm_score": 3,
"selected": false,
"text": "<p>I'am using VisualStdio 2008.\nIn this case I often set <strong><code>Preprocessor Definitions</code></strong></p>\n\n<blockquote>\n <p><strong>Menu \\ Project \\ [ProjectName] Properties... Alt+F7</strong></p>\n</blockquote>\n\n<p>If click this menu or press Alt + F7 in project window, you can see <strong>\"Property Pages\"</strong> window.</p>\n\n<p>Then see menu on left of window.</p>\n\n<blockquote>\n <p><strong>Configuration Properties \\ C/C++ \\ Preprocessor</strong></p>\n</blockquote>\n\n<p>Then add <strong><code>_CRT_SECURE_NO_WARNINGS</code></strong> to <strong>\\ Preprocessor Definitions</strong>.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | With the *Visual Studio 2005 C++ compiler*, I get the following warning when my code uses the `fopen()` and such calls:
```none
1>foo.cpp(5) : warning C4996: 'fopen' was declared deprecated
1> c:\program files\microsoft visual studio 8\vc\include\stdio.h(234) : see declaration of 'fopen'
1> Message: 'This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.'
```
How do I prevent this? | It looks like Microsoft has deprecated lots of calls which use buffers to improve code security. However, the solutions they're providing aren't portable. Anyway, if you aren't interested in using the secure version of their calls (like **fopen\_s**), you need to place a definition of **\_CRT\_SECURE\_NO\_DEPRECATE** before your included header files. For example:
```
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
```
The preprocessor directive can also be added to your project settings to effect it on all the files under the project. To do this add **\_CRT\_SECURE\_NO\_DEPRECATE** to *Project Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions*. |
14,389 | <p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p>
<p>The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within <code>[a-zA-Z0-9'\-]</code>)</p>
<p>How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..</p>
<pre><code>config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """
config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars'])
config['name_parse'] = [
# foo_[s01]_[e01]
re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])),
# foo.1x09*
re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.s01.e01, foo.s01_e01
re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.103*
re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.0103*
re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
]
</code></pre>
| [
{
"answer_id": 14391,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<p>Use a subrange of <code>[\\u0000-\\uFFFF]</code> for what you want.</p>\n\n<p>You can also use the <code>re.UNICODE</code> compile flag. <a href=\"http://docs.python.org/lib/re-syntax.html\" rel=\"nofollow noreferrer\">The docs</a> say that if <code>UNICODE</code> is set, <code>\\w</code> will match the characters <code>[0-9_]</code> plus whatever is classified as alphanumeric in the Unicode character properties database. </p>\n\n<p>See also <a href=\"http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html\" rel=\"nofollow noreferrer\">http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html</a>.</p>\n"
},
{
"answer_id": 14399,
"author": "grapefrukt",
"author_id": 914,
"author_profile": "https://Stackoverflow.com/users/914",
"pm_score": 0,
"selected": false,
"text": "<p>\\X seems to be available as a generic word-character in some languages, it allows you to match a single character disregarding of how many bytes it takes up. Might be useful.</p>\n"
},
{
"answer_id": 14420,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 2,
"selected": false,
"text": "<p>In Mastering Regular Expressions from Jeffrey Friedl (great book) it is mentioned that you could use \\p{Letter} which will match unicode stuff that is considered a letter.</p>\n"
},
{
"answer_id": 5519872,
"author": "MRAB",
"author_id": 688213,
"author_profile": "https://Stackoverflow.com/users/688213",
"pm_score": 3,
"selected": false,
"text": "<p>Python's re module doesn't support \\p{Letter} or \\X. However, the <a href=\"http://pypi.python.org/pypi/regex\" rel=\"noreferrer\">new regex implementation on PyPI</a> does.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] | I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)
The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within `[a-zA-Z0-9'\-]`)
How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..
```
config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&*()_+=-[]{}"'.,<>`~? """
config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars'])
config['name_parse'] = [
# foo_[s01]_[e01]
re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])),
# foo.1x09*
re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.s01.e01, foo.s01_e01
re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.103*
re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
# foo.0103*
re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])),
]
``` | Use a subrange of `[\u0000-\uFFFF]` for what you want.
You can also use the `re.UNICODE` compile flag. [The docs](http://docs.python.org/lib/re-syntax.html) say that if `UNICODE` is set, `\w` will match the characters `[0-9_]` plus whatever is classified as alphanumeric in the Unicode character properties database.
See also <http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-05/2560.html>. |
14,402 | <p>In my simple OpenGL program I get the following error about exit redefinition:</p>
<pre><code>1>c:\program files\microsoft visual studio 8\vc\include\stdlib.h(406) : error C2381: 'exit' : redefinition; __declspec(noreturn) differs
1> c:\program files\microsoft visual studio 8\vc\platformsdk\include\gl\glut.h(146) : see declaration of 'exit'
</code></pre>
<p>I'm using Nate Robins' <a href="http://www.xmission.com/~nate/glut.html" rel="noreferrer">GLUT for Win32</a> and get this error with Visual Studio 2005 or Visual C++ 2005 (Express Edition). What is the cause of this error and how do I fix it?</p>
| [
{
"answer_id": 14403,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 7,
"selected": true,
"text": "<p><strong>Cause:</strong></p>\n\n<p>The <strong>stdlib.h</strong> which ships with the recent versions of Visual Studio has a different (and conflicting) definition of the <strong>exit()</strong> function. It clashes with the definition in <strong>glut.h</strong>.</p>\n\n<p><strong>Solution:</strong></p>\n\n<p>Override the definition in glut.h with that in stdlib.h. Place the stdlib.h line above the glut.h line in your code.</p>\n\n<pre><code>#include <stdlib.h>\n#include <GL/glut.h>\n</code></pre>\n"
},
{
"answer_id": 1689566,
"author": "Alex",
"author_id": 205130,
"author_profile": "https://Stackoverflow.com/users/205130",
"pm_score": 4,
"selected": false,
"text": "<p>or this...\nTo fix the error, right click on the project name in the Solution Explorer tab and select Properties -> C/C++ -> Preprocessor -> Preprocessor definitions and append GLUT_BUILDING_LIB to the existing definitions, seperated by semicolons. </p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | In my simple OpenGL program I get the following error about exit redefinition:
```
1>c:\program files\microsoft visual studio 8\vc\include\stdlib.h(406) : error C2381: 'exit' : redefinition; __declspec(noreturn) differs
1> c:\program files\microsoft visual studio 8\vc\platformsdk\include\gl\glut.h(146) : see declaration of 'exit'
```
I'm using Nate Robins' [GLUT for Win32](http://www.xmission.com/~nate/glut.html) and get this error with Visual Studio 2005 or Visual C++ 2005 (Express Edition). What is the cause of this error and how do I fix it? | **Cause:**
The **stdlib.h** which ships with the recent versions of Visual Studio has a different (and conflicting) definition of the **exit()** function. It clashes with the definition in **glut.h**.
**Solution:**
Override the definition in glut.h with that in stdlib.h. Place the stdlib.h line above the glut.h line in your code.
```
#include <stdlib.h>
#include <GL/glut.h>
``` |
14,413 | <p>I want to use the functions exposed under the OpenGL extensions. I'm on Windows, how do I do this?</p>
| [
{
"answer_id": 14414,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 5,
"selected": true,
"text": "<p><strong>Easy solution</strong>: Use <a href=\"http://glew.sourceforge.net/\" rel=\"nofollow noreferrer\">GLEW</a>. See how <a href=\"https://stackoverflow.com/questions/17370/using-glew-to-use-opengl-extensions-under-windows\">here</a>.</p>\n\n<p><strong>Hard solution</strong>:\nIf you have a <strong>really strong reason</strong> not to use GLEW, here's how to achieve the same without it:</p>\n\n<p>Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the <a href=\"http://www.opengl.org/registry/\" rel=\"nofollow noreferrer\">OpenGL Extension Registry</a>.</p>\n\n<blockquote>\n <p>Example: I wish to use the capabilities of the <a href=\"http://oss.sgi.com/projects/ogl-sample/registry/EXT/framebuffer_object.txt\" rel=\"nofollow noreferrer\">EXT_framebuffer_object</a> extension. The APIs I wish to use from this extension are:</p>\n</blockquote>\n\n<pre><code>glGenFramebuffersEXT()\nglBindFramebufferEXT()\nglFramebufferTexture2DEXT()\nglCheckFramebufferStatusEXT()\nglDeleteFramebuffersEXT()\n</code></pre>\n\n<p>Check if your graphic card supports the extension you wish to use. If it does, then your work is almost done! Download and install the latest drivers and SDKs for your graphics card.</p>\n\n<blockquote>\n <p>Example: The graphics card in my PC is a <strong>NVIDIA 6600 GT</strong>. So, I visit the <a href=\"http://developer.nvidia.com/object/nvidia_opengl_specs.html\" rel=\"nofollow noreferrer\">NVIDIA OpenGL Extension Specifications</a> webpage and find that the <a href=\"http://www.nvidia.com/dev_content/nvopenglspecs/GL_EXT_framebuffer_object.txt\" rel=\"nofollow noreferrer\">EXT_framebuffer_object</a> extension is supported. I then download the latest <a href=\"http://developer.nvidia.com/object/sdk_home.html\" rel=\"nofollow noreferrer\">NVIDIA OpenGL SDK</a> and install it.</p>\n</blockquote>\n\n<p>Your graphic card manufacturer provides a <strong>glext.h</strong> header file (or a similarly named header file) with all the declarations needed to use the supported OpenGL extensions. (Note that not all extensions might be supported.) Either place this header file somewhere your compiler can pick it up or include its directory in your compiler's include directories list.</p>\n\n<p>Add a <code>#include <glext.h></code> line in your code to include the header file into your code.</p>\n\n<p>Open <strong><a href=\"http://oss.sgi.com/projects/ogl-sample/ABI/glext.h\" rel=\"nofollow noreferrer\">glext.h</a></strong>, find the API you wish to use and grab its corresponding <em>ugly-looking</em> declaration.</p>\n\n<blockquote>\n <p>Example: I search for the above framebuffer APIs and find their corresponding ugly-looking declarations:</p>\n</blockquote>\n\n<pre><code>typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); for GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);\n</code></pre>\n\n<p>All this means is that your header file has the API declaration in 2 forms. One is a wgl-like ugly function pointer declaration. The other is a sane looking function declaration.</p>\n\n<p>For each extension API you wish to use, add in your code declarations of the function name as a type of the ugly-looking string.</p>\n\n<blockquote>\n <p>Example:</p>\n</blockquote>\n\n<pre><code>PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT;\nPFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT;\nPFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT;\nPFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT;\nPFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;\n</code></pre>\n\n<p>Though it looks ugly, all we're doing is to declare function pointers of the type corresponding to the extension API.</p>\n\n<p>Initialize these function pointers with their rightful functions. These functions are exposed by the library or driver. We need to use <strong>wglGetProcAddress()</strong> function to do this.</p>\n\n<blockquote>\n <p>Example:</p>\n</blockquote>\n\n<pre><code>glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress(\"glGenFramebuffersEXT\");\nglBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress(\"glBindFramebufferEXT\");\nglFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress(\"glFramebufferTexture2DEXT\");\nglCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress(\"glCheckFramebufferStatusEXT\");\nglDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress(\"glDeleteFramebuffersEXT\");\n</code></pre>\n\n<p>Don't forget to check the function pointers for <em>NULL</em>. If by chance <strong>wglGetProcAddress()</strong> couldn't find the extension function, it would've initialized the pointer with NULL.</p>\n\n<blockquote>\n <p>Example:</p>\n</blockquote>\n\n<pre><code>if (NULL == glGenFramebuffersEXT || NULL == glBindFramebufferEXT || NULL == glFramebufferTexture2DEXT\n || NULL == glCheckFramebufferStatusEXT || NULL == glDeleteFramebuffersEXT)\n{\n // Extension functions not loaded!\n exit(1);\n}\n</code></pre>\n\n<p>That's it, we're done! You can now use these function pointers just as if the function calls existed.</p>\n\n<blockquote>\n <p>Example:</p>\n</blockquote>\n\n<pre><code>glGenFramebuffersEXT(1, &fbo);\nglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);\nglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorTex[0], 0);\n</code></pre>\n\n<p><strong>Reference:</strong> <a href=\"http://www.gamedev.net/reference/articles/article1929.asp\" rel=\"nofollow noreferrer\">Moving Beyond OpenGL 1.1 for Windows</a> by Dave Astle — The article is a bit dated, but has all the information you need to understand why this pathetic situation exists on Windows and how to get around it.</p>\n"
},
{
"answer_id": 17364,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 0,
"selected": false,
"text": "<p>@Kronikarz: From the looks of it, <strong>GLEW</strong> seems to be the way of the future. NVIDIA already ships it along with its <strong><a href=\"http://developer.nvidia.com/object/sdk_home.html\" rel=\"nofollow noreferrer\">OpenGL SDK</a></strong>. And its latest release was in 2007 compared to GLEE which was in 2006.</p>\n\n<p>But, the usage of both libraries looks almost the same to me. (GLEW has an <em>init()</em> which needs to be called before anything else though.) So, you don't need to switch unless you find some extension not being supported under GLEE.</p>\n"
},
{
"answer_id": 765306,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A 'Very strong reason' not to use GLEW might be that the library is not supported by your compiler/IDE. E.g: Borland C++ Builder.</p>\n\n<p>In that case, you might want to rebuild the library from source. If it works, great, otherwise manual extension loading isnt as bad as it is made to sound.</p>\n"
},
{
"answer_id": 9866471,
"author": "Steve Howard",
"author_id": 446649,
"author_profile": "https://Stackoverflow.com/users/446649",
"pm_score": 0,
"selected": false,
"text": "<p>GL3W is a public-domain script that creates a library which loads only core functionality for OpenGL 3/4. It can be found on github at:</p>\n\n<p><a href=\"https://github.com/skaslev/gl3w\" rel=\"nofollow\">https://github.com/skaslev/gl3w</a></p>\n\n<p>GL3W requires Python 2.6 to generate the libraries and headers for OpenGL; it does not require Python after that.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] | I want to use the functions exposed under the OpenGL extensions. I'm on Windows, how do I do this? | **Easy solution**: Use [GLEW](http://glew.sourceforge.net/). See how [here](https://stackoverflow.com/questions/17370/using-glew-to-use-opengl-extensions-under-windows).
**Hard solution**:
If you have a **really strong reason** not to use GLEW, here's how to achieve the same without it:
Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the [OpenGL Extension Registry](http://www.opengl.org/registry/).
>
> Example: I wish to use the capabilities of the [EXT\_framebuffer\_object](http://oss.sgi.com/projects/ogl-sample/registry/EXT/framebuffer_object.txt) extension. The APIs I wish to use from this extension are:
>
>
>
```
glGenFramebuffersEXT()
glBindFramebufferEXT()
glFramebufferTexture2DEXT()
glCheckFramebufferStatusEXT()
glDeleteFramebuffersEXT()
```
Check if your graphic card supports the extension you wish to use. If it does, then your work is almost done! Download and install the latest drivers and SDKs for your graphics card.
>
> Example: The graphics card in my PC is a **NVIDIA 6600 GT**. So, I visit the [NVIDIA OpenGL Extension Specifications](http://developer.nvidia.com/object/nvidia_opengl_specs.html) webpage and find that the [EXT\_framebuffer\_object](http://www.nvidia.com/dev_content/nvopenglspecs/GL_EXT_framebuffer_object.txt) extension is supported. I then download the latest [NVIDIA OpenGL SDK](http://developer.nvidia.com/object/sdk_home.html) and install it.
>
>
>
Your graphic card manufacturer provides a **glext.h** header file (or a similarly named header file) with all the declarations needed to use the supported OpenGL extensions. (Note that not all extensions might be supported.) Either place this header file somewhere your compiler can pick it up or include its directory in your compiler's include directories list.
Add a `#include <glext.h>` line in your code to include the header file into your code.
Open **[glext.h](http://oss.sgi.com/projects/ogl-sample/ABI/glext.h)**, find the API you wish to use and grab its corresponding *ugly-looking* declaration.
>
> Example: I search for the above framebuffer APIs and find their corresponding ugly-looking declarations:
>
>
>
```
typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); for GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);
```
All this means is that your header file has the API declaration in 2 forms. One is a wgl-like ugly function pointer declaration. The other is a sane looking function declaration.
For each extension API you wish to use, add in your code declarations of the function name as a type of the ugly-looking string.
>
> Example:
>
>
>
```
PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT;
PFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT;
PFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT;
PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT;
PFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;
```
Though it looks ugly, all we're doing is to declare function pointers of the type corresponding to the extension API.
Initialize these function pointers with their rightful functions. These functions are exposed by the library or driver. We need to use **wglGetProcAddress()** function to do this.
>
> Example:
>
>
>
```
glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress("glGenFramebuffersEXT");
glBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress("glBindFramebufferEXT");
glFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress("glFramebufferTexture2DEXT");
glCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress("glCheckFramebufferStatusEXT");
glDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress("glDeleteFramebuffersEXT");
```
Don't forget to check the function pointers for *NULL*. If by chance **wglGetProcAddress()** couldn't find the extension function, it would've initialized the pointer with NULL.
>
> Example:
>
>
>
```
if (NULL == glGenFramebuffersEXT || NULL == glBindFramebufferEXT || NULL == glFramebufferTexture2DEXT
|| NULL == glCheckFramebufferStatusEXT || NULL == glDeleteFramebuffersEXT)
{
// Extension functions not loaded!
exit(1);
}
```
That's it, we're done! You can now use these function pointers just as if the function calls existed.
>
> Example:
>
>
>
```
glGenFramebuffersEXT(1, &fbo);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorTex[0], 0);
```
**Reference:** [Moving Beyond OpenGL 1.1 for Windows](http://www.gamedev.net/reference/articles/article1929.asp) by Dave Astle — The article is a bit dated, but has all the information you need to understand why this pathetic situation exists on Windows and how to get around it. |
14,451 | <p>What is the best way to make a delphi application (delphi 2007 for win32 here) go completely full screen, removing the application border and covering windows task bar ?</p>
<p>I am looking for something similar to what IE does when you hit F11.</p>
<p>I wish this to be a run time option for the user not a design time decision by my good self.</p>
<p>As Mentioned in the accepted answer </p>
<pre><code>BorderStyle := bsNone;
</code></pre>
<p>was part of the way to do it. Strangely I kept getting a <code>E2010 Incompatible types: 'TFormBorderStyle' and 'TBackGroundSymbol'</code> error when using that line (another type had <code>bsNone</code> defined).</p>
<p>To overcome this I had to use : </p>
<pre><code>BorderStyle := Forms.bsNone;
</code></pre>
| [
{
"answer_id": 14458,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>Maximize the form and <a href=\"http://delphi.about.com/cs/adptips2000/a/bltip0100_5.htm\" rel=\"nofollow noreferrer\">hide the title bar</a>. The maximize line is done from memory, but I'm pretty sure WindowState is the property you want.</p>\n\n<p>There's also <a href=\"http://www.delphicorner.f9.co.uk/articles/forms5.htm\" rel=\"nofollow noreferrer\">this</a> article, but that seems too complicated to me.</p>\n\n<pre><code>procedure TForm1.FormCreate(Sender: TObject) ;\nbegin\n //maximize the window\n WindowState := wsMaximized;\n //hide the title bar\n SetWindowLong(Handle,GWL_STYLE,GetWindowLong(Handle,GWL_STYLE) and not WS_CAPTION);\n ClientHeight := Height;\nend;\n</code></pre>\n\n<p>Edit: Here's a complete example, with \"full screen\" and \"restore\" options. I've broken out the different parts into little procedures for maximum clarity, so this could be greatly compressed into just a few lines.</p>\n\n<pre><code>unit Unit1;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, StdCtrls;\n\ntype\n TForm1 = class(TForm)\n btnGoFullScreen: TButton;\n btnNotFullScreen: TButton;\n btnShowTitleBar: TButton;\n btnHideTitleBar: TButton;\n btnQuit: TButton;\n procedure btnGoFullScreenClick(Sender: TObject);\n procedure btnShowTitleBarClick(Sender: TObject);\n procedure btnHideTitleBarClick(Sender: TObject);\n procedure btnNotFullScreenClick(Sender: TObject);\n procedure btnQuitClick(Sender: TObject);\n private\n SavedLeft : integer;\n SavedTop : integer;\n SavedWidth : integer;\n SavedHeight : integer;\n SavedWindowState : TWindowState;\n procedure FullScreen;\n procedure NotFullScreen;\n procedure SavePosition;\n procedure HideTitleBar;\n procedure ShowTitleBar;\n procedure RestorePosition;\n procedure MaximizeWindow;\n public\n { Public declarations }\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.btnQuitClick(Sender: TObject);\nbegin\n Application.Terminate;\nend;\n\nprocedure TForm1.btnGoFullScreenClick(Sender: TObject);\nbegin\n FullScreen;\nend;\n\nprocedure TForm1.btnNotFullScreenClick(Sender: TObject);\nbegin\n NotFullScreen;\nend;\n\nprocedure TForm1.btnShowTitleBarClick(Sender: TObject);\nbegin\n ShowTitleBar;\nend;\n\nprocedure TForm1.btnHideTitleBarClick(Sender: TObject);\nbegin\n HideTitleBar;\nend;\n\nprocedure TForm1.FullScreen;\nbegin\n SavePosition;\n HideTitleBar;\n MaximizeWindow;\nend;\n\nprocedure TForm1.HideTitleBar;\nbegin\n SetWindowLong(Handle,GWL_STYLE,GetWindowLong(Handle,GWL_STYLE) and not WS_CAPTION);\n ClientHeight := Height;\nend;\n\nprocedure TForm1.MaximizeWindow;\nbegin\n WindowState := wsMaximized;\nend;\n\nprocedure TForm1.NotFullScreen;\nbegin\n RestorePosition;\n ShowTitleBar;\nend;\n\nprocedure TForm1.RestorePosition;\nbegin\n //this proc uses what we saved in \"SavePosition\"\n WindowState := SavedWindowState;\n Top := SavedTop;\n Left := SavedLeft;\n Width := SavedWidth;\n Height := SavedHeight;\nend;\n\nprocedure TForm1.SavePosition;\nbegin\n SavedLeft := Left;\n SavedHeight := Height;\n SavedTop := Top;\n SavedWidth := Width;\n SavedWindowState := WindowState;\nend;\n\nprocedure TForm1.ShowTitleBar;\nbegin\n SetWindowLong(Handle,gwl_Style,GetWindowLong(Handle,gwl_Style) or ws_Caption or ws_border);\n Height := Height + GetSystemMetrics(SM_CYCAPTION);\n Refresh;\nend;\n\nend.\n</code></pre>\n"
},
{
"answer_id": 14472,
"author": "Roddy",
"author_id": 1737,
"author_profile": "https://Stackoverflow.com/users/1737",
"pm_score": 6,
"selected": true,
"text": "<p>Well, this has always worked for me. Seems a bit simpler...</p>\n\n<pre><code>procedure TForm52.Button1Click(Sender: TObject);\nbegin\n BorderStyle := bsNone;\n WindowState := wsMaximized;\nend;\n</code></pre>\n"
},
{
"answer_id": 14480,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 3,
"selected": false,
"text": "<p>A Google search turned up the following, additional methods:</p>\n\n<p>(though I think I'd try Roddy's method first)</p>\n\n<h2><a href=\"http://delphi.about.com/cs/adptips2000/a/bltip0600_2.htm\" rel=\"noreferrer\">Manually fill the screen</a> (from: About Delphi)</h2>\n\n<pre><code>procedure TSomeForm.FormShow(Sender: TObject) ;\nvar\n r : TRect;\nbegin\n Borderstyle := bsNone;\n SystemParametersInfo\n (SPI_GETWORKAREA, 0, @r,0) ;\n SetBounds\n (r.Left, r.Top, r.Right-r.Left, r.Bottom-r.Top) ;\nend;\n</code></pre>\n\n<h2>Variation on a theme by Roddy</h2>\n\n<pre><code>FormStyle := fsStayOnTop;\nBorderStyle := bsNone;\nLeft := 0;\nTop := 0;\nWidth := Screen.Width;\nHeight := Screen.Height;\n</code></pre>\n\n<h2><a href=\"http://groups.google.nl/group/borland.public.delphi.objectpascal/msg/1cc7e07b0e80150e?hl=en\" rel=\"noreferrer\">The WinAPI way</a> (by Peter Below from TeamB)</h2>\n\n<pre><code>private // in form declaration\n Procedure WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo);\n message WM_GETMINMAXINFO;\n\nProcedure TForm1.WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo);\n Begin\n inherited;\n With msg.MinMaxInfo^.ptMaxTrackSize Do Begin\n X := GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth);\n Y := GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight\n);\n End;\n End;\n\nprocedure TForm1.Button2Click(Sender: TObject);\nConst\n Rect: TRect = (Left:0; Top:0; Right:0; Bottom:0);\n FullScreen: Boolean = False;\nbegin\n FullScreen := not FullScreen; \n If FullScreen Then Begin\n Rect := BoundsRect;\n SetBounds(\n Left - ClientOrigin.X,\n Top - ClientOrigin.Y,\n GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth),\n GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight ));\n // Label2.caption := IntToStr(GetDeviceCaps( Canvas.handle, VERTRES ));\n End\n Else\n BoundsRect := Rect;\nend; \n</code></pre>\n"
},
{
"answer_id": 3157913,
"author": "Freddie Bell",
"author_id": 381084,
"author_profile": "https://Stackoverflow.com/users/381084",
"pm_score": 1,
"selected": false,
"text": "<p>How to constrain a sub-form within the Mainform like it was an MDI app., but without the headaches! (Note: The replies on this page helped me get this working, so that's why I posted my solution here)</p>\n\n<pre><code>private\n{ Private declarations }\n StickyAt: Word;\n procedure WMWINDOWPOSCHANGING(Var Msg: TWMWINDOWPOSCHANGING); Message M_WINDOWPOSCHANGING;\n Procedure WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo); message WM_GETMINMAXINFO;\n</code></pre>\n\n<p>later...</p>\n\n<pre><code> procedure TForm2.WMWINDOWPOSCHANGING(var Msg: TWMWINDOWPOSCHANGING);\n var\n A, B: Integer;\n iFrameSize: Integer;\n iCaptionHeight: Integer;\n iMenuHeight: Integer;\n begin\n\n iFrameSize := GetSystemMetrics(SM_CYFIXEDFRAME);\n iCaptionHeight := GetSystemMetrics(SM_CYCAPTION);\n iMenuHeight := GetSystemMetrics(SM_CYMENU);\n\n // inside the Mainform client area\n A := Application.MainForm.Left + iFrameSize;\n B := Application.MainForm.Top + iFrameSize + iCaptionHeight + iMenuHeight;\n\n with Msg.WindowPos^ do\n begin\n\n if x <= A + StickyAt then\n x := A;\n\n if x + cx >= A + Application.MainForm.ClientWidth - StickyAt then\n x := (A + Application.MainForm.ClientWidth) - cx + 1;\n\n if y <= B + StickyAt then\n y := B;\n\n if y + cy >= B + Application.MainForm.ClientHeight - StickyAt then\n y := (B + Application.MainForm.ClientHeight) - cy + 1;\n\n end;\nend;\n</code></pre>\n\n<p>and yet more...</p>\n\n<pre><code>Procedure TForm2.WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo);\nvar\n iFrameSize: Integer;\n iCaptionHeight: Integer;\n iMenuHeight: Integer;\nBegin\n inherited;\n iFrameSize := GetSystemMetrics(SM_CYFIXEDFRAME);\n iCaptionHeight := GetSystemMetrics(SM_CYCAPTION);\n iMenuHeight := GetSystemMetrics(SM_CYMENU);\n With msg.MinMaxInfo^.ptMaxPosition Do\n begin\n // position of top when maximised\n X := Application.MainForm.Left + iFrameSize + 1;\n Y := Application.MainForm.Top + iFrameSize + iCaptionHeight + iMenuHeight + 1;\n end;\n With msg.MinMaxInfo^.ptMaxSize Do\n Begin\n // width and height when maximized\n X := Application.MainForm.ClientWidth;\n Y := Application.MainForm.ClientHeight;\n End;\n With msg.MinMaxInfo^.ptMaxTrackSize Do\n Begin\n // maximum size when maximised\n X := Application.MainForm.ClientWidth;\n Y := Application.MainForm.ClientHeight;\n End;\n // to do: minimum size (maybe)\nEnd;\n</code></pre>\n"
},
{
"answer_id": 11867212,
"author": "Taras",
"author_id": 889787,
"author_profile": "https://Stackoverflow.com/users/889787",
"pm_score": 2,
"selected": false,
"text": "<p>Put to the form <strong><em>onShow</em></strong> event such code:</p>\n\n<pre><code> WindowState:=wsMaximized;\n</code></pre>\n\n<p>And to the <strong><em>OnCanResize</em></strong> this:</p>\n\n<pre><code> if (newwidth<width) and (newheight<height) then\n Resize:=false;\n</code></pre>\n"
},
{
"answer_id": 17927052,
"author": "Edijs Kolesnikovičs",
"author_id": 2578854,
"author_profile": "https://Stackoverflow.com/users/2578854",
"pm_score": 0,
"selected": false,
"text": "<p>You need to make sure Form position is poDefaultPosOnly.</p>\n\n<pre><code>Form1.Position := poDefaultPosOnly;\nForm1.FormStyle := fsStayOnTop;\nForm1.BorderStyle := bsNone;\nForm1.Left := 0;\nForm1.Top := 0;\nForm1.Width := Screen.Width;\nForm1.Height := Screen.Height;\n</code></pre>\n\n<p>Tested and works on Win7 x64.</p>\n"
},
{
"answer_id": 23679070,
"author": "Noener",
"author_id": 3218191,
"author_profile": "https://Stackoverflow.com/users/3218191",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>Align = alClient \nFormStyle = fsStayOnTop\n</code></pre>\n\n<p>This always align to the primary monitor;</p>\n"
},
{
"answer_id": 23985225,
"author": "Jon Lennart Aasenden",
"author_id": 544838,
"author_profile": "https://Stackoverflow.com/users/544838",
"pm_score": 0,
"selected": false,
"text": "<p>Hm. Looking at the responses I seem to remember dealing with this about 8 years ago when I coded a game. To make debugging easier, I used the device-context of a normal, Delphi form as the source for a fullscreen display.</p>\n\n<p>The point being, that DirectX is capable of running any device context fullscreen - including the one allocated by your form.</p>\n\n<p>So to give an app \"true\" fullscreen capabilities, track down a DirectX library for Delphi and it will probably contain what you need out of the box.</p>\n"
},
{
"answer_id": 53226931,
"author": "Jacek Krawczyk",
"author_id": 1960514,
"author_profile": "https://Stackoverflow.com/users/1960514",
"pm_score": 1,
"selected": false,
"text": "<p>In my case, the only working solution is:</p>\n\n<pre><code>procedure TFormHelper.FullScreenMode;\nbegin\n BorderStyle := bsNone;\n ShowWindowAsync(Handle, SW_MAXIMIZE);\nend;\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1724/"
] | What is the best way to make a delphi application (delphi 2007 for win32 here) go completely full screen, removing the application border and covering windows task bar ?
I am looking for something similar to what IE does when you hit F11.
I wish this to be a run time option for the user not a design time decision by my good self.
As Mentioned in the accepted answer
```
BorderStyle := bsNone;
```
was part of the way to do it. Strangely I kept getting a `E2010 Incompatible types: 'TFormBorderStyle' and 'TBackGroundSymbol'` error when using that line (another type had `bsNone` defined).
To overcome this I had to use :
```
BorderStyle := Forms.bsNone;
``` | Well, this has always worked for me. Seems a bit simpler...
```
procedure TForm52.Button1Click(Sender: TObject);
begin
BorderStyle := bsNone;
WindowState := wsMaximized;
end;
``` |
14,464 | <p>I have a structure which I need to populate and write to disk (several actually).</p>
<p>An example is:</p>
<pre><code>byte-6
bit0 - original_or_copy
bit1 - copyright
bit2 - data_alignment_indicator
bit3 - PES_priority
bit4-bit5 - PES_scrambling control.
bit6-bit7 - reserved
</code></pre>
<p>In C I might do something like the following:</p>
<pre><code>struct PESHeader {
unsigned reserved:2;
unsigned scrambling_control:2;
unsigned priority:1;
unsigned data_alignment_indicator:1;
unsigned copyright:1;
unsigned original_or_copy:1;
};
</code></pre>
<p>Is there any way to do this in C# that would enable me to access the bits using the struct dereferencing dot operator? </p>
<p>For a couple of structures, I can just do bit shifting wrapped in an accessor function.</p>
<p>I have loads of structures to handle in this way, so I'm looking for something that's easier to read and quicker to write.</p>
| [
{
"answer_id": 14466,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": "<p>Could an Enum with the Flags Attribute help maybe? See here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/8447/enum-flags-attribute#8460\">What does the [Flags] Enum Attribute mean in C#?</a></p>\n"
},
{
"answer_id": 14475,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "<p>You want <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute(VS.71).aspx\" rel=\"noreferrer\">StructLayoutAttribute</a></p>\n\n<pre><code>[StructLayout(LayoutKind.Explicit, Size=1, CharSet=CharSet.Ansi)]\npublic struct Foo \n{ [FieldOffset(0)]public byte original_or_copy; \n [FieldOffset(0)]public byte copyright;\n [FieldOffset(0)]public byte data_alignment_indicator; \n [FieldOffset(0)]public byte PES_priority; \n [FieldOffset(0)]public byte PES_scrambling_control; \n [FieldOffset(0)]public byte reserved; \n}\n</code></pre>\n\n<p>This is really a union but you can use it as a bitfield--you just have to be conscious of where in the byte the bits for each field are supposed to be. Utility functions and/or constants to AND against can help.</p>\n\n<pre><code>const byte _original_or_copy = 1;\nconst byte _copyright = 2;\n\n//bool ooo = foo.original_or_copy();\nstatic bool original_or_copy(this Foo foo) \n{ return (foo.original_or_copy & _original_or_copy) == original_or_copy;\n} \n</code></pre>\n\n<p>There is also LayoutKind.Sequential which will allow you to do it the C way.</p>\n"
},
{
"answer_id": 14517,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "<p>By using an enum you can do this, but will look awkward.</p>\n\n<pre><code>[Flags]\npublic enum PESHeaderFlags\n{\n IsCopy = 1, // implied that if not present, then it is an original\n IsCopyrighted = 2,\n IsDataAligned = 4,\n Priority = 8,\n ScramblingControlType1 = 0,\n ScramblingControlType2 = 16,\n ScramblingControlType3 = 32,\n ScramblingControlType4 = 16+32,\n ScramblingControlFlags = ScramblingControlType1 | ScramblingControlType2 | ... ype4\n etc.\n}\n</code></pre>\n"
},
{
"answer_id": 14540,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>A flags enum can work too, I think, if you make it a byte enum:</p>\n\n<pre><code>[Flags] enum PesHeaders : byte { /* ... */ }\n</code></pre>\n"
},
{
"answer_id": 14591,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 7,
"selected": true,
"text": "<p>I'd probably knock together something using attributes, then a conversion class to convert suitably attributed structures to the bitfield primitives. Something like...</p>\n\n<pre><code>using System;\n\nnamespace BitfieldTest\n{\n [global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\n sealed class BitfieldLengthAttribute : Attribute\n {\n uint length;\n\n public BitfieldLengthAttribute(uint length)\n {\n this.length = length;\n }\n\n public uint Length { get { return length; } }\n }\n\n static class PrimitiveConversion\n {\n public static long ToLong<T>(T t) where T : struct\n {\n long r = 0;\n int offset = 0;\n\n // For every field suitably attributed with a BitfieldLength\n foreach (System.Reflection.FieldInfo f in t.GetType().GetFields())\n {\n object[] attrs = f.GetCustomAttributes(typeof(BitfieldLengthAttribute), false);\n if (attrs.Length == 1)\n {\n uint fieldLength = ((BitfieldLengthAttribute)attrs[0]).Length;\n\n // Calculate a bitmask of the desired length\n long mask = 0;\n for (int i = 0; i < fieldLength; i++)\n mask |= 1 << i;\n\n r |= ((UInt32)f.GetValue(t) & mask) << offset;\n\n offset += (int)fieldLength;\n }\n }\n\n return r;\n }\n }\n\n struct PESHeader\n {\n [BitfieldLength(2)]\n public uint reserved;\n [BitfieldLength(2)]\n public uint scrambling_control;\n [BitfieldLength(1)]\n public uint priority;\n [BitfieldLength(1)]\n public uint data_alignment_indicator;\n [BitfieldLength(1)]\n public uint copyright;\n [BitfieldLength(1)]\n public uint original_or_copy;\n };\n\n public class MainClass\n {\n public static void Main(string[] args)\n {\n PESHeader p = new PESHeader();\n\n p.reserved = 3;\n p.scrambling_control = 2;\n p.data_alignment_indicator = 1;\n\n long l = PrimitiveConversion.ToLong(p);\n\n\n for (int i = 63; i >= 0; i--)\n {\n Console.Write( ((l & (1l << i)) > 0) ? \"1\" : \"0\");\n }\n\n Console.WriteLine();\n\n return;\n }\n }\n}\n</code></pre>\n\n<p>Which produces the expected ...000101011. Of course, it needs more error checking and a slightly saner typing, but the concept is (I think) sound, reusable, and lets you knock out easily maintained structures by the dozen.</p>\n\n<p>adamw</p>\n"
},
{
"answer_id": 5420979,
"author": "Conrad",
"author_id": 610090,
"author_profile": "https://Stackoverflow.com/users/610090",
"pm_score": 3,
"selected": false,
"text": "<p>While it is a class, using <code>BitArray</code> seems like the way to least reinvent the wheel. Unless you're really pressed for performance, this is the simplest option. (Indexes can be referenced with the <code>[]</code> operator.)</p>\n"
},
{
"answer_id": 7636680,
"author": "Christophe Lambrechts",
"author_id": 976896,
"author_profile": "https://Stackoverflow.com/users/976896",
"pm_score": 3,
"selected": false,
"text": "<p>You could also use the <code>BitVector32</code> and especially the <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.specialized.bitvector32.section.aspx\" rel=\"noreferrer\"><code>Section struct</code></a>. The example is very good.</p>\n"
},
{
"answer_id": 11145067,
"author": "Zbyl",
"author_id": 407758,
"author_profile": "https://Stackoverflow.com/users/407758",
"pm_score": 4,
"selected": false,
"text": "<p>As Christophe Lambrechts suggested BitVector32 provides a solution. Jitted performance should be adequate, but don't know for sure.\nHere's the code illustrating this solution:</p>\n\n<pre><code>public struct rcSpan\n{\n //C# Spec 10.4.5.1: The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.\n internal static readonly BitVector32.Section sminSection = BitVector32.CreateSection(0x1FFF);\n internal static readonly BitVector32.Section smaxSection = BitVector32.CreateSection(0x1FFF, sminSection);\n internal static readonly BitVector32.Section areaSection = BitVector32.CreateSection(0x3F, smaxSection);\n\n internal BitVector32 data;\n\n //public uint smin : 13; \n public uint smin\n {\n get { return (uint)data[sminSection]; }\n set { data[sminSection] = (int)value; }\n }\n\n //public uint smax : 13; \n public uint smax\n {\n get { return (uint)data[smaxSection]; }\n set { data[smaxSection] = (int)value; }\n }\n\n //public uint area : 6; \n public uint area\n {\n get { return (uint)data[areaSection]; }\n set { data[areaSection] = (int)value; }\n }\n}\n</code></pre>\n\n<p>You can do a lot this way. You can do even better without using BitVector32, by providing handmade accessors for every field:</p>\n\n<pre><code>public struct rcSpan2\n{\n internal uint data;\n\n //public uint smin : 13; \n public uint smin\n {\n get { return data & 0x1FFF; }\n set { data = (data & ~0x1FFFu ) | (value & 0x1FFF); }\n }\n\n //public uint smax : 13; \n public uint smax\n {\n get { return (data >> 13) & 0x1FFF; }\n set { data = (data & ~(0x1FFFu << 13)) | (value & 0x1FFF) << 13; }\n }\n\n //public uint area : 6; \n public uint area\n {\n get { return (data >> 26) & 0x3F; }\n set { data = (data & ~(0x3F << 26)) | (value & 0x3F) << 26; }\n }\n}\n</code></pre>\n\n<p>Surprisingly this last, handmade solution seems to be the most convenient, least convoluted, and the shortest one. That's of course only my personal preference.</p>\n"
},
{
"answer_id": 29326393,
"author": "SunsetQuest",
"author_id": 2352507,
"author_profile": "https://Stackoverflow.com/users/2352507",
"pm_score": 4,
"selected": false,
"text": "<p>One more based off of Zbyl's answer. This one is a little easier to change around for me - I just have to adjust the sz0,sz1... and also make sure mask# and loc# are correct in the Set/Get blocks.</p>\n\n<p>Performance wise, it should be the same as they both resolved to 38 MSIL statements. (constants are resolved at compile time)</p>\n\n<pre><code>public struct MyStruct\n{\n internal uint raw;\n\n const int sz0 = 4, loc0 = 0, mask0 = ((1 << sz0) - 1) << loc0;\n const int sz1 = 4, loc1 = loc0 + sz0, mask1 = ((1 << sz1) - 1) << loc1;\n const int sz2 = 4, loc2 = loc1 + sz1, mask2 = ((1 << sz2) - 1) << loc2;\n const int sz3 = 4, loc3 = loc2 + sz2, mask3 = ((1 << sz3) - 1) << loc3;\n\n public uint Item0\n {\n get { return (uint)(raw & mask0) >> loc0; }\n set { raw = (uint)(raw & ~mask0 | (value << loc0) & mask0); }\n }\n\n public uint Item1\n {\n get { return (uint)(raw & mask1) >> loc1; }\n set { raw = (uint)(raw & ~mask1 | (value << loc1) & mask1); }\n }\n\n public uint Item2\n {\n get { return (uint)(raw & mask2) >> loc2; }\n set { raw = (uint)(raw & ~mask2 | (value << loc2) & mask2); }\n }\n\n public uint Item3\n {\n get { return (uint)((raw & mask3) >> loc3); }\n set { raw = (uint)(raw & ~mask3 | (value << loc3) & mask3); }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 38189258,
"author": "stalendp",
"author_id": 6053477,
"author_profile": "https://Stackoverflow.com/users/6053477",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote one, share it, may help someone:</p>\n\n<pre><code>[global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\npublic sealed class BitInfoAttribute : Attribute {\n byte length;\n public BitInfoAttribute(byte length) {\n this.length = length;\n }\n public byte Length { get { return length; } }\n}\n\npublic abstract class BitField {\n\n public void parse<T>(T[] vals) {\n analysis().parse(this, ArrayConverter.convert<T, uint>(vals));\n }\n\n public byte[] toArray() {\n return ArrayConverter.convert<uint, byte>(analysis().toArray(this));\n }\n\n public T[] toArray<T>() {\n return ArrayConverter.convert<uint, T>(analysis().toArray(this));\n }\n\n static Dictionary<Type, BitTypeInfo> bitInfoMap = new Dictionary<Type, BitTypeInfo>();\n private BitTypeInfo analysis() {\n Type type = this.GetType();\n if (!bitInfoMap.ContainsKey(type)) {\n List<BitInfo> infos = new List<BitInfo>();\n\n byte dataIdx = 0, offset = 0;\n foreach (System.Reflection.FieldInfo f in type.GetFields()) {\n object[] attrs = f.GetCustomAttributes(typeof(BitInfoAttribute), false);\n if (attrs.Length == 1) {\n byte bitLen = ((BitInfoAttribute)attrs[0]).Length;\n if (offset + bitLen > 32) {\n dataIdx++;\n offset = 0;\n }\n infos.Add(new BitInfo(f, bitLen, dataIdx, offset));\n offset += bitLen;\n }\n }\n bitInfoMap.Add(type, new BitTypeInfo(dataIdx + 1, infos.ToArray()));\n }\n return bitInfoMap[type];\n }\n}\n\nclass BitTypeInfo {\n public int dataLen { get; private set; }\n public BitInfo[] bitInfos { get; private set; }\n\n public BitTypeInfo(int _dataLen, BitInfo[] _bitInfos) {\n dataLen = _dataLen;\n bitInfos = _bitInfos;\n }\n\n public uint[] toArray<T>(T obj) {\n uint[] datas = new uint[dataLen];\n foreach (BitInfo bif in bitInfos) {\n bif.encode(obj, datas);\n }\n return datas;\n }\n\n public void parse<T>(T obj, uint[] vals) {\n foreach (BitInfo bif in bitInfos) {\n bif.decode(obj, vals);\n }\n }\n}\n\nclass BitInfo {\n\n private System.Reflection.FieldInfo field;\n private uint mask;\n private byte idx, offset, shiftA, shiftB;\n private bool isUnsigned = false;\n\n public BitInfo(System.Reflection.FieldInfo _field, byte _bitLen, byte _idx, byte _offset) {\n field = _field;\n mask = (uint)(((1 << _bitLen) - 1) << _offset);\n idx = _idx;\n offset = _offset;\n shiftA = (byte)(32 - _offset - _bitLen);\n shiftB = (byte)(32 - _bitLen);\n\n if (_field.FieldType == typeof(bool)\n || _field.FieldType == typeof(byte)\n || _field.FieldType == typeof(char)\n || _field.FieldType == typeof(uint)\n || _field.FieldType == typeof(ulong)\n || _field.FieldType == typeof(ushort)) {\n isUnsigned = true;\n }\n }\n\n public void encode(Object obj, uint[] datas) {\n if (isUnsigned) {\n uint val = (uint)Convert.ChangeType(field.GetValue(obj), typeof(uint));\n datas[idx] |= ((uint)(val << offset) & mask);\n } else {\n int val = (int)Convert.ChangeType(field.GetValue(obj), typeof(int));\n datas[idx] |= ((uint)(val << offset) & mask);\n }\n }\n\n public void decode(Object obj, uint[] datas) {\n if (isUnsigned) {\n field.SetValue(obj, Convert.ChangeType((((uint)(datas[idx] & mask)) << shiftA) >> shiftB, field.FieldType));\n } else {\n field.SetValue(obj, Convert.ChangeType((((int)(datas[idx] & mask)) << shiftA) >> shiftB, field.FieldType));\n }\n }\n}\n\npublic class ArrayConverter {\n public static T[] convert<T>(uint[] val) {\n return convert<uint, T>(val);\n }\n\n public static T1[] convert<T0, T1>(T0[] val) {\n T1[] rt = null;\n // type is same or length is same\n // refer to http://stackoverflow.com/questions/25759878/convert-byte-to-sbyte\n if (typeof(T0) == typeof(T1)) { \n rt = (T1[])(Array)val;\n } else {\n int len = Buffer.ByteLength(val);\n int w = typeWidth<T1>();\n if (w == 1) { // bool\n rt = new T1[len * 8];\n } else if (w == 8) {\n rt = new T1[len];\n } else { // w > 8\n int nn = w / 8;\n int len2 = (len / nn) + ((len % nn) > 0 ? 1 : 0);\n rt = new T1[len2];\n }\n\n Buffer.BlockCopy(val, 0, rt, 0, len);\n }\n return rt;\n }\n\n public static string toBinary<T>(T[] vals) {\n StringBuilder sb = new StringBuilder();\n int width = typeWidth<T>();\n int len = Buffer.ByteLength(vals);\n for (int i = len-1; i >=0; i--) {\n sb.Append(Convert.ToString(Buffer.GetByte(vals, i), 2).PadLeft(8, '0')).Append(\" \");\n }\n return sb.ToString();\n }\n\n private static int typeWidth<T>() {\n int rt = 0;\n if (typeof(T) == typeof(bool)) { // x\n rt = 1;\n } else if (typeof(T) == typeof(byte)) { // x\n rt = 8;\n } else if (typeof(T) == typeof(sbyte)) {\n rt = 8;\n } else if (typeof(T) == typeof(ushort)) { // x\n rt = 16;\n } else if (typeof(T) == typeof(short)) {\n rt = 16;\n } else if (typeof(T) == typeof(char)) {\n rt = 16;\n } else if (typeof(T) == typeof(uint)) { // x\n rt = 32;\n } else if (typeof(T) == typeof(int)) {\n rt = 32;\n } else if (typeof(T) == typeof(float)) {\n rt = 32;\n } else if (typeof(T) == typeof(ulong)) { // x\n rt = 64;\n } else if (typeof(T) == typeof(long)) {\n rt = 64;\n } else if (typeof(T) == typeof(double)) {\n rt = 64;\n } else {\n throw new Exception(\"Unsupport type : \" + typeof(T).Name);\n }\n return rt;\n }\n}\n</code></pre>\n\n<p>and the usage: </p>\n\n<pre><code>class MyTest01 : BitField {\n [BitInfo(3)]\n public bool d0;\n [BitInfo(3)]\n public short d1;\n [BitInfo(3)]\n public int d2;\n [BitInfo(3)]\n public int d3;\n [BitInfo(3)]\n public int d4;\n [BitInfo(3)]\n public int d5;\n\n public MyTest01(bool _d0, short _d1, int _d2, int _d3, int _d4, int _d5) {\n d0 = _d0;\n d1 = _d1;\n d2 = _d2;\n d3 = _d3;\n d4 = _d4;\n d5 = _d5;\n }\n\n public MyTest01(byte[] datas) {\n parse(datas);\n }\n\n public new string ToString() {\n return string.Format(\"d0: {0}, d1: {1}, d2: {2}, d3: {3}, d4: {4}, d5: {5} \\r\\nbinary => {6}\",\n d0, d1, d2, d3, d4, d5, ArrayConverter.toBinary(toArray()));\n }\n};\n\nclass MyTest02 : BitField {\n [BitInfo(5)]\n public bool val0;\n [BitInfo(5)]\n public byte val1;\n [BitInfo(15)]\n public uint val2;\n [BitInfo(15)]\n public float val3;\n [BitInfo(15)]\n public int val4;\n [BitInfo(15)]\n public int val5;\n [BitInfo(15)]\n public int val6;\n\n public MyTest02(bool v0, byte v1, uint v2, float v3, int v4, int v5, int v6) {\n val0 = v0;\n val1 = v1;\n val2 = v2;\n val3 = v3;\n val4 = v4;\n val5 = v5;\n val6 = v6;\n }\n\n public MyTest02(byte[] datas) {\n parse(datas);\n }\n\n public new string ToString() {\n return string.Format(\"val0: {0}, val1: {1}, val2: {2}, val3: {3}, val4: {4}, val5: {5}, val6: {6}\\r\\nbinary => {7}\",\n val0, val1, val2, val3, val4, val5, val6, ArrayConverter.toBinary(toArray()));\n }\n}\n\npublic class MainClass {\n\n public static void Main(string[] args) {\n MyTest01 p = new MyTest01(false, 1, 2, 3, -1, -2);\n Debug.Log(\"P:: \" + p.ToString());\n MyTest01 p2 = new MyTest01(p.toArray());\n Debug.Log(\"P2:: \" + p2.ToString());\n\n MyTest02 t = new MyTest02(true, 1, 12, -1.3f, 4, -5, 100);\n Debug.Log(\"t:: \" + t.ToString());\n MyTest02 t2 = new MyTest02(t.toArray());\n Debug.Log(\"t:: \" + t.ToString());\n\n Console.Read();\n return;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 55834344,
"author": "Vito Marolda",
"author_id": 6681740,
"author_profile": "https://Stackoverflow.com/users/6681740",
"pm_score": 3,
"selected": false,
"text": "<p>I find myself quite comfortable with these helper functions:</p>\n\n<pre><code>uint SetBits(uint word, uint value, int pos, int size)\n{\n uint mask = ((((uint)1) << size) - 1) << pos;\n word &= ~mask; //resettiamo le posizioni\n word |= (value << pos) & mask;\n return word;\n}\n\nuint ReadBits(uint word, int pos, int size)\n{\n uint mask = ((((uint)1) << size) - 1) << pos;\n return (word & mask) >> pos;\n}\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>uint the_word;\n\npublic uint Itemx\n{\n get { return ReadBits(the_word, 5, 2); }\n set { the_word = SetBits(the_word, value, 5, 2) }\n}\n</code></pre>\n"
},
{
"answer_id": 68870859,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote one this morning with T4. :) Same example as Zbyl, though I threw in a bit of uint sizing fun. This is just a first pass, it could obviously use a little error checking. Also the bitFields spec array would be nicer in a separate file, maybe a .ttinclude, or a json/yaml..</p>\n<pre><code>=== BitFields.tt ===\n\n<#@ template language="C#" #>\n<#@ assembly name="System.Core" #>\n<#@ import namespace="System.Linq" #>\n\n<#\nvar bitFields = new[]\n{\n new\n {\n Name = "rcSpan2", Fields = new[] { ("smin", 13), ("smax", 13), ("area", 6) },\n }, \n};\n\nforeach (var bitField in bitFields)\n{\n static string getType(int size) =>\n size switch\n {\n > 32 => "ulong",\n > 16 => "uint",\n > 8 => "ushort",\n _ => "byte",\n };\n\n var bitFieldType = getType(bitField.Fields.Sum(f => f.Item2)); \n#>\npublic struct <#=bitField.Name#>\n{\n <#=bitFieldType#> _bitfield;\n\n<#\nvar offset = 0;\nforeach (var (fieldName, fieldSize) in bitField.Fields)\n{\n var fieldType = getType(fieldSize);\n var fieldMask = $"0x{((1UL<<fieldSize)-1):X}U";\n#>\n public <#=fieldType#> <#=fieldName#> // : <#=fieldSize#>\n {\n get => (<#=fieldType#>)(<#=offset > 0 ? $"(_bitfield >> {offset})" : "_bitfield"#> & <#=fieldMask#>);\n set => _bitfield = (<#=bitFieldType#>)((_bitfield & ~((<#=bitFieldType#>)<#=fieldMask#> << <#=offset#>)) | ((<#=bitFieldType#>)(value & <#=fieldMask#>) << <#=offset#>));\n } \n<#\n offset += fieldSize;\n}\n#>\n}\n\n<#}#>\n\n=== BitFields.cs === (generated)\n\npublic struct rcSpan2\n{\n uint _bitfield;\n\n public ushort smin // : 13\n {\n get => (ushort)(_bitfield & 0x1FFFU);\n set => _bitfield = (uint)((_bitfield & ~((uint)0x1FFFU << 0)) | ((uint)(value & 0x1FFFU) << 0));\n } \n public ushort smax // : 13\n {\n get => (ushort)((_bitfield >> 13) & 0x1FFFU);\n set => _bitfield = (uint)((_bitfield & ~((uint)0x1FFFU << 13)) | ((uint)(value & 0x1FFFU) << 13));\n } \n public byte area // : 6\n {\n get => (byte)((_bitfield >> 26) & 0x3FU);\n set => _bitfield = (uint)((_bitfield & ~((uint)0x3FU << 26)) | ((uint)(value & 0x3FU) << 26));\n } \n}\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006/"
] | I have a structure which I need to populate and write to disk (several actually).
An example is:
```
byte-6
bit0 - original_or_copy
bit1 - copyright
bit2 - data_alignment_indicator
bit3 - PES_priority
bit4-bit5 - PES_scrambling control.
bit6-bit7 - reserved
```
In C I might do something like the following:
```
struct PESHeader {
unsigned reserved:2;
unsigned scrambling_control:2;
unsigned priority:1;
unsigned data_alignment_indicator:1;
unsigned copyright:1;
unsigned original_or_copy:1;
};
```
Is there any way to do this in C# that would enable me to access the bits using the struct dereferencing dot operator?
For a couple of structures, I can just do bit shifting wrapped in an accessor function.
I have loads of structures to handle in this way, so I'm looking for something that's easier to read and quicker to write. | I'd probably knock together something using attributes, then a conversion class to convert suitably attributed structures to the bitfield primitives. Something like...
```
using System;
namespace BitfieldTest
{
[global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
sealed class BitfieldLengthAttribute : Attribute
{
uint length;
public BitfieldLengthAttribute(uint length)
{
this.length = length;
}
public uint Length { get { return length; } }
}
static class PrimitiveConversion
{
public static long ToLong<T>(T t) where T : struct
{
long r = 0;
int offset = 0;
// For every field suitably attributed with a BitfieldLength
foreach (System.Reflection.FieldInfo f in t.GetType().GetFields())
{
object[] attrs = f.GetCustomAttributes(typeof(BitfieldLengthAttribute), false);
if (attrs.Length == 1)
{
uint fieldLength = ((BitfieldLengthAttribute)attrs[0]).Length;
// Calculate a bitmask of the desired length
long mask = 0;
for (int i = 0; i < fieldLength; i++)
mask |= 1 << i;
r |= ((UInt32)f.GetValue(t) & mask) << offset;
offset += (int)fieldLength;
}
}
return r;
}
}
struct PESHeader
{
[BitfieldLength(2)]
public uint reserved;
[BitfieldLength(2)]
public uint scrambling_control;
[BitfieldLength(1)]
public uint priority;
[BitfieldLength(1)]
public uint data_alignment_indicator;
[BitfieldLength(1)]
public uint copyright;
[BitfieldLength(1)]
public uint original_or_copy;
};
public class MainClass
{
public static void Main(string[] args)
{
PESHeader p = new PESHeader();
p.reserved = 3;
p.scrambling_control = 2;
p.data_alignment_indicator = 1;
long l = PrimitiveConversion.ToLong(p);
for (int i = 63; i >= 0; i--)
{
Console.Write( ((l & (1l << i)) > 0) ? "1" : "0");
}
Console.WriteLine();
return;
}
}
}
```
Which produces the expected ...000101011. Of course, it needs more error checking and a slightly saner typing, but the concept is (I think) sound, reusable, and lets you knock out easily maintained structures by the dozen.
adamw |
14,491 | <p>What is the proper way for an MFC application to cleanly close itself?</p>
| [
{
"answer_id": 14492,
"author": "Mike",
"author_id": 1743,
"author_profile": "https://Stackoverflow.com/users/1743",
"pm_score": 4,
"selected": false,
"text": "<pre><code>AfxGetMainWnd()->PostMessage(WM_CLOSE);\n</code></pre>\n"
},
{
"answer_id": 14663,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 2,
"selected": false,
"text": "<p>In support of @Mike's answer, the reason to use this method is to trigger the correct shutdown sequence. Especially important for MDI/SDI applications because it gives a chance for documents to prompt for save before exit or to cancel the exit.</p>\n\n<p>@Matt Noguchi, your method will circumvent this sequence (which may be the desired effect, I suppose, but you've probably got <em>problems</em> if you're short-circuiting the normal teardown.</p>\n"
},
{
"answer_id": 14841,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "<pre><code>PostQuitMessage( [exit code] );\n</code></pre>\n"
},
{
"answer_id": 91465,
"author": "Gautam Jain",
"author_id": 15065,
"author_profile": "https://Stackoverflow.com/users/15065",
"pm_score": 1,
"selected": false,
"text": "<p>If it is a dialog based application you can do it by calling EndDialog() function.</p>\n\n<p>If it is an SDI/MDI based application you can call DestroyWindow. But before which you will need to do the cleanup yourself (closing documents, deallocating memory and resources, destroying any additional windows created etc).</p>\n"
},
{
"answer_id": 8768957,
"author": "Bruno Schwarzkorpf",
"author_id": 1115458,
"author_profile": "https://Stackoverflow.com/users/1115458",
"pm_score": 5,
"selected": true,
"text": "<p>Programatically Terminate an MFC Application</p>\n\n<pre><code> void ExitMFCApp()\n {\n // same as double-clicking on main window close box\n ASSERT(AfxGetMainWnd() != NULL);\n AfxGetMainWnd()->SendMessage(WM_CLOSE);\n }\n</code></pre>\n\n<p><a href=\"http://support.microsoft.com/kb/117320\">http://support.microsoft.com/kb/117320</a></p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743/"
] | What is the proper way for an MFC application to cleanly close itself? | Programatically Terminate an MFC Application
```
void ExitMFCApp()
{
// same as double-clicking on main window close box
ASSERT(AfxGetMainWnd() != NULL);
AfxGetMainWnd()->SendMessage(WM_CLOSE);
}
```
<http://support.microsoft.com/kb/117320> |
14,505 | <p>In the Full .NET framework you can use the Color.FromArgb() method to create a new color with alpha blending, like this:</p>
<pre><code>Color blended = Color.FromArgb(alpha, color);
</code></pre>
<p>or</p>
<pre><code>Color blended = Color.FromArgb(alpha, red, green , blue);
</code></pre>
<p>However in the Compact Framework (2.0 specifically), neither of those methods are available, you only get:</p>
<pre><code>Color.FromArgb(int red, int green, int blue);
</code></pre>
<p>and</p>
<pre><code>Color.FromArgb(int val);
</code></pre>
<p>The first one, obviously, doesn't even let you enter an alpha value, but the documentation for the latter shows that "val" is a 32bit ARGB value (as 0xAARRGGBB as opposed to the standard 24bit 0xRRGGBB), so it would make sense that you could just build the ARGB value and pass it to the function. I tried this with the following:</p>
<pre><code>private Color FromARGB(byte alpha, byte red, byte green, byte blue)
{
int val = (alpha << 24) | (red << 16) | (green << 8) | blue;
return Color.FromArgb(val);
}
</code></pre>
<p>But no matter what I do, the alpha blending never works, the resulting color always as full opacity, even when setting the alpha value to 0.</p>
<p>Has anyone gotten this to work on the Compact Framework?</p>
| [
{
"answer_id": 14525,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": true,
"text": "<p>Apparently, it's not quite that simple, but <a href=\"http://blogs.msdn.com/chrislorton/archive/2006/04/07/570649.aspx\" rel=\"nofollow noreferrer\">still possible</a>, if you have Windows Mobile 5.0 or newer.</p>\n"
},
{
"answer_id": 14529,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Apparently, it's not quite that\n simple, but still possible, if you\n have Windows Mobile 5.0 or newer.</p>\n</blockquote>\n\n<p>Wow...definitely not worth it if I have to put all that code in (and do native interop!)\nGood to know though, thanks for the link.</p>\n"
},
{
"answer_id": 199366,
"author": "Peter Walke",
"author_id": 12497,
"author_profile": "https://Stackoverflow.com/users/12497",
"pm_score": 1,
"selected": false,
"text": "<p>There is a <a href=\"http://www.codeplex.com/alphamobilecontrols\" rel=\"nofollow noreferrer\">codeplex site</a> out there that seems to do the heavy lifting of com interop for you:</p>\n"
},
{
"answer_id": 2870347,
"author": "fede",
"author_id": 345622,
"author_profile": "https://Stackoverflow.com/users/345622",
"pm_score": 0,
"selected": false,
"text": "<p>i take this code and i add this </p>\n\n<pre><code>device.RenderState.AlphaBlendEnable = true;\ndevice.RenderState.AlphaFunction = Compare.Greater;\ndevice.RenderState.AlphaTestEnable = true;\ndevice.RenderState.DestinationBlend = Blend.InvSourceAlpha;\ndevice.RenderState.SourceBlend = Blend.SourceAlpha;\ndevice.RenderState.DiffuseMaterialSource = ColorSource.Material;\n</code></pre>\n\n<p>in the initialized routine and it work very well, thank you </p>\n"
},
{
"answer_id": 11091758,
"author": "Ben Kunz",
"author_id": 1464789,
"author_profile": "https://Stackoverflow.com/users/1464789",
"pm_score": 0,
"selected": false,
"text": "<p>CE 6.0 does not support alpha blending. WM 5.0 and above do, but not through the .NET CF, you will need to P/Invoke GDI stuff to do so. There are ready-made solutions out there, however, if you are interested i can dig the links out tomorrow at the office. I have to work with CE 6.0 currently so i don't have them on my mind.</p>\n\n<p>If you are using CE 6.0 you can use pseudo-transparency by reserving a transparency background color (e.g. ff00ff or something similiarly ugly) and using that in your images for transparent areas. Then, your parent controls must implement a simple interface that allows re-drawing the relevant portion on your daughter controls' graphics buffer. Note that this will not give you a true \"alpha channel\" but rather just a hard on-off binary kind of transparency.</p>\n\n<p>It's not as bad as it sounds. Take a look at the OpenNETCF ImageButton for starters. If you are going to use this method, i have a somewhat extended version of some simple controls with this technique lying around if you are interested.</p>\n\n<p>One additional drawback is that this technique relies on the parent control implementing a special interface, and the daugther controls using it in drawing. So with closed-source components (i.e. also the stock winforms components) you are out of luck.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] | In the Full .NET framework you can use the Color.FromArgb() method to create a new color with alpha blending, like this:
```
Color blended = Color.FromArgb(alpha, color);
```
or
```
Color blended = Color.FromArgb(alpha, red, green , blue);
```
However in the Compact Framework (2.0 specifically), neither of those methods are available, you only get:
```
Color.FromArgb(int red, int green, int blue);
```
and
```
Color.FromArgb(int val);
```
The first one, obviously, doesn't even let you enter an alpha value, but the documentation for the latter shows that "val" is a 32bit ARGB value (as 0xAARRGGBB as opposed to the standard 24bit 0xRRGGBB), so it would make sense that you could just build the ARGB value and pass it to the function. I tried this with the following:
```
private Color FromARGB(byte alpha, byte red, byte green, byte blue)
{
int val = (alpha << 24) | (red << 16) | (green << 8) | blue;
return Color.FromArgb(val);
}
```
But no matter what I do, the alpha blending never works, the resulting color always as full opacity, even when setting the alpha value to 0.
Has anyone gotten this to work on the Compact Framework? | Apparently, it's not quite that simple, but [still possible](http://blogs.msdn.com/chrislorton/archive/2006/04/07/570649.aspx), if you have Windows Mobile 5.0 or newer. |
14,527 | <p>I need to be able to find the last occurrence of a character within an element.</p>
<p>For example:</p>
<pre><code><mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl>
</code></pre>
<p>If I try to locate it through using <code>substring-before(mediaurl, '.')</code> and <code>substring-after(mediaurl, '.')</code> then it will, of course, match on the first dot. </p>
<p>How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT.</p>
| [
{
"answer_id": 14547,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>How about tokenize with \"/\" and take the last element from the array ?</p>\n\n<pre><code>Example: tokenize(\"XPath is fun\", \"\\s+\")\nResult: (\"XPath\", \"is\", \"fun\")\n</code></pre>\n\n<p>Was an XSLT fiddler sometime back... lost touch now. But HTH</p>\n"
},
{
"answer_id": 14686,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using XSLT 2.0, it's easy:</p>\n\n<pre><code> <xsl:variable name=\"extension\" select=\"tokenize($filename, '\\.')[last()]\"/>\n</code></pre>\n\n<p>If you're not, it's a bit harder. There's a good example from the <a href=\"http://oreilly.com/catalog/9780596003722/toc.html\" rel=\"nofollow noreferrer\">O'Reilly XSLT Cookbook</a>. Search for \"Tokenizing a String.\"</p>\n\n<p>I believe there's also an EXSLT function, if you have that available.</p>\n"
},
{
"answer_id": 16414,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 5,
"selected": true,
"text": "<p>The following is an example of a template that would produce the required output in XSLT 1.0:</p>\n\n<pre><code><xsl:template name=\"getExtension\">\n<xsl:param name=\"filename\"/>\n\n <xsl:choose>\n <xsl:when test=\"contains($filename, '.')\">\n <xsl:call-template name=\"getExtension\">\n <xsl:with-param name=\"filename\" select=\"substring-after($filename, '.')\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$filename\"/>\n </xsl:otherwise>\n </xsl:choose>\n</xsl:template>\n\n<xsl:template match=\"/\">\n <xsl:call-template name=\"getExtension\">\n <xsl:with-param name=\"filename\" select=\"'http://www.blah.com/path/to/file/media.jpg'\"/>\n </xsl:call-template>\n</xsl:template>\n</code></pre>\n"
},
{
"answer_id": 28006,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 0,
"selected": false,
"text": "<p>For reference, this problem is usually called \"substring-after-last\" in XSLT.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] | I need to be able to find the last occurrence of a character within an element.
For example:
```
<mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl>
```
If I try to locate it through using `substring-before(mediaurl, '.')` and `substring-after(mediaurl, '.')` then it will, of course, match on the first dot.
How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT. | The following is an example of a template that would produce the required output in XSLT 1.0:
```
<xsl:template name="getExtension">
<xsl:param name="filename"/>
<xsl:choose>
<xsl:when test="contains($filename, '.')">
<xsl:call-template name="getExtension">
<xsl:with-param name="filename" select="substring-after($filename, '.')"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$filename"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="/">
<xsl:call-template name="getExtension">
<xsl:with-param name="filename" select="'http://www.blah.com/path/to/file/media.jpg'"/>
</xsl:call-template>
</xsl:template>
``` |
14,577 | <p>Imagine the scene, you're updating some legacy Sybase code and come across a cursor. The stored procedure builds up a result set in a #temporary table which is all ready to be returned except that one of columns isn't terribly human readable, it's an alphanumeric code.</p>
<p>What we need to do, is figure out the possible distinct values of this code, call another stored procedure to cross reference these discrete values and then update the result set with the newly deciphered values:</p>
<pre><code>declare c_lookup_codes for
select distinct lookup_code
from #workinprogress
while(1=1)
begin
fetch c_lookup_codes into @lookup_code
if @@sqlstatus<>0
begin
break
end
exec proc_code_xref @lookup_code @xref_code OUTPUT
update #workinprogress
set xref = @xref_code
where lookup_code = @lookup_code
end
</code></pre>
<p>Now then, whilst this may give some folks palpitations, it does work. My question is, how best would one avoid this kind of thing?</p>
<p>_NB: for the purposes of this example you can also imagine that the result set is in the region of 500k rows and that there are 100 distinct values of look_up_code and finally, that it is not possible to have a table with the xref values in as the logic in proc_code_xref is too arcane._</p>
| [
{
"answer_id": 14671,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 1,
"selected": false,
"text": "<p>Unless you are willing to duplicate the code in the xref proc, there is no way to avoid using a cursor.</p>\n"
},
{
"answer_id": 14699,
"author": "David Hayes",
"author_id": 1769,
"author_profile": "https://Stackoverflow.com/users/1769",
"pm_score": 2,
"selected": true,
"text": "<p>You have to have a XRef table if you want to take out the cursor. Assuming you know the 100 distinct lookup values (and that they're static) it's simple to generate one by calling proc_code_xref 100 times and inserting the results into a table</p>\n"
},
{
"answer_id": 988077,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 0,
"selected": false,
"text": "<p>They say, that if you must use cursor, then, you must have done something wrong ;-) here's solution without cursor:</p>\n\n<pre><code>declare @lookup_code char(8)\n\nselect distinct lookup_code\ninto #lookup_codes\nfrom #workinprogress\n\nwhile 1=1\nbegin\n select @lookup_code = lookup_code from #lookup_codes\n\n if @@rowcount = 0 break\n\n exec proc_code_xref @lookup_code @xref_code OUTPUT\n\n delete #lookup_codes\n where lookup_code = @lookup_code\nend\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] | Imagine the scene, you're updating some legacy Sybase code and come across a cursor. The stored procedure builds up a result set in a #temporary table which is all ready to be returned except that one of columns isn't terribly human readable, it's an alphanumeric code.
What we need to do, is figure out the possible distinct values of this code, call another stored procedure to cross reference these discrete values and then update the result set with the newly deciphered values:
```
declare c_lookup_codes for
select distinct lookup_code
from #workinprogress
while(1=1)
begin
fetch c_lookup_codes into @lookup_code
if @@sqlstatus<>0
begin
break
end
exec proc_code_xref @lookup_code @xref_code OUTPUT
update #workinprogress
set xref = @xref_code
where lookup_code = @lookup_code
end
```
Now then, whilst this may give some folks palpitations, it does work. My question is, how best would one avoid this kind of thing?
\_NB: for the purposes of this example you can also imagine that the result set is in the region of 500k rows and that there are 100 distinct values of look\_up\_code and finally, that it is not possible to have a table with the xref values in as the logic in proc\_code\_xref is too arcane.\_ | You have to have a XRef table if you want to take out the cursor. Assuming you know the 100 distinct lookup values (and that they're static) it's simple to generate one by calling proc\_code\_xref 100 times and inserting the results into a table |
14,614 | <p>First off, I understand the reasons why an interface or abstract class (in the .NET/C# terminology) cannot have abstract static methods. My question is then more focused on the best design solution.</p>
<p>What I want is a set of "helper" classes that all have their own static methods such that if I get objects A, B, and C from a third party vendor, I can have helper classes with methods such as</p>
<pre>
AHelper.RetrieveByID(string id);
AHelper.RetrieveByName(string name);
AHelper.DumpToDatabase();
</pre>
<p>Since my AHelper, BHelper, and CHelper classes will all basically have the same methods, it seems to makes sense to move these methods to an interface that these classes then derive from. However, wanting these methods to be static precludes me from having a generic interface or abstract class for all of them to derive from.</p>
<p>I could always make these methods non-static and then instantiate the objects first such as</p>
<pre>
AHelper a = new AHelper();
a.DumpToDatabase();
</pre>
<p>However, this code doesn't seem as intuitive to me. What are your suggestions? Should I abandon using an interface or abstract class altogether (the situation I'm in now) or can this possibly be refactored to accomplish the design I'm looking for?</p>
| [
{
"answer_id": 14622,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>In C# 3.0, static methods can be used on interfaces as if they were a part of them by using extension methods, as with DumpToDatabase() below:</p>\n\n<pre><code>static class HelperMethods\n { //IHelper h = new HeleperA();\n //h.DumpToDatabase() \n public static void DumpToDatabase(this IHelper helper) { /* ... */ }\n\n //IHelper h = a.RetrieveByID(5)\n public static IHelper RetrieveByID(this ObjectA a, int id) \n { \n return new HelperA(a.GetByID(id));\n }\n\n //Ihelper h = b.RetrieveByID(5) \n public static IHelper RetrieveByID(this ObjectB b, int id)\n { \n return new HelperB(b.GetById(id.ToString())); \n }\n }\n</code></pre>\n"
},
{
"answer_id": 14633,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>I personally would perhaps question why each of the types need to have a static method before even thinking further..</p>\n\n<p>Why not create a utlity class with the static methods that they need to share? (e.g. <code>ClassHelper.RetrieveByID(string id)</code> or <code>ClassHelper<ClassA>.RetrieveByID(string id)</code></p>\n\n<p>In my experience with these sort of \"roadblocks\" the problem is not the limitations of the language, but the limitations of my design..</p>\n"
},
{
"answer_id": 14641,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<p>How are ObjectA and AHelper related? Is <code>AHelper.RetrieveByID()</code> the same logic as <code>BHelper.RetrieveByID()</code></p>\n\n<p>If Yes, how about a Utility class based approach (class with public static methods only and no state)</p>\n\n<pre><code>static [return type] Helper.RetrieveByID(ObjectX x) \n</code></pre>\n"
},
{
"answer_id": 14655,
"author": "jerhinesmith",
"author_id": 1108,
"author_profile": "https://Stackoverflow.com/users/1108",
"pm_score": 0,
"selected": false,
"text": "<p>How do I post feedback on Stack Overflow? Edit my original post or post an \"answer\"? Anyway, I thought it might help to give an example of what is going on in AHelper.RetrieveByID() and BHelper.RetreiveByID()</p>\n\n<p>Basically, both of these methods are going up against a third party webservice that returns various a generic (castable) object using a Query method that takes in a pseudo-SQL string as its only parameters.</p>\n\n<p>So, AHelper.RetrieveByID(string ID) might look like</p>\n\n<pre>\npublic static AObject RetrieveByID(string ID)\n{\n QueryResult qr = webservice.query(\"SELECT Id,Name FROM AObject WHERE Id = '\" + ID + \"'\");\n\n return (AObject)qr.records[0];\n}\n\npublic static BObject RetrieveByID(string ID)\n{\n QueryResult qr = webservice.query(\"SELECT Id,Name,Company FROM BObject WHERE Id = '\" + ID + \"'\");\n\n return (BObject)qr.records[0];\n}\n</pre>\n\n<p>Hopefully that helps. As you can see, the two methods are similar, but the query can be quite a bit different based on the different object type being returned.</p>\n\n<p>Oh, and Rob, I completely agree -- this is more than likely a limitation of my design and not the language. :)</p>\n"
},
{
"answer_id": 14657,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 0,
"selected": false,
"text": "<p>Are you looking for polymorphic behavior? Then you'll want the interface and normal constructor. What is unintuitive about calling a constructor? If you don't need polymorphism (sounds like you don't use it now), then you can stick with your static methods. If these are all wrappers around a vendor component, then maybe you might try to use a factory method to create them like VendorBuilder.GetVendorThing(\"A\") which could return an object of type IVendorWrapper.</p>\n"
},
{
"answer_id": 14672,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>You can't overload methods by varying just the return type.</p>\n\n<p>You can use different names: </p>\n\n<pre><code>static AObject GetAObject(string id);\nstatic BObject GetBObject(string id);\n</code></pre>\n\n<p>Or you can create a class with casting operators:</p>\n\n<pre><code>class AOrBObject\n{ \n string id;\n AOrBObject(string id) {this.id = id;}\n\n static public AOrBObject RetrieveByID(string id)\n {\n return new AOrBObject(id);\n }\n\n public static AObject explicit operator(AOrBObject ab) \n { \n return AObjectQuery(ab.id);\n }\n\n public static BObject explicit operator(AOrBObject ab)\n { \n return BObjectQuery(ab.id);\n } \n}\n</code></pre>\n\n<p>Then you can call it like so:</p>\n\n<pre><code> var a = (AObject) AOrBObject.RetrieveByID(5);\n var b = (BObject) AOrBObject.RetrieveByID(5); \n</code></pre>\n"
},
{
"answer_id": 14683,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 3,
"selected": true,
"text": "<p>Looking at <a href=\"https://stackoverflow.com/questions/14614/static-methods-in-an-interfaceabstract-class#14655\">your response</a> I am thinking along the following lines:</p>\n\n<ul>\n<li>You could just have a static method that takes a type parameter and performs the expected logic based on the type.</li>\n<li>You could create a virtual method in your abstract base, where you specify the SQL in the concrete class. So that contains all the common code that is required by both (e.g. exectuting the command and returning the object) while encapsulating the \"specialist\" bits (e.g. the SQL) in the sub classes.</li>\n</ul>\n\n<p>I prefer the second option, although its of course down to you. If you need me to go into further detail, please let me know and I will be happy to edit/update :)</p>\n"
},
{
"answer_id": 14692,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>For a generic solution to your example, you can do this:</p>\n\n<pre><code>public static T RetrieveByID<T>(string ID)\n{\n var fieldNames = getFieldNamesBasedOnType(typeof(T));\n QueryResult qr = webservice.query(\"SELECT \"+fieldNames + \" FROM \"\n + tyepof(T).Name\n +\" WHERE Id = '\" + ID + \"'\");\n return (T) qr.records[0];\n}\n</code></pre>\n"
},
{
"answer_id": 14693,
"author": "rptony",
"author_id": 1781,
"author_profile": "https://Stackoverflow.com/users/1781",
"pm_score": 3,
"selected": false,
"text": "<p>If I were you I would try to avoid any statics. IMHO I always ended up with some sort of synchronization issues down the road with statics. That being said you are presenting a classic example of generic programming using templates. I will adopt the template based solution of Rob Copper presented in one of the posts above. </p>\n"
},
{
"answer_id": 14720,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/users/1659/marxidad\">marxidad</a> Just a quick point to note, Justin has already said that the SQL varies a lot dependant on the type, so I have worked on the basis that it could be something <em>completely</em> different dependant on the type, hence delegating it to the subclasses in question. Whereas your solution couples the SQL <strong>VERY</strong> tightly to the Type (i.e. it <em>is</em> the SQL).</p>\n\n<p><a href=\"https://stackoverflow.com/users/1781/rptony\">rptony</a> Good point on the possible sync issues with statics, one I failed to mention, so thank you :) Also, its Rob <strong>Cooper</strong> (not Copper) BTW ;) :D ( <em>EDIT:</em> Just thought I would mention that in case it <em>wasn't</em> a typo, I expect it is, so no problem!)</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] | First off, I understand the reasons why an interface or abstract class (in the .NET/C# terminology) cannot have abstract static methods. My question is then more focused on the best design solution.
What I want is a set of "helper" classes that all have their own static methods such that if I get objects A, B, and C from a third party vendor, I can have helper classes with methods such as
```
AHelper.RetrieveByID(string id);
AHelper.RetrieveByName(string name);
AHelper.DumpToDatabase();
```
Since my AHelper, BHelper, and CHelper classes will all basically have the same methods, it seems to makes sense to move these methods to an interface that these classes then derive from. However, wanting these methods to be static precludes me from having a generic interface or abstract class for all of them to derive from.
I could always make these methods non-static and then instantiate the objects first such as
```
AHelper a = new AHelper();
a.DumpToDatabase();
```
However, this code doesn't seem as intuitive to me. What are your suggestions? Should I abandon using an interface or abstract class altogether (the situation I'm in now) or can this possibly be refactored to accomplish the design I'm looking for? | Looking at [your response](https://stackoverflow.com/questions/14614/static-methods-in-an-interfaceabstract-class#14655) I am thinking along the following lines:
* You could just have a static method that takes a type parameter and performs the expected logic based on the type.
* You could create a virtual method in your abstract base, where you specify the SQL in the concrete class. So that contains all the common code that is required by both (e.g. exectuting the command and returning the object) while encapsulating the "specialist" bits (e.g. the SQL) in the sub classes.
I prefer the second option, although its of course down to you. If you need me to go into further detail, please let me know and I will be happy to edit/update :) |
14,617 | <p>I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?</p>
| [
{
"answer_id": 14629,
"author": "David Hayes",
"author_id": 1769,
"author_profile": "https://Stackoverflow.com/users/1769",
"pm_score": 5,
"selected": false,
"text": "<p>This was the solution I came up with\n<a href=\"http://sourceforge.net/projects/sshtools/\" rel=\"noreferrer\">http://sourceforge.net/projects/sshtools/</a> (most error handling omitted for clarity). This is an excerpt from <a href=\"http://www.spindriftpages.net/blog/dave/2007/11/27/sshtools-j2ssh-java-sshsftp-library\" rel=\"noreferrer\">my blog</a></p>\n\n<pre><code>SshClient ssh = new SshClient();\nssh.connect(host, port);\n//Authenticate\nPasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();\npasswordAuthenticationClient.setUsername(userName);\npasswordAuthenticationClient.setPassword(password);\nint result = ssh.authenticate(passwordAuthenticationClient);\nif(result != AuthenticationProtocolState.COMPLETE){\n throw new SFTPException(\"Login to \" + host + \":\" + port + \" \" + userName + \"/\" + password + \" failed\");\n}\n//Open the SFTP channel\nSftpClient client = ssh.openSftpClient();\n//Send the file\nclient.put(filePath);\n//disconnect\nclient.quit();\nssh.disconnect();\n</code></pre>\n"
},
{
"answer_id": 15937,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 9,
"selected": true,
"text": "<p>Another option is to consider looking at the <a href=\"http://www.jcraft.com/jsch/\" rel=\"noreferrer\" title=\"JSch library\">JSch library</a>. JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.</p>\n\n<p>It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.</p>\n\n<p>Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)</p>\n\n<pre><code>JSch jsch = new JSch();\n\nString knownHostsFilename = \"/home/username/.ssh/known_hosts\";\njsch.setKnownHosts( knownHostsFilename );\n\nSession session = jsch.getSession( \"remote-username\", \"remote-host\" ); \n{\n // \"interactive\" version\n // can selectively update specified known_hosts file \n // need to implement UserInfo interface\n // MyUserInfo is a swing implementation provided in \n // examples/Sftp.java in the JSch dist\n UserInfo ui = new MyUserInfo();\n session.setUserInfo(ui);\n\n // OR non-interactive version. Relies in host key being in known-hosts file\n session.setPassword( \"remote-password\" );\n}\n\nsession.connect();\n\nChannel channel = session.openChannel( \"sftp\" );\nchannel.connect();\n\nChannelSftp sftpChannel = (ChannelSftp) channel;\n\nsftpChannel.get(\"remote-file\", \"local-file\" );\n// OR\nInputStream in = sftpChannel.get( \"remote-file\" );\n // process inputstream as needed\n\nsftpChannel.exit();\nsession.disconnect();\n</code></pre>\n"
},
{
"answer_id": 16851,
"author": "Boris Terzic",
"author_id": 1996,
"author_profile": "https://Stackoverflow.com/users/1996",
"pm_score": 5,
"selected": false,
"text": "<p>A nice abstraction on top of Jsch is Apache <a href=\"http://commons.apache.org/vfs/\" rel=\"noreferrer\">commons-vfs</a> which offers a virtual filesystem API that makes accessing and writing SFTP files almost transparent. Worked well for us.</p>\n"
},
{
"answer_id": 433052,
"author": "Brian Clapper",
"author_id": 53495,
"author_profile": "https://Stackoverflow.com/users/53495",
"pm_score": 0,
"selected": false,
"text": "<p>The best solution I've found is <a href=\"http://www.lag.net/paramiko/\" rel=\"nofollow noreferrer\">Paramiko</a>. There's a Java version.</p>\n"
},
{
"answer_id": 548977,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You also have JFileUpload with SFTP add-on (Java too):\n<a href=\"http://www.jfileupload.com/products/sftp/index.html\" rel=\"nofollow noreferrer\">http://www.jfileupload.com/products/sftp/index.html</a></p>\n"
},
{
"answer_id": 915030,
"author": "Bruce Blackshaw",
"author_id": 109114,
"author_profile": "https://Stackoverflow.com/users/109114",
"pm_score": 2,
"selected": false,
"text": "<p>Try <a href=\"http://www.enterprisedt.com/products/edtftpjssl/overview.html\" rel=\"nofollow noreferrer\">edtFTPj/PRO</a>, a mature, robust SFTP client library that supports connection pools and asynchronous operations. Also supports FTP and FTPS so all bases for secure file transfer are covered.</p>\n"
},
{
"answer_id": 1011405,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I use this SFTP API called Zehon, it's great, so easy to use with a lot of sample code. Here is the site <a href=\"http://www.zehon.com\" rel=\"nofollow noreferrer\">http://www.zehon.com</a></p>\n"
},
{
"answer_id": 2404783,
"author": "shikhar",
"author_id": 126346,
"author_profile": "https://Stackoverflow.com/users/126346",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://github.com/hierynomus/sshj\" rel=\"nofollow noreferrer\">hierynomus/sshj</a> has a complete implementation of SFTP version 3 (what OpenSSH implements)</p>\n\n<p>Example code from <a href=\"https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SFTPUpload.java\" rel=\"nofollow noreferrer\">SFTPUpload.java</a></p>\n\n<pre><code>package net.schmizz.sshj.examples;\n\nimport net.schmizz.sshj.SSHClient;\nimport net.schmizz.sshj.sftp.SFTPClient;\nimport net.schmizz.sshj.xfer.FileSystemFile;\n\nimport java.io.File;\nimport java.io.IOException;\n\n/** This example demonstrates uploading of a file over SFTP to the SSH server. */\npublic class SFTPUpload {\n\n public static void main(String[] args)\n throws IOException {\n final SSHClient ssh = new SSHClient();\n ssh.loadKnownHosts();\n ssh.connect(\"localhost\");\n try {\n ssh.authPublickey(System.getProperty(\"user.name\"));\n final String src = System.getProperty(\"user.home\") + File.separator + \"test_file\";\n final SFTPClient sftp = ssh.newSFTPClient();\n try {\n sftp.put(new FileSystemFile(src), \"/tmp\");\n } finally {\n sftp.close();\n }\n } finally {\n ssh.disconnect();\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 2548590,
"author": "Chris J",
"author_id": 165119,
"author_profile": "https://Stackoverflow.com/users/165119",
"pm_score": 6,
"selected": false,
"text": "<p>Below is an example using Apache Common VFS:</p>\n\n<pre><code>FileSystemOptions fsOptions = new FileSystemOptions();\nSftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, \"no\");\nFileSystemManager fsManager = VFS.getManager();\nString uri = \"sftp://user:password@host:port/absolute-path\";\nFileObject fo = fsManager.resolveFile(uri, fsOptions);\n</code></pre>\n"
},
{
"answer_id": 2690861,
"author": "Iraklis",
"author_id": 172467,
"author_profile": "https://Stackoverflow.com/users/172467",
"pm_score": 7,
"selected": false,
"text": "<p>Here is the complete source code of an example using <a href=\"http://www.jcraft.com/jsch/\" rel=\"noreferrer\">JSch</a> without having to worry about the ssh key checking.</p>\n\n<pre><code>import com.jcraft.jsch.*;\n\npublic class TestJSch {\n public static void main(String args[]) {\n JSch jsch = new JSch();\n Session session = null;\n try {\n session = jsch.getSession(\"username\", \"127.0.0.1\", 22);\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n session.setPassword(\"password\");\n session.connect();\n\n Channel channel = session.openChannel(\"sftp\");\n channel.connect();\n ChannelSftp sftpChannel = (ChannelSftp) channel;\n sftpChannel.get(\"remotefile.txt\", \"localfile.txt\");\n sftpChannel.exit();\n session.disconnect();\n } catch (JSchException e) {\n e.printStackTrace(); \n } catch (SftpException e) {\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4728735,
"author": "Dee Kay",
"author_id": 580515,
"author_profile": "https://Stackoverflow.com/users/580515",
"pm_score": 2,
"selected": false,
"text": "<p>I found complete working example for SFTP in java using JSCH API \n<a href=\"http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/\" rel=\"nofollow\">http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/</a></p>\n"
},
{
"answer_id": 5229795,
"author": "Pushpinder Rattan",
"author_id": 480686,
"author_profile": "https://Stackoverflow.com/users/480686",
"pm_score": 2,
"selected": false,
"text": "<p>Andy, to delete file on remote system you need to use <code>(channelExec)</code> of JSch and pass unix/linux commands to delete it.</p>\n"
},
{
"answer_id": 18005722,
"author": "Zon",
"author_id": 1112963,
"author_profile": "https://Stackoverflow.com/users/1112963",
"pm_score": 2,
"selected": false,
"text": "<p>Though answers above were very helpful, I've spent a day to make them work, facing various exceptions like \"broken channel\", \"rsa key unknown\" and \"packet corrupt\".</p>\n\n<p>Below is a working reusable class for SFTP FILES UPLOAD/DOWNLOAD using JSch library.</p>\n\n<p>Upload usage:</p>\n\n<pre><code>SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png\", /path/to/destinationfile.png\");\n</code></pre>\n\n<p>Download usage:</p>\n\n<pre><code>SFTPFileCopy download = new SFTPFileCopy(false, \"/path/to/sourcefile.png\", \"/path/to/destinationfile.png\");\n</code></pre>\n\n<p>The class code:</p>\n\n<pre><code>import com.jcraft.jsch.Channel;\nimport com.jcraft.jsch.ChannelSftp;\nimport com.jcraft.jsch.JSch;\nimport com.jcraft.jsch.Session;\nimport com.jcraft.jsch.UIKeyboardInteractive;\nimport com.jcraft.jsch.UserInfo;\nimport java.io.BufferedInputStream;\nimport java.io.BufferedOutputStream;\nimport java.io.ByteArrayInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport javax.swing.JOptionPane;\nimport menue.Menue;\n\npublic class SFTPFileCopy1 {\n\n public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {\n Session session = null;\n Channel channel = null;\n ChannelSftp sftpChannel = null;\n try {\n JSch jsch = new JSch();\n //jsch.setKnownHosts(\"/home/user/.putty/sshhostkeys\");\n session = jsch.getSession(\"login\", \"mysite.com\", 22);\n session.setPassword(\"password\");\n\n UserInfo ui = new MyUserInfo() {\n public void showMessage(String message) {\n\n JOptionPane.showMessageDialog(null, message);\n\n }\n\n public boolean promptYesNo(String message) {\n\n Object[] options = {\"yes\", \"no\"};\n\n int foo = JOptionPane.showOptionDialog(null,\n message,\n \"Warning\",\n JOptionPane.DEFAULT_OPTION,\n JOptionPane.WARNING_MESSAGE,\n null, options, options[0]);\n\n return foo == 0;\n\n }\n };\n session.setUserInfo(ui);\n\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n session.connect();\n channel = session.openChannel(\"sftp\");\n channel.setInputStream(System.in);\n channel.setOutputStream(System.out);\n channel.connect();\n sftpChannel = (ChannelSftp) channel;\n\n if (upload) { // File upload.\n byte[] bufr = new byte[(int) new File(sourcePath).length()];\n FileInputStream fis = new FileInputStream(new File(sourcePath));\n fis.read(bufr);\n ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);\n sftpChannel.put(fileStream, destPath);\n fileStream.close();\n } else { // File download.\n byte[] buffer = new byte[1024];\n BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));\n OutputStream os = new FileOutputStream(new File(destPath));\n BufferedOutputStream bos = new BufferedOutputStream(os);\n int readCount;\n while ((readCount = bis.read(buffer)) > 0) {\n bos.write(buffer, 0, readCount);\n }\n bis.close();\n bos.close();\n }\n } catch (Exception e) {\n System.out.println(e);\n } finally {\n if (sftpChannel != null) {\n sftpChannel.exit();\n }\n if (channel != null) {\n channel.disconnect();\n }\n if (session != null) {\n session.disconnect();\n }\n }\n }\n\n public static abstract class MyUserInfo\n implements UserInfo, UIKeyboardInteractive {\n\n public String getPassword() {\n return null;\n }\n\n public boolean promptYesNo(String str) {\n return false;\n }\n\n public String getPassphrase() {\n return null;\n }\n\n public boolean promptPassphrase(String message) {\n return false;\n }\n\n public boolean promptPassword(String message) {\n return false;\n }\n\n public void showMessage(String message) {\n }\n\n public String[] promptKeyboardInteractive(String destination,\n String name,\n String instruction,\n String[] prompt,\n boolean[] echo) {\n\n return null;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 18975867,
"author": "AZ_",
"author_id": 185022,
"author_profile": "https://Stackoverflow.com/users/185022",
"pm_score": 4,
"selected": false,
"text": "<p>See <a href=\"http://www.mysamplecode.com/2013/06/sftp-apache-commons-file-download.html\" rel=\"nofollow noreferrer\">http://www.mysamplecode.com/2013/06/sftp-apache-commons-file-download.html</a></p>\n<blockquote>\n<p>Apache Commons SFTP library</p>\n</blockquote>\n<p><strong>Common java properties file for all the examples</strong></p>\n<p>serverAddress=111.222.333.444</p>\n<p>userId=myUserId</p>\n<p>password=myPassword</p>\n<p>remoteDirectory=products/</p>\n<p>localDirectory=import/</p>\n<blockquote>\n<p>Upload file to remote server using SFTP</p>\n</blockquote>\n<pre><code>import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.Selectors;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class SendMyFiles {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n SendMyFiles sendMyFiles = new SendMyFiles();\n if (args.length < 1)\n {\n System.err.println("Usage: java " + sendMyFiles.getClass().getName()+\n " Properties_file File_To_FTP ");\n System.exit(1);\n }\n \n String propertiesFile = args[0].trim();\n String fileToFTP = args[1].trim();\n sendMyFiles.startFTP(propertiesFile, fileToFTP);\n \n }\n \n public boolean startFTP(String propertiesFilename, String fileToFTP){\n \n props = new Properties();\n StandardFileSystemManager manager = new StandardFileSystemManager();\n \n try {\n \n props.load(new FileInputStream("properties/" + propertiesFilename));\n String serverAddress = props.getProperty("serverAddress").trim();\n String userId = props.getProperty("userId").trim();\n String password = props.getProperty("password").trim();\n String remoteDirectory = props.getProperty("remoteDirectory").trim();\n String localDirectory = props.getProperty("localDirectory").trim();\n \n //check if the file exists\n String filepath = localDirectory + fileToFTP;\n File file = new File(filepath);\n if (!file.exists())\n throw new RuntimeException("Error. Local file not found");\n \n //Initializes the file manager\n manager.init();\n \n //Setup our SFTP configuration\n FileSystemOptions opts = new FileSystemOptions();\n SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n opts, "no");\n SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n \n //Create the SFTP URI using the host name, userid, password, remote path and file name\n String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + \n remoteDirectory + fileToFTP;\n \n // Create local file object\n FileObject localFile = manager.resolveFile(file.getAbsolutePath());\n \n // Create remote file object\n FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n // Copy local file to sftp server\n remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);\n System.out.println("File upload successful");\n \n }\n catch (Exception ex) {\n ex.printStackTrace();\n return false;\n }\n finally {\n manager.close();\n }\n \n return true;\n }\n \n \n}\n</code></pre>\n<blockquote>\n<p>Download file from remote server using SFTP</p>\n</blockquote>\n<pre><code>import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.Selectors;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class GetMyFiles {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n GetMyFiles getMyFiles = new GetMyFiles();\n if (args.length < 1)\n {\n System.err.println("Usage: java " + getMyFiles.getClass().getName()+\n " Properties_filename File_To_Download ");\n System.exit(1);\n }\n \n String propertiesFilename = args[0].trim();\n String fileToDownload = args[1].trim();\n getMyFiles.startFTP(propertiesFilename, fileToDownload);\n \n }\n \n public boolean startFTP(String propertiesFilename, String fileToDownload){\n \n props = new Properties();\n StandardFileSystemManager manager = new StandardFileSystemManager();\n \n try {\n \n props.load(new FileInputStream("properties/" + propertiesFilename));\n String serverAddress = props.getProperty("serverAddress").trim();\n String userId = props.getProperty("userId").trim();\n String password = props.getProperty("password").trim();\n String remoteDirectory = props.getProperty("remoteDirectory").trim();\n String localDirectory = props.getProperty("localDirectory").trim();\n \n \n //Initializes the file manager\n manager.init();\n \n //Setup our SFTP configuration\n FileSystemOptions opts = new FileSystemOptions();\n SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n opts, "no");\n SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n \n //Create the SFTP URI using the host name, userid, password, remote path and file name\n String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + \n remoteDirectory + fileToDownload;\n \n // Create local file object\n String filepath = localDirectory + fileToDownload;\n File file = new File(filepath);\n FileObject localFile = manager.resolveFile(file.getAbsolutePath());\n \n // Create remote file object\n FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n // Copy local file to sftp server\n localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);\n System.out.println("File download successful");\n \n }\n catch (Exception ex) {\n ex.printStackTrace();\n return false;\n }\n finally {\n manager.close();\n }\n \n return true;\n }\n \n}\n</code></pre>\n<blockquote>\n<p>Delete a file on remote server using SFTP</p>\n</blockquote>\n<pre><code>import java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class DeleteRemoteFile {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n DeleteRemoteFile getMyFiles = new DeleteRemoteFile();\n if (args.length < 1)\n {\n System.err.println("Usage: java " + getMyFiles.getClass().getName()+\n " Properties_filename File_To_Delete ");\n System.exit(1);\n }\n \n String propertiesFilename = args[0].trim();\n String fileToDownload = args[1].trim();\n getMyFiles.startFTP(propertiesFilename, fileToDownload);\n \n }\n \n public boolean startFTP(String propertiesFilename, String fileToDownload){\n \n props = new Properties();\n StandardFileSystemManager manager = new StandardFileSystemManager();\n \n try {\n \n props.load(new FileInputStream("properties/" + propertiesFilename));\n String serverAddress = props.getProperty("serverAddress").trim();\n String userId = props.getProperty("userId").trim();\n String password = props.getProperty("password").trim();\n String remoteDirectory = props.getProperty("remoteDirectory").trim();\n \n \n //Initializes the file manager\n manager.init();\n \n //Setup our SFTP configuration\n FileSystemOptions opts = new FileSystemOptions();\n SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n opts, "no");\n SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n \n //Create the SFTP URI using the host name, userid, password, remote path and file name\n String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + \n remoteDirectory + fileToDownload;\n \n //Create remote file object\n FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n //Check if the file exists\n if(remoteFile.exists()){\n remoteFile.delete();\n System.out.println("File delete successful");\n }\n \n }\n catch (Exception ex) {\n ex.printStackTrace();\n return false;\n }\n finally {\n manager.close();\n }\n \n return true;\n }\n \n}\n</code></pre>\n"
},
{
"answer_id": 36422906,
"author": "Sasha",
"author_id": 91495,
"author_profile": "https://Stackoverflow.com/users/91495",
"pm_score": 5,
"selected": false,
"text": "<p>There is a nice comparison of the 3 mature Java libraries for SFTP: <a href=\"https://www.javacodegeeks.com/2015/08/commons-vfs-sshj-and-jsch-in-comparison.html\" rel=\"noreferrer\">Commons VFS, SSHJ and JSch</a> </p>\n\n<p>To sum up SSHJ has the clearest API and it's the best out of them if you don't need other storages support provided by Commons VFS.</p>\n\n<p>Here is edited SSHJ example from <a href=\"https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SFTPDownload.java\" rel=\"noreferrer\">github</a>:</p>\n\n<pre><code>final SSHClient ssh = new SSHClient();\nssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())\nssh.connect(\"localhost\");\ntry {\n ssh.authPassword(\"user\", \"password\"); // or ssh.authPublickey(System.getProperty(\"user.name\"))\n final SFTPClient sftp = ssh.newSFTPClient();\n try {\n sftp.get(\"test_file\", \"/tmp/test.tmp\");\n } finally {\n sftp.close();\n }\n} finally {\n ssh.disconnect();\n}\n</code></pre>\n"
},
{
"answer_id": 46559783,
"author": "Ankur jain",
"author_id": 641001,
"author_profile": "https://Stackoverflow.com/users/641001",
"pm_score": 3,
"selected": false,
"text": "<p>JSch library is the powerful library that can be used to read file from SFTP server. Below is the tested code to read file from SFTP location line by line</p>\n\n<pre><code>JSch jsch = new JSch();\n Session session = null;\n try {\n session = jsch.getSession(\"user\", \"127.0.0.1\", 22);\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n session.setPassword(\"password\");\n session.connect();\n\n Channel channel = session.openChannel(\"sftp\");\n channel.connect();\n ChannelSftp sftpChannel = (ChannelSftp) channel;\n\n InputStream stream = sftpChannel.get(\"/usr/home/testfile.txt\");\n try {\n BufferedReader br = new BufferedReader(new InputStreamReader(stream));\n String line;\n while ((line = br.readLine()) != null) {\n System.out.println(line);\n }\n\n } catch (IOException io) {\n System.out.println(\"Exception occurred during reading file from SFTP server due to \" + io.getMessage());\n io.getMessage();\n\n } catch (Exception e) {\n System.out.println(\"Exception occurred during reading file from SFTP server due to \" + e.getMessage());\n e.getMessage();\n\n }\n\n sftpChannel.exit();\n session.disconnect();\n } catch (JSchException e) {\n e.printStackTrace();\n } catch (SftpException e) {\n e.printStackTrace();\n }\n</code></pre>\n\n<p>Please refer the <a href=\"https://ankurjain26.blogspot.in/2017/09/reading-file-from-remote-server-using.html\" rel=\"noreferrer\">blog</a> for whole program.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1769/"
] | I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this? | Another option is to consider looking at the [JSch library](http://www.jcraft.com/jsch/ "JSch library"). JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.
It supports both user/pass and certificate-based logins nicely, as well as all a whole host of other yummy SSH2 features.
Here's a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)
```
JSch jsch = new JSch();
String knownHostsFilename = "/home/username/.ssh/known_hosts";
jsch.setKnownHosts( knownHostsFilename );
Session session = jsch.getSession( "remote-username", "remote-host" );
{
// "interactive" version
// can selectively update specified known_hosts file
// need to implement UserInfo interface
// MyUserInfo is a swing implementation provided in
// examples/Sftp.java in the JSch dist
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
// OR non-interactive version. Relies in host key being in known-hosts file
session.setPassword( "remote-password" );
}
session.connect();
Channel channel = session.openChannel( "sftp" );
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get("remote-file", "local-file" );
// OR
InputStream in = sftpChannel.get( "remote-file" );
// process inputstream as needed
sftpChannel.exit();
session.disconnect();
``` |
14,698 | <p>When I try to precompile a *.pc file that contains a #warning directive I recieve the following error:</p>
<blockquote>
<p>PCC-S-02014, Encountered the symbol "warning" when expecting one of the following: (bla bla bla).</p>
</blockquote>
<p>Can I somehow convince Pro*C to ignore the thing if it doesn't know what to do with it? I can't remove the <code>#warning</code> directive as it's used in a header file that I can't change and must include.</p>
| [
{
"answer_id": 14999,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 0,
"selected": false,
"text": "<p>You can't. Pro*C only knows #if and #include. My best advice would be to preprocess the file as part of your build process to remove stuff Pro*C won't like. Something like</p>\n\n<pre><code>grep -v -E '^#(warning|pragma|define)' unchangeable.h >unchangeable.pc.h\n</code></pre>\n\n<p>My other advice would be to avoid the abomination which is Pro*C, but I'm guessing you're stuck with it...</p>\n"
},
{
"answer_id": 23585,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 4,
"selected": true,
"text": "<p>According to the <em>Pro*C/C++ Programmer's Guide</em> (chapter 5 \"Advanced Topics\"), Pro*C silently ignores a number of preprocessor directives including #error and #pragma, but sadly not #warning. Since your warning directives are included in a header file, you might be able to use the ORA_PROC macro:</p>\n\n<pre><code>#ifndef ORA_PROC\n#include <irrelevant.h>\n#endif\n</code></pre>\n\n<p>For some reason, Pro*C errors out if you try to hide a straight #warning that way, however. </p>\n"
},
{
"answer_id": 76234,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 0,
"selected": false,
"text": "<p>Jons Ericsons answer is correct.</p>\n\n<p>There is a second circumstance where you may need to use that trick.</p>\n\n<p>Some versions of Pro*c can't deal with include files that don't have a file extension.</p>\n\n<p>The ORA_PROC constant is one workable solution to that problem as well.</p>\n"
},
{
"answer_id": 336382,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>/bin/make -f /css/hwmig/pcprg/proc9i32.mk PROCFLAGS=\"sqlcheck=SEMANTICS userid=cssd/india09\" PCCSRC=bic I_SYM=include= pc1\n proc sqlcheck=SEMANTICS userid=cssd/india09 iname=bic include=. include=/oracle/Ora92/precomp/public include=/oracle/Ora92/rdbms/public include=/oracle/Ora92/rdbms/demo include=/oracle/Ora92/plsql/public include=/oracle/Ora92/network/public</p>\n\n<p>Pro*C/C++: Release 9.2.0.6.0 - Production on Tue Dec 2 14:05:38 2008</p>\n\n<p>Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.</p>\n\n<p>System default option values taken from: /oracle/Ora92/precomp/admin/pcscfg.cfg</p>\n\n<p>Syntax error at line 135, column 2, file /usr/include/standards.h:\nError at line 135, column 2 in file /usr/include/standards.h</p>\n\n<h1>warning The -qdfp option is required to process DFP code in headers.</h1>\n\n<p>.1\nPCC-S-02014, Encountered the symbol \"warning\" when expecting one of the followin\ng:</p>\n\n<p>a numeric constant, newline, define, elif, else, endif,\n error, if, ifdef, ifndef, include, line, pragma, undef,\n an immediate preprocessor command, a C token,\nThe symbol \"newline,\" was substituted for \"warning\" to continue.</p>\n\n<p>Syntax error at line 30, column 7, file bic.pc:\nError at line 30, column 7 in file bic.pc\nFILE <em>fp;\n......1\nPCC-S-02201, Encountered the symbol \"</em>\" when expecting one of the following:</p>\n\n<p>; , = ( [\nThe symbol \";\" was substituted for \"*\" to continue.</p>\n\n<p>Error at line 0, column 0 in file bic.pc\nPCC-F-02102, Fatal error while doing C preprocessing</p>\n"
},
{
"answer_id": 1051407,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Remove below two lines from /usr/include/standards.h</p>\n<h1>warning The -qdfp option is required to process DFP code in headers.</h1>\n<h1>else</h1>\n"
},
{
"answer_id": 3911475,
"author": "Ludwig",
"author_id": 472884,
"author_profile": "https://Stackoverflow.com/users/472884",
"pm_score": 2,
"selected": false,
"text": "<p>use option <code>parse=none</code> with proc</p>\n"
},
{
"answer_id": 4734773,
"author": "yijy",
"author_id": 581350,
"author_profile": "https://Stackoverflow.com/users/581350",
"pm_score": -1,
"selected": false,
"text": "<p>Modify <code>/usr/include/standards.h</code>.<br>\nDelete the line <code>#warning The -qdfp option is required to process DFP code in headers.</code> The proc does not support the <code>#warning</code>,just <code>#else</code> <code>#if</code> etc.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733/"
] | When I try to precompile a \*.pc file that contains a #warning directive I recieve the following error:
>
> PCC-S-02014, Encountered the symbol "warning" when expecting one of the following: (bla bla bla).
>
>
>
Can I somehow convince Pro\*C to ignore the thing if it doesn't know what to do with it? I can't remove the `#warning` directive as it's used in a header file that I can't change and must include. | According to the *Pro\*C/C++ Programmer's Guide* (chapter 5 "Advanced Topics"), Pro\*C silently ignores a number of preprocessor directives including #error and #pragma, but sadly not #warning. Since your warning directives are included in a header file, you might be able to use the ORA\_PROC macro:
```
#ifndef ORA_PROC
#include <irrelevant.h>
#endif
```
For some reason, Pro\*C errors out if you try to hide a straight #warning that way, however. |
14,708 | <p>What's the DOS FINDSTR equivalent for <a href="http://en.wikipedia.org/wiki/Windows_PowerShell" rel="noreferrer">PowerShell</a>? I need to search a bunch of log files for "ERROR".</p>
| [
{
"answer_id": 14724,
"author": "Monroecheeseman",
"author_id": 1351,
"author_profile": "https://Stackoverflow.com/users/1351",
"pm_score": 5,
"selected": false,
"text": "<p>Here's the quick answer </p>\n\n<pre><code>Get-ChildItem -Recurse -Include *.log | select-string ERROR \n</code></pre>\n\n<p>I found it <a href=\"http://www.interact-sw.co.uk/iangblog/2006/06/03/pshfindstr\" rel=\"noreferrer\">here</a> which has a great indepth answer!</p>\n"
},
{
"answer_id": 14725,
"author": "slipsec",
"author_id": 1635,
"author_profile": "https://Stackoverflow.com/users/1635",
"pm_score": 0,
"selected": false,
"text": "<pre><code>if ($entry.EntryType -eq \"Error\")\n</code></pre>\n\n<p>Being Object Oriented, you want to test the property in question with one of the standard comparison operators you can find <a href=\"http://www.computerperformance.co.uk/powershell/powershell_syntax.htm#Operators_\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I have a <a href=\"http://slipsec.blogspot.com/2008/04/monitoring-remote-event-logs-from.html\" rel=\"nofollow noreferrer\">PS script</a> watching logs remotely for me right now - some simple modification should make it work for you.</p>\n\n<p>edit: I suppose I should also add that is a cmdlet built for this already if you don't want to unroll the way I did. Check out:</p>\n\n<pre><code>man Get-EventLog\nGet-EventLog -newest 5 -logname System -EntryType Error\n</code></pre>\n"
},
{
"answer_id": 14737,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 3,
"selected": false,
"text": "<p>For example, find all instances of \"#include\" in the c files in this directory and all sub-directories.</p>\n\n<pre><code>gci -r -i *.c | select-string \"#include\"\n</code></pre>\n\n<p>gci is an alias for get-childitem</p>\n"
},
{
"answer_id": 15032,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 2,
"selected": false,
"text": "<p>Just to expand on Monroecheeseman's answer. gci is an alias for Get-ChildItem (which is the equivalent to dir or ls), the -r switch does a recursive search and -i means include.</p>\n\n<p>Piping the result of that query to select-string has it read each file and look for lines matching a regular expression (the provided one in this case is ERROR, but it can be any .NET regular expression). </p>\n\n<p>The result will be a collection of match objects, showing the line matching, the file, and and other related information.</p>\n"
},
{
"answer_id": 12324320,
"author": "Chris Rudd",
"author_id": 1229736,
"author_profile": "https://Stackoverflow.com/users/1229736",
"pm_score": 0,
"selected": false,
"text": "<p>On a related note, here's a search that will list all the files containing a particular regex search or string. It could use some improvement so feel free to work on it. Also if someone wanted to encapsulate it in a function that would be welcome.</p>\n\n<p>I'm new here so if this should go in it's own topic just let me know. I figured I'd put it her since this looks mostly related.</p>\n\n<pre><code># Search in Files Script\n# ---- Set these before you begin ---- \n$FolderToSearch=\"C:\\\" # UNC paths are ok, but remember you're mass reading file contents over the network\n$Search=\"Looking For This\" # accepts regex format\n$IncludeSubfolders=$True #BUG: if this is set $False then $FileIncludeFilter must be \"*\" or you will always get 0 results\n$AllMatches=$False\n$FileIncludeFilter=\"*\".split(\",\") # Restricting to specific file types is faster than excluding everything else\n$FileExcludeFilter=\"*.exe,*.dll,*.wav,*.mp3,*.gif,*.jpg,*.png,*.ghs,*.rar,*.iso,*.zip,*.vmdk,*.dat,*.pst,*.gho\".split(\",\")\n\n# ---- Initialize ----\nif ($AllMatches -eq $True) {$SelectParam=@{AllMatches=$True}}\nelse {$SelectParam=@{List=$True}}\nif ($IncludeSubfolders -eq $True) {$RecurseParam=@{Recurse=$True}}\nelse {$RecurseParam=@{Recurse=$False}}\n\n# ---- Build File List ---- \n#$Files=Get-Content -Path=\"$env:userprofile\\Desktop\\FileList.txt\" # For searching a manual list of files\nWrite-Host \"Building file list...\" -NoNewline\n$Files=Get-ChildItem -Include $FileIncludeFilter -Exclude $FileExcludeFilter -Path $FolderToSearch -ErrorAction silentlycontinue @RecurseParam|Where-Object{-not $_.psIsContainer} # @RecurseParam is basically -Recurse=[$True|$False]\n#$Files=$Files|Out-GridView -PassThru -Title 'Select the Files to Search' # Manually choose files to search, requires powershell 3.0\nWrite-Host \"Done\"\n\n# ---- Begin Search ---- \nWrite-Host \"Searching Files...\"\n$Files|\n Select-String $Search @SelectParam| #The @ instead of $ lets me pass the hastable as a list of parameters. @SelectParam is either -List or -AllMatches\n Tee-Object -Variable Results|\n Select-Object Path\nWrite-Host \"Search Complete\"\n#$Results|Group-Object path|ForEach-Object{$path=$_.name; $matches=$_.group|%{[string]::join(\"`t\", $_.Matches)}; \"$path`t$matches\"} # Show results including the matches separated by tabs (useful if using regex search)\n\n<# Other Stuff\n #-- Saving and restoring results\n $Results|Export-Csv \"$env:appdata\\SearchResults.txt\" # $env:appdata can be replaced with any UNC path, this just seemed like a logical place to default to\n $Results=Import-Csv \"$env:appdata\\SearchResults.txt\"\n\n #-- alternate search patterns\n $Search=\"(\\d[-|]{0,}){15,19}\" #Rough CC Match\n#>\n</code></pre>\n"
},
{
"answer_id": 21749061,
"author": "deostroll",
"author_id": 145682,
"author_profile": "https://Stackoverflow.com/users/145682",
"pm_score": 0,
"selected": false,
"text": "<p>This is not the best way to do this:</p>\n\n<pre><code>gci <the_directory_path> -filter *.csv | where { $_.OpenText().ReadToEnd().Contains(\"|\") -eq $true }\n</code></pre>\n\n<p>This helped me find all csv files which had the <code>|</code> character in them.</p>\n"
},
{
"answer_id": 35832654,
"author": "skataben",
"author_id": 873131,
"author_profile": "https://Stackoverflow.com/users/873131",
"pm_score": 0,
"selected": false,
"text": "<p>PowerShell has basically precluded the need for <em>findstr.exe</em> as the previous answers demonstrate. Any of these answers should work fine.</p>\n\n<p>However, <strong>if you actually need to use <em>findstr.exe</em></strong> (as was my case) here is a PowerShell wrapper for it:</p>\n\n<p>Use the <code>-Verbose</code> option to output the <em>findstr</em> command line.</p>\n\n<hr>\n\n<pre><code>function Find-String\n{\n [CmdletBinding(DefaultParameterSetName='Path')]\n param\n (\n [Parameter(Mandatory=$true, Position=0)]\n [string]\n $Pattern,\n\n [Parameter(ParameterSetName='Path', Mandatory=$false, Position=1, ValueFromPipeline=$true)]\n [string[]]\n $Path,\n\n [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]\n [Alias('PSPath')]\n [string[]]\n $LiteralPath,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $IgnoreCase,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $UseLiteral,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $Recurse,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $Force,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $AsCustomObject\n )\n\n begin\n {\n $value = $Pattern.Replace('\\', '\\\\\\\\').Replace('\"', '\\\"')\n\n $findStrArgs = @(\n '/N'\n '/O'\n @('/R', '/L')[[bool]$UseLiteral]\n \"/c:$value\"\n )\n\n if ($IgnoreCase)\n {\n $findStrArgs += '/I'\n }\n\n function GetCmdLine([array]$argList)\n {\n ($argList | foreach { @($_, \"`\"$_`\"\")[($_.Trim() -match '\\s')] }) -join ' '\n }\n }\n\n process\n {\n $PSBoundParameters[$PSCmdlet.ParameterSetName] | foreach {\n try\n {\n $_ | Get-ChildItem -Recurse:$Recurse -Force:$Force -ErrorAction Stop | foreach {\n try\n {\n $file = $_\n $argList = $findStrArgs + $file.FullName\n\n Write-Verbose \"findstr.exe $(GetCmdLine $argList)\"\n\n findstr.exe $argList | foreach {\n if (-not $AsCustomObject)\n {\n return \"${file}:$_\"\n }\n\n $split = $_.Split(':', 3)\n\n [pscustomobject] @{\n File = $file\n Line = $split[0]\n Column = $split[1]\n Value = $split[2]\n }\n }\n }\n catch\n {\n Write-Error -ErrorRecord $_\n }\n }\n }\n catch\n {\n Write-Error -ErrorRecord $_\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 63909531,
"author": "Patrick Burwell",
"author_id": 10836810,
"author_profile": "https://Stackoverflow.com/users/10836810",
"pm_score": 0,
"selected": false,
"text": "<p>FYI:\nIf you update to Powershell version 7 you can use grep...\nI know egrep is in powershell on Azure CLI...\nBut SS is there!\nAn old article here: [https://devblogs.microsoft.com/powershell/select-string-and-grep/]</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1351/"
] | What's the DOS FINDSTR equivalent for [PowerShell](http://en.wikipedia.org/wiki/Windows_PowerShell)? I need to search a bunch of log files for "ERROR". | Here's the quick answer
```
Get-ChildItem -Recurse -Include *.log | select-string ERROR
```
I found it [here](http://www.interact-sw.co.uk/iangblog/2006/06/03/pshfindstr) which has a great indepth answer! |
14,717 | <p>We're having sporadic, random query timeouts on our SQL Server 2005 cluster. I own a few apps that use it, so I'm helping out in the investigation. When watching the % CPU time in regular ol' Perfmon, you can certainly see it pegging out. However, SQL activity monitor only gives cumulative CPU and IO time used by a process, not what it's using right then, or over a specific timeframe. Perhaps I could use the profiler and run a trace, but this cluster is very heavily used and I'm afraid I'd be looking for a needle in a haystack. Am I barking up the wrong tree?</p>
<p>Does anyone have some good methods for tracking down expensive queries/processes in this environment?</p>
| [
{
"answer_id": 14730,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 2,
"selected": false,
"text": "<p>Profiler may seem like a \"needle in a haystack\" approach, but it may turn up something useful. Try running it for a couple of minutes while the databases are under typical load, and see if any queries stand out as taking way too much time or hogging resources in some way. While a situation like this could point to some general issue, it could also be related to some specific issue with one or two sites, which mess things up enough in certain circumstances to cause very poor performance across the board.</p>\n"
},
{
"answer_id": 14757,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 2,
"selected": false,
"text": "<p>We use Quest's <a href=\"http://www.quest.com/spotlight-on-sql-server-enterprise/\" rel=\"nofollow noreferrer\">Spotlight</a> product. Obviously it's an investment in time and money so it might not help you out in the short term but if you are have a large SQL environment it's pretty useful.</p>\n"
},
{
"answer_id": 14766,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 5,
"selected": true,
"text": "<p>This will give you the top 50 statements by average CPU time, check here for other scripts: <a href=\"http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true</a></p>\n\n<pre><code>SELECT TOP 50\n qs.total_worker_time/qs.execution_count as [Avg CPU Time],\n SUBSTRING(qt.text,qs.statement_start_offset/2, \n (case when qs.statement_end_offset = -1 \n then len(convert(nvarchar(max), qt.text)) * 2 \n else qs.statement_end_offset end -qs.statement_start_offset)/2) \n as query_text,\n qt.dbid, dbname=db_name(qt.dbid),\n qt.objectid \nFROM sys.dm_exec_query_stats qs\ncross apply sys.dm_exec_sql_text(qs.sql_handle) as qt\nORDER BY \n [Avg CPU Time] DESC\n</code></pre>\n"
},
{
"answer_id": 14778,
"author": "ChrisAnnODell",
"author_id": 1758,
"author_profile": "https://Stackoverflow.com/users/1758",
"pm_score": 2,
"selected": false,
"text": "<p>As Yaakov says, run profiler for a few minutes under typical load and save the results to a table which will allow you to run queries against the results making it much easier to spot any resource hogging queries.</p>\n"
},
{
"answer_id": 14794,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "<p>Run Profiler and filter for queries that take more than a certain number of reads. For the application I worked on, any non-reporting query that took more than 5000 reads deserved a second look. Your app may have a different threshold, but the idea is the same.</p>\n"
},
{
"answer_id": 14868,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.sommarskog.se/sqlutil/aba_lockinfo.html\" rel=\"nofollow noreferrer\">This utility</a> by Erland Sommarskog is awesomely useful.</p>\n\n<p>It's a stored procedure you add to your database. Run it whenever you want to see what queries are active and get a good picture of locks, blocks, etc. I use it regularly when things seem gummed up.</p>\n"
},
{
"answer_id": 14876,
"author": "Paul G",
"author_id": 162,
"author_profile": "https://Stackoverflow.com/users/162",
"pm_score": 2,
"selected": false,
"text": "<p>I've found the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=1d3a4a0d-7e0c-4730-8204-e419218c1efc&displaylang=en\" rel=\"nofollow noreferrer\">Performance Dashboard Reports</a> to be very helpful. They are a set of custom RS reports supplied by Microsoft. You just have to run the installer on your client PC and then run the setup.sql on the SQL Server instance. </p>\n\n<p>After that, right click on a database (does not matter which one) in SSMS and goto Reports -> Custom Reports. Navigate to and select the performance_dashboard_main.rdl which is located at in the \\Program Files\\Microsoft SQL Server\\90\\Tools\\PerformanceDashboard folder by default. You only need to do this once. After the first time, it will show up in the reports list. </p>\n\n<p>The main dashboard view will show CPU utilization over time, among other things. You can refresh it occasionally. When you see a spike, just click on the bar in the graph to get the detail data behind it.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
] | We're having sporadic, random query timeouts on our SQL Server 2005 cluster. I own a few apps that use it, so I'm helping out in the investigation. When watching the % CPU time in regular ol' Perfmon, you can certainly see it pegging out. However, SQL activity monitor only gives cumulative CPU and IO time used by a process, not what it's using right then, or over a specific timeframe. Perhaps I could use the profiler and run a trace, but this cluster is very heavily used and I'm afraid I'd be looking for a needle in a haystack. Am I barking up the wrong tree?
Does anyone have some good methods for tracking down expensive queries/processes in this environment? | This will give you the top 50 statements by average CPU time, check here for other scripts: <http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true>
```
SELECT TOP 50
qs.total_worker_time/qs.execution_count as [Avg CPU Time],
SUBSTRING(qt.text,qs.statement_start_offset/2,
(case when qs.statement_end_offset = -1
then len(convert(nvarchar(max), qt.text)) * 2
else qs.statement_end_offset end -qs.statement_start_offset)/2)
as query_text,
qt.dbid, dbname=db_name(qt.dbid),
qt.objectid
FROM sys.dm_exec_query_stats qs
cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt
ORDER BY
[Avg CPU Time] DESC
``` |
14,731 | <p>Normally I would just use:</p>
<pre><code>HttpContext.Current.Server.UrlEncode("url");
</code></pre>
<p>But since this is a console application, <code>HttpContext.Current</code> is always going to be <code>null</code>.</p>
<p>Is there another method that does the same thing that I could use?</p>
| [
{
"answer_id": 14734,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 2,
"selected": false,
"text": "<p>Try using the UrlEncode method in the HttpUtility class.</p>\n\n<ol>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx</a></li>\n</ol>\n"
},
{
"answer_id": 14736,
"author": "Andrew Taylor",
"author_id": 1776,
"author_profile": "https://Stackoverflow.com/users/1776",
"pm_score": 6,
"selected": false,
"text": "<p>I'm not a .NET guy, but, can't you use:</p>\n\n<pre><code>HttpUtility.UrlEncode Method (String)\n</code></pre>\n\n<p>Which is described here:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/4fkewx0t.aspx\" rel=\"noreferrer\">HttpUtility.UrlEncode Method (String) on MSDN</a></p>\n"
},
{
"answer_id": 14739,
"author": "Vaibhav",
"author_id": 380,
"author_profile": "https://Stackoverflow.com/users/380",
"pm_score": 1,
"selected": false,
"text": "<p>HttpUtility.UrlEncode(\"url\") in System.Web.</p>\n"
},
{
"answer_id": 14742,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 1,
"selected": false,
"text": "<p>use the static HttpUtility.UrlEncode method. </p>\n"
},
{
"answer_id": 14745,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "<p>You'll want to use </p>\n\n<pre><code>System.Web.HttpUtility.urlencode(\"url\")\n</code></pre>\n\n<p>Make sure you have system.web as one of the references in your project. I don't think it's included as a reference by default in console applications.</p>\n"
},
{
"answer_id": 390650,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this problem myself, and rather than add the System.Web assembly to my project, I wrote a class for encoding/decoding URLs (its pretty simple, and I've done some testing, but not a lot). I've included the source code below. Please: leave the comment at the top if you reuse this, don't blame me if it breaks, learn from the code.</p>\n\n<pre><code>''' <summary>\n''' URL encoding class. Note: use at your own risk.\n''' Written by: Ian Hopkins (http://www.lucidhelix.com)\n''' Date: 2008-Dec-23\n''' </summary>\nPublic Class UrlHelper\n Public Shared Function Encode(ByVal str As String) As String\n Dim charClass = String.Format(\"0-9a-zA-Z{0}\", Regex.Escape(\"-_.!~*'()\"))\n Dim pattern = String.Format(\"[^{0}]\", charClass)\n Dim evaluator As New MatchEvaluator(AddressOf EncodeEvaluator)\n\n ' replace the encoded characters\n Return Regex.Replace(str, pattern, evaluator)\n End Function\n\n Private Shared Function EncodeEvaluator(ByVal match As Match) As String\n ' Replace the \" \"s with \"+\"s\n If (match.Value = \" \") Then\n Return \"+\"\n End If\n Return String.Format(\"%{0:X2}\", Convert.ToInt32(match.Value.Chars(0)))\n End Function\n\n Public Shared Function Decode(ByVal str As String) As String\n Dim evaluator As New MatchEvaluator(AddressOf DecodeEvaluator)\n\n ' Replace the \"+\"s with \" \"s\n str = str.Replace(\"+\"c, \" \"c)\n\n ' Replace the encoded characters\n Return Regex.Replace(str, \"%[0-9a-zA-Z][0-9a-zA-Z]\", evaluator)\n End Function\n\n Private Shared Function DecodeEvaluator(ByVal match As Match) As String\n Return \"\" + Convert.ToChar(Integer.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber))\n End Function\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 650823,
"author": "Anjisan",
"author_id": 25304,
"author_profile": "https://Stackoverflow.com/users/25304",
"pm_score": 2,
"selected": false,
"text": "<p>Kibbee offers the real answer. Yes, HttpUtility.UrlEncode is the right method to use, but it will not be available by default for a console application. You <strong>must</strong> add a reference to System.Web. To do that,</p>\n\n<ol>\n<li>In your solution explorer, right click on references</li>\n<li>Choose \"add reference\"</li>\n<li>In the \"Add Reference\" dialog box, use the .NET tab</li>\n<li>Scroll down to System.Web, select that, and hit ok</li>\n</ol>\n\n<p>NOW you can use the UrlEncode method. You'll still want to add,</p>\n\n<p>using System.Web </p>\n\n<p>at the top of your console app or use the full namespace when calling the method,</p>\n\n<p>System.Web.HttpUtility.UrlEncode(someString)</p>\n"
},
{
"answer_id": 4006817,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 4,
"selected": false,
"text": "<p>The code from Ian Hopkins does the trick for me without having to add a reference to System.Web. Here is a port to C# for those who are not using VB.NET: </p>\n\n<pre><code>/// <summary>\n/// URL encoding class. Note: use at your own risk.\n/// Written by: Ian Hopkins (http://www.lucidhelix.com)\n/// Date: 2008-Dec-23\n/// (Ported to C# by t3rse (http://www.t3rse.com))\n/// </summary>\npublic class UrlHelper\n{\n public static string Encode(string str) {\n var charClass = String.Format(\"0-9a-zA-Z{0}\", Regex.Escape(\"-_.!~*'()\"));\n return Regex.Replace(str, \n String.Format(\"[^{0}]\", charClass),\n new MatchEvaluator(EncodeEvaluator));\n }\n\n public static string EncodeEvaluator(Match match)\n {\n return (match.Value == \" \")?\"+\" : String.Format(\"%{0:X2}\", Convert.ToInt32(match.Value[0]));\n }\n\n public static string DecodeEvaluator(Match match) {\n return Convert.ToChar(int.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber)).ToString();\n }\n\n public static string Decode(string str) \n {\n return Regex.Replace(str.Replace('+', ' '), \"%[0-9a-zA-Z][0-9a-zA-Z]\", new MatchEvaluator(DecodeEvaluator));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8931490,
"author": "Ostati",
"author_id": 2654100,
"author_profile": "https://Stackoverflow.com/users/2654100",
"pm_score": 7,
"selected": true,
"text": "<p>Try this!</p>\n\n<pre><code>Uri.EscapeUriString(url);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>Uri.EscapeDataString(data)\n</code></pre>\n\n<p>No need to reference System.Web.</p>\n\n<p><strong>Edit:</strong> Please see <a href=\"https://stackoverflow.com/a/34189188/7391\">another</a> SO answer for more...</p>\n"
},
{
"answer_id": 35093168,
"author": "Devson Technologies",
"author_id": 1232988,
"author_profile": "https://Stackoverflow.com/users/1232988",
"pm_score": 3,
"selected": false,
"text": "<p>Add <code>using System.Net;</code> then use: <code>WebUtility.UrlDecode(string)</code><br />\nor Fully-Qualify: <code>System.Net.WebUtility.UrlDecode(string)</code></p>\n<p>No need to add any additional References.<br />\nThe <code>WebUtility</code> is included (by Default) in <code>System</code> (under the "<em>References</em>" Project Folder).</p>\n"
},
{
"answer_id": 38713004,
"author": "Girjesh Kumar Vishwakarma",
"author_id": 5126961,
"author_profile": "https://Stackoverflow.com/users/5126961",
"pm_score": 0,
"selected": false,
"text": "<p>Best thing is to Add Reference to System.web..dll</p>\n\n<p>and use \nvar EncodedUrl=System.Web.HttpUtility.UrlEncode(\"URL_TEXT\");</p>\n\n<p>You can find the File at <a href=\"http://originaldll.com/download/11019.dll\" rel=\"nofollow noreferrer\">System.web.dll</a></p>\n"
},
{
"answer_id": 48805794,
"author": "Jason",
"author_id": 7391,
"author_profile": "https://Stackoverflow.com/users/7391",
"pm_score": 0,
"selected": false,
"text": "<p>Uri.EscapeUriString should not be used for escaping a string to be passed in a URL as it does not encode all characters as you might expect. The '+' is a good example which is not escaped. This then gets converted to a space in the URL since this is what it means in a simple URI. Obviously that causes massive issues the minute you try and pass something like a base 64 encoded string in the URL and spaces appear all over your string at the receiving end.</p>\n\n<p>You can use HttpUtility.UrlEncode and add the required references to your project (and if you're communicating with a web application then I see no reason why you shouldn't do this).</p>\n\n<p>Alternatively use Uri.EscapeDataString over Uri.EscapeUriString as explained very well here: <a href=\"https://stackoverflow.com/a/34189188/7391\">https://stackoverflow.com/a/34189188/7391</a></p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469/"
] | Normally I would just use:
```
HttpContext.Current.Server.UrlEncode("url");
```
But since this is a console application, `HttpContext.Current` is always going to be `null`.
Is there another method that does the same thing that I could use? | Try this!
```
Uri.EscapeUriString(url);
```
Or
```
Uri.EscapeDataString(data)
```
No need to reference System.Web.
**Edit:** Please see [another](https://stackoverflow.com/a/34189188/7391) SO answer for more... |
14,801 | <p>Suppose you have the following EJB 3 interfaces/classes:</p>
<pre><code>public interface Repository<E>
{
public void delete(E entity);
}
public abstract class AbstractRepository<E> implements Repository<E>
{
public void delete(E entity){
//...
}
}
public interface FooRepository<Foo>
{
//other methods
}
@Local(FooRepository.class)
@Stateless
public class FooRepositoryImpl extends
AbstractRepository<Foo> implements FooRepository
{
@Override
public void delete(Foo entity){
//do something before deleting the entity
super.delete(entity);
}
//other methods
}
</code></pre>
<p>And then another bean that accesses the <code>FooRepository</code> bean :</p>
<pre><code>//...
@EJB
private FooRepository fooRepository;
public void someMethod(Foo foo)
{
fooRepository.delete(foo);
}
//...
</code></pre>
<p>However, the overriding method is never executed when the delete method of the <code>FooRepository</code> bean is called. Instead, only the implementation of the delete method that is defined in <code>AbstractRepository</code> is executed. </p>
<p>What am I doing wrong or is it simply a limitation of Java/EJB 3 that generics and inheritance don't play well together yet ?</p>
| [
{
"answer_id": 14920,
"author": "Mike Deck",
"author_id": 1247,
"author_profile": "https://Stackoverflow.com/users/1247",
"pm_score": 1,
"selected": false,
"text": "<p>Can you write a unit test against your FooRepository class just using it as a POJO. If that works as expected then I'm not familiar with any reason why it would function differently inside a container.</p>\n\n<p>I suspect there is something else going on and it will probably be easier to debug if you test it as a POJO.</p>\n"
},
{
"answer_id": 15279,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 3,
"selected": true,
"text": "<p>I tried it with a pojo and it seems to work. I had to modify your code a bit.\nI think your interfaces were a bit off, but I'm not sure.</p>\n\n<p>I assumed \"Foo\" was a concrete type, but if not I can do some more testing for you.</p>\n\n<p>I just wrote a main method to test this.\nI hope this helps!</p>\n\n<pre><code>public static void main(String[] args){\n FooRepository fooRepository = new FooRepositoryImpl();\n fooRepository.delete(new Foo(\"Bar\"));\n}\n\npublic class Foo\n{\n private String value;\n\n public Foo(String inValue){\n super();\n value = inValue;\n }\n public String toString(){\n return value;\n }\n}\n\npublic interface Repository<E>\n{\n public void delete(E entity);\n}\n\npublic interface FooRepository extends Repository<Foo>\n{\n //other methods\n}\n\npublic class AbstractRespository<E> implements Repository<E>\n{\n public void delete(E entity){\n System.out.println(\"Delete-\" + entity.toString());\n }\n}\n\npublic class FooRepositoryImpl extends AbstractRespository<Foo> implements FooRepository\n{\n @Override\n public void delete(Foo entity){\n //do something before deleting the entity\n System.out.println(\"something before\");\n super.delete(entity);\n }\n}\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793/"
] | Suppose you have the following EJB 3 interfaces/classes:
```
public interface Repository<E>
{
public void delete(E entity);
}
public abstract class AbstractRepository<E> implements Repository<E>
{
public void delete(E entity){
//...
}
}
public interface FooRepository<Foo>
{
//other methods
}
@Local(FooRepository.class)
@Stateless
public class FooRepositoryImpl extends
AbstractRepository<Foo> implements FooRepository
{
@Override
public void delete(Foo entity){
//do something before deleting the entity
super.delete(entity);
}
//other methods
}
```
And then another bean that accesses the `FooRepository` bean :
```
//...
@EJB
private FooRepository fooRepository;
public void someMethod(Foo foo)
{
fooRepository.delete(foo);
}
//...
```
However, the overriding method is never executed when the delete method of the `FooRepository` bean is called. Instead, only the implementation of the delete method that is defined in `AbstractRepository` is executed.
What am I doing wrong or is it simply a limitation of Java/EJB 3 that generics and inheritance don't play well together yet ? | I tried it with a pojo and it seems to work. I had to modify your code a bit.
I think your interfaces were a bit off, but I'm not sure.
I assumed "Foo" was a concrete type, but if not I can do some more testing for you.
I just wrote a main method to test this.
I hope this helps!
```
public static void main(String[] args){
FooRepository fooRepository = new FooRepositoryImpl();
fooRepository.delete(new Foo("Bar"));
}
public class Foo
{
private String value;
public Foo(String inValue){
super();
value = inValue;
}
public String toString(){
return value;
}
}
public interface Repository<E>
{
public void delete(E entity);
}
public interface FooRepository extends Repository<Foo>
{
//other methods
}
public class AbstractRespository<E> implements Repository<E>
{
public void delete(E entity){
System.out.println("Delete-" + entity.toString());
}
}
public class FooRepositoryImpl extends AbstractRespository<Foo> implements FooRepository
{
@Override
public void delete(Foo entity){
//do something before deleting the entity
System.out.println("something before");
super.delete(entity);
}
}
``` |
14,857 | <p><strong>Bounty:</strong> I will send $5 via paypal for an answer that fixes this problem for me.</p>
<p>I'm not sure what VS setting I've changed or if it's a web.config setting or what, but I keep getting this error in the error list and yet all solutions build fine. Here are some examples:</p>
<pre>
Error 5 'CompilerGlobalScopeAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. C:\projects\MyProject\Web\Controls\EmailStory.ascx 609 184 C:\...\Web\
Error 6 'ArrayList' is ambiguous in the namespace 'System.Collections'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 13 28 C:\...\Web\
Error 7 'Exception' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 37 21 C:\...\Web\
Error 8 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 47 64 C:\...\Web\
Error 9 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 140 72 C:\...\Web\
Error 10 'Array' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 147 35 C:\...\Web\
[...etc...]
Error 90 'DateTime' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\App_Code\XsltHelperFunctions.vb 13 8 C:\...\Web\
</pre>
<p>As you can imagine, it's really annoying since there are blue squiggly underlines everywhere in the code, and filtering out relevant errors in the Error List pane is near impossible. I've checked the default ASP.Net web.config and machine.config but nothing seemed to stand out there.</p>
<hr>
<p><em>Edit:</em> Here's some of the source where the errors are occurring:</p>
<pre><code>'Error #5: whole line is blue underlined'
<%= addEmailToList.ToolTip %>
'Error #6: ArrayList is blue underlined'
Private _emails As New ArrayList()
'Error #7: Exception is blue underlined'
Catch ex As Exception
'Error #8: System.EventArgs is blue underlined'
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Error #9: System.EventArgs is blue underlined'
Protected Sub sendMessage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendMessage.Click
'Error #10: Array is blue underlined'
Me.emailSentTo.Text = Array.Join(";", mailToAddresses)
'Error #90: DateTime is blue underlined'
If DateTime.TryParse(data, dateValue) Then
</code></pre>
<hr>
<p><em>Edit</em>: GacUtil results</p>
<pre>
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\gacutil -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 1.1.4318.0
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
The Global Assembly Cache contains the following assemblies:
The cache of ngen files contains the following entries:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d003700430039004
40037004500430036000000
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00370043003
900450036003100370035000000
Number of items = 2
</pre>
<pre>
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
The Global Assembly Cache contains the following assemblies:
Number of items = 0
</pre>
<hr>
<p><em>Edit</em>: interesting results from ngen:</p>
<pre><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ngen display mscorlib /verbose
Microsoft (R) CLR Native Image Generator - Version 2.0.50727.832
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
NGEN Roots:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
ScenarioDefault
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
ScenarioNoDependencies
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
NGEN Roots that depend on "mscorlib":
[...a bunch of stuff...]
Native Images:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
</code></pre>
<p>There should only be one mscorlib in the native images, correct? How can I get rid of the others?</p>
| [
{
"answer_id": 14861,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 0,
"selected": false,
"text": "<p>When asking for help diagnosing compilation problems, it often helps to post the offending source code :)</p>\n\n<p>These errors really mean that the specified name conflicts with another and the compiler cannot resolve this. It does look a little odd tho..</p>\n"
},
{
"answer_id": 14875,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>I've been hit by this as well, specifically System.Data.SqlClient. Try unchecking namespaces in the Project manager and manually including them in the .vb file, like you would with C#:</p>\n\n<p>Imports System.Data.SqlClient</p>\n"
},
{
"answer_id": 14877,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>Take one error (like ArrayList) and replace the type with the full-qualified name (I'm not sure, but I guess here: System.Collection.ArrayList). If the error vanishes, you really have a resolving conflict. If not, it's something else.<br>\nIf all solutions build \"fine\" with these errors, I suggest cleaning your projects. Delete all compiled stuff (dll, pdb, whatsoever), also shadow cached ones. Maybe it compiles because it uses an old version of something.</p>\n"
},
{
"answer_id": 15027,
"author": "John Smithers",
"author_id": 1069,
"author_profile": "https://Stackoverflow.com/users/1069",
"pm_score": 0,
"selected": false,
"text": "<p>I know this sounds odd, but do you use \"Build\" or \"Rebuild\" to build the solution? If I have funny problems like that, a \"Rebuild All\" to the solution helps.</p>\n"
},
{
"answer_id": 92755,
"author": "Spell",
"author_id": 7185,
"author_profile": "https://Stackoverflow.com/users/7185",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same error recently.\nHere's how I fixed it (I hope it works for you too):</p>\n\n<p>-Open your project properties, go to the references section.</p>\n\n<p>-Remove the reference to System in the upper section.</p>\n\n<p>I think it's referencing System twice but it's only showing once. Hence the ambigous references.</p>\n"
},
{
"answer_id": 96161,
"author": "Richard Morgan",
"author_id": 2258,
"author_profile": "https://Stackoverflow.com/users/2258",
"pm_score": 2,
"selected": true,
"text": "<p>Based on the results of your gacutil output (thanks for doing that; I think it helps), I would say you need to try and run a repair on the .NET Framework install and Visual Studio 2005. I'm not sure if that will fix it, but as you can see from the output of the gacutil, you have none for 2.0.</p>\n\n<p>From my VS2005 Command Prompt, I get:</p>\n\n<pre>\nMicrosoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nThe Global Assembly Cache contains the following assemblies:\n mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86\n\nNumber of items = 1\n</pre>\n\n<p>From my VS2003 Command Prompt, I get:</p>\n\n<pre>\nMicrosoft (R) .NET Global Assembly Cache Utility. Version 1.1.4322.573\nCopyright (C) Microsoft Corporation 1998-2002. All rights reserved.\n\nThe Global Assembly Cache contains the following assemblies:\n\nThe cache of ngen files contains the following entries:\n mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000\n mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00330037004200440036004600430034000000\n\nNumber of items = 2\n</pre>\n"
},
{
"answer_id": 592297,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Yesterday I got the same in VS2005 ASP.NET web site project: suddenly, with any previous significant code change, loads of 'x' is ambiguous in the namespace 'y' appeared, all of them originated from very fundamental symbols, like EventArgs, Type, DBNull, etc.</p>\n\n<p>Immediate reason of that is double-referenced mscorlib, as I can see in VS's Class View. The true reason, I believe, is the automatic Windows Update which had forced me to restart the machine minutes before.</p>\n\n<p>Trying such stunts like establishing a brand new ASP.NET web site project, copy-paste the source text on it (on the same machine - doesn't help) or move the project on the second machine with the same VS2005 installation (it helps, project works normally) I'm nearly sure there is nothing wrong with my code, but with my VS/.NET configuration. And I desperately don't know how to cure it, as there is no trace on the Internet describing similar troubles, apart from this one.</p>\n"
},
{
"answer_id": 592331,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 0,
"selected": false,
"text": "<p>Reinstall <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=0856eacb-4362-4b0d-8edd-aab15c5e04f5&displaylang=en\" rel=\"nofollow noreferrer\">.Net Framework 2.0</a>.</p>\n\n<p>That should fix it. Afterwards, <code>gacutil</code> (from v2.0) would show 1 <code>mscorlib</code> and not 0.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | **Bounty:** I will send $5 via paypal for an answer that fixes this problem for me.
I'm not sure what VS setting I've changed or if it's a web.config setting or what, but I keep getting this error in the error list and yet all solutions build fine. Here are some examples:
```
Error 5 'CompilerGlobalScopeAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. C:\projects\MyProject\Web\Controls\EmailStory.ascx 609 184 C:\...\Web\
Error 6 'ArrayList' is ambiguous in the namespace 'System.Collections'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 13 28 C:\...\Web\
Error 7 'Exception' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 37 21 C:\...\Web\
Error 8 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 47 64 C:\...\Web\
Error 9 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 140 72 C:\...\Web\
Error 10 'Array' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 147 35 C:\...\Web\
[...etc...]
Error 90 'DateTime' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\App_Code\XsltHelperFunctions.vb 13 8 C:\...\Web\
```
As you can imagine, it's really annoying since there are blue squiggly underlines everywhere in the code, and filtering out relevant errors in the Error List pane is near impossible. I've checked the default ASP.Net web.config and machine.config but nothing seemed to stand out there.
---
*Edit:* Here's some of the source where the errors are occurring:
```
'Error #5: whole line is blue underlined'
<%= addEmailToList.ToolTip %>
'Error #6: ArrayList is blue underlined'
Private _emails As New ArrayList()
'Error #7: Exception is blue underlined'
Catch ex As Exception
'Error #8: System.EventArgs is blue underlined'
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Error #9: System.EventArgs is blue underlined'
Protected Sub sendMessage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendMessage.Click
'Error #10: Array is blue underlined'
Me.emailSentTo.Text = Array.Join(";", mailToAddresses)
'Error #90: DateTime is blue underlined'
If DateTime.TryParse(data, dateValue) Then
```
---
*Edit*: GacUtil results
```
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\gacutil -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 1.1.4318.0
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
The Global Assembly Cache contains the following assemblies:
The cache of ngen files contains the following entries:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d003700430039004
40037004500430036000000
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00370043003
900450036003100370035000000
Number of items = 2
```
```
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
The Global Assembly Cache contains the following assemblies:
Number of items = 0
```
---
*Edit*: interesting results from ngen:
```
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ngen display mscorlib /verbose
Microsoft (R) CLR Native Image Generator - Version 2.0.50727.832
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
NGEN Roots:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
ScenarioDefault
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
ScenarioNoDependencies
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
NGEN Roots that depend on "mscorlib":
[...a bunch of stuff...]
Native Images:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
```
There should only be one mscorlib in the native images, correct? How can I get rid of the others? | Based on the results of your gacutil output (thanks for doing that; I think it helps), I would say you need to try and run a repair on the .NET Framework install and Visual Studio 2005. I'm not sure if that will fix it, but as you can see from the output of the gacutil, you have none for 2.0.
From my VS2005 Command Prompt, I get:
```
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
The Global Assembly Cache contains the following assemblies:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=x86
Number of items = 1
```
From my VS2003 Command Prompt, I get:
```
Microsoft (R) .NET Global Assembly Cache Utility. Version 1.1.4322.573
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
The Global Assembly Cache contains the following assemblies:
The cache of ngen files contains the following entries:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00330037004200440036004600430034000000
Number of items = 2
``` |
14,873 | <p>I've noticed that a few Wordpress blogs have query statistics present in their footer that simply state the number of queries and the total time required to process them for the particular page, reading something like:</p>
<blockquote>
<p>23 queries. 0.448 seconds</p>
</blockquote>
<p>I was wondering how this is accomplished. Is it through the use of a particular Wordpress plug-in or perhaps from using some particular php function in the page's code?</p>
| [
{
"answer_id": 14972,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 5,
"selected": true,
"text": "<p>Try adding this to the bottom of the footer in your template:</p>\n\n<pre><code><?php echo $wpdb->num_queries; ?> <?php _e('queries'); ?>. <?php timer_stop(1); ?> <?php _e('seconds'); ?>\n</code></pre>\n"
},
{
"answer_id": 15386,
"author": "Carl Russmann",
"author_id": 1347,
"author_profile": "https://Stackoverflow.com/users/1347",
"pm_score": 3,
"selected": false,
"text": "<p>To explain pix0r's code:</p>\n\n<ul>\n<li><p><code>$wpdb->num_queries</code> is the number of database queries.</p></li>\n<li><p><code>_e</code> is for localization: <a href=\"http://faq.wordpress.net/view.php?p=50\" rel=\"nofollow noreferrer\">http://faq.wordpress.net/view.php?p=50</a></p></li>\n<li><p><code>timer_stop()</code> returns the amount of time taken to render the page: <br> <a href=\"http://codex.wordpress.org/Function_Reference/timer_stop\" rel=\"nofollow noreferrer\">http://codex.wordpress.org/Function_Reference/timer_stop</a></p></li>\n</ul>\n"
},
{
"answer_id": 23636709,
"author": "Manoj H L",
"author_id": 2095317,
"author_profile": "https://Stackoverflow.com/users/2095317",
"pm_score": 1,
"selected": false,
"text": "<p>wordpress has a easy solution now</p>\n\n<p>There is a function called <a href=\"http://codex.wordpress.org/Function_Reference/get_num_queries\" rel=\"nofollow\"><code>get_num_queries()</code></a> and as specified in other answers <a href=\"http://codex.wordpress.org/Function_Reference/timer_stop\" rel=\"nofollow\"><code>timer_stop()</code></a>.</p>\n\n<pre><code><?php echo get_num_queries(); _e(' queries'); ?> in <?php timer_stop(1); _e(' seconds'); ?></p>\n</code></pre>\n\n<p><code>get_num_queries()</code> - returns the number of database queries during the WordPress execution and accepts no parameters </p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] | I've noticed that a few Wordpress blogs have query statistics present in their footer that simply state the number of queries and the total time required to process them for the particular page, reading something like:
>
> 23 queries. 0.448 seconds
>
>
>
I was wondering how this is accomplished. Is it through the use of a particular Wordpress plug-in or perhaps from using some particular php function in the page's code? | Try adding this to the bottom of the footer in your template:
```
<?php echo $wpdb->num_queries; ?> <?php _e('queries'); ?>. <?php timer_stop(1); ?> <?php _e('seconds'); ?>
``` |
14,874 | <p>For part of my application I have a need to create an image of a certain view and all of its subviews.</p>
<p>To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.</p>
<p>I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level.</p>
| [
{
"answer_id": 14947,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html#//apple_ref/occ/instm/NSView/dataWithPDFInsideRect:\" rel=\"nofollow noreferrer\" title=\"-[NSData dataWithPDFInsideRect:]\"><code>-[NSView dataWithPDFInsideRect:]</code></a> to render the entire hierarchy of the view you send it to into a PDF, returned as an <code>NSData</code> object. You can then do whatever you wish with that, including render it into a bitmap.</p>\n\n<p>Are you sure you want a bitmap representation though? After all, that PDF could be (at least in theory) resolution-independent.</p>\n"
},
{
"answer_id": 15489,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSBitmapImageRep_Class/Reference/Reference.html#//apple_ref/occ/instm/NSBitmapImageRep/initWithFocusedViewRect:\" rel=\"nofollow noreferrer\" title=\"-[NSBitmapImageRep initWithFocusedViewRect:]\"><code>-[NSBitmapImageRep initWithFocusedViewRect:]</code></a> after locking focus on a view to have the view render itself (and its subviews) into the given rectangle.</p>\n"
},
{
"answer_id": 66556,
"author": "charles",
"author_id": 9900,
"author_profile": "https://Stackoverflow.com/users/9900",
"pm_score": 3,
"selected": true,
"text": "<p>I found that writing the drawing code myself was the best way to:</p>\n\n<ul>\n<li>deal with potential transparency issues (some of the other options do add a white background to the whole image)</li>\n<li>performance was much better</li>\n</ul>\n\n<p>The code below is not perfect, because it does not deal with scaling issues when going from bounds to frames, but it does take into account the isFlipped state, and works very well for what I used it for. Note that it only draws the subviews (and the subsubviews,... recursively), but getting it to also draw itself is very easy, just add a <code>[self drawRect:[self bounds]]</code> in the implementation of <code>imageWithSubviews</code>.</p>\n\n<pre><code>- (void)drawSubviews\n{\n BOOL flipped = [self isFlipped];\n\n for ( NSView *subview in [self subviews] ) {\n\n // changes the coordinate system so that the local coordinates of the subview (bounds) become the coordinates of the superview (frame)\n // the transform assumes bounds and frame have the same size, and bounds origin is (0,0)\n // handling of 'isFlipped' also probably unreliable\n NSAffineTransform *transform = [NSAffineTransform transform];\n if ( flipped ) {\n [transform translateXBy:subview.frame.origin.x yBy:NSMaxY(subview.frame)];\n [transform scaleXBy:+1.0 yBy:-1.0];\n } else\n [transform translateXBy:subview.frame.origin.x yBy:subview.frame.origin.y];\n [transform concat];\n\n // recursively draw the subview and sub-subviews\n [subview drawRect:[subview bounds]];\n [subview drawSubviews];\n\n // reset the transform to get back a clean graphic contexts for the rest of the drawing\n [transform invert];\n [transform concat];\n }\n}\n\n- (NSImage *)imageWithSubviews\n{\n NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease];\n [image lockFocus];\n // it seems NSImage cannot use flipped coordinates the way NSView does (the method 'setFlipped:' does not seem to help)\n // Use instead an NSAffineTransform\n if ( [self isFlipped] ) {\n NSAffineTransform *transform = [NSAffineTransform transform];\n [transform translateXBy:0 yBy:NSMaxY(self.bounds)];\n [transform scaleXBy:+1.0 yBy:-1.0];\n [transform concat];\n }\n [self drawSubviews];\n [image unlockFocus];\n return image;\n}\n</code></pre>\n"
},
{
"answer_id": 71696,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>What you want to do is available explicitly already. See the section \"NSView Drawing Redirection API\" in the 10.4 AppKit release notes.</p>\n\n<p>Make an NSBitmapImageRep for caching and clear it:</p>\n\n<pre><code>NSGraphicsContext *bitmapGraphicsContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:cacheBitmapImageRep];\n[NSGraphicsContext saveGraphicsState];\n[NSGraphicsContext setCurrentContext:bitmapGraphicsContext];\n[[NSColor clearColor] set];\nNSRectFill(NSMakeRect(0, 0, [cacheBitmapImageRep size].width, [cacheBitmapImageRep size].height));\n[NSGraphicsContext restoreGraphicsState];\n</code></pre>\n\n<p>Cache to it:</p>\n\n<pre><code>-[NSView cacheDisplayInRect:toBitmapImageRep:]\n</code></pre>\n\n<p>If you want to more generally draw into a specified context handling view recursion and transparency correctly, </p>\n\n<pre><code>-[NSView displayRectIgnoringOpacity:inContext:]\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] | For part of my application I have a need to create an image of a certain view and all of its subviews.
To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.
I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level. | I found that writing the drawing code myself was the best way to:
* deal with potential transparency issues (some of the other options do add a white background to the whole image)
* performance was much better
The code below is not perfect, because it does not deal with scaling issues when going from bounds to frames, but it does take into account the isFlipped state, and works very well for what I used it for. Note that it only draws the subviews (and the subsubviews,... recursively), but getting it to also draw itself is very easy, just add a `[self drawRect:[self bounds]]` in the implementation of `imageWithSubviews`.
```
- (void)drawSubviews
{
BOOL flipped = [self isFlipped];
for ( NSView *subview in [self subviews] ) {
// changes the coordinate system so that the local coordinates of the subview (bounds) become the coordinates of the superview (frame)
// the transform assumes bounds and frame have the same size, and bounds origin is (0,0)
// handling of 'isFlipped' also probably unreliable
NSAffineTransform *transform = [NSAffineTransform transform];
if ( flipped ) {
[transform translateXBy:subview.frame.origin.x yBy:NSMaxY(subview.frame)];
[transform scaleXBy:+1.0 yBy:-1.0];
} else
[transform translateXBy:subview.frame.origin.x yBy:subview.frame.origin.y];
[transform concat];
// recursively draw the subview and sub-subviews
[subview drawRect:[subview bounds]];
[subview drawSubviews];
// reset the transform to get back a clean graphic contexts for the rest of the drawing
[transform invert];
[transform concat];
}
}
- (NSImage *)imageWithSubviews
{
NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease];
[image lockFocus];
// it seems NSImage cannot use flipped coordinates the way NSView does (the method 'setFlipped:' does not seem to help)
// Use instead an NSAffineTransform
if ( [self isFlipped] ) {
NSAffineTransform *transform = [NSAffineTransform transform];
[transform translateXBy:0 yBy:NSMaxY(self.bounds)];
[transform scaleXBy:+1.0 yBy:-1.0];
[transform concat];
}
[self drawSubviews];
[image unlockFocus];
return image;
}
``` |
14,884 | <p>Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:</p>
<pre><code>Array
(
[leg0] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 5000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 5
[cost] => 1000
)
)
[leg1] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 3000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 3
[cost] => 1000
)
)
[leg2] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 4000
)
[FedEx] => Array
(
[days] => 1
[cost] => 3000
)
[Conway] => Array
(
[days] => 2
[cost] => 5000
)
)
)
</code></pre>
<p>How would you go about finding the best combination programmatically?</p>
<p>My best attempt so far (third or fourth algorithm) is:</p>
<ol>
<li>Find the longest shipper for each leg</li>
<li>Eliminate the most "expensive" one</li>
<li>Find the cheapest shipper for each leg</li>
<li>Calculate the total cost & days</li>
<li>If days are acceptable, finish, else, goto 1</li>
</ol>
<p>Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):</p>
<pre><code>$shippers["leg1"] = array(
"UPS" => array("days" => 1, "cost" => 4000),
"Conway" => array("days" => 3, "cost" => 3200),
"FedEx" => array("days" => 8, "cost" => 1000)
);
$shippers["leg2"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$shippers["leg3"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$times = 0;
$totalDays = 9999999;
print "<h1>Shippers to Choose From:</h1><pre>";
print_r($shippers);
print "</pre><br />";
while($totalDays > $maxDays && $times < 500){
$totalDays = 0;
$times++;
$worstShipper = null;
$longestShippers = null;
$cheapestShippers = null;
foreach($shippers as $legName => $leg){
//find longest shipment for each leg (in terms of days)
unset($longestShippers[$legName]);
$longestDays = null;
if(count($leg) > 1){
foreach($leg as $shipperName => $shipper){
if(empty($longestDays) || $shipper["days"] > $longestDays){
$longestShippers[$legName]["days"] = $shipper["days"];
$longestShippers[$legName]["cost"] = $shipper["cost"];
$longestShippers[$legName]["name"] = $shipperName;
$longestDays = $shipper["days"];
}
}
}
}
foreach($longestShippers as $leg => $shipper){
$shipper["totalCost"] = $shipper["days"] * $shipper["cost"];
//print $shipper["totalCost"] . " &lt;?&gt; " . $worstShipper["totalCost"] . ";";
if(empty($worstShipper) || $shipper["totalCost"] > $worstShipper["totalCost"]){
$worstShipper = $shipper;
$worstShipperLeg = $leg;
}
}
//print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"];
unset($shippers[$worstShipperLeg][$worstShipper["name"]]);
print "<h1>Next:</h1><pre>";
print_r($shippers);
print "</pre><br />";
foreach($shippers as $legName => $leg){
//find cheapest shipment for each leg (in terms of cost)
unset($cheapestShippers[$legName]);
$lowestCost = null;
foreach($leg as $shipperName => $shipper){
if(empty($lowestCost) || $shipper["cost"] < $lowestCost){
$cheapestShippers[$legName]["days"] = $shipper["days"];
$cheapestShippers[$legName]["cost"] = $shipper["cost"];
$cheapestShippers[$legName]["name"] = $shipperName;
$lowestCost = $shipper["cost"];
}
}
//recalculate days and see if we are under max days...
$totalDays += $cheapestShippers[$legName]['days'];
}
//print "<h2>totalDays: $totalDays</h2>";
}
print "<h1>Chosen Shippers:</h1><pre>";
print_r($cheapestShippers);
print "</pre>";
</code></pre>
<p>I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....</p>
<p>EDIT:
To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.</p>
<p>The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.</p>
<p>So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm.</p>
| [
{
"answer_id": 14892,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds like what you have is called a \"linear programming problem\". It also sounds like a homework problem, no offense. </p>\n\n<p>The classical solution to a LP problem is called the \"Simplex Method\". Google it.</p>\n\n<p>However, to use that method, you must have the problem correctly formulated to describe your requirements. </p>\n\n<p>Still, it may be possible to enumerate all possible paths, since you have such a small set. Such a thing won't scale, though. </p>\n"
},
{
"answer_id": 14895,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 3,
"selected": false,
"text": "<p>Sounds like a job for <a href=\"http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\" rel=\"noreferrer\">Dijkstra's algorithm</a>:</p>\n\n<blockquote>\n <p>Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1959, <a href=\"http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\" rel=\"noreferrer\">1</a> is a graph search algorithm that solves the single-source shortest path problem for a graph with non negative edge path costs, outputting a shortest path tree. This algorithm is often used in routing.</p>\n</blockquote>\n\n<p>There are also implementation details in the Wikipedia article.</p>\n"
},
{
"answer_id": 14899,
"author": "Kevin Sheffield",
"author_id": 590,
"author_profile": "https://Stackoverflow.com/users/590",
"pm_score": 4,
"selected": true,
"text": "<p>Could alter some of the <a href=\"http://en.wikipedia.org/wiki/Shortest_path_problem\" rel=\"noreferrer\">shortest path algorithms</a>, like Dijkstra's, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold. Should find the cheapest that gets you in under your threshold that way</p>\n"
},
{
"answer_id": 14904,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>If I knew I only had to deal with 5 cities, in a predetermined order, and that there were only 3 routes between adjacent cities, I'd brute force it. No point in being elegant.</p>\n\n<p>If, on the other hand, this were a homework assignment and I were supposed to produce an algorithm that could actually scale, I'd probably take a different approach.</p>\n"
},
{
"answer_id": 14906,
"author": "Baltimark",
"author_id": 1179,
"author_profile": "https://Stackoverflow.com/users/1179",
"pm_score": -1,
"selected": false,
"text": "<p>I think that Dijkstra's algorithm is for finding a shortest path. </p>\n\n<p><strong>cmcculloh</strong> is looking for the minimal cost subject to the constraint that he gets it there in 5 days. </p>\n\n<p>So, merely finding the quickest way won't get him there cheapest, and getting there for the cheapest, won't get it there in the required amount of time. </p>\n"
},
{
"answer_id": 23622,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "<p>This is a <a href=\"http://en.wikipedia.org/wiki/List_of_knapsack_problems\" rel=\"nofollow noreferrer\">knapsack problem</a>. The weights are the days in transit, and the profit should be $5000 - cost of leg. Eliminate all negative costs and go from there!</p>\n"
},
{
"answer_id": 104979,
"author": "Eonwe",
"author_id": 19198,
"author_profile": "https://Stackoverflow.com/users/19198",
"pm_score": 2,
"selected": false,
"text": "<p>As Baltimark said, this is basically a Linear programming problem. If only the coefficients for the shippers (1 for included, 0 for not included) were not (binary) integers for each leg, this would be more easily solveable. Now you need to find some (binary) integer linear programming (ILP) heuristics as the problem is NP-hard.\nSee <a href=\"http://en.wikipedia.org/wiki/Linear_programming#Integer_unknowns\" rel=\"nofollow noreferrer\" title=\"Wikipedia on integer linear programming\">Wikipedia on integer linear programming</a> for links; on my linear programming course we used at least <a href=\"http://en.wikipedia.org/wiki/Branch_and_bound\" rel=\"nofollow noreferrer\" title=\"Branch and bound\">Branch and bound</a>.</p>\n\n<p>Actually now that I think of it, this special case is solveable without actual ILP as the amount of days does not matter as long as it is <= 5. Now start by choosing the cheapest carrier for first choice (Conway 5:1000). Next you choose yet again the cheapest, resulting 8 days and 4000 currency units which is too much so we abort that. By trying others too we see that they all results days > 5 so we back to first choice and try the second cheapest (FedEx 2:3000) and then ups in the second and fedex in the last. This gives us total of 4 days and 9000 currency units.</p>\n\n<p>We then could use this cost to prune other searches in the tree that would by some subtree-stage result costs larger that the one we've found already and leave that subtree unsearched from that point on.\nThis only works as long as we can know that searching in the subtree will not produce a better results, as we do here when costs cannot be negative.</p>\n\n<p>Hope this rambling helped a bit :). </p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:
```
Array
(
[leg0] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 5000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 5
[cost] => 1000
)
)
[leg1] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 3000
)
[FedEx] => Array
(
[days] => 2
[cost] => 3000
)
[Conway] => Array
(
[days] => 3
[cost] => 1000
)
)
[leg2] => Array
(
[UPS] => Array
(
[days] => 1
[cost] => 4000
)
[FedEx] => Array
(
[days] => 1
[cost] => 3000
)
[Conway] => Array
(
[days] => 2
[cost] => 5000
)
)
)
```
How would you go about finding the best combination programmatically?
My best attempt so far (third or fourth algorithm) is:
1. Find the longest shipper for each leg
2. Eliminate the most "expensive" one
3. Find the cheapest shipper for each leg
4. Calculate the total cost & days
5. If days are acceptable, finish, else, goto 1
Quickly mocked-up in PHP (note that the test array below works swimmingly, but if you try it with the test array from above, it does not find the correct combination):
```
$shippers["leg1"] = array(
"UPS" => array("days" => 1, "cost" => 4000),
"Conway" => array("days" => 3, "cost" => 3200),
"FedEx" => array("days" => 8, "cost" => 1000)
);
$shippers["leg2"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$shippers["leg3"] = array(
"UPS" => array("days" => 1, "cost" => 3500),
"Conway" => array("days" => 2, "cost" => 2800),
"FedEx" => array("days" => 4, "cost" => 900)
);
$times = 0;
$totalDays = 9999999;
print "<h1>Shippers to Choose From:</h1><pre>";
print_r($shippers);
print "</pre><br />";
while($totalDays > $maxDays && $times < 500){
$totalDays = 0;
$times++;
$worstShipper = null;
$longestShippers = null;
$cheapestShippers = null;
foreach($shippers as $legName => $leg){
//find longest shipment for each leg (in terms of days)
unset($longestShippers[$legName]);
$longestDays = null;
if(count($leg) > 1){
foreach($leg as $shipperName => $shipper){
if(empty($longestDays) || $shipper["days"] > $longestDays){
$longestShippers[$legName]["days"] = $shipper["days"];
$longestShippers[$legName]["cost"] = $shipper["cost"];
$longestShippers[$legName]["name"] = $shipperName;
$longestDays = $shipper["days"];
}
}
}
}
foreach($longestShippers as $leg => $shipper){
$shipper["totalCost"] = $shipper["days"] * $shipper["cost"];
//print $shipper["totalCost"] . " <?> " . $worstShipper["totalCost"] . ";";
if(empty($worstShipper) || $shipper["totalCost"] > $worstShipper["totalCost"]){
$worstShipper = $shipper;
$worstShipperLeg = $leg;
}
}
//print "worst shipper is: shippers[$worstShipperLeg][{$worstShipper['name']}]" . $shippers[$worstShipperLeg][$worstShipper["name"]]["days"];
unset($shippers[$worstShipperLeg][$worstShipper["name"]]);
print "<h1>Next:</h1><pre>";
print_r($shippers);
print "</pre><br />";
foreach($shippers as $legName => $leg){
//find cheapest shipment for each leg (in terms of cost)
unset($cheapestShippers[$legName]);
$lowestCost = null;
foreach($leg as $shipperName => $shipper){
if(empty($lowestCost) || $shipper["cost"] < $lowestCost){
$cheapestShippers[$legName]["days"] = $shipper["days"];
$cheapestShippers[$legName]["cost"] = $shipper["cost"];
$cheapestShippers[$legName]["name"] = $shipperName;
$lowestCost = $shipper["cost"];
}
}
//recalculate days and see if we are under max days...
$totalDays += $cheapestShippers[$legName]['days'];
}
//print "<h2>totalDays: $totalDays</h2>";
}
print "<h1>Chosen Shippers:</h1><pre>";
print_r($cheapestShippers);
print "</pre>";
```
I think I may have to actually do some sort of thing where I literally make each combination one by one (with a series of loops) and add up the total "score" of each, and find the best one....
EDIT:
To clarify, this isn't a "homework" assignment (I'm not in school). It is part of my current project at work.
The requirements (as always) have been constantly changing. If I were given the current constraints at the time I began working on this problem, I would be using some variant of the A\* algorithm (or Dijkstra's or shortest path or simplex or something). But everything has been morphing and changing, and that brings me to where I'm at right now.
So I guess that means I need to forget about all the crap I've done to this point and just go with what I know I should go with, which is a path finding algorithm. | Could alter some of the [shortest path algorithms](http://en.wikipedia.org/wiki/Shortest_path_problem), like Dijkstra's, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold. Should find the cheapest that gets you in under your threshold that way |
14,923 | <p>I'm thinking of learning the <code>ASP.NET MVC</code> framework for an upcoming project. Can I use the advanced routing to create long URLs based on the sitemap hierarchy?</p>
<p>Example navigation path:</p>
<p><strong>Home > Shop > Products > Household > Kitchen > Cookware > Cooksets > Nonstick</strong></p>
<p>Typical (I think) MVC URL:<br/>
<a href="http://example.com/products/category/NonstickCooksets" rel="nofollow noreferrer">http://example.com/products/category/NonstickCooksets</a></p>
<p>Desired URL:<br/>
<a href="http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick" rel="nofollow noreferrer">http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick</a></p>
<p>Can I do this?</p>
| [
{
"answer_id": 14991,
"author": "J Wynia",
"author_id": 1124,
"author_profile": "https://Stackoverflow.com/users/1124",
"pm_score": 2,
"selected": false,
"text": "<p>The MVC routing lets you define pretty much any structure you want, you just need to define what each of the pieces mean semantically. You can have bits that are \"hard-coded\", like \"shop/products\", and then define the rest as variable, \"{category}/{subcategory}/{speciality}\", etc.</p>\n\n<p>You can also define several routes that all map to the same end point if you like. Basically, when a URL comes into your MVC app, it goes through the routing table until it finds a pattern that matches, fills in the variables and passes the request off to the appropriate controller for processing.</p>\n\n<p>While the default route is a simple Controller, Action, Id kind of setup, that's certainly not the extent of what you can do.</p>\n"
},
{
"answer_id": 36833,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 4,
"selected": true,
"text": "<p>Zack, if I understand right you want unlimited depth of the subcategories. No biggie, since MVC Preview 3 (I think 3 or 4) this has been solved.</p>\n\n<p>Just define a route like</p>\n\n<p>\"{controller}/{action}/{*categoryPath}\"</p>\n\n<p>for an url such as :</p>\n\n<p><a href=\"http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick\" rel=\"noreferrer\">http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick</a></p>\n\n<p>you should have a ShopController with a Products action :</p>\n\n<pre><code>public class ShopController : Controller\n{\n...\n public ActionResult Products(string categoryPath)\n {\n // the categoryPath value would be\n // \"household/kitchen/cookware/cooksets/nonstick\". Process it (for ex. split it)\n // and then decide what you do..\n return View();\n }\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | I'm thinking of learning the `ASP.NET MVC` framework for an upcoming project. Can I use the advanced routing to create long URLs based on the sitemap hierarchy?
Example navigation path:
**Home > Shop > Products > Household > Kitchen > Cookware > Cooksets > Nonstick**
Typical (I think) MVC URL:
<http://example.com/products/category/NonstickCooksets>
Desired URL:
<http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick>
Can I do this? | Zack, if I understand right you want unlimited depth of the subcategories. No biggie, since MVC Preview 3 (I think 3 or 4) this has been solved.
Just define a route like
"{controller}/{action}/{\*categoryPath}"
for an url such as :
<http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick>
you should have a ShopController with a Products action :
```
public class ShopController : Controller
{
...
public ActionResult Products(string categoryPath)
{
// the categoryPath value would be
// "household/kitchen/cookware/cooksets/nonstick". Process it (for ex. split it)
// and then decide what you do..
return View();
}
``` |
14,934 | <p>.NET, Java and other high level database API's in various language often provide techniques known as prepared statements and parameter binding as opposed to sending plain text commands to the Database server. What I would like to know is what happens when you execute a statement like this:</p>
<pre><code>SqlCommand cmd = new SqlCommand("GetMemberByID");
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@ID", memberID);
para.DbType = DbType.Integer;
cmd.Parameters.Add(param);
</code></pre>
<p>I know this is a best practice. SQL injection attacks are minimized this way. But what exactly happens under the hood when you execute these statements? Is the end result still a SQL safe string? If not, what is the end result? And is this enough to prevent SQL injection attacks?</p>
| [
{
"answer_id": 14946,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/c-api-prepared-statements.html\" rel=\"nofollow noreferrer\">The MySQL manual page</a> on prepared statements provides lots of information (which should apply to any other RDBMS).</p>\n\n<p>Basically, your statement is parsed and processed ahead of time, and the parameters are sent separately instead of being handled along with the SQL code. This eliminates SQL-injection attacks because the SQL is parsed before the parameters are even set.</p>\n"
},
{
"answer_id": 14986,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using MS SQL, load up the profiler and you'll see what SQL statements are generated when you use parameterised queries. Here's an example (I'm using Enterprise Libary 3.1, but the results are the same using SqlParameters directly) against SQL Server 2005:</p>\n\n<pre><code>string sql = \"SELECT * FROM tblDomains WHERE DomainName = @DomName AND DomainID = @Did\";\nDatabase db = DatabaseFactory.CreateDatabase();\nusing(DbCommand cmd = db.GetSqlStringCommand(sql))\n{\n db.AddInParameter(cmd, \"DomName\", DbType.String, \"xxxxx.net\");\n db.AddInParameter(cmd, \"Did\", DbType.Int32, 500204);\n\n DataSet ds = db.ExecuteDataSet(cmd);\n}\n</code></pre>\n\n<p>This generates:</p>\n\n<pre><code>exec sp[underscore]executesql N'SELECT * FROM tblDomains WHERE DomainName = @DomName AND DomainID = @Did',\n N'@DomName nvarchar(9),\n @Did int',\n @DomName=N'xxxxx.net',\n @Did=500204\n</code></pre>\n\n<p>You can also see here, if quotation characters were passed as parameters, they are escaped accordingly:</p>\n\n<pre><code>db.AddInParameter(cmd, \"DomName\", DbType.String, \"'xxxxx.net\");\n\nexec sp[underscore]executesql N'SELECT * FROM tblDomains WHERE DomainName = @DomName AND DomainID = @Did',\n N'@DomName nvarchar(10),\n @Did int',\n @DomName=N'''xxxxx.net',\n @Did=500204\n</code></pre>\n"
},
{
"answer_id": 14995,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 0,
"selected": false,
"text": "<p>in layman terms: if a prepared statement is sent then the DB will use a plan if it is available, it doesn't not have to recreate a plan every time this query is sent over but only the values of the params have changed. this is very similar to how procs work, the additional benefit with procs is that you can give permission through procs only and not to the underlying tables at all</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | .NET, Java and other high level database API's in various language often provide techniques known as prepared statements and parameter binding as opposed to sending plain text commands to the Database server. What I would like to know is what happens when you execute a statement like this:
```
SqlCommand cmd = new SqlCommand("GetMemberByID");
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@ID", memberID);
para.DbType = DbType.Integer;
cmd.Parameters.Add(param);
```
I know this is a best practice. SQL injection attacks are minimized this way. But what exactly happens under the hood when you execute these statements? Is the end result still a SQL safe string? If not, what is the end result? And is this enough to prevent SQL injection attacks? | [The MySQL manual page](http://dev.mysql.com/doc/refman/5.0/en/c-api-prepared-statements.html) on prepared statements provides lots of information (which should apply to any other RDBMS).
Basically, your statement is parsed and processed ahead of time, and the parameters are sent separately instead of being handled along with the SQL code. This eliminates SQL-injection attacks because the SQL is parsed before the parameters are even set. |
14,943 | <p>What is the best way to disable <kbd>Alt</kbd> + <kbd>F4</kbd> in a c# win form to prevent the user from closing the form?</p>
<p>I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.</p>
| [
{
"answer_id": 14949,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 4,
"selected": false,
"text": "<p>You could handle the <code>FormClosing</code> event and set <code>FormClosingEventArgs.Cancel</code> to <code>true</code>.</p>\n"
},
{
"answer_id": 14960,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 8,
"selected": true,
"text": "<p>This does the job:</p>\n\n<pre><code>private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n e.Cancel = true;\n}\n</code></pre>\n\n<p>Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form_closing event before closing the form:</p>\n\n<pre><code>this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);\nthis.Close();\n</code></pre>\n"
},
{
"answer_id": 14984,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 2,
"selected": false,
"text": "<p>Would FormClosing be called even when you're programatically closing the window? If so, you'd probably want to add some code to allow the form to be closed when you're finished with it (instead of always canceling the operation)</p>\n"
},
{
"answer_id": 15236,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 4,
"selected": false,
"text": "<p>Note that it is considered bad form for an application to completely prevent itself from closing. You should check the event arguments for the Closing event to determine how and why your application was asked to close. If it is because of a Windows shutdown, you should not prevent the close from happening.</p>\n"
},
{
"answer_id": 15243,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.</p>\n</blockquote>\n\n<p>If the user is determined to close your app (and knowledgeable) enough to press alt+f4, they'll most likely also be knowledgeable enough to run task manager and kill your application instead.</p>\n\n<p>At least with alt+f4 your app can do a graceful shutdown, rather than just making people kill it. From experience, people killing your app means corrupt config files, broken databases, half-finished tasks that you can't resume, and many other painful things.</p>\n\n<p>At least prompt them with 'are you sure' rather than flat out preventing it.</p>\n"
},
{
"answer_id": 49349,
"author": "Matt Warren",
"author_id": 4500,
"author_profile": "https://Stackoverflow.com/users/4500",
"pm_score": 6,
"selected": false,
"text": "<p>If you look at the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.closereason?view=netframework-4.7.2\" rel=\"noreferrer\">value</a> of <code>FormClosingEventArgs e.CloseReason</code>, it will tell you why the form is being closed. You can then decide what to do, the possible values are:</p>\n\n<p><strong>Member name</strong> - Description</p>\n\n<hr>\n\n<p><strong>None</strong> - The cause of the closure was not defined or could not be determined.</p>\n\n<p><strong>WindowsShutDown</strong> - The operating system is closing all applications before shutting down.</p>\n\n<p><strong>MdiFormClosing</strong> - The parent form of this multiple document interface (MDI) form is closing.</p>\n\n<p><strong>UserClosing</strong> - The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the window's control menu, or pressing <kbd>ALT</kbd>+<kbd>F4</kbd>.</p>\n\n<p><strong>TaskManagerClosing</strong> - The Microsoft Windows Task Manager is closing the application.</p>\n\n<p><strong>FormOwnerClosing</strong> - The owner form is closing.</p>\n\n<p><strong>ApplicationExitCall</strong> - The Exit method of the Application class was invoked.</p>\n"
},
{
"answer_id": 428005,
"author": "antsyawn",
"author_id": 53324,
"author_profile": "https://Stackoverflow.com/users/53324",
"pm_score": 5,
"selected": false,
"text": "<p>I believe this is the right way to do it:</p>\n\n<pre><code>protected override void OnFormClosing(FormClosingEventArgs e)\n{\n switch (e.CloseReason)\n {\n case CloseReason.UserClosing:\n e.Cancel = true;\n break;\n }\n\n base.OnFormClosing(e);\n}\n</code></pre>\n"
},
{
"answer_id": 15216009,
"author": "linquize",
"author_id": 1031218,
"author_profile": "https://Stackoverflow.com/users/1031218",
"pm_score": 2,
"selected": false,
"text": "<p>Subscribe FormClosing event</p>\n\n<pre><code>private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n e.Cancel = e.CloseReason == CloseReason.UserClosing;\n}\n</code></pre>\n\n<p>Only one line in the method body.</p>\n"
},
{
"answer_id": 37909195,
"author": "Bharath theorare",
"author_id": 2700841,
"author_profile": "https://Stackoverflow.com/users/2700841",
"pm_score": -1,
"selected": false,
"text": "<p>Hide close button on form by using the following in constructor of the form:</p>\n\n<pre><code>this.ControlBox = false;\n</code></pre>\n"
},
{
"answer_id": 47331474,
"author": "Brahim Bourass",
"author_id": 8947184,
"author_profile": "https://Stackoverflow.com/users/8947184",
"pm_score": 3,
"selected": false,
"text": "<p>This is a hack to disable <kbd>Alt</kbd> + <kbd>F4</kbd>.</p>\n\n<pre><code>private void test_FormClosing(object sender, FormClosingEventArgs e)\n{\n if (this.ModifierKeys == Keys.Alt || this.ModifierKeys == Keys.F4) \n { \n e.Cancel = true; \n } \n}\n</code></pre>\n"
},
{
"answer_id": 50615223,
"author": "Condorkunka",
"author_id": 5999286,
"author_profile": "https://Stackoverflow.com/users/5999286",
"pm_score": 2,
"selected": false,
"text": "<p>This does the job:</p>\n\n<pre><code>bool myButtonWasClicked = false;\nprivate void Exit_Click(object sender, EventArgs e)\n{\n myButtonWasClicked = true;\n Application.Exit();\n}\nprivate void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n if (myButtonWasClicked)\n {\n e.Cancel = false;\n }\n else\n {\n e.Cancel = true;\n }\n\n\n}\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/14943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1375/"
] | What is the best way to disable `Alt` + `F4` in a c# win form to prevent the user from closing the form?
I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it. | This does the job:
```
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
```
Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form\_closing event before closing the form:
```
this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Close();
``` |
15,023 | <p>In WindowsForms world you can get a list of available image encoders/decoders with</p>
<pre><code>System.Drawing.ImageCodecInfo.GetImageDecoders() / GetImageEncoders()
</code></pre>
<p>My question is, is there a way to do something analogous for the WPF world that would allow me to get a list of available </p>
<pre><code>System.Windows.Media.Imaging.BitmapDecoder / BitmapEncoder
</code></pre>
| [
{
"answer_id": 15388,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 1,
"selected": false,
"text": "<p>Hopefully someone will correct me if I'm wrong, but I don't think there's anything like that in WPF. But hopefully this is one of the many cases where advances in the technology have rendered obsolete the way we're used to doing things. Like \"how do I wind my digital watch?\"</p>\n\n<p>To my understanding, the reason why ImageCodecInfo.GetImageDecoders() is necessary in System.Drawing has to do with the kludgy nature of System.Drawing itself: System.Drawing is a managed wrapper around GDI+, which is an unmanaged wrapper around a portion of the Win32 API. So there might be a reason why a new codec would be installed in Windows without .NET inherently knowing about it. And what's returned from GetImageDecoders() is just a bunch of strings that are typically passed back into System.Drawing/GDI+, and used to find and configure the appropriate DLL for reading/saving your image.</p>\n\n<p>On the other hand, in WPF, the standard encoders and decoders are built into the framework, and, if I'm not mistaken, don't depend on anything that that isn't guaranteed to be installed as part of the framework. The following classes inherit from BitmapEncoder and are available out-of-the-box with WPF: BmpBitmapEncoder, GifBitmapEncoder, JpegBitmapEncoder, PngBitmapEncoder, TiffBitmapEncoder, WmpBitmapEncoder. There are BitmapDecoders for all the same formats, plus IconBitmapDecoder and LateBoundBitmapDecoder.</p>\n\n<p>You may be dealing with a case I'm not imagining, but it seems to me that if you're having to use a class that inherits from BitmapEncoder but wasn't included with WPF, it's probably your own custom class that you would install with your application.</p>\n\n<p>Hope this helps. If I'm missing a necessary part of the picture, please let me know.</p>\n"
},
{
"answer_id": 17448,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "<p>You've got to love .NET reflection. I worked on the WPF team and can't quite think of anything better off the top of my head. The following code produces this list on my machine:</p>\n\n<pre><code>Bitmap Encoders:\nSystem.Windows.Media.Imaging.BmpBitmapEncoder\nSystem.Windows.Media.Imaging.GifBitmapEncoder\nSystem.Windows.Media.Imaging.JpegBitmapEncoder\nSystem.Windows.Media.Imaging.PngBitmapEncoder\nSystem.Windows.Media.Imaging.TiffBitmapEncoder\nSystem.Windows.Media.Imaging.WmpBitmapEncoder\n\nBitmap Decoders:\nSystem.Windows.Media.Imaging.BmpBitmapDecoder\nSystem.Windows.Media.Imaging.GifBitmapDecoder\nSystem.Windows.Media.Imaging.IconBitmapDecoder\nSystem.Windows.Media.Imaging.LateBoundBitmapDecoder\nSystem.Windows.Media.Imaging.JpegBitmapDecoder\nSystem.Windows.Media.Imaging.PngBitmapDecoder\nSystem.Windows.Media.Imaging.TiffBitmapDecoder\nSystem.Windows.Media.Imaging.WmpBitmapDecoder\n</code></pre>\n\n<p>There is a comment in the code where to add additional assemblies (if you support plugins for example). Also, you will want to filter the decoder list to remove:</p>\n\n<pre><code>System.Windows.Media.Imaging.LateBoundBitmapDecoder\n</code></pre>\n\n<p>More sophisticated filtering using constructor pattern matching is possible, but I don't feel like writing it. :-)</p>\n\n<p>All you need to do now is instantiate the encoders and decoders to use them. Also, you can get better names by retrieving the <code>CodecInfo</code> property of the encoder decoders. This class will give you human readable names among other factoids.</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Windows.Media.Imaging;\n\nnamespace Codecs {\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(\"Bitmap Encoders:\");\n AllEncoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));\n Console.WriteLine(\"\\nBitmap Decoders:\");\n AllDecoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));\n Console.ReadKey();\n }\n\n static IEnumerable<Type> AllEncoderTypes {\n get {\n return AllSubclassesOf(typeof(BitmapEncoder));\n }\n }\n\n static IEnumerable<Type> AllDecoderTypes {\n get {\n return AllSubclassesOf(typeof(BitmapDecoder));\n }\n }\n\n static IEnumerable<Type> AllSubclassesOf(Type type) {\n var r = new Reflector();\n // Add additional assemblies here\n return r.AllSubclassesOf(type);\n }\n }\n\n class Reflector {\n List<Assembly> assemblies = new List<Assembly> { \n typeof(BitmapDecoder).Assembly\n };\n public IEnumerable<Type> AllSubclassesOf(Type super) {\n foreach (var a in assemblies) {\n foreach (var t in a.GetExportedTypes()) {\n if (t.IsSubclassOf(super)) {\n yield return t;\n }\n }\n }\n }\n }\n}\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In WindowsForms world you can get a list of available image encoders/decoders with
```
System.Drawing.ImageCodecInfo.GetImageDecoders() / GetImageEncoders()
```
My question is, is there a way to do something analogous for the WPF world that would allow me to get a list of available
```
System.Windows.Media.Imaging.BitmapDecoder / BitmapEncoder
``` | You've got to love .NET reflection. I worked on the WPF team and can't quite think of anything better off the top of my head. The following code produces this list on my machine:
```
Bitmap Encoders:
System.Windows.Media.Imaging.BmpBitmapEncoder
System.Windows.Media.Imaging.GifBitmapEncoder
System.Windows.Media.Imaging.JpegBitmapEncoder
System.Windows.Media.Imaging.PngBitmapEncoder
System.Windows.Media.Imaging.TiffBitmapEncoder
System.Windows.Media.Imaging.WmpBitmapEncoder
Bitmap Decoders:
System.Windows.Media.Imaging.BmpBitmapDecoder
System.Windows.Media.Imaging.GifBitmapDecoder
System.Windows.Media.Imaging.IconBitmapDecoder
System.Windows.Media.Imaging.LateBoundBitmapDecoder
System.Windows.Media.Imaging.JpegBitmapDecoder
System.Windows.Media.Imaging.PngBitmapDecoder
System.Windows.Media.Imaging.TiffBitmapDecoder
System.Windows.Media.Imaging.WmpBitmapDecoder
```
There is a comment in the code where to add additional assemblies (if you support plugins for example). Also, you will want to filter the decoder list to remove:
```
System.Windows.Media.Imaging.LateBoundBitmapDecoder
```
More sophisticated filtering using constructor pattern matching is possible, but I don't feel like writing it. :-)
All you need to do now is instantiate the encoders and decoders to use them. Also, you can get better names by retrieving the `CodecInfo` property of the encoder decoders. This class will give you human readable names among other factoids.
```
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Windows.Media.Imaging;
namespace Codecs {
class Program {
static void Main(string[] args) {
Console.WriteLine("Bitmap Encoders:");
AllEncoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));
Console.WriteLine("\nBitmap Decoders:");
AllDecoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));
Console.ReadKey();
}
static IEnumerable<Type> AllEncoderTypes {
get {
return AllSubclassesOf(typeof(BitmapEncoder));
}
}
static IEnumerable<Type> AllDecoderTypes {
get {
return AllSubclassesOf(typeof(BitmapDecoder));
}
}
static IEnumerable<Type> AllSubclassesOf(Type type) {
var r = new Reflector();
// Add additional assemblies here
return r.AllSubclassesOf(type);
}
}
class Reflector {
List<Assembly> assemblies = new List<Assembly> {
typeof(BitmapDecoder).Assembly
};
public IEnumerable<Type> AllSubclassesOf(Type super) {
foreach (var a in assemblies) {
foreach (var t in a.GetExportedTypes()) {
if (t.IsSubclassOf(super)) {
yield return t;
}
}
}
}
}
}
``` |
15,034 | <p>When building a VS 2008 solution with 19 projects I sometimes get:</p>
<pre><code>The "GenerateResource" task failed unexpectedly.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.WriteByte(Byte value)
at System.IO.BinaryWriter.Write(Byte value)
at System.Resources.ResourceWriter.Write7BitEncodedInt(BinaryWriter store, Int32 value)
at System.Resources.ResourceWriter.Generate()
at System.Resources.ResourceWriter.Dispose(Boolean disposing)
at System.Resources.ResourceWriter.Close()
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(IResourceWriter writer)
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(String filename)
at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile, String outFile)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, ArrayList inputs, ArrayList outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass)
at Microsoft.Build.Tasks.GenerateResource.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) C:\Windows\Microsoft.NET\Framework\v3.5
</code></pre>
<p>Usually happens after VS has been running for about 4 hours; the only way to get VS to compile properly is to close out VS, and start it again.</p>
<p>I'm on a machine with 3GB Ram. TaskManager shows the devenv.exe working set to be 578060K, and the entire memory allocation for the machine is 1.78GB. It should have more than enough ram to generate the resources.</p>
| [
{
"answer_id": 15055,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": true,
"text": "<p>I used to hit this now and again with larger solutions. My tactic was to break the larger solution down into smaller solutions.</p>\n\n<p>You could also try:</p>\n\n<p><a href=\"http://stevenharman.net/blog/archive/2008/04/29/hacking-visual-studio-to-use-more-than-2gigabytes-of-memory.aspx\" rel=\"nofollow noreferrer\">http://stevenharman.net/blog/archive/2008/04/29/hacking-visual-studio-to-use-more-than-2gigabytes-of-memory.aspx</a></p>\n"
},
{
"answer_id": 15063,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like a bug.</p>\n\n<p><a href=\"http://www.codeprof.com/dev-archive/66/6-27-664019.shtm\" rel=\"nofollow noreferrer\">http://www.codeprof.com/dev-archive/66/6-27-664019.shtm</a></p>\n\n<p>Toward the bottom, someone suggests adding:</p>\n\n<blockquote>\n <p><GenerateResourceNeverLockTypeAssemblies>true</GenerateResourceNeverLockTypeAssemblies></p>\n</blockquote>\n\n<p>to your project file. Seems kind of dubious, but worth a shot.</p>\n"
},
{
"answer_id": 15067,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/5154ef26-ccfe-44d5-a322-6804b61ac774/systemoutofmemoryexception?forum=clr\" rel=\"nofollow noreferrer\">https://social.msdn.microsoft.com/Forums/vstudio/en-US/5154ef26-ccfe-44d5-a322-6804b61ac774/systemoutofmemoryexception?forum=clr</a>:</p>\n\n<p>Try deleting the .suo file and re-opening the solution.</p>\n"
},
{
"answer_id": 4811373,
"author": "Chris Woodruff",
"author_id": 495565,
"author_profile": "https://Stackoverflow.com/users/495565",
"pm_score": 1,
"selected": false,
"text": "<p>In case someone else is looking in the future...</p>\n\n<p>In my case, turned out I had a corrupted resx file.<br>\nI had increased my GDI handles and the compile error went away.</p>\n\n<p>But then when I tried to run the app (with the debugger),\nWe have a login screen that loads the main screen. The login screen called the main screen's \"show\" event... and the main object never got instantiated - with no error's being raised. </p>\n\n<p>I reverted the resx file to a previous one and everything is fine now.</p>\n\n<p>Visual Studio 2008, VB.Net, Windows 7</p>\n"
},
{
"answer_id": 8679710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Can you please try adding this property under the first PropertyGroup in your project file?</p>\n\n<pre><code><GenerateResourceNeverLockTypeAssemblies>true</GenerateResourceNeverLockTypeAssemblies>\n</code></pre>\n\n<p>Let me know if that works.</p>\n"
},
{
"answer_id": 34311467,
"author": "user5686483",
"author_id": 5686483,
"author_profile": "https://Stackoverflow.com/users/5686483",
"pm_score": 0,
"selected": false,
"text": "<p>I have already passed by this erros sometimes. All you must do is delete all files in the obj path. After that clean and rebuild your solution and it´s done.</p>\n"
},
{
"answer_id": 34332233,
"author": "Sten Björsell",
"author_id": 5687641,
"author_profile": "https://Stackoverflow.com/users/5687641",
"pm_score": 0,
"selected": false,
"text": "<p>\"Clean solution\" works fine. Top Menu Build ->Clean , then build, debug and \npublish all work fine again. Also antivirus like AVAST best disabled to publish and install trouble free. Re-enable after.</p>\n"
},
{
"answer_id": 53006965,
"author": "gowtham kondari",
"author_id": 10009737,
"author_profile": "https://Stackoverflow.com/users/10009737",
"pm_score": 0,
"selected": false,
"text": "<p>TFS likes to mark files as Read Only.\ndelete the contents of obj/x86 </p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365/"
] | When building a VS 2008 solution with 19 projects I sometimes get:
```
The "GenerateResource" task failed unexpectedly.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.WriteByte(Byte value)
at System.IO.BinaryWriter.Write(Byte value)
at System.Resources.ResourceWriter.Write7BitEncodedInt(BinaryWriter store, Int32 value)
at System.Resources.ResourceWriter.Generate()
at System.Resources.ResourceWriter.Dispose(Boolean disposing)
at System.Resources.ResourceWriter.Close()
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(IResourceWriter writer)
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(String filename)
at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile, String outFile)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, ArrayList inputs, ArrayList outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass)
at Microsoft.Build.Tasks.GenerateResource.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) C:\Windows\Microsoft.NET\Framework\v3.5
```
Usually happens after VS has been running for about 4 hours; the only way to get VS to compile properly is to close out VS, and start it again.
I'm on a machine with 3GB Ram. TaskManager shows the devenv.exe working set to be 578060K, and the entire memory allocation for the machine is 1.78GB. It should have more than enough ram to generate the resources. | I used to hit this now and again with larger solutions. My tactic was to break the larger solution down into smaller solutions.
You could also try:
<http://stevenharman.net/blog/archive/2008/04/29/hacking-visual-studio-to-use-more-than-2gigabytes-of-memory.aspx> |
15,040 | <p>I am using xampp on Windows, but I would like to use something closer to my server setup.</p>
<p><a href="http://phpimpact.wordpress.com/2008/05/24/virtual-appliances-lamp-development-made-easy/" rel="nofollow noreferrer">Federico Cargnelutti tutorial</a> explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.</p>
<p>ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder.</p>
| [
{
"answer_id": 15044,
"author": "Dinoboff",
"author_id": 1771,
"author_profile": "https://Stackoverflow.com/users/1771",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming you have VMware workstation, VMware player or anything that can run vmware appliance, you just need to:</p>\n\n<ol>\n<li>Download, unzip <a href=\"http://www.vmware.com/appliances/directory/1248\" rel=\"nofollow noreferrer\">Ubuntu 8.04 Server</a> and start the virtual machine.</li>\n<li>Update ubuntu and set the layout and the timezone:\n\n<pre>\nsudo apt-get update\nsudo apt-get upgrade\nsudo dpkg-reconfigure console-setup\nsudo dpkg-reconfigure tzdata\nsudo vim /etc/network/interfaces\n</pre></li>\n<li><a href=\"http://www.cyberciti.biz/tips/howto-ubuntu-linux-convert-dhcp-network-configuration-to-static-ip-configuration.html\" rel=\"nofollow noreferrer\">set a fixed IP</a> (Optional). </li>\n<li>install apache+mysql+php:\n\n<pre>sudo tasksel install lamp-server\n</pre></li>\n</ol>\n"
},
{
"answer_id": 15054,
"author": "helloandre",
"author_id": 50,
"author_profile": "https://Stackoverflow.com/users/50",
"pm_score": 0,
"selected": false,
"text": "<p>I don't really understand your question because i really didn't see one. But i'll do my best to infer two: to change your keyboard layout, check this <a href=\"http://ubuntuforums.org/showthread.php?t=884533&highlight=change+keyboard+layout\" rel=\"nofollow noreferrer\">forum post</a> on ubuntu forums and to change the timezone, check this <a href=\"http://ubuntuforums.org/showthread.php?t=665255&highlight=change+time+zone\" rel=\"nofollow noreferrer\">forum post</a>.</p>\n"
},
{
"answer_id": 15683,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 4,
"selected": true,
"text": "<p>This is my install scrpt, I use it on debian servers, but it will work in Ubuntu (Ubuntu is built on Debian)</p>\n\n<pre><code>apt-get -yq update\napt-get -yq upgrade\napt-get -yq install sudo\napt-get -yq install gcc\napt-get -yq install g++\napt-get -yq install make\napt-get -yq install apache2\napt-get -yq install php5\napt-get -yq install php5-curl\napt-get -yq install php5-mysql\napt-get -yq install php5-gd\napt-get -yq install mysql-common\napt-get -yq install mysql-client\napt-get -yq install mysql-server\napt-get -yq install phpmyadmin\napt-get -yq install samba\necho '[global]\n workgroup = workgroup\n server string = %h server\n dns proxy = no\n log file = /var/log/samba/log.%m\n max log size = 1000\n syslog = 0\n panic action = /usr/share/samba/panic-action %d\n encrypt passwords = true\n passdb backend = tdbsam\n obey pam restrictions = yes\n ;invalid users = root\n unix password sync = no\n passwd program = /usr/bin/passwd %u\n passwd chat = *Enter\\snew\\sUNIX\\spassword:* %n\\n *Retype\\snew\\sUNIX\\spassword:* %n\\n *password\\supdated\\ssuccessfully* .\n socket options = TCP_NODELAY\n[homes]\n comment = Home Directories\n browseable = no\n writable = no\n create mask = 0700\n directory mask = 0700\n valid users = %S\n[www]\n comment = WWW\n writable = yes\n locking = no\n path = /var/www\n public = yes' > /etc/samba/smb.conf\n(echo SAMBAPASSWORD; echo SAMBAPASSWORD) | smbpasswd -sa root\necho 'NameVirtualHost *\n<VirtualHost *>\n ServerAdmin webmaster@localhost\n DocumentRoot /var/www/\n <Directory />\n Options FollowSymLinks\n AllowOverride None\n </Directory>\n <Directory /var/www/>\n Options Indexes FollowSymLinks MultiViews\n AllowOverride None\n Order allow,deny\n allow from all\n </Directory>\n ErrorLog /var/log/apache2/error.log\n LogLevel warn\n CustomLog /var/log/apache2/access.log combined\n ServerSignature On\n</VirtualHost>' > /etc/apache2/sites-enabled/000-default\n/etc/init.d/apache2 stop\n/etc/init.d/samba stop\n/etc/init.d/apache2 start\n/etc/init.d/samba start\n</code></pre>\n\n<p>edit: add this to set your MySQL password</p>\n\n<pre><code>/etc/init.d/mysql stop\necho \"UPDATE mysql.user SET Password=PASSWORD('MySQLPasswrod') WHERE User='root'; FLUSH PRIVILEGES;\" > /root/MySQLPassword\nmysqld_safe --init-file=/root/MySQLPassword &\nsleep 1\n/etc/init.d/mysql stop\nsleep 1\n/etc/init.d/mysql start\n</code></pre>\n\n<p>end edit</p>\n\n<p>This is a bit specailised but you get the idea, if you save this to a file ('install' for example) all you have to do is:</p>\n\n<pre><code>chmod +x install\n./install\n</code></pre>\n\n<p>Some of my apt-get commands are not necessary, because apt will automatically get the dependencies but I prefer to be specific, for my installs.</p>\n"
},
{
"answer_id": 30280,
"author": "dmityugov",
"author_id": 3232,
"author_profile": "https://Stackoverflow.com/users/3232",
"pm_score": 2,
"selected": false,
"text": "<p>Provided this question is properly tagged, you can select LAMP server option during installation of Ubuntu. This will install and configure all required components automatically. A detailed instruction on how to do this can be found, for example, there: <a href=\"http://www.ubuntugeek.com/ubuntu-804-hardy-heron-lamp-server-setup.html\" rel=\"nofollow noreferrer\">http://www.ubuntugeek.com/ubuntu-804-hardy-heron-lamp-server-setup.html</a></p>\n"
},
{
"answer_id": 275516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can rapidly customize LAMP, RoR, Python Django, Java Stack, Spring, etc servers for Ubuntu-based VM images at <a href=\"http://www.elasticserver.com\" rel=\"nofollow noreferrer\">http://www.elasticserver.com</a> - Unbuntu 8.04LTS now supported.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1771/"
] | I am using xampp on Windows, but I would like to use something closer to my server setup.
[Federico Cargnelutti tutorial](http://phpimpact.wordpress.com/2008/05/24/virtual-appliances-lamp-development-made-easy/) explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.
ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder. | This is my install scrpt, I use it on debian servers, but it will work in Ubuntu (Ubuntu is built on Debian)
```
apt-get -yq update
apt-get -yq upgrade
apt-get -yq install sudo
apt-get -yq install gcc
apt-get -yq install g++
apt-get -yq install make
apt-get -yq install apache2
apt-get -yq install php5
apt-get -yq install php5-curl
apt-get -yq install php5-mysql
apt-get -yq install php5-gd
apt-get -yq install mysql-common
apt-get -yq install mysql-client
apt-get -yq install mysql-server
apt-get -yq install phpmyadmin
apt-get -yq install samba
echo '[global]
workgroup = workgroup
server string = %h server
dns proxy = no
log file = /var/log/samba/log.%m
max log size = 1000
syslog = 0
panic action = /usr/share/samba/panic-action %d
encrypt passwords = true
passdb backend = tdbsam
obey pam restrictions = yes
;invalid users = root
unix password sync = no
passwd program = /usr/bin/passwd %u
passwd chat = *Enter\snew\sUNIX\spassword:* %n\n *Retype\snew\sUNIX\spassword:* %n\n *password\supdated\ssuccessfully* .
socket options = TCP_NODELAY
[homes]
comment = Home Directories
browseable = no
writable = no
create mask = 0700
directory mask = 0700
valid users = %S
[www]
comment = WWW
writable = yes
locking = no
path = /var/www
public = yes' > /etc/samba/smb.conf
(echo SAMBAPASSWORD; echo SAMBAPASSWORD) | smbpasswd -sa root
echo 'NameVirtualHost *
<VirtualHost *>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
ErrorLog /var/log/apache2/error.log
LogLevel warn
CustomLog /var/log/apache2/access.log combined
ServerSignature On
</VirtualHost>' > /etc/apache2/sites-enabled/000-default
/etc/init.d/apache2 stop
/etc/init.d/samba stop
/etc/init.d/apache2 start
/etc/init.d/samba start
```
edit: add this to set your MySQL password
```
/etc/init.d/mysql stop
echo "UPDATE mysql.user SET Password=PASSWORD('MySQLPasswrod') WHERE User='root'; FLUSH PRIVILEGES;" > /root/MySQLPassword
mysqld_safe --init-file=/root/MySQLPassword &
sleep 1
/etc/init.d/mysql stop
sleep 1
/etc/init.d/mysql start
```
end edit
This is a bit specailised but you get the idea, if you save this to a file ('install' for example) all you have to do is:
```
chmod +x install
./install
```
Some of my apt-get commands are not necessary, because apt will automatically get the dependencies but I prefer to be specific, for my installs. |
15,047 | <p>I'm working on a WinForm .Net application with the basic UI that includes toolbar buttons, menu items and keystrokes that all initiate the same underlying code. Right now the event handlers for each of these call a common method to perform the function.</p>
<p>From what I've read this type of action could be handled by the <a href="http://www.dofactory.com/Patterns/PatternCommand.aspx" rel="noreferrer">Command design pattern</a> with the additional benefit of automatically enabling/disabling or checking/unchecking the UI elements.</p>
<p>I've been searching the net for a good example project, but really haven't found one. Does anyone have a good example that can be shared?</p>
| [
{
"answer_id": 15103,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 1,
"selected": false,
"text": "<p>Try open source, .NET editors like <a href=\"http://sharpdevelop.net/OpenSource/SD/\" rel=\"nofollow noreferrer\">SharpDevelop</a> or <a href=\"http://notepad-plus.sourceforge.net/uk/site.htm\" rel=\"nofollow noreferrer\">Notepad++</a>.</p>\n\n<p>There is (naturally) some discussion of the Command Pattern at <a href=\"http://c2.com/cgi/wiki?CommandPattern\" rel=\"nofollow noreferrer\">http://c2.com/cgi/wiki?CommandPattern</a> that might be helpful.</p>\n"
},
{
"answer_id": 15207,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 5,
"selected": true,
"text": "<p>Let's first make sure we know what the Command pattern is:</p>\n\n<blockquote>\n <p>Command pattern encapsulates a request\n as an object and gives it a known\n public interface. Command Pattern\n ensures that every object receives its\n own commands and provides a decoupling\n between sender and receiver. A sender\n is an object that invokes an\n operation, and a receiver is an object\n that receives the request and acts on\n it.</p>\n</blockquote>\n\n<p>Here's an example for you. There are many ways you can do this, but I am going to take an interface base approach to make the code more testable for you. I am not sure what language you prefer, but I am writing this in C#.</p>\n\n<p>First, create an interface that describes a Command.</p>\n\n<pre><code>public interface ICommand\n{\n void Execute();\n}\n</code></pre>\n\n<p>Second, create command objects that will implement the command interface.</p>\n\n<pre><code>public class CutCommand : ICommand\n{\n public void Execute()\n {\n // Put code you like to execute when the CutCommand.Execute method is called.\n }\n}\n</code></pre>\n\n<p>Third, we need to setup our invoker or sender object.</p>\n\n<pre><code>public class TextOperations\n{\n public void Invoke(ICommand command)\n {\n command.Execute();\n }\n}\n</code></pre>\n\n<p>Fourth, create the client object that will use the invoker/sender object.</p>\n\n<pre><code>public class Client\n{\n static void Main()\n {\n TextOperations textOperations = new TextOperations();\n textOperation.Invoke(new CutCommand());\n }\n}\n</code></pre>\n\n<p>I hope you can take this example and put it into use for the application you are working on. If you would like more clarification, just let me know.</p>\n"
},
{
"answer_id": 20747,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": false,
"text": "<p>Your on the right track. Basically you will have a model that represents the document. You will use this model in the CutCommand. You will want to change the CutCommand's constructor to accept the information you want to cut. Then everytime, say the Cut Button is clicked, you invoke a new CutCommand and passing the arguments in the constructor. Then use those arguments in the class when the Execute method is called.</p>\n"
},
{
"answer_id": 20801,
"author": "Imran",
"author_id": 1897,
"author_profile": "https://Stackoverflow.com/users/1897",
"pm_score": 1,
"selected": false,
"text": "<p>Qt uses Command Pattern for Menubar/Toolbar items.</p>\n\n<p>QActions are created seperately from QMenuItem and QToolbar, and the Actions can be assigned to QMenuItem and QToolbar with setAction() and addAction() method respectively.</p>\n\n<p><a href=\"https://derefer.it/http://web.archive.org/web/20100801023349/http://cartan.cas.suffolk.edu/oopdocbook/html/menus.html\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20100801023349/http://cartan.cas.suffolk.edu/oopdocbook/html/menus.html</a></p>\n\n<p><a href=\"https://derefer.it/http://web.archive.org/web/20100729211835/http://cartan.cas.suffolk.edu/oopdocbook/html/actions.html\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20100729211835/http://cartan.cas.suffolk.edu/oopdocbook/html/actions.html</a></p>\n"
},
{
"answer_id": 34513005,
"author": "Dzianis Yafimau",
"author_id": 3877717,
"author_profile": "https://Stackoverflow.com/users/3877717",
"pm_score": 0,
"selected": false,
"text": "<p>I can't help you with example link, but can provide example by myself.</p>\n\n<p>1) Define ICommand interface:</p>\n\n<pre><code>public interface ICommand {\n void Do();\n void Undo();\n}\n</code></pre>\n\n<p>2) Do your ICommand implementations for concrete commands, but also define abstract base class for them:</p>\n\n<pre><code>public abstract class WinFormCommand : ICommand {\n\n}\n</code></pre>\n\n<p>3) Create command invoker:</p>\n\n<pre><code>public interface ICommandInvoker {\n void Invoke(ICommand command);\n void ReDo();\n void UnDo();\n}\n\npublic interface ICommandDirector {\n void Enable(ICommand);\n void Disable(ICommand);\n}\n\npublic class WinFormsCommandInvoker : ICommandInvoker, ICommandDirector {\n\n private readonly Dictionary<ICommand, bool> _commands;\n private readonly Queue<ICommand> _commandsQueue; \n private readonly IButtonDirector _buttonDirector;\n\n // you can define additional queue for support of ReDo operation\n\n public WinFormsCommandInvoker(ICommandsBuilder builder, IButtonDirector buttonDirector) {\n _commands = builder.Build();\n _buttonDirector = buttonDirector;\n _commandsQueue = new Queue<ICommand>();\n } \n\n public void Invoke(ICommand command) {\n command.Do();\n __commandsQueue.Enqueue(command);\n }\n\n public void ReDo() {\n //you can implement this using additional queue\n }\n\n public void UnDo() {\n var command = __commandsQueue.Dequeue();\n command.Undo();\n }\n\n public void Enable(ICommand command) {\n _commands.[command] = true;\n _buttonDirector.Enable(command);\n }\n\n public void Disable(ICommand command) {\n _commands.[command] = false;\n _buttonDirector.Disable(command); \n }\n}\n</code></pre>\n\n<p>4) Now you can implement your ICommandsBuilder, IButtonDirector and add other interfaces such as ICheckBoxDirector to WinFormsCommandInvoker.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1752/"
] | I'm working on a WinForm .Net application with the basic UI that includes toolbar buttons, menu items and keystrokes that all initiate the same underlying code. Right now the event handlers for each of these call a common method to perform the function.
From what I've read this type of action could be handled by the [Command design pattern](http://www.dofactory.com/Patterns/PatternCommand.aspx) with the additional benefit of automatically enabling/disabling or checking/unchecking the UI elements.
I've been searching the net for a good example project, but really haven't found one. Does anyone have a good example that can be shared? | Let's first make sure we know what the Command pattern is:
>
> Command pattern encapsulates a request
> as an object and gives it a known
> public interface. Command Pattern
> ensures that every object receives its
> own commands and provides a decoupling
> between sender and receiver. A sender
> is an object that invokes an
> operation, and a receiver is an object
> that receives the request and acts on
> it.
>
>
>
Here's an example for you. There are many ways you can do this, but I am going to take an interface base approach to make the code more testable for you. I am not sure what language you prefer, but I am writing this in C#.
First, create an interface that describes a Command.
```
public interface ICommand
{
void Execute();
}
```
Second, create command objects that will implement the command interface.
```
public class CutCommand : ICommand
{
public void Execute()
{
// Put code you like to execute when the CutCommand.Execute method is called.
}
}
```
Third, we need to setup our invoker or sender object.
```
public class TextOperations
{
public void Invoke(ICommand command)
{
command.Execute();
}
}
```
Fourth, create the client object that will use the invoker/sender object.
```
public class Client
{
static void Main()
{
TextOperations textOperations = new TextOperations();
textOperation.Invoke(new CutCommand());
}
}
```
I hope you can take this example and put it into use for the application you are working on. If you would like more clarification, just let me know. |
15,053 | <p>I'm trying to create a custom workflow action with an output parameter for error handling. Working from various examples, I can't get Parameter Direction="Out" to work. Everything seems right, but when I try to assign the output to the "error" variable in SharePoint Designer, it places asterisks around it and flags it as a workflow error. Here is what the action XML looks like:</p>
<pre><code><Action Name="Create Folder"
ClassName="ActivityLibrary.CreateFolderActivityTest"
Assembly="ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxx"
AppliesTo="all"
CreatesInList="ListId"
Category="Custom">
<RuleDesigner Sentence="Create a folder %1 in the %2 base folder. If an error occurs it will be output to %3.">
<FieldBind Field="FolderName" Text="folder name" Id="1" />
<FieldBind Field="BaseFolderPath" Text="folder path" Id="2"/>
<FieldBind Field="OutError" DesignerType="ParameterNames" Text="out error" Id="3"/>
</RuleDesigner>
<Parameters>
<Parameter Name="FolderName" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="BaseFolderPath" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="OutError" Type="System.String, mscorlib" Direction="Out" />
</Parameters>
</Action>
</code></pre>
| [
{
"answer_id": 18993,
"author": "Mauro",
"author_id": 2208,
"author_profile": "https://Stackoverflow.com/users/2208",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure the issue is with the parameters and not maybe the variable in SPD? Certainly nothing looks wrong with your XML.</p>\n\n<p>I always hated the way SPD and workflows make you create a variable within the workflow and another within the page to assign to the same value as the workflow variable.</p>\n"
},
{
"answer_id": 375112,
"author": "slf",
"author_id": 13263,
"author_profile": "https://Stackoverflow.com/users/13263",
"pm_score": 1,
"selected": false,
"text": "<p>I think you may want Direction=\"InOut\" from the looks of the binding</p>\n"
},
{
"answer_id": 552913,
"author": "Charlie",
"author_id": 466531,
"author_profile": "https://Stackoverflow.com/users/466531",
"pm_score": 0,
"selected": false,
"text": "<p>Did you get anywhere with this? I suspect the problem was more likely in your logic code rather than this xml (.actions) file. It looks perfectly acceptable to me.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1533/"
] | I'm trying to create a custom workflow action with an output parameter for error handling. Working from various examples, I can't get Parameter Direction="Out" to work. Everything seems right, but when I try to assign the output to the "error" variable in SharePoint Designer, it places asterisks around it and flags it as a workflow error. Here is what the action XML looks like:
```
<Action Name="Create Folder"
ClassName="ActivityLibrary.CreateFolderActivityTest"
Assembly="ActivityLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=xxxxxxxxxxx"
AppliesTo="all"
CreatesInList="ListId"
Category="Custom">
<RuleDesigner Sentence="Create a folder %1 in the %2 base folder. If an error occurs it will be output to %3.">
<FieldBind Field="FolderName" Text="folder name" Id="1" />
<FieldBind Field="BaseFolderPath" Text="folder path" Id="2"/>
<FieldBind Field="OutError" DesignerType="ParameterNames" Text="out error" Id="3"/>
</RuleDesigner>
<Parameters>
<Parameter Name="FolderName" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="BaseFolderPath" Type="System.String, mscorlib" Direction="In" />
<Parameter Name="OutError" Type="System.String, mscorlib" Direction="Out" />
</Parameters>
</Action>
``` | I think you may want Direction="InOut" from the looks of the binding |
15,056 | <p>What are some macros that you have found useful in Visual Studio for code manipulation and automation? </p>
| [
{
"answer_id": 15107,
"author": "RZachary",
"author_id": 1393,
"author_profile": "https://Stackoverflow.com/users/1393",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to add in code snippets as well, they help to speed up the development time and increase productivity.</p>\n\n<p>The standard VB code snippets come with the default installation. The C# code snippets must be downloaded and added seperately. (Link below for those)</p>\n\n<p>As far as macros go, I generally have not used any but the working with Visual studio 2005 book has some pretty good ones in there.</p>\n\n<p>C# Code snippets Link:\n<a href=\"http://www.codinghorror.com/blog/files/ms-csharp-snippets.7z.zip\" rel=\"nofollow noreferrer\">http://www.codinghorror.com/blog/files/ms-csharp-snippets.7z.zip</a> \n(Jeff Atwood provided the link)\nHIH</p>\n"
},
{
"answer_id": 15113,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<p>This is one of the handy ones I use on HTML and XML files:</p>\n\n<pre><code>''''replaceunicodechars.vb\nOption Strict Off\nOption Explicit Off\nImports EnvDTE\nImports System.Diagnostics\n\nPublic Module ReplaceUnicodeChars\n\n Sub ReplaceUnicodeChars()\n DTE.ExecuteCommand(\"Edit.Find\")\n ReplaceAllChar(ChrW(8230), \"&#8230;\") ' ellipses\n ReplaceAllChar(ChrW(8220), \"&#8220;\") ' left double quote\n ReplaceAllChar(ChrW(8221), \"&#8221;\") ' right double quote\n ReplaceAllChar(ChrW(8216), \"&#8216;\") ' left single quote\n ReplaceAllChar(ChrW(8217), \"&#8217;\") ' right single quote\n ReplaceAllChar(ChrW(8211), \"&#8211;\") ' en dash\n ReplaceAllChar(ChrW(8212), \"&#8212;\") ' em dash\n ReplaceAllChar(ChrW(176), \"&#176;\") ' °\n ReplaceAllChar(ChrW(188), \"&#188;\") ' ¼\n ReplaceAllChar(ChrW(189), \"&#189;\") ' ½\n ReplaceAllChar(ChrW(169), \"&#169;\") ' ©\n ReplaceAllChar(ChrW(174), \"&#174;\") ' ®\n ReplaceAllChar(ChrW(8224), \"&#8224;\") ' dagger\n ReplaceAllChar(ChrW(8225), \"&#8225;\") ' double-dagger\n ReplaceAllChar(ChrW(185), \"&#185;\") ' ¹\n ReplaceAllChar(ChrW(178), \"&#178;\") ' ²\n ReplaceAllChar(ChrW(179), \"&#179;\") ' ³\n ReplaceAllChar(ChrW(153), \"&#8482;\") ' ™\n ''ReplaceAllChar(ChrW(0), \"&#0;\")\n\n DTE.Windows.Item(Constants.vsWindowKindFindReplace).Close()\n End Sub\n\n Sub ReplaceAllChar(ByVal findWhat, ByVal replaceWith)\n DTE.Find.FindWhat = findWhat\n DTE.Find.ReplaceWith = replaceWith\n DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument\n DTE.Find.MatchCase = False\n DTE.Find.MatchWholeWord = False\n DTE.Find.MatchInHiddenText = True\n DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral\n DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone\n DTE.Find.Action = vsFindAction.vsFindActionReplaceAll\n DTE.Find.Execute()\n End Sub\n\nEnd Module\n</code></pre>\n\n<p>It's useful when you have to do any kind of data entry and want to escape everything at once.</p>\n"
},
{
"answer_id": 32858,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>This is one I created which allows you to easily change the Target Framework Version of all projects in a solution: <a href=\"https://web.archive.org/web/20170713162713/http://geekswithblogs.net:80/sdorman/archive/2008/07/18/visual-studio-2008-and-targetframeworkversion.aspx\" rel=\"nofollow noreferrer\">http://geekswithblogs.net/sdorman/archive/2008/07/18/visual-studio-2008-and-targetframeworkversion.aspx</a></p>\n"
},
{
"answer_id": 32868,
"author": "FantaMango77",
"author_id": 2374,
"author_profile": "https://Stackoverflow.com/users/2374",
"pm_score": 1,
"selected": false,
"text": "<p>I'm using <a href=\"http://blog.jpboodhoo.com\" rel=\"nofollow noreferrer\">Jean-Paul Boodhoo</a>'s <a href=\"http://blog.jpboodhoo.com/SmallUpdateToBDDMacro.aspx\" rel=\"nofollow noreferrer\">BDD macro</a>. It replaces whitespace characters with underscores within the header line of a method signature. This way I can type the names of a test case, for example, as a normal sentence, hit a keyboard shortcut and I have valid method signature.</p>\n"
},
{
"answer_id": 32884,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 3,
"selected": false,
"text": "<p>This is my macro to close the solution, delete the intellisense file, and reopen the solution. Essential if you're working in native C++.</p>\n\n<pre><code>Sub UpdateIntellisense()\n Dim solution As Solution = DTE.Solution\n Dim filename As String = solution.FullName\n Dim ncbFile As System.Text.StringBuilder = New System.Text.StringBuilder\n ncbFile.Append(System.IO.Path.GetDirectoryName(filename) + \"\\\")\n ncbFile.Append(System.IO.Path.GetFileNameWithoutExtension(filename))\n ncbFile.Append(\".ncb\")\n solution.Close(True)\n System.IO.File.Delete(ncbFile.ToString())\n solution.Open(filename)\nEnd Sub\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | What are some macros that you have found useful in Visual Studio for code manipulation and automation? | This is one of the handy ones I use on HTML and XML files:
```
''''replaceunicodechars.vb
Option Strict Off
Option Explicit Off
Imports EnvDTE
Imports System.Diagnostics
Public Module ReplaceUnicodeChars
Sub ReplaceUnicodeChars()
DTE.ExecuteCommand("Edit.Find")
ReplaceAllChar(ChrW(8230), "…") ' ellipses
ReplaceAllChar(ChrW(8220), "“") ' left double quote
ReplaceAllChar(ChrW(8221), "”") ' right double quote
ReplaceAllChar(ChrW(8216), "‘") ' left single quote
ReplaceAllChar(ChrW(8217), "’") ' right single quote
ReplaceAllChar(ChrW(8211), "–") ' en dash
ReplaceAllChar(ChrW(8212), "—") ' em dash
ReplaceAllChar(ChrW(176), "°") ' °
ReplaceAllChar(ChrW(188), "¼") ' ¼
ReplaceAllChar(ChrW(189), "½") ' ½
ReplaceAllChar(ChrW(169), "©") ' ©
ReplaceAllChar(ChrW(174), "®") ' ®
ReplaceAllChar(ChrW(8224), "†") ' dagger
ReplaceAllChar(ChrW(8225), "‡") ' double-dagger
ReplaceAllChar(ChrW(185), "¹") ' ¹
ReplaceAllChar(ChrW(178), "²") ' ²
ReplaceAllChar(ChrW(179), "³") ' ³
ReplaceAllChar(ChrW(153), "™") ' ™
''ReplaceAllChar(ChrW(0), "�")
DTE.Windows.Item(Constants.vsWindowKindFindReplace).Close()
End Sub
Sub ReplaceAllChar(ByVal findWhat, ByVal replaceWith)
DTE.Find.FindWhat = findWhat
DTE.Find.ReplaceWith = replaceWith
DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument
DTE.Find.MatchCase = False
DTE.Find.MatchWholeWord = False
DTE.Find.MatchInHiddenText = True
DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral
DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone
DTE.Find.Action = vsFindAction.vsFindActionReplaceAll
DTE.Find.Execute()
End Sub
End Module
```
It's useful when you have to do any kind of data entry and want to escape everything at once. |
15,062 | <p>How do I convert function input parameters to the right type?</p>
<p>I want to return a string that has part of the URL passed into it removed.</p>
<p><strong>This works, but it uses a hard-coded string:</strong></p>
<pre><code>function CleanUrl($input)
{
$x = "http://google.com".Replace("http://", "")
return $x
}
$SiteName = CleanUrl($HostHeader)
echo $SiteName
</code></pre>
<p><strong>This fails:</strong></p>
<pre><code>function CleanUrl($input)
{
$x = $input.Replace("http://", "")
return $x
}
Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'.
At M:\PowerShell\test.ps1:13 char:21
+ $x = $input.Replace( <<<< "http://", "")
</code></pre>
| [
{
"answer_id": 15068,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 3,
"selected": false,
"text": "<pre><code>function CleanUrl([string] $url)\n{\n return $url.Replace(\"http://\", \"\")\n}\n</code></pre>\n"
},
{
"answer_id": 15094,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": -1,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code>function CleanUrl($input)\n{\n return $input.Replace(\"http://\", \"\")\n}\n</code></pre>\n"
},
{
"answer_id": 15136,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 5,
"selected": true,
"text": "<p>The concept here is correct.</p>\n\n<p>The problem is with the variable name you have chosen. $input is a reserved variable used by PowerShell to represent an array of pipeline input. If you change your variable name, you should not have any problem.</p>\n\n<p>PowerShell does have <a href=\"https://technet.microsoft.com/en-us/library/hh847759.aspx\" rel=\"nofollow noreferrer\">a replace operator</a>, so you could make your function into</p>\n\n<pre><code>function CleanUrl($url)\n{\n return $url -replace 'http://'\n}\n</code></pre>\n"
},
{
"answer_id": 68811,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 4,
"selected": false,
"text": "<p>Steve's answer works. The problem with your attempt to reproduce ESV's script is that you're using <code>$input</code>, which is a reserved variable (it automatically collects multiple piped input into a single variable).</p>\n\n<p>You should, however, use .Replace() unless you need the extra feature(s) of -replace (it handles regular expressions, etc).</p>\n\n<pre><code>function CleanUrl([string]$url)\n{\n $url.Replace(\"http://\",\"\")\n}\n</code></pre>\n\n<p>That will work, but so would:</p>\n\n<pre><code>function CleanUrl([string]$url)\n{\n $url -replace \"http://\",\"\"\n}\n</code></pre>\n\n<p>Also, when you invoke a PowerShell function, don't use parenthesis:</p>\n\n<pre><code>$HostHeader = \"http://google.com\"\n$SiteName = CleanUrl $HostHeader\nWrite-Host $SiteName\n</code></pre>\n\n<p>Hope that helps. By the way, to demonstrate $input:</p>\n\n<pre><code>function CleanUrls\n{\n $input -replace \"http://\",\"\"\n}\n\n# Notice these are arrays ...\n$HostHeaders = @(\"http://google.com\",\"http://stackoverflow.com\")\n$SiteNames = $HostHeader | CleanUrls\nWrite-Output $SiteNames\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] | How do I convert function input parameters to the right type?
I want to return a string that has part of the URL passed into it removed.
**This works, but it uses a hard-coded string:**
```
function CleanUrl($input)
{
$x = "http://google.com".Replace("http://", "")
return $x
}
$SiteName = CleanUrl($HostHeader)
echo $SiteName
```
**This fails:**
```
function CleanUrl($input)
{
$x = $input.Replace("http://", "")
return $x
}
Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'.
At M:\PowerShell\test.ps1:13 char:21
+ $x = $input.Replace( <<<< "http://", "")
``` | The concept here is correct.
The problem is with the variable name you have chosen. $input is a reserved variable used by PowerShell to represent an array of pipeline input. If you change your variable name, you should not have any problem.
PowerShell does have [a replace operator](https://technet.microsoft.com/en-us/library/hh847759.aspx), so you could make your function into
```
function CleanUrl($url)
{
return $url -replace 'http://'
}
``` |
15,163 | <p>In some VB6 code, I have a handler for a TreeView's Collapse event:</p>
<pre><code>Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)
</code></pre>
<p>This is called whenever a node in the tree is collapsed, whether by the user or programmatically. As it turns out, through some roundabout execution, it may happen that this handler will wind up telling a node to collapse, leading to infinite recursion.</p>
<p>I can think of multiple ways to skin this cat, but what seems simplest to me is to tell the TreeView not to raise events for some period of time. I can't find a simple call to let me do this, though. Has anyone successfully done this, or do I need to keep track of state in some other manner so I can respond appropriately when recursive events come along?</p>
| [
{
"answer_id": 15591,
"author": "Phil Bachmann",
"author_id": 1855,
"author_profile": "https://Stackoverflow.com/users/1855",
"pm_score": 2,
"selected": true,
"text": "<p>I think that like many events in VB, it can't be switched off.</p>\n\n<p>Just set a boolean flag as you've suggested.</p>\n"
},
{
"answer_id": 16629,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "<p>@Phil - I came to the same conclusion. My implementation of <code>MyTree_Collapse</code> now looks something like this (where <code>m_bHandlingCallback</code> is a member variable):</p>\n\n<pre><code>Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)\n If m_bHandlingCallback Then Exit Sub\n\n m_bHandlingCallback = True\n DoSomeStuff\n m_bHandlingCallback = False\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 148286,
"author": "Guillermo Phillips",
"author_id": 441661,
"author_profile": "https://Stackoverflow.com/users/441661",
"pm_score": 0,
"selected": false,
"text": "<p>I would declare the flag variable as STATIC in the Sub. This avoids making the variable global and makes it keep its value between calls.</p>\n"
},
{
"answer_id": 1813531,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "<p>Another way in VB6 is to have an alternate <code>WithEvents</code> reference to the control:</p>\n\n<pre><code>Private WithEvents alt as TreeView\n</code></pre>\n\n<p>and in <code>Form_Load</code>:</p>\n\n<pre><code>Private Sub Form_Load()\nSet alt = MyTree\nEnd Sub\n</code></pre>\n\n<p>Now <code>alt</code> will receive lots of events like this:</p>\n\n<pre><code>Private Sub alt_Collapse(ByVal Node as MSComCtlLib.Node)\nSet alt = Nothing\n'DoSomeStuff'\nSet alt = MyTree\nEnd Sub\n</code></pre>\n\n<p>But, during the <code>DoSomeStuff</code>, the events are unhooked - which also applies to all other event <code>Sub</code>s for <code>alt</code> without the need for them to have intrusive changes.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863/"
] | In some VB6 code, I have a handler for a TreeView's Collapse event:
```
Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)
```
This is called whenever a node in the tree is collapsed, whether by the user or programmatically. As it turns out, through some roundabout execution, it may happen that this handler will wind up telling a node to collapse, leading to infinite recursion.
I can think of multiple ways to skin this cat, but what seems simplest to me is to tell the TreeView not to raise events for some period of time. I can't find a simple call to let me do this, though. Has anyone successfully done this, or do I need to keep track of state in some other manner so I can respond appropriately when recursive events come along? | I think that like many events in VB, it can't be switched off.
Just set a boolean flag as you've suggested. |
15,171 | <p>In the linux file system, where should user scripts be placed?</p>
<p>I'm thinking specifically python scripts to be called by cron.</p>
| [
{
"answer_id": 15177,
"author": "Matt McMinn",
"author_id": 1322,
"author_profile": "https://Stackoverflow.com/users/1322",
"pm_score": 4,
"selected": false,
"text": "<p>If you're talking about scripts created by a user that will be run from that users crontab, I typically put those in either a bin or scripts folder in the home directory, or if they're intended to be shared between users, a /usr/local/scripts directory.</p>\n"
},
{
"answer_id": 15189,
"author": "icco",
"author_id": 1063,
"author_profile": "https://Stackoverflow.com/users/1063",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a strong beleiver that if a file is made by a user, it goes in his user directory (/home/username) if he didn't make it then it gets more complicated. I have in the past just put them in either /usr/local/bin, /bin, or /usr/local/scripts, I'm not sure about etch, but you need to check to make sure that /usr/local/scripts is actually in Cron's $PATH.</p>\n"
},
{
"answer_id": 15194,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 0,
"selected": false,
"text": "<p>You can also add paths to your crontab file as shown in a <a href=\"https://stackoverflow.com/questions/13204/why-doesnt-my-cron-job-work-properly#13220\">previous cron-related question</a>.</p>\n"
},
{
"answer_id": 15374,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 2,
"selected": false,
"text": "<p>How about /home/username/bin?</p>\n\n<p>Add ~/bin to $PATH and make the script executable with chmod +x filename.</p>\n"
},
{
"answer_id": 15476,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 2,
"selected": false,
"text": "<p>personally I prefer</p>\n\n<pre><code>/home/username/.bin\n</code></pre>\n\n<p>This way the bin folder is hidden but you can still add it to the PATH and execute all scripts with the x-bit inside.</p>\n\n<p>I like my home directory to be clean (at first glance) with very few folders.</p>\n"
},
{
"answer_id": 35327,
"author": "flight",
"author_id": 3377,
"author_profile": "https://Stackoverflow.com/users/3377",
"pm_score": 3,
"selected": false,
"text": "<p>For whom it interests, the <a href=\"http://www.pathname.com/fhs/\" rel=\"noreferrer\">Filesystem Hierarchy Standard (FHS)</a> is a standards document and still a very good read. I describes the foundation for almost any Linux distribution and is officially endorsed e.g. by <a href=\"http://www.debian.org/doc/packaging-manuals/fhs/fhs-2.3.html\" rel=\"noreferrer\">Debian</a> and the Linux Standards Base (LSB).</p>\n\n<p>You won't find any positive answer for that question, though, since ... it's not defined ;-). Only thing I can say: Don't put in /bin (neither in /usr/bin). /usr/local/scripts is unusual as well. $HOME/bin seems to be an acceptable place, iff the script is only used by this single user.</p>\n"
},
{
"answer_id": 1759292,
"author": "pete",
"author_id": 214121,
"author_profile": "https://Stackoverflow.com/users/214121",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://www.debian.org/doc/maint-guide/ch-modify.en.html\" rel=\"nofollow noreferrer\">Debian guide</a> can be quite useful when it comes to Ubuntu:</p>\n\n<blockquote>\n <p>Normally, programs install themselves in the /usr/local subdirectories. But, Debian packages must not use that directory, since it is reserved for system administrator's (or user's) private use</p>\n</blockquote>\n\n<p><code>/usr/local/bin</code> seems to be acceptable according to the guide.</p>\n\n<p>Personally I put my scripts in <code>$HOME/.scripts</code>.</p>\n\n<p>I wish that LSB would specifically address this question though.</p>\n"
},
{
"answer_id": 7989517,
"author": "c33s",
"author_id": 590247,
"author_profile": "https://Stackoverflow.com/users/590247",
"pm_score": 6,
"selected": true,
"text": "<p>the information i got:</p>\n\n<pre><code>/usr/local/sbin custom script meant for root\n/usr/local/bin custom script meant for all users including non-root\n</code></pre>\n\n<p>chatlog snips from irc.debian.org #debian:</p>\n\n<pre><code>(02:48:49) c33s: question: where is the _correct_ location, to put custom scripts\nfor the root user (like a script on a webserver for createing everything needed \nfor a new webuser)? is it /bin, /usr/local/bin,...? /usr/local/scripts is \nmentioned in (*link to this page*)\n(02:49:15) Hydroxide: c33s: typically /usr/local/sbin\n(02:49:27) Hydroxide: c33s: no idea what /usr/local/scripts would be\n(02:49:32) Hydroxide: it's nonstandard\n(02:49:53) Hydroxide: if it's a custom script meant for all users including \nnon-root, then /usr/local/bin\n(02:52:43) Hydroxide: c33s: Debian follows the Filesystem Hierarchy Standard, \nwith a very small number of exceptions, which is online in several formats at \nhttp://www.pathname.com/fhs/ (also linked from http://www.debian.org/devel/ and \nseparately online at http://www.debian.org/doc/packaging-manuals/fhs/fhs-2.3.html)\n(02:53:03) Hydroxide: c33s: if you have the debian-policy package installed, it's \nalso in several formats at /usr/share/doc/debian-policy/fhs/ on your system\n(02:53:37) Hydroxide: c33s: most linux distributions follow that standard, though \nusually less strictly and with more deviations than Debian.\n</code></pre>\n\n<p>thanks go out to Hydroxide</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479/"
] | In the linux file system, where should user scripts be placed?
I'm thinking specifically python scripts to be called by cron. | the information i got:
```
/usr/local/sbin custom script meant for root
/usr/local/bin custom script meant for all users including non-root
```
chatlog snips from irc.debian.org #debian:
```
(02:48:49) c33s: question: where is the _correct_ location, to put custom scripts
for the root user (like a script on a webserver for createing everything needed
for a new webuser)? is it /bin, /usr/local/bin,...? /usr/local/scripts is
mentioned in (*link to this page*)
(02:49:15) Hydroxide: c33s: typically /usr/local/sbin
(02:49:27) Hydroxide: c33s: no idea what /usr/local/scripts would be
(02:49:32) Hydroxide: it's nonstandard
(02:49:53) Hydroxide: if it's a custom script meant for all users including
non-root, then /usr/local/bin
(02:52:43) Hydroxide: c33s: Debian follows the Filesystem Hierarchy Standard,
with a very small number of exceptions, which is online in several formats at
http://www.pathname.com/fhs/ (also linked from http://www.debian.org/devel/ and
separately online at http://www.debian.org/doc/packaging-manuals/fhs/fhs-2.3.html)
(02:53:03) Hydroxide: c33s: if you have the debian-policy package installed, it's
also in several formats at /usr/share/doc/debian-policy/fhs/ on your system
(02:53:37) Hydroxide: c33s: most linux distributions follow that standard, though
usually less strictly and with more deviations than Debian.
```
thanks go out to Hydroxide |
15,204 | <p>What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET?</p>
| [
{
"answer_id": 15210,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 6,
"selected": true,
"text": "<p>For C#:</p>\n\n<pre><code>foreach(ObjectType objectItem in objectTypeList)\n{\n // ...do some stuff\n}\n</code></pre>\n\n<p>Answer for VB.NET from <strong>Purple Ant</strong>:</p>\n\n<pre><code>For Each objectItem as ObjectType in objectTypeList\n 'Do some stuff '\nNext\n</code></pre>\n"
},
{
"answer_id": 15212,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "<p>I may be missing something, but iterating through a generic list should be fairly simple if you use my examples below. The List<> class implements the IList and IEnumerable interfaces so that you can easily iterate through them basically any way you want.</p>\n\n<p>The most efficient way would be to use a for loop: </p>\n\n<pre><code>for(int i = 0; i < genericList.Count; ++i) \n{\n // Loop body\n}\n</code></pre>\n\n<p>You may also choose to use a foreach loop:</p>\n\n<pre><code>foreach(<insertTypeHere> o in genericList)\n{\n // Loop body\n}\n</code></pre>\n"
},
{
"answer_id": 15218,
"author": "Brian G Swanson",
"author_id": 1795,
"author_profile": "https://Stackoverflow.com/users/1795",
"pm_score": 2,
"selected": false,
"text": "<p>For VB.NET:</p>\n\n<p><pre><code>For Each tmpObject as ObjectType in ObjectTypeList\n 'Do some stuff '\nNext</pre></code></p>\n"
},
{
"answer_id": 15222,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "<p>Without knowing the internal implementation of a list, I think generally the best way to iterate over it would be a foreach loop. Because foreach uses an IEnumerator to walk over the list, it's up to the list itself to determine how to move from object to object.</p>\n\n<p>If the internal implementation was, say, a linked list, then a simple for loop would be quite a bit slower than a foreach.</p>\n\n<p>Does that make sense?</p>\n"
},
{
"answer_id": 15232,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "<p>With any generic implementation of IEnumerable the best way is:</p>\n\n<pre><code>//C#\nforeach( var item in listVariable) {\n //do stuff\n}\n</code></pre>\n\n<p>There is an important exception however. IEnumerable involves an overhead of Current() and MoveNext() that is what the foreach loop is actually compiled into.</p>\n\n<p>When you have a simple array of structs:</p>\n\n<pre><code>//C#\nint[] valueTypeArray;\nfor(int i=0; i < valueTypeArray.Length; ++i) {\n int item = valueTypeArray[i];\n //do stuff\n}\n</code></pre>\n\n<p>Is quicker.</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>Following a discussion with @Steven Sudit (see comments) I think my original advice may be out of date or mistaken, so I ran some tests:</p>\n\n<pre><code>// create a list to test with\nvar theList = Enumerable.Range(0, 100000000).ToList();\n\n// time foreach\nvar sw = Stopwatch.StartNew();\nforeach (var item in theList)\n{\n int inLoop = item;\n}\nConsole.WriteLine(\"list foreach: \" + sw.Elapsed.ToString());\n\nsw.Reset();\nsw.Start();\n\n// time for\nint cnt = theList.Count;\nfor (int i = 0; i < cnt; i++)\n{\n int inLoop = theList[i];\n}\nConsole.WriteLine(\"list for : \" + sw.Elapsed.ToString());\n\n// now run the same tests, but with an array\nvar theArray = theList.ToArray();\n\nsw.Reset();\nsw.Start();\n\nforeach (var item in theArray)\n{\n int inLoop = item;\n}\nConsole.WriteLine(\"array foreach: \" + sw.Elapsed.ToString());\n\nsw.Reset();\nsw.Start();\n\n// time for\ncnt = theArray.Length;\nfor (int i = 0; i < cnt; i++)\n{\n int inLoop = theArray[i];\n}\nConsole.WriteLine(\"array for : \" + sw.Elapsed.ToString());\n\nConsole.ReadKey();\n</code></pre>\n\n<p>So, I ran this in release with all optimisations:</p>\n\n<pre><code>list foreach: 00:00:00.5137506\nlist for : 00:00:00.2417709\narray foreach: 00:00:00.1085653\narray for : 00:00:00.0954890\n</code></pre>\n\n<p>And then debug without optimisations:</p>\n\n<pre><code>list foreach: 00:00:01.1289015\nlist for : 00:00:00.9945345\narray foreach: 00:00:00.6405422\narray for : 00:00:00.4913245\n</code></pre>\n\n<p>So it appears fairly consistent, <code>for</code> is quicker than <code>foreach</code> and arrays are quicker than generic lists.</p>\n\n<p>However, this is across 100,000,000 iterations and the difference is about .4 of a second between the fastest and slowest methods. Unless you're doing massive performance critical loops it just isn't worth worrying about.</p>\n"
},
{
"answer_id": 15238,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 3,
"selected": false,
"text": "<p>C#</p>\n\n<pre><code>myList<string>().ForEach(\n delegate(string name)\n {\n Console.WriteLine(name);\n });\n</code></pre>\n\n<p>Anonymous delegates are not currently implemented in VB.Net, but both C# and VB.Net should be able to do lambdas:</p>\n\n<p>C#</p>\n\n<pre><code>myList<string>().ForEach(name => Console.WriteLine(name));\n</code></pre>\n\n<p>VB.Net</p>\n\n<pre><code>myList(Of String)().ForEach(Function(name) Console.WriteLine(name))\n</code></pre>\n\n<hr>\n\n<p>As Grauenwolf pointed out the above VB won't compile since the lambda doesn't return a value. A normal ForEach loop as others have suggested is probably the easiest for now, but as usual it takes a block of code to do what C# can do in one line.</p>\n\n<hr>\n\n<p>Here's a trite example of why this might be useful: this gives you the ability to pass in the loop logic from another scope than where the IEnumerable exists, so you don't even have to expose it if you don't want to.</p>\n\n<p>Say you have a list of relative url paths that you want to make absolute:</p>\n\n<pre><code>public IEnumerable<String> Paths(Func<String> formatter) {\n List<String> paths = new List<String>()\n {\n \"/about\", \"/contact\", \"/services\"\n };\n\n return paths.ForEach(formatter);\n}\n</code></pre>\n\n<p>So then you could call the function this way:</p>\n\n<pre><code>var hostname = \"myhost.com\";\nvar formatter = f => String.Format(\"http://{0}{1}\", hostname, f);\nIEnumerable<String> absolutePaths = Paths(formatter);\n</code></pre>\n\n<p>Giving you <code>\"http://myhost.com/about\", \"http://myhost.com/contact\"</code> etc. Obviously there are better ways to accomplish this in this specfic example, I'm just trying to demonstrate the basic principle.</p>\n"
},
{
"answer_id": 15527,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 2,
"selected": false,
"text": "<p>It depends on your application:</p>\n\n<ul>\n<li>for loop, if efficiency is a priority</li>\n<li>foreach loop or ForEach method, whichever communicates your intent more clearly</li>\n</ul>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1224/"
] | What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET? | For C#:
```
foreach(ObjectType objectItem in objectTypeList)
{
// ...do some stuff
}
```
Answer for VB.NET from **Purple Ant**:
```
For Each objectItem as ObjectType in objectTypeList
'Do some stuff '
Next
``` |
15,219 | <p>I'm using the Infragistics grid and I'm having a difficult time using a drop-down list as the value selector for one of my columns.</p>
<p>I tried reading the documentation but Infragistics' documentation is not so good. I've also taken a look at this <a href="http://news.infragistics.com/forums/p/9063/45792.aspx" rel="nofollow noreferrer">discussion</a> with no luck.</p>
<p>What I'm doing so far:</p>
<pre><code>col.Type = ColumnType.DropDownList;
col.DataType = "System.String";
col.ValueList = myValueList;
</code></pre>
<p>where <code>myValueList</code> is:</p>
<pre><code>ValueList myValueList = new ValueList();
myValueList.Prompt = "My text prompt";
myValueList.DisplayStyle = ValueListDisplayStyle.DisplayText;
foreach(MyObjectType item in MyObjectTypeCollection)
{
myValueList.ValueItems.Add(item.ID, item.Text); // Note that the ID is a string (not my design)
}
</code></pre>
<p>When I look at the page, I expect to see a drop-down list in the cells for this column, but my columns are empty.</p>
| [
{
"answer_id": 16347,
"author": "Erick B",
"author_id": 1373,
"author_profile": "https://Stackoverflow.com/users/1373",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example from one of my pages:</p>\n\n<pre><code>UltraWebGrid uwgMyGrid = new UltraWebGrid();\nuwgMyGrid.Columns.Add(\"colTest\", \"Test Dropdown\");\nuwgMyGrid.Columns.FromKey(\"colTest\").Type = ColumnType.DropDownList;\nuwgMyGrid.Columns.FromKey(\"colTest\").ValueList.ValueListItems.Insert(0, \"ONE\", \"Choice 1\");\nuwgMyGrid.Columns.FromKey(\"colTest\").ValueList.ValueListItems.Insert(1, \"TWO\", \"Choice 2\");\n</code></pre>\n"
},
{
"answer_id": 18507,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": true,
"text": "<p>I've found what was wrong.</p>\n\n<p>The column must allow updates.</p>\n\n<pre><code>uwgMyGrid.Columns.FromKey(\"colTest\").AllowUpdate = AllowUpdate.Yes;\n</code></pre>\n"
},
{
"answer_id": 2681542,
"author": "regor",
"author_id": 322104,
"author_profile": "https://Stackoverflow.com/users/322104",
"pm_score": 0,
"selected": false,
"text": "<pre><code> public void MakeCellValueListDropDownList(UltraWebGrid grid, string columnName, string valueListName, string[] listArray)\n {\n //Set the column to be a dropdownlist\n UltraGridColumn Col = grid.Columns.FromKey(columnName); \n Col.Type = ColumnType.DropDownList;\n Col.DataType = \"System.String\";\n\n try\n {\n ValueList ValList = grid.DisplayLayout.Bands[0].Columns.FromKey(columnName).ValueList;\n ValList.DataSource = listArray;\n foreach (string item in listArray)\n {\n ValList.ValueListItems.Add(item);\n }\n ValList.DataBind();\n }\n catch (ArgumentException)\n {\n\n }\n }\n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] | I'm using the Infragistics grid and I'm having a difficult time using a drop-down list as the value selector for one of my columns.
I tried reading the documentation but Infragistics' documentation is not so good. I've also taken a look at this [discussion](http://news.infragistics.com/forums/p/9063/45792.aspx) with no luck.
What I'm doing so far:
```
col.Type = ColumnType.DropDownList;
col.DataType = "System.String";
col.ValueList = myValueList;
```
where `myValueList` is:
```
ValueList myValueList = new ValueList();
myValueList.Prompt = "My text prompt";
myValueList.DisplayStyle = ValueListDisplayStyle.DisplayText;
foreach(MyObjectType item in MyObjectTypeCollection)
{
myValueList.ValueItems.Add(item.ID, item.Text); // Note that the ID is a string (not my design)
}
```
When I look at the page, I expect to see a drop-down list in the cells for this column, but my columns are empty. | I've found what was wrong.
The column must allow updates.
```
uwgMyGrid.Columns.FromKey("colTest").AllowUpdate = AllowUpdate.Yes;
``` |
15,240 | <p>I'd like to make a debug logging function with the same parameters as <code>printf</code>. But one that can be removed by the pre-processor during optimized builds.</p>
<p>For example:</p>
<pre><code>Debug_Print("Warning: value %d > 3!\n", value);
</code></pre>
<p>I've looked at variadic macros but those aren't available on all platforms. <code>gcc</code> supports them, <code>msvc</code> does not.</p>
| [
{
"answer_id": 15248,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 1,
"selected": false,
"text": "<p>What platforms are they not available on? stdarg is part of the standard library:</p>\n\n<p><a href=\"http://www.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html\" rel=\"nofollow noreferrer\">http://www.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html</a></p>\n\n<p>Any platform not providing it is not a standard C implementation (or very, very old). For those, you will have to use varargs:</p>\n\n<p><a href=\"http://opengroup.org/onlinepubs/007908775/xsh/varargs.h.html\" rel=\"nofollow noreferrer\">http://opengroup.org/onlinepubs/007908775/xsh/varargs.h.html</a></p>\n"
},
{
"answer_id": 15262,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 4,
"selected": false,
"text": "<p>Here's something that I do in C/C++. First off, you write a function that uses the varargs stuff (see the link in Stu's posting). Then do something like this:</p>\n\n<pre><code>\n int debug_printf( const char *fmt, ... );\n #if defined( DEBUG )\n #define DEBUG_PRINTF(x) debug_printf x\n #else\n #define DEBUG_PRINTF(x)\n #endif\n\n DEBUG_PRINTF(( \"Format string that takes %s %s\\n\", \"any number\", \"of args\" ));\n</code></pre>\n\n<p>All you have to remember is to use double-parens when calling the debug function, and the whole line will get removed in non-DEBUG code.</p>\n"
},
{
"answer_id": 15269,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:</p>\n\n<pre><code>#include <stdio.h>\n\nvoid XTrace0(LPCTSTR lpszText)\n{\n ::OutputDebugString(lpszText);\n}\n\nvoid XTrace(LPCTSTR lpszFormat, ...)\n{\n va_list args;\n va_start(args, lpszFormat);\n int nBuf;\n TCHAR szBuffer[512]; // get rid of this hard-coded buffer\n nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);\n ::OutputDebugString(szBuffer);\n va_end(args);\n}\n</code></pre>\n\n<p>Then a typical #ifdef switch:</p>\n\n<pre><code>#ifdef _DEBUG\n#define XTRACE XTrace\n#else\n#define XTRACE\n#endif\n</code></pre>\n\n<p>Well that can be cleaned up quite a bit but it's the basic idea.</p>\n"
},
{
"answer_id": 15281,
"author": "hyperlogic",
"author_id": 1841,
"author_profile": "https://Stackoverflow.com/users/1841",
"pm_score": 3,
"selected": false,
"text": "<p>Ah, vsprintf() was the thing I was missing. I can use this to pass the variable argument list directly to printf():</p>\n\n<pre><code>#include <stdarg.h>\n#include <stdio.h>\n\nvoid DBG_PrintImpl(char * format, ...)\n{\n char buffer[256];\n va_list args;\n va_start(args, format);\n vsprintf(buffer, format, args);\n printf(\"%s\", buffer);\n va_end(args);\n}\n</code></pre>\n\n<p>Then wrap the whole thing in a macro.</p>\n"
},
{
"answer_id": 17029,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "<p>Another fun way to stub out variadic functions is:</p>\n\n<pre><code>#define function sizeof\n</code></pre>\n"
},
{
"answer_id": 17932,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "<p>In C++ you can use the streaming operator to simplify things:</p>\n\n<pre><code>#if defined _DEBUG\n\nclass Trace\n{\npublic:\n static Trace &GetTrace () { static Trace trace; return trace; }\n Trace &operator << (int value) { /* output int */ return *this; }\n Trace &operator << (short value) { /* output short */ return *this; }\n Trace &operator << (Trace &(*function)(Trace &trace)) { return function (*this); }\n static Trace &Endl (Trace &trace) { /* write newline and flush output */ return trace; }\n // and so on\n};\n\n#define TRACE(message) Trace::GetTrace () << message << Trace::Endl\n\n#else\n#define TRACE(message)\n#endif\n</code></pre>\n\n<p>and use it like:</p>\n\n<pre><code>void Function (int param1, short param2)\n{\n TRACE (\"param1 = \" << param1 << \", param2 = \" << param2);\n}\n</code></pre>\n\n<p>You can then implement customised trace output for classes in much the same way you would do it for outputting to <code>std::cout</code>.</p>\n"
},
{
"answer_id": 42775,
"author": "David Bryson",
"author_id": 3663,
"author_profile": "https://Stackoverflow.com/users/3663",
"pm_score": 1,
"selected": false,
"text": "<p>Part of the problem with this kind of functionality is that often it requires\nvariadic macros. These were standardized fairly recently(C99), and lots of\nold C compilers do not support the standard, or have their own special work\naround.</p>\n\n<p>Below is a debug header I wrote that has several cool features:</p>\n\n<ul>\n<li>Supports C99 and C89 syntax for debug macros</li>\n<li>Enable/Disable output based on function argument</li>\n<li>Output to file descriptor(file io)</li>\n</ul>\n\n<p>Note: For some reason I had some slight code formatting problems.</p>\n\n<pre><code>#ifndef _DEBUG_H_\n#define _DEBUG_H_\n#if HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"stdarg.h\"\n#include \"stdio.h\"\n\n#define ENABLE 1\n#define DISABLE 0\n\nextern FILE* debug_fd;\n\nint debug_file_init(char *file);\nint debug_file_close(void);\n\n#if HAVE_C99\n#define PRINT(x, format, ...) \\\nif ( x ) { \\\nif ( debug_fd != NULL ) { \\\nfprintf(debug_fd, format, ##__VA_ARGS__); \\\n} \\\nelse { \\\nfprintf(stdout, format, ##__VA_ARGS__); \\\n} \\\n}\n#else\nvoid PRINT(int enable, char *fmt, ...);\n#endif\n\n#if _DEBUG\n#if HAVE_C99\n#define DEBUG(x, format, ...) \\\nif ( x ) { \\\nif ( debug_fd != NULL ) { \\\nfprintf(debug_fd, \"%s : %d \" format, __FILE__, __LINE__, ##__VA_ARGS__); \\\n} \\\nelse { \\\nfprintf(stderr, \"%s : %d \" format, __FILE__, __LINE__, ##__VA_ARGS__); \\\n} \\\n}\n\n#define DEBUGPRINT(x, format, ...) \\\nif ( x ) { \\\nif ( debug_fd != NULL ) { \\\nfprintf(debug_fd, format, ##__VA_ARGS__); \\\n} \\\nelse { \\\nfprintf(stderr, format, ##__VA_ARGS__); \\\n} \\\n}\n#else /* HAVE_C99 */\n\nvoid DEBUG(int enable, char *fmt, ...);\nvoid DEBUGPRINT(int enable, char *fmt, ...);\n\n#endif /* HAVE_C99 */\n#else /* _DEBUG */\n#define DEBUG(x, format, ...)\n#define DEBUGPRINT(x, format, ...)\n#endif /* _DEBUG */\n\n#endif /* _DEBUG_H_ */\n</code></pre>\n"
},
{
"answer_id": 55663,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>@CodingTheWheel:</p>\n\n<p>There is one slight problem with your approach. Consider a call such as</p>\n\n<pre><code>XTRACE(\"x=%d\", x);\n</code></pre>\n\n<p>This works fine in the debug build, but in the release build it will expand to:</p>\n\n<pre><code>(\"x=%d\", x);\n</code></pre>\n\n<p>Which is perfectly legitimate C and will compile and usually run without side-effects but generates unnecessary code. The approach I usually use to eliminate that problem is:</p>\n\n<ol>\n<li><p>Make the XTrace function return an int (just return 0, the return value doesn't matter)</p></li>\n<li><p>Change the #define in the #else clause to:</p>\n\n<pre><code>0 && XTrace\n</code></pre></li>\n</ol>\n\n<p>Now the release version will expand to:</p>\n\n<pre><code>0 && XTrace(\"x=%d\", x);\n</code></pre>\n\n<p>and any decent optimizer will throw away the whole thing since short-circuit evaluation would have prevented anything after the && from ever being executed.</p>\n\n<p>Of course, just as I wrote that last sentence, I realized that perhaps the original form might be optimized away too and in the case of side effects, such as function calls passed as parameters to XTrace, it might be a better solution since it will make sure that debug and release versions will behave the same.</p>\n"
},
{
"answer_id": 67428,
"author": "snstrand",
"author_id": 10089,
"author_profile": "https://Stackoverflow.com/users/10089",
"pm_score": 5,
"selected": false,
"text": "<p>This is how I do debug print outs in C++. Define 'dout' (debug out) like this:</p>\n\n<pre><code>#ifdef DEBUG\n#define dout cout\n#else\n#define dout 0 && cout\n#endif\n</code></pre>\n\n<p>In the code I use 'dout' just like 'cout'.</p>\n\n<pre><code>dout << \"in foobar with x= \" << x << \" and y= \" << y << '\\n';\n</code></pre>\n\n<p>If the preprocessor replaces 'dout' with '0 && cout' note that << has higher precedence than && and short-circuit evaluation of && makes the whole line evaluate to 0. Since the 0 is not used the compiler generates no code at all for that line.</p>\n"
},
{
"answer_id": 689659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Have a look at this thread:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/679979/\">How to make a variadic macro (variable number of arguments)</a></li>\n</ul>\n\n<p>It should answer your question.</p>\n"
},
{
"answer_id": 13020140,
"author": "Koffiman",
"author_id": 914689,
"author_profile": "https://Stackoverflow.com/users/914689",
"pm_score": 0,
"selected": false,
"text": "<p>Having come across the problem today, my solution is the following macro:</p>\n<pre><code> static TCHAR __DEBUG_BUF[1024];\n #define DLog(fmt, ...) swprintf(__DEBUG_BUF, fmt, ##__VA_ARGS__); OutputDebugString(__DEBUG_BUF) \n \n</code></pre>\n<p>You can then call the function like this:</p>\n<pre><code> int value = 42;\n DLog(L"The answer is: %d\\n", value);\n</code></pre>\n"
},
{
"answer_id": 18129398,
"author": "mousomer",
"author_id": 281617,
"author_profile": "https://Stackoverflow.com/users/281617",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I use:</p>\n\n<pre><code>inline void DPRINTF(int level, char *format, ...)\n{\n# ifdef _DEBUG_LOG\n va_list args;\n va_start(args, format);\n if(debugPrint & level) {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n# endif /* _DEBUG_LOG */\n}\n</code></pre>\n\n<p>which costs absolutely nothing at run-time when the _DEBUG_LOG flag is turned off.</p>\n"
},
{
"answer_id": 39186784,
"author": "Orwellophile",
"author_id": 912236,
"author_profile": "https://Stackoverflow.com/users/912236",
"pm_score": 0,
"selected": false,
"text": "<p>This is a TCHAR version of user's answer, so it will work as ASCII (<em>normal</em>), or Unicode mode (more or less).</p>\n\n<pre><code>#define DEBUG_OUT( fmt, ...) DEBUG_OUT_TCHAR( \\\n TEXT(##fmt), ##__VA_ARGS__ )\n#define DEBUG_OUT_TCHAR( fmt, ...) \\\n Trace( TEXT(\"[DEBUG]\") #fmt, \\\n ##__VA_ARGS__ )\nvoid Trace(LPCTSTR format, ...)\n{\n LPTSTR OutputBuf;\n OutputBuf = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, \\\n (size_t)(4096 * sizeof(TCHAR)));\n va_list args;\n va_start(args, format);\n int nBuf;\n _vstprintf_s(OutputBuf, 4095, format, args);\n ::OutputDebugString(OutputBuf);\n va_end(args);\n LocalFree(OutputBuf); // tyvm @sam shaw\n}\n</code></pre>\n\n<p><em>I say, \"more or less\", because it won't automatically convert ASCII string arguments to WCHAR, but it should get you out of most Unicode scrapes without having to worry about wrapping the format string in TEXT() or preceding it with L.</em></p>\n\n<p>Largely derived from <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680582(v=vs.85).aspx\" rel=\"nofollow\">MSDN: Retrieving the Last-Error Code</a></p>\n"
},
{
"answer_id": 63047805,
"author": "parth_07",
"author_id": 3447475,
"author_profile": "https://Stackoverflow.com/users/3447475",
"pm_score": 0,
"selected": false,
"text": "<p>Not exactly what's asked in the question . But this code will be helpful for debugging purposes , it will print each variable's value along with it's name . This is completely type independent and supports variable number of arguments.\nAnd can even display values of STL's nicely , given that you overload output operator for them</p>\n<pre><code>#define show(args...) describe(#args,args);\ntemplate<typename T>\nvoid describe(string var_name,T value)\n{\n clog<<var_name<<" = "<<value<<" ";\n}\n\ntemplate<typename T,typename... Args>\nvoid describe(string var_names,T value,Args... args)\n{\n string::size_type pos = var_names.find(',');\n string name = var_names.substr(0,pos);\n var_names = var_names.substr(pos+1);\n clog<<name<<" = "<<value<<" | ";\n describe(var_names,args...);\n}\n</code></pre>\n<p>Sample Use :</p>\n<pre><code>int main()\n{\n string a;\n int b;\n double c;\n a="string here";\n b = 7;\n c= 3.14;\n show(a,b,c);\n}\n</code></pre>\n<p>Output :</p>\n<pre><code>a = string here | b = 7 | c = 3.14 \n</code></pre>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] | I'd like to make a debug logging function with the same parameters as `printf`. But one that can be removed by the pre-processor during optimized builds.
For example:
```
Debug_Print("Warning: value %d > 3!\n", value);
```
I've looked at variadic macros but those aren't available on all platforms. `gcc` supports them, `msvc` does not. | I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:
```
#include <stdio.h>
void XTrace0(LPCTSTR lpszText)
{
::OutputDebugString(lpszText);
}
void XTrace(LPCTSTR lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
int nBuf;
TCHAR szBuffer[512]; // get rid of this hard-coded buffer
nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
::OutputDebugString(szBuffer);
va_end(args);
}
```
Then a typical #ifdef switch:
```
#ifdef _DEBUG
#define XTRACE XTrace
#else
#define XTRACE
#endif
```
Well that can be cleaned up quite a bit but it's the basic idea. |
15,247 | <p>Given a list of locations such as</p>
<pre class="lang-html prettyprint-override"><code> <td>El Cerrito, CA</td>
<td>Corvallis, OR</td>
<td>Morganton, NC</td>
<td>New York, NY</td>
<td>San Diego, CA</td>
</code></pre>
<p>What's the easiest way to generate a Google Map with pushpins for each location?</p>
| [
{
"answer_id": 15257,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 1,
"selected": false,
"text": "<p>I guess more information would be needed to really give you an answer, but over at Django Pluggables there is a <a href=\"http://djangoplugables.com/projects/django-googlemap/\" rel=\"nofollow noreferrer\">django-googlemap plugin</a> that might be of help.</p>\n\n<p><strong>Edit:</strong> Adam has a much better answer. When it doubt look at the API examples. </p>\n"
},
{
"answer_id": 15265,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 3,
"selected": false,
"text": "<p>Check out the <a href=\"http://code.google.com/apis/maps/documentation/examples/\" rel=\"noreferrer\">Google Maps API Examples</a>\nThey make it pretty simple and their API documentation is great.\nMost of the examples are for doing all the code in JavaScript on the client side, but there are APIs for other languages available as well.</p>\n"
},
{
"answer_id": 15346,
"author": "mauriciopastrana",
"author_id": 547,
"author_profile": "https://Stackoverflow.com/users/547",
"pm_score": 1,
"selected": false,
"text": "<p>Try this: <a href=\"http://www.google.com/uds/solutions/wizards/mapsearch.html\" rel=\"nofollow noreferrer\">http://www.google.com/uds/solutions/wizards/mapsearch.html</a></p>\n\n<p>It's a google maps wizard which will generate the code for you. Not the best for your application; but a good place to \"get your feet wet\" ;)</p>\n\n<p>Edit: (found the link), <a href=\"http://econym.googlepages.com/index.htm\" rel=\"nofollow noreferrer\">here's a good Google Maps API stepwise tutorial.</a></p>\n\n<p>Good luck!</p>\n\n<p>/mp</p>\n"
},
{
"answer_id": 17132,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 5,
"selected": true,
"text": "<p>I'm assuming you have the basics for Maps in your code already with your API Key.</p>\n\n<pre><code><head>\n <script \n type=\"text/javascript\"\n href=\"http://maps.google.com/maps?\n file=api&v=2&key=xxxxx\">\n function createMap() {\n var map = new GMap2(document.getElementById(\"map\"));\n map.setCenter(new GLatLng(37.44, -122.14), 14);\n }\n </script>\n</head>\n<body onload=\"createMap()\" onunload=\"GUnload()\">\n</code></pre>\n\n<p>Everything in Google Maps is based off of latitude (lat) and longitude (lng).<br />\nSo to create a simple marker you will just create a GMarker with the lat and lng.</p>\n\n<pre><code>var where = new GLatLng(37.925243,-122.307358); //Lat and Lng for El Cerrito, CA\nvar marker = new GMarker(where); // Create marker (Pinhead thingy)\nmap.setCenter(where); // Center map on marker\nmap.addOverlay(marker); // Add marker to map\n</code></pre>\n\n<p>However if you don't want to look up the Lat and Lng for each city you can use Google's Geo Coder. Heres an example:</p>\n\n<pre><code>var address = \"El Cerrito, CA\";\nvar geocoder = new GClientGeocoder;\ngeocoder.getLatLng(address, function(point) {\n if (point) {\n map.clearOverlays(); // Clear all markers\n map.addOverlay(new GMarker(point)); // Add marker to map\n map.setCenter(point, 10); // Center and zoom map on marker\n }\n});\n</code></pre>\n\n<p>So I would just create an array of GLatLng's of every city from the GeoCoder and then draw them on the map.</p>\n"
},
{
"answer_id": 17159,
"author": "solrevdev",
"author_id": 2041,
"author_profile": "https://Stackoverflow.com/users/2041",
"pm_score": 1,
"selected": false,
"text": "<p>Here are some links but as with most things i have not got round to trying them yet.</p>\n\n<p><a href=\"http://gathadams.com/2007/08/21/add-google-maps-to-your-net-site-in-10-minutes/\" rel=\"nofollow noreferrer\">http://gathadams.com/2007/08/21/add-google-maps-to-your-net-site-in-10-minutes/</a></p>\n\n<p><a href=\"http://www.mapbuilder.net/\" rel=\"nofollow noreferrer\">http://www.mapbuilder.net/</a></p>\n\n<p>Cheers\nJohn</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] | Given a list of locations such as
```html
<td>El Cerrito, CA</td>
<td>Corvallis, OR</td>
<td>Morganton, NC</td>
<td>New York, NY</td>
<td>San Diego, CA</td>
```
What's the easiest way to generate a Google Map with pushpins for each location? | I'm assuming you have the basics for Maps in your code already with your API Key.
```
<head>
<script
type="text/javascript"
href="http://maps.google.com/maps?
file=api&v=2&key=xxxxx">
function createMap() {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.44, -122.14), 14);
}
</script>
</head>
<body onload="createMap()" onunload="GUnload()">
```
Everything in Google Maps is based off of latitude (lat) and longitude (lng).
So to create a simple marker you will just create a GMarker with the lat and lng.
```
var where = new GLatLng(37.925243,-122.307358); //Lat and Lng for El Cerrito, CA
var marker = new GMarker(where); // Create marker (Pinhead thingy)
map.setCenter(where); // Center map on marker
map.addOverlay(marker); // Add marker to map
```
However if you don't want to look up the Lat and Lng for each city you can use Google's Geo Coder. Heres an example:
```
var address = "El Cerrito, CA";
var geocoder = new GClientGeocoder;
geocoder.getLatLng(address, function(point) {
if (point) {
map.clearOverlays(); // Clear all markers
map.addOverlay(new GMarker(point)); // Add marker to map
map.setCenter(point, 10); // Center and zoom map on marker
}
});
```
So I would just create an array of GLatLng's of every city from the GeoCoder and then draw them on the map. |
15,254 | <p>Is it possible to actually make use of placement new in portable code when using it for arrays?</p>
<p>It appears that the pointer you get back from new[] is not always the same as the address you pass in (5.3.4, note 12 in the standard seems to confirm that this is correct), but I don't see how you can allocate a buffer for the array to go in if this is the case.</p>
<p>The following example shows the problem. Compiled with Visual Studio, this example results in memory corruption:</p>
<pre><code>#include <new>
#include <stdio.h>
class A
{
public:
A() : data(0) {}
virtual ~A() {}
int data;
};
int main()
{
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
A *pA = new(pBuffer) A[NUMELEMENTS];
// With VC++, pA will be four bytes higher than pBuffer
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// Debug runtime will assert here due to heap corruption
delete[] pBuffer;
return 0;
}
</code></pre>
<p>Looking at the memory, the compiler seems to be using the first four bytes of the buffer to store a count of the number of items in it. This means that because the buffer is only <code>sizeof(A)*NUMELEMENTS</code> big, the last element in the array is written into unallocated heap.</p>
<p>So the question is can you find out how much additional overhead your implementation wants in order to use placement new[] safely? Ideally, I need a technique that's portable between different compilers. Note that, at least in VC's case, the overhead seems to differ for different classes. For instance, if I remove the virtual destructor in the example, the address returned from new[] is the same as the address I pass in.</p>
| [
{
"answer_id": 15273,
"author": "Yossi Kreinin",
"author_id": 1648,
"author_profile": "https://Stackoverflow.com/users/1648",
"pm_score": 1,
"selected": false,
"text": "<p>I think gcc does the same thing as MSVC, but of course this doesn't make it \"portable\".</p>\n\n<p>I think you can work around the problem when NUMELEMENTS is indeed a compile time constant, like so:</p>\n\n<p><code>\ntypedef A Arr[NUMELEMENTS];</p>\n\n<p>A* p = new (buffer) Arr;\n</code></p>\n\n<p>This should use the scalar placement new.</p>\n"
},
{
"answer_id": 15343,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 6,
"selected": true,
"text": "<p>Personally I'd go with the option of not using placement new on the array and instead use placement new on each item in the array individually. For example:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n const int NUMELEMENTS=20;\n\n char *pBuffer = new char[NUMELEMENTS*sizeof(A)];\n A *pA = (A*)pBuffer;\n\n for(int i = 0; i < NUMELEMENTS; ++i)\n {\n pA[i] = new (pA + i) A();\n }\n\n printf(\"Buffer address: %x, Array address: %x\\n\", pBuffer, pA);\n\n // dont forget to destroy!\n for(int i = 0; i < NUMELEMENTS; ++i)\n {\n pA[i].~A();\n } \n\n delete[] pBuffer;\n\n return 0;\n}\n</code></pre>\n\n<p>Regardless of the method you use, make sure you manually destroy each of those items in the array before you delete pBuffer, as you could end up with leaks ;)</p>\n\n<p><em>Note</em>: I haven't compiled this, but I think it should work (I'm on a machine that doesn't have a C++ compiler installed). It still indicates the point :) Hope it helps in some way!</p>\n\n<hr>\n\n<p>Edit:</p>\n\n<p>The reason it needs to keep track of the number of elements is so that it can iterate through them when you call delete on the array and make sure the destructors are called on each of the objects. If it doesn't know how many there are it wouldn't be able to do this.</p>\n"
},
{
"answer_id": 15372,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 2,
"selected": false,
"text": "<p>Similar to how you would use a single element to calculate the size for one placement-new, use an array of those elements to calculate the size required for an array.</p>\n\n<p>If you require the size for other calculations where the number of elements may not be known you can use sizeof(A[1]) and multiply by your required element count.</p>\n\n<p>e.g</p>\n\n<pre><code>char *pBuffer = new char[ sizeof(A[NUMELEMENTS]) ];\nA *pA = (A*)pBuffer;\n\nfor(int i = 0; i < NUMELEMENTS; ++i)\n{\n pA[i] = new (pA + i) A();\n}\n</code></pre>\n"
},
{
"answer_id": 15403,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks for the replies. Using placement new for each item in the array was the solution I ended up using when I ran into this (sorry, should have mentioned that in the question). I just felt that there must have been something I was missing about doing it with placement new[]. As it is, it seems like placement new[] is essentially unusable thanks to the standard allowing the compiler to add an additional unspecified overhead to the array. I don't see how you could ever use it safely and portably.</p>\n\n<p>I'm not even really clear why it needs the additional data, as you wouldn't call delete[] on the array anyway, so I don't entirely see why it needs to know how many items are in it.</p>\n"
},
{
"answer_id": 15547,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>@James</p>\n\n<blockquote>\n <p>I'm not even really clear why it needs the additional data, as you wouldn't call delete[] on the array anyway, so I don't entirely see why it needs to know how many items are in it.</p>\n</blockquote>\n\n<p>After giving this some thought, I agree with you. There is no reason why placement new should need to store the number of elements, because there is no placement delete. Since there's no placement delete, there's no reason for placement new to store the number of elements.</p>\n\n<p>I also tested this with gcc on my Mac, using a class with a destructor. On my system, placement new was <em>not</em> changing the pointer. This makes me wonder if this is a VC++ issue, and whether this might violate the standard (the standard doesn't specifically address this, so far as I can find).</p>\n"
},
{
"answer_id": 15948,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 3,
"selected": false,
"text": "<p>@Derek</p>\n\n<p>5.3.4, section 12 talks about the array allocation overhead and, unless I'm misreading it, it seems to suggest to me that it is valid for the compiler to add it on placement new as well:</p>\n\n<blockquote>\n <p>This overhead may be applied in all array new-expressions, including those referencing the library function operator new[](std::size_t, void*) and other placement allocation functions. The amount of overhead may vary from one invocation of new to another.</p>\n</blockquote>\n\n<p>That said, I think VC was the only compiler that gave me trouble with this, out of it, GCC, Codewarrior and ProDG. I'd have to check again to be sure, though.</p>\n"
},
{
"answer_id": 17011,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "<p>Placement new itself is portable, but the assumptions you make about what it does with a specified block of memory are not portable. Like what was said before, if you were a compiler and were given a chunk of memory, how would you know how to allocate an array and properly destruct each element if all you had was a pointer? (See the interface of operator delete[].)</p>\n\n<p>Edit:</p>\n\n<p>And there actually is a placement delete, only it is only called when a constructor throws an exception while allocating an array with placement new[].</p>\n\n<p>Whether new[] actually needs to keep track of the number of elements somehow is something that is left up to the standard, which leaves it up to the compiler. Unfortunately, in this case.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739/"
] | Is it possible to actually make use of placement new in portable code when using it for arrays?
It appears that the pointer you get back from new[] is not always the same as the address you pass in (5.3.4, note 12 in the standard seems to confirm that this is correct), but I don't see how you can allocate a buffer for the array to go in if this is the case.
The following example shows the problem. Compiled with Visual Studio, this example results in memory corruption:
```
#include <new>
#include <stdio.h>
class A
{
public:
A() : data(0) {}
virtual ~A() {}
int data;
};
int main()
{
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
A *pA = new(pBuffer) A[NUMELEMENTS];
// With VC++, pA will be four bytes higher than pBuffer
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// Debug runtime will assert here due to heap corruption
delete[] pBuffer;
return 0;
}
```
Looking at the memory, the compiler seems to be using the first four bytes of the buffer to store a count of the number of items in it. This means that because the buffer is only `sizeof(A)*NUMELEMENTS` big, the last element in the array is written into unallocated heap.
So the question is can you find out how much additional overhead your implementation wants in order to use placement new[] safely? Ideally, I need a technique that's portable between different compilers. Note that, at least in VC's case, the overhead seems to differ for different classes. For instance, if I remove the virtual destructor in the example, the address returned from new[] is the same as the address I pass in. | Personally I'd go with the option of not using placement new on the array and instead use placement new on each item in the array individually. For example:
```
int main(int argc, char* argv[])
{
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
A *pA = (A*)pBuffer;
for(int i = 0; i < NUMELEMENTS; ++i)
{
pA[i] = new (pA + i) A();
}
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// dont forget to destroy!
for(int i = 0; i < NUMELEMENTS; ++i)
{
pA[i].~A();
}
delete[] pBuffer;
return 0;
}
```
Regardless of the method you use, make sure you manually destroy each of those items in the array before you delete pBuffer, as you could end up with leaks ;)
*Note*: I haven't compiled this, but I think it should work (I'm on a machine that doesn't have a C++ compiler installed). It still indicates the point :) Hope it helps in some way!
---
Edit:
The reason it needs to keep track of the number of elements is so that it can iterate through them when you call delete on the array and make sure the destructors are called on each of the objects. If it doesn't know how many there are it wouldn't be able to do this. |
15,266 | <p>Using <strong>NSURLRequest</strong>, I am trying to access a web site that has an expired certificate. When I send the request, my <strong>connection:didFailWithError</strong> delegate method is invoked with the following info:</p>
<pre><code>-1203, NSURLErrorDomain, bad server certificate
</code></pre>
<p>My searches have only turned up one solution: a hidden class method in NSURLRequest:</p>
<pre><code>[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:myHost];
</code></pre>
<p>However, I don't want to use private APIs in a production app for obvious reasons.</p>
<p>Any suggestions on what to do? Do I need to use CFNetwork APIs, and if so, two questions:</p>
<ul>
<li>Any sample code I can use to get started? I haven't found any online.</li>
<li>If I use CFNetwork for this, do I have to ditch NSURL entirely?</li>
</ul>
<hr>
<p>EDIT:</p>
<p>iPhone OS 3.0 introduced a supported method for doing this. More details here: <a href="https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert">How to use NSURLConnection to connect with SSL for an untrusted cert?</a></p>
| [
{
"answer_id": 15963,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 1,
"selected": false,
"text": "<p>I've hit the same issue - I was developing a SOAP client, and the dev server has a \"homegrown\" certificate. I wasn't able to solve the issue even using that method, since I wasn't using NSURL, but the (poorly documented and apparently abandoned) WS methods, and decided for the time being to (internally) just use a non-SSL connection.</p>\n\n<p>Having said that, however, the question that springs to mind is, if you aren't willing to use a private API in a production app, should you be allowing access to a site with a dodgy certificate?</p>\n\n<p>I'll quote <a href=\"http://www.cocoabuilder.com/archive/message/cocoa/2008/3/4/200413\" rel=\"nofollow noreferrer\">Jens Alfke</a>:</p>\n\n<blockquote>\n <p>That's not just a theoretical security problem. Something<br>\n like 25% of public DNS servers have been compromised, according to<br>\n recent reports, and can direct users to phishing/malware/ad sites even<br>\n if they enter the domain name properly. The only thing protecting you<br>\n from that is SSL certificate checking.</p>\n</blockquote>\n"
},
{
"answer_id": 20480,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 1,
"selected": false,
"text": "<p>Can you create a self signed certificate and add your custom certificate authority to the trusted CAs? I'm not quite sure how this would work on the iPhone, but I'd assume on Mac OS X you would add these to the Keychain.</p>\n\n<p>You may also be interested in this post <a href=\"http://www.cocoabuilder.com/archive/message/cocoa/2008/5/22/207740\" rel=\"nofollow noreferrer\">Re: How to handle bad certificate error in NSURLDownload</a></p>\n"
},
{
"answer_id": 215532,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If it's for an internal server for testing purposes, why not just import the test server's certificate into the KeyChain and set custom trust settings?</p>\n"
},
{
"answer_id": 245903,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 3,
"selected": false,
"text": "<p>The supported way of doing this requires using CFNetwork. You have to do is attach a kCFStreamPropertySSLSettings to the stream that specifies kCFStreamSSLValidatesCertificateChain == kCFBooleanFalse. Below is some quick code that does it, minus checking for valid results add cleaning up. Once you have done this You can use CFReadStreamRead() to get the data.</p>\n\n<pre><code>CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, CFSTR(\"http://www.apple.com\"), NULL);\nCFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR(\"GET\"), myURL, kCFHTTPVersion1_1);\nCFReadStreamRef myStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest);\nCFMutableDictionaryRef myDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);\nCFDictionarySetValue(myDict, kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse);\nCFReadStreamSetProperty(myStream, kCFStreamPropertySSLSettings, myDict); \nCFReadStreamOpen(myStream);\n</code></pre>\n"
},
{
"answer_id": 309821,
"author": "chews",
"author_id": 33966,
"author_profile": "https://Stackoverflow.com/users/33966",
"pm_score": 0,
"selected": false,
"text": "<p>Another option would be to use an alternate connection library.</p>\n\n<p>I am a huge fan of AsyncSocket and it has support for self signed certs</p>\n\n<p><a href=\"http://code.google.com/p/cocoaasyncsocket/\" rel=\"nofollow noreferrer\">http://code.google.com/p/cocoaasyncsocket/</a></p>\n\n<p>Take a look, I think it is way more robust then the standard NSURLRequests.</p>\n"
},
{
"answer_id": 2195434,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 3,
"selected": true,
"text": "<p>iPhone OS 3.0 introduced a supported way of doing this that doesn't require the lower-level CFNetwork APIs. More details here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert\">How to use NSURLConnection to connect with SSL for an untrusted cert?</a></p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544/"
] | Using **NSURLRequest**, I am trying to access a web site that has an expired certificate. When I send the request, my **connection:didFailWithError** delegate method is invoked with the following info:
```
-1203, NSURLErrorDomain, bad server certificate
```
My searches have only turned up one solution: a hidden class method in NSURLRequest:
```
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:myHost];
```
However, I don't want to use private APIs in a production app for obvious reasons.
Any suggestions on what to do? Do I need to use CFNetwork APIs, and if so, two questions:
* Any sample code I can use to get started? I haven't found any online.
* If I use CFNetwork for this, do I have to ditch NSURL entirely?
---
EDIT:
iPhone OS 3.0 introduced a supported method for doing this. More details here: [How to use NSURLConnection to connect with SSL for an untrusted cert?](https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert) | iPhone OS 3.0 introduced a supported way of doing this that doesn't require the lower-level CFNetwork APIs. More details here:
[How to use NSURLConnection to connect with SSL for an untrusted cert?](https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert) |
15,272 | <p>I want a data structure that will allow querying <em>how many items in last <strong>X</strong> minutes</em>. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple items having same timestamp).</p>
<p>So far it seems that with LINQ I could easily filter items with timestamp greater than a given time and aggregate a count. Though I'm hesitant to try to work .NET 3.5 specific stuff into my production environment yet. Are there any other suggestions for a similar data structure?</p>
<p>The other part that I'm interested in is <em>aging</em> old data out, If I'm only going to be asking for counts of items less than 6 hours ago I would like anything older than that to be removed from my data structure because this may be a long-running program.</p>
| [
{
"answer_id": 15316,
"author": "dmo",
"author_id": 1807,
"author_profile": "https://Stackoverflow.com/users/1807",
"pm_score": 2,
"selected": false,
"text": "<p>I think that an important consideration will be the frequency of querying vs. adding/removing. If you will do frequent querying (especially if you'll have a large collection) a B-tree may be the way to go:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/B-tree\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/B-tree</a></p>\n\n<p>You could have some thread go through and clean up this tree periodically or make it part of the search (again, depending on the usage). Basically, you'll do a tree search to find the spot \"x minutes ago\", then count the number of children on the nodes with newer times. If you keep the number of children under the nodes up to date, this sum can be done quickly.</p>\n"
},
{
"answer_id": 15904,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": true,
"text": "<p>A simple linked list can be used for this.</p>\n\n<p>Basically you add new items to the end, and remove too old items from the start, it is a cheap data structure.</p>\n\n<p>example-code:</p>\n\n<pre><code>list.push_end(new_data)\nwhile list.head.age >= age_limit:\n list.pop_head()\n</code></pre>\n\n<p>If the list will be busy enough to warrant chopping off larger pieces than one at a time, then I agree with <a href=\"https://stackoverflow.com/users/1807/dmo\">dmo</a>, use a tree structure or something similar that allows pruning on a higher level.</p>\n"
},
{
"answer_id": 2699852,
"author": "ehosca",
"author_id": 199771,
"author_profile": "https://Stackoverflow.com/users/199771",
"pm_score": 2,
"selected": false,
"text": "<p>a cache with sliding expiration will do the job ....</p>\n\n<p>stuff your items in and the cache handles the aging ....</p>\n\n<p><a href=\"http://www.sharedcache.com/cms/\" rel=\"nofollow noreferrer\">http://www.sharedcache.com/cms/</a></p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] | I want a data structure that will allow querying *how many items in last **X** minutes*. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple items having same timestamp).
So far it seems that with LINQ I could easily filter items with timestamp greater than a given time and aggregate a count. Though I'm hesitant to try to work .NET 3.5 specific stuff into my production environment yet. Are there any other suggestions for a similar data structure?
The other part that I'm interested in is *aging* old data out, If I'm only going to be asking for counts of items less than 6 hours ago I would like anything older than that to be removed from my data structure because this may be a long-running program. | A simple linked list can be used for this.
Basically you add new items to the end, and remove too old items from the start, it is a cheap data structure.
example-code:
```
list.push_end(new_data)
while list.head.age >= age_limit:
list.pop_head()
```
If the list will be busy enough to warrant chopping off larger pieces than one at a time, then I agree with [dmo](https://stackoverflow.com/users/1807/dmo), use a tree structure or something similar that allows pruning on a higher level. |
15,310 | <p>First off I understand that it is a horrible idea to run extremely large/long running reports. I am aware that Microsoft has a rule of thumb stating that a SSRS report should take no longer than 30 seconds to execute. However sometimes gargantuan reports are a preferred evil due to external forces such complying with state laws.</p>
<p>At my place of employment, we have an asp.net (2.0) app that we have migrated from Crystal Reports to SSRS. Due to the large user base and complex reporting UI requirements we have a set of screens that accepts user inputted parameters and creates schedules to be run over night. Since the application supports multiple reporting frameworks we do not use the scheduling/snapshot facilities of SSRS. All of the reports in the system are generated by a scheduled console app which takes user entered parameters and generates the reports with the corresponding reporting solutions the reports were created with. In the case of SSRS reports, the console app generates the SSRS reports and exports them as PDFs via the SSRS web service API. </p>
<p>So far SSRS has been much easier to deal with than Crystal with the exception of a certain 25,000 page report that we have recently converted from crystal reports to SSRS. The SSRS server is a 64bit 2003 server with 32 gigs of ram running SSRS 2005. All of our smaller reports work fantastically, but we are having trouble with our larger reports such as this one. Unfortunately, we can't seem to generate the aforemention report through the web service API. The following error occurs roughly 30-35 minutes into the generation/export:</p>
<p>Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.</p>
<p>The web service call is something I'm sure you all have seen before: </p>
<pre><code>data = rs.Render(this.ReportPath, this.ExportFormat, null, deviceInfo,
selectedParameters, null, null, out encoding, out mimeType, out usedParameters,
out warnings, out streamIds);
</code></pre>
<p>The odd thing is that this report will run/render/export if the report is run directly on the reporting server using the report manager. The proc that produces the data for the report runs for about 5 minutes. The report renders in SSRS native format in the browser/viewer after about 12 minutes. Exporting to pdf through the browser/viewer in the report manager takes an additional 55 minutes. This works reliably and it produces a whopping 1.03gb pdf.</p>
<p>Here are some of the more obvious things I've tried to get the report working via the web service API: </p>
<ul>
<li>set the HttpRuntime ExecutionTimeout
value to 3 hours on the report
server</li>
<li>disabled http keep alives on the report server</li>
<li>increased the script timeout on the report server</li>
<li>set the report to never time out on the server</li>
<li>set the report timeout to several hours on the client call </li>
</ul>
<p>From the tweaks I have tried, I am fairly comfortable saying that any timeout issues have been eliminated. </p>
<p>Based off of my research of the error message, I believe that the web service API does not send chunked responses by default. This means that it tries to send all 1.3gb over the wire in one response. At a certain point, IIS throws in the towel. Unfortunately the API abstracts away web service configuration so I can't seem to find a way to enable response chunking. </p>
<ol>
<li>Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?</li>
<li>Is there a way to turn on response chunking for SSRS?</li>
<li>Does anyone else have any other theories as to why this runs on the server but not through the API?</li>
</ol>
<p>EDIT: After reading kcrumley's post I began to take a look at the average page size by taking file size / page count. Interestingly enough on smaller reports the math works out so that each page is roughly 5K. Interestingly, when the report gets larger this "average" increases. An 8000 page report for example is averaging over 40K/page. Very odd. I will also add that the number of records per page is set except for the last page in each grouping, so it's not a case where some pages have more records than another. </p>
| [
{
"answer_id": 16729,
"author": "Kevin Crumley",
"author_id": 1818,
"author_profile": "https://Stackoverflow.com/users/1818",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <ol>\n <li>Does anyone know of anyway to\n reduce/optimize the PDF export phase\n and or the size of the PDF without\n lowering the total page count?</li>\n </ol>\n</blockquote>\n\n<p>I have a few ideas and questions:<br>\n1. Is this a graphics-heavy report? If not, do you have tables that start out as text but are converted into a graphic by the SSRS PDF renderer (check if you can select the text in the PDF)? 41K per page might be more than it should be, or it might not, depending on how information-dense your report is. But we've had cases where we had minor issues with a report's layout, like having a table bleed into the page's margins, that resulted in the SSRS PDF renderer \"throwing up its hands\" and rendering the table as an image instead of as text. Obviously, the fewer graphics in your report, the smaller your file size will be.<br>\n2. Is there a way that you could easily break the report into pieces? E.g., if it's a 10-location report, where Location 1 is followed by Location 2, etc., on your final report, could you run the Location 1 portion independent of the Location 2 portion, etc.? If so, you could join the 10 sub-reports into one final PDF using <a href=\"http://pdfsharp.com/\" rel=\"nofollow noreferrer\">PDFSharp</a> after you've received them all. This leads to some difficulties with page numbering, but nothing insurmountable.</p>\n\n<blockquote>\n <p>3. Does anyone else have any other\n theories as to why this runs on the\n server but not through the API?</p>\n</blockquote>\n\n<p>My guess would be the sheer size of the report. I don't remember everything about what's an IIS setting and what's SSRS-specific, but there might be some overall IIS settings (maybe in Metabase.xml) that you would have to be updated to even allow that much data to pass through. </p>\n\n<p>You could isolate the question of whether the time is the problem by taking one of your working reports and building in a long wait time in your stored procedures with WAITFOR (assuming SQL Server for your DBMS).</p>\n\n<p>Not solutions, per se, but ideas. Hope it helps.</p>\n"
},
{
"answer_id": 1104489,
"author": "Robert4Real",
"author_id": 68532,
"author_profile": "https://Stackoverflow.com/users/68532",
"pm_score": 2,
"selected": false,
"text": "<p>Obviously, its a huge report, in fact it's closer to a 1.3 GB database, than a report.</p>\n\n<p>Have you thought of finding a way to split it into multiple pieces and then combine them together? (use one of several different ways to combine PDFs listed on this site.)</p>\n"
},
{
"answer_id": 10481764,
"author": "StuartLC",
"author_id": 314291,
"author_profile": "https://Stackoverflow.com/users/314291",
"pm_score": 2,
"selected": false,
"text": "<p>We narrowed down the large PDF exports from SSRS and found 2 main culprits</p>\n\n<p>1) Unless images are JPG or PNG colour type 3, they are expanded to BMP's See <a href=\"http://social.msdn.microsoft.com/Forums/da-DK/sqlreportingservices/thread/9434eb2b-562a-488b-9f07-fff7cf6c39fc\" rel=\"nofollow\">here</a></p>\n\n<p>2) Unless you configure SSRS to behave otherwise (not recommended), then SSRS will embed fonts or font subsets into the PDF, unless they are one of the <a href=\"http://www.aivosto.com/vbtips/pdf-optimize.html\" rel=\"nofollow\">5 'standard' PDF fonts</a>.</p>\n\n<p>Although none of the standard fonts (other than Symbol I guess) are installed on most Windows OS's out of the box, we've found that if you use <code>Times New Roman, Courier New, or Arial</code> then forward and reverse font substitution will take place.</p>\n\n<p>The easiest way to convert your RDL's is to view them as XML and search and replace the <code>FontFamily</code> tags.</p>\n\n<p>If you have to use a non standard font, then, you can still minimize the damage:</p>\n\n<ul>\n<li>Use as few fonts as you can. Search through the RDL XML to make sure there aren't any redundant fonts.</li>\n<li>Use TTF fonts if you use different sizes of the font.</li>\n<li>Try not to mix normal, bold and italic variants of the font, else it will be embedded multiple times.</li>\n</ul>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644/"
] | First off I understand that it is a horrible idea to run extremely large/long running reports. I am aware that Microsoft has a rule of thumb stating that a SSRS report should take no longer than 30 seconds to execute. However sometimes gargantuan reports are a preferred evil due to external forces such complying with state laws.
At my place of employment, we have an asp.net (2.0) app that we have migrated from Crystal Reports to SSRS. Due to the large user base and complex reporting UI requirements we have a set of screens that accepts user inputted parameters and creates schedules to be run over night. Since the application supports multiple reporting frameworks we do not use the scheduling/snapshot facilities of SSRS. All of the reports in the system are generated by a scheduled console app which takes user entered parameters and generates the reports with the corresponding reporting solutions the reports were created with. In the case of SSRS reports, the console app generates the SSRS reports and exports them as PDFs via the SSRS web service API.
So far SSRS has been much easier to deal with than Crystal with the exception of a certain 25,000 page report that we have recently converted from crystal reports to SSRS. The SSRS server is a 64bit 2003 server with 32 gigs of ram running SSRS 2005. All of our smaller reports work fantastically, but we are having trouble with our larger reports such as this one. Unfortunately, we can't seem to generate the aforemention report through the web service API. The following error occurs roughly 30-35 minutes into the generation/export:
Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.
The web service call is something I'm sure you all have seen before:
```
data = rs.Render(this.ReportPath, this.ExportFormat, null, deviceInfo,
selectedParameters, null, null, out encoding, out mimeType, out usedParameters,
out warnings, out streamIds);
```
The odd thing is that this report will run/render/export if the report is run directly on the reporting server using the report manager. The proc that produces the data for the report runs for about 5 minutes. The report renders in SSRS native format in the browser/viewer after about 12 minutes. Exporting to pdf through the browser/viewer in the report manager takes an additional 55 minutes. This works reliably and it produces a whopping 1.03gb pdf.
Here are some of the more obvious things I've tried to get the report working via the web service API:
* set the HttpRuntime ExecutionTimeout
value to 3 hours on the report
server
* disabled http keep alives on the report server
* increased the script timeout on the report server
* set the report to never time out on the server
* set the report timeout to several hours on the client call
From the tweaks I have tried, I am fairly comfortable saying that any timeout issues have been eliminated.
Based off of my research of the error message, I believe that the web service API does not send chunked responses by default. This means that it tries to send all 1.3gb over the wire in one response. At a certain point, IIS throws in the towel. Unfortunately the API abstracts away web service configuration so I can't seem to find a way to enable response chunking.
1. Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?
2. Is there a way to turn on response chunking for SSRS?
3. Does anyone else have any other theories as to why this runs on the server but not through the API?
EDIT: After reading kcrumley's post I began to take a look at the average page size by taking file size / page count. Interestingly enough on smaller reports the math works out so that each page is roughly 5K. Interestingly, when the report gets larger this "average" increases. An 8000 page report for example is averaging over 40K/page. Very odd. I will also add that the number of records per page is set except for the last page in each grouping, so it's not a case where some pages have more records than another. | >
> 1. Does anyone know of anyway to
> reduce/optimize the PDF export phase
> and or the size of the PDF without
> lowering the total page count?
>
>
>
I have a few ideas and questions:
1. Is this a graphics-heavy report? If not, do you have tables that start out as text but are converted into a graphic by the SSRS PDF renderer (check if you can select the text in the PDF)? 41K per page might be more than it should be, or it might not, depending on how information-dense your report is. But we've had cases where we had minor issues with a report's layout, like having a table bleed into the page's margins, that resulted in the SSRS PDF renderer "throwing up its hands" and rendering the table as an image instead of as text. Obviously, the fewer graphics in your report, the smaller your file size will be.
2. Is there a way that you could easily break the report into pieces? E.g., if it's a 10-location report, where Location 1 is followed by Location 2, etc., on your final report, could you run the Location 1 portion independent of the Location 2 portion, etc.? If so, you could join the 10 sub-reports into one final PDF using [PDFSharp](http://pdfsharp.com/) after you've received them all. This leads to some difficulties with page numbering, but nothing insurmountable.
>
> 3. Does anyone else have any other
> theories as to why this runs on the
> server but not through the API?
>
>
>
My guess would be the sheer size of the report. I don't remember everything about what's an IIS setting and what's SSRS-specific, but there might be some overall IIS settings (maybe in Metabase.xml) that you would have to be updated to even allow that much data to pass through.
You could isolate the question of whether the time is the problem by taking one of your working reports and building in a long wait time in your stored procedures with WAITFOR (assuming SQL Server for your DBMS).
Not solutions, per se, but ideas. Hope it helps. |
15,334 | <p>I have recently started using Vim as my text editor and am currently working on my own customizations.</p>
<p>I suppose keyboard mappings can do pretty much anything, but for the time being I'm using them as a sort of snippets facility almost exclusively.</p>
<p>So, for example, if I type <code>def{TAB}</code> (<code>:imap def{TAB} def ():<ESC>3ha</code>), it expands to:</p>
<pre><code>def |(): # '|' represents the caret
</code></pre>
<p>This works as expected, but I find it annoying when Vim waits for a full command while I'm typing a word containing "def" and am not interested in expanding it.</p>
<ul>
<li>Is there a way to avoid this or use this function more effectively to this end?</li>
<li>Is any other Vim feature better suited for this?</li>
</ul>
<hr>
<p>After taking a quick look at <a href="http://www.vim.org/scripts/script.php?script_id=1318" rel="noreferrer">SnippetsEmu</a>, it looks like it's the best option and much easier to customize than I first thought.</p>
<p>To continue with the previous example:</p>
<pre><code>:Snippet def <{}>():
</code></pre>
<p>Once defined, you can expand your snippet by typing <code>def{TAB}</code>.</p>
| [
{
"answer_id": 15886,
"author": "MDCore",
"author_id": 1896,
"author_profile": "https://Stackoverflow.com/users/1896",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://www.vim.org/scripts/script.php?script_id=1318\" rel=\"nofollow noreferrer\">SnippetsEmu</a> is a useful snippets plugin. </p>\n"
},
{
"answer_id": 32324,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 2,
"selected": false,
"text": "<p>As noted by MDCore, <a href=\"http://www.vim.org/scripts/script.php?script_id=1318\" rel=\"nofollow noreferrer\">SnippetsEmu</a> is a popular Vim script that does just that and more. If you need only expanding (without moving back the caret), you can use the standard <code>:ab[breviate]</code> command.</p>\n\n<pre><code>:ab[breviate] [<expr>] {lhs} {rhs}\n add abbreviation for {lhs} to {rhs}. If {lhs} already\n existed it is replaced with the new {rhs}. {rhs} may\n contain spaces.\n See |:map-<expr>| for the optional <expr> argument.\n</code></pre>\n"
},
{
"answer_id": 255647,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 3,
"selected": false,
"text": "<p>If SnippetsEmu is too heavy or ambitious for what you need (it was for me), I wrote a plugin that manages snippets based on filetype. It even has tab completion when picking the snippet! :)</p>\n\n<p>Get it here: <a href=\"http://www.vim.org/scripts/script.php?script_id=2152\" rel=\"noreferrer\">snippets.vim</a></p>\n"
},
{
"answer_id": 879590,
"author": "SergioAraujo",
"author_id": 2571881,
"author_profile": "https://Stackoverflow.com/users/2571881",
"pm_score": 5,
"selected": false,
"text": "<p>Snipmate - like texmate :)\n<a href=\"http://www.vim.org/scripts/script.php?script_id=2540\" rel=\"noreferrer\">http://www.vim.org/scripts/script.php?script_id=2540</a></p>\n\n<p>video:\n<a href=\"http://vimeo.com/3535418\" rel=\"noreferrer\">http://vimeo.com/3535418</a></p>\n\n<pre><code>snippet def \n \"\"\" ${1:docstring} \"\"\"\n def ${2:name}:\n return ${3:value}\n</code></pre>\n"
},
{
"answer_id": 9919910,
"author": "alwillis",
"author_id": 395537,
"author_profile": "https://Stackoverflow.com/users/395537",
"pm_score": 3,
"selected": false,
"text": "<p>I just installed <a href=\"https://github.com/vim-scripts/UltiSnips#readme\" rel=\"noreferrer\">UltiSnips</a>. There’s a good article that explains why you might choose UltiSnips: <a href=\"http://fueledbylemons.com/blog/2011/07/27/why-ultisnips/\" rel=\"noreferrer\">Why UltiSnips?</a></p>\n\n<p>I haven’t used any of the other snippet plugins; I decided to take the plunge with one that seemed full-featured and would be able to accommodate me as I gain more Vim skills and want to do more sophisticated things.</p>\n"
},
{
"answer_id": 13133097,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>As another suggestion (although slightly different) using vim's built in functionality:</p>\n\n<pre><code>:iabbrev def def(): #<LEFT><LEFT><LEFT><LEFT><LEFT>\n</code></pre>\n\n<p>Now whenever you type def followed by a space or other non-word character, it will expand to the same as what you've given as the output of SnippetsEmu (the space comes from the space you entered to trigger the completion). </p>\n\n<p>This approach doesn't suffer the \"lag\" issue you encountered using :inoremap, and is built-into vim. For more information on this feature, look at <code>:help abbrev</code>.</p>\n\n<p>You may be concerned that being triggered by space not tab it will trigger unnecessarily, but in general vim is pretty smart about when to trigger it. The issue can be additionally mitigated by enabling the abbreviation only for certain file-types (eg, python):</p>\n\n<pre><code>au filetype python :iabbrev ... etc\n</code></pre>\n\n<p>Snip[ets] (Manager|Emu|Mate|.vim) is of course also a perfect solution, but it's nice to be aware of the alternatives (especially when they are built in). </p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670/"
] | I have recently started using Vim as my text editor and am currently working on my own customizations.
I suppose keyboard mappings can do pretty much anything, but for the time being I'm using them as a sort of snippets facility almost exclusively.
So, for example, if I type `def{TAB}` (`:imap def{TAB} def ():<ESC>3ha`), it expands to:
```
def |(): # '|' represents the caret
```
This works as expected, but I find it annoying when Vim waits for a full command while I'm typing a word containing "def" and am not interested in expanding it.
* Is there a way to avoid this or use this function more effectively to this end?
* Is any other Vim feature better suited for this?
---
After taking a quick look at [SnippetsEmu](http://www.vim.org/scripts/script.php?script_id=1318), it looks like it's the best option and much easier to customize than I first thought.
To continue with the previous example:
```
:Snippet def <{}>():
```
Once defined, you can expand your snippet by typing `def{TAB}`. | [SnippetsEmu](http://www.vim.org/scripts/script.php?script_id=1318) is a useful snippets plugin. |
15,390 | <p>What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.</p>
<p>Our JavaScript code is roughly "namespaced" as:</p>
<pre><code>var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
</code></pre>
<p>At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes <em>forever</em> to find anything in the JavaScript code and the browser still has a dozen files to download.</p>
<p>Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?</p>
| [
{
"answer_id": 15402,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 5,
"selected": true,
"text": "<p>The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.</p>\n\n<p>If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a <code><script src='/path/to/js/$file.js' type='text/javascript'></code> in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files.</p>\n\n<p>When deploying to production, you should have a script that combines them all into one JS file and \"minifies\" it to keep the size down.</p>\n"
},
{
"answer_id": 15411,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 2,
"selected": false,
"text": "<p>For server efficiency's sake, it is best to combine all of your javascript into one minified file.</p>\n\n<p>Determine the order in which code is required and then place the minified code in the order it is required in a single file.</p>\n\n<p>The key is to reduce the number of requests required to load your page, which is why you should have all javascript in a single file for production.</p>\n\n<p>I'd recommend keeping files split up for development and then create a build script to combine/compile everything.</p>\n\n<p>Also, as a good rule of thumb, make sure you include your JavaScript toward the end of your page. If JavaScript is included in the header (or anywhere early in the page), it will stop all other requests from being made until it is loaded, even if pipelining is turned on. If it is at the end of the page, you won't have this problem.</p>\n"
},
{
"answer_id": 15440,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 2,
"selected": false,
"text": "<p>Just a sidenode - Steve already pointed out, you should really \"minify\" your JS files. In JS, whitespaces actually matter. If you have thousand lines of JS and you strip only the unrequired newlines you have already saved about 1K. I think you get the point.</p>\n\n<p>There are tools, for this job. And you should never modify the \"minified\"/stripped/obfuscated JS by hand! Never!</p>\n"
},
{
"answer_id": 16968,
"author": "Kieron",
"author_id": 588,
"author_profile": "https://Stackoverflow.com/users/588",
"pm_score": 2,
"selected": false,
"text": "<p>In our big javascript applications, we write all our code in small separate files - one file per 'class' or functional group, using a kind-of-like-Java namespacing/directory structure. We then have:</p>\n\n<ul>\n<li>A compile-time step that takes all our code and minifies it (using a variant of JSMin) to reduce download size</li>\n<li>A compile-time step that takes the classes that are always or almost always needed and concatenates them into a large bundle to reduce round trips to the server</li>\n<li>A 'classloader' that loads the remaining classes at runtime on demand.</li>\n</ul>\n"
},
{
"answer_id": 25322,
"author": "gregh",
"author_id": 2687,
"author_profile": "https://Stackoverflow.com/users/2687",
"pm_score": 1,
"selected": false,
"text": "<p>Read the code of other (good) javascript apps and see how they handle things. But I start out with a file per class. But once its ready for production, I would combine the files into one large file and minify.</p>\n\n<p>The only reason, I would not combine the files, is if I didn't need all the files on all the pages.</p>\n"
},
{
"answer_id": 39011,
"author": "paulgreg",
"author_id": 3122,
"author_profile": "https://Stackoverflow.com/users/3122",
"pm_score": 3,
"selected": false,
"text": "<p>Also, I suggest you to use Google's <a href=\"http://code.google.com/apis/ajaxlibs/documentation/\" rel=\"noreferrer\">AJAX Libraries API</a> in order to load external libraries. </p>\n\n<p>It's a Google developer tool which bundle majors JavaScript libraries and make it easier to deploy, upgrade and make them lighter by always using compressed versions.</p>\n\n<p>Also, it make your project simpler and lighter because you don't need to download, copy and maintain theses libraries files in your project.</p>\n\n<p>Use it this way :</p>\n\n<pre><code>google.load(\"jquery\", \"1.2.3\");\ngoogle.load(\"jqueryui\", \"1.5.2\");\ngoogle.load(\"prototype\", \"1.6\");\ngoogle.load(\"scriptaculous\", \"1.8.1\");\ngoogle.load(\"mootools\", \"1.11\");\ngoogle.load(\"dojo\", \"1.1.1\");\n</code></pre>\n"
},
{
"answer_id": 17899149,
"author": "martyglaubitz",
"author_id": 657341,
"author_profile": "https://Stackoverflow.com/users/657341",
"pm_score": 1,
"selected": false,
"text": "<p>My strategy consist of 2 major techniques: AMD modules (to avoid dozens of script tags) and the Module pattern (to avoid tightly coupling of the parts of your application)</p>\n\n<p>AMD Modules: very straight forward, see here: <a href=\"http://requirejs.org/docs/api.html\" rel=\"nofollow\">http://requirejs.org/docs/api.html</a> also it's able to package all the parts of your app into one minified JS file: <a href=\"http://requirejs.org/docs/optimization.html\" rel=\"nofollow\">http://requirejs.org/docs/optimization.html</a></p>\n\n<p>Module Pattern: i used this Library: <a href=\"https://github.com/flosse/scaleApp\" rel=\"nofollow\">https://github.com/flosse/scaleApp</a> you asking now what is this ? more infos here: <a href=\"http://www.youtube.com/watch?v=7BGvy-S-Iag\" rel=\"nofollow\">http://www.youtube.com/watch?v=7BGvy-S-Iag</a></p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1848/"
] | What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.
Our JavaScript code is roughly "namespaced" as:
```
var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
```
At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes *forever* to find anything in the JavaScript code and the browser still has a dozen files to download.
Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices? | The approach that I've found works for me is having seperate JS files for each class (just as you would in Java, C# and others). Alternatively you can group your JS into application functional areas if that's easier for you to navigate.
If you put all your JS files into one directory, you can have your server-side environment (PHP for instance) loop through each file in that directory and output a `<script src='/path/to/js/$file.js' type='text/javascript'>` in some header file that is included by all your UI pages. You'll find this auto-loading especially handy if you're regularly creating and removing JS files.
When deploying to production, you should have a script that combines them all into one JS file and "minifies" it to keep the size down. |
15,395 | <p>Linq To SQL or Entity framework both integrate nicely with SQL Server 2005.</p>
<p>The SQL Server 2008 spec sheet promises even better integration - but I can't see it.</p>
<p>What are some examples of what you can do Linq-wise when talking to a 2008 server that you can't when talking to SQL Server 2005?</p>
| [
{
"answer_id": 15431,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>it has full support for the new data types. lol. beyond that you got me, other than possibilities of optimised queries (like the merge command, etc).</p>\n"
},
{
"answer_id": 15441,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>I am guessing most of it has to do on the server anyways. They probably optimized the query execution as for differences I don't know except for the new types.</p>\n"
},
{
"answer_id": 153273,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>There is a problem of paging over a joined set that SQL 2005 mis-interprets.</p>\n\n<pre><code>var orders = (\nfrom c in Customers\nfrom o in c.Orders\nselect new {c, o}\n).Skip(10).Take(10).ToList();\n</code></pre>\n\n<p>LINQ generates a ROW_Number against the joined set. SQL2005 generates a bad plan from that code. Here's a link to the <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3091519&SiteID=1\" rel=\"nofollow noreferrer\">discussion</a>.</p>\n\n<p>Edit#2: I'd like to clarify that I don't know that SQL2008 solves this problem. I'm just hopeful.</p>\n"
},
{
"answer_id": 153408,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<p>This <a href=\"http://www.microsoft.com/sqlserver/2008/en/us/linq.aspx\" rel=\"nofollow noreferrer\">marketing link</a> claims</p>\n\n<p>\"Write data access code directly against a Microsoft SQL Server database, using LINQ to SQL.\"</p>\n\n<p>Which is basically untrue.</p>\n\n<p>Linq To SQL is query comprehension translated into expression trees translated into SQL, optimized by the query optimizer and then run against SQL Server database. \"directly\" feh.</p>\n"
},
{
"answer_id": 3653486,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 0,
"selected": false,
"text": "<p>Unless LINQ exposes the new MERGE statement, no.</p>\n\n<p>There is little effective difference in the engines especially from an ORM/client view</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855/"
] | Linq To SQL or Entity framework both integrate nicely with SQL Server 2005.
The SQL Server 2008 spec sheet promises even better integration - but I can't see it.
What are some examples of what you can do Linq-wise when talking to a 2008 server that you can't when talking to SQL Server 2005? | There is a problem of paging over a joined set that SQL 2005 mis-interprets.
```
var orders = (
from c in Customers
from o in c.Orders
select new {c, o}
).Skip(10).Take(10).ToList();
```
LINQ generates a ROW\_Number against the joined set. SQL2005 generates a bad plan from that code. Here's a link to the [discussion](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3091519&SiteID=1).
Edit#2: I'd like to clarify that I don't know that SQL2008 solves this problem. I'm just hopeful. |
15,399 | <p>My firm have a talented and smart operations staff who are working very hard. I'd like to give them a SQL-execution tool that helps them avoid common, easily-detected SQL mistakes that are easy to make when they are in a hurry. Can anyone suggest such a tool? Details follow.</p>
<p>Part of the operations team remit is writing very complex ad-hoc SQL queries. Not surprisingly, operators sometimes make mistakes in the queries they write because they are so busy. </p>
<p>Luckily, their queries are all SELECTs not data-changing SQL, and they are running on a copy of the database anyway. Still, we'd like to prevent errors in the SQL they run. For instance, sometimes the mistakes lead to long-running queries that slow down the duplicate system they're using and inconvenience others until we find the culprit query and kill it. Worse, occasionally the mistakes lead to apparently-correct answers that we don't catch until much later, with consequent embarrassment. </p>
<p>Our developers also make mistakes in complex code that they write, but they have Eclipse and various plugins (such as <a href="http://findbugs.sourceforge.net/" rel="nofollow noreferrer" title="FindBugs">FindBugs</a>) that catch errors as they type. I'd like to give operators something similar - ideally it would see</p>
<pre><code>SELECT U.NAME, C.NAME FROM USER U, COMPANY C WHERE U.NAME = 'ibell';
</code></pre>
<p>and before you executed, it would say "Hey, did you realise that's a Cartesian product? Are you sure you want to do that?" It doesn't have to be very smart - finding obviously missing join conditions and similar evident errors would be fine.</p>
<p>It looks like <a href="http://www.toadsoft.com/" rel="nofollow noreferrer" title="TOAD">TOAD</a> should do this but I can't seem to find anything about such a feature. Are there other tools like TOAD that can provide this kind of semi-intelligent error correction?</p>
<p>Update: I forgot to mention that we're using MySQL.</p>
| [
{
"answer_id": 15405,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 0,
"selected": false,
"text": "<p>You might find <a href=\"http://www.red-gate.com/Products/SQL_Prompt/index.htm\" rel=\"nofollow noreferrer\">SQL Prompt</a> from redgate useful. I'm not sure what database engine you're using, as it's only for MSSQL Server</p>\n"
},
{
"answer_id": 15587,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not expecting anything like this to exist. The tool would have to first implement everything that the SQL parser in your database implements, and then it would have to do a data model analysis to predict \"bad\" queries.</p>\n\n<p>Your best bet might be to write a plugin for a text editor that did some basic checking for suspicious patterns and highlighted them differently than the standard .sql mode. But even that would be quite difficult.</p>\n\n<p>I would be happy with a tool that set off alarm bells whenever I typed in an update statement without a where clause. And perhaps administered a mild electric shock, since it's usually about 1 in the morning after a long day when mistakes like that happen.</p>\n"
},
{
"answer_id": 15600,
"author": "Robby Slaughter",
"author_id": 1854,
"author_profile": "https://Stackoverflow.com/users/1854",
"pm_score": 0,
"selected": false,
"text": "<p>It would be pretty easy to build this by setting up a sample database with a extremely small amount of dummy data, which would receive the query first. A couple of things will happen:</p>\n\n<ol>\n<li>You might get a SQL syntax error, which would not load the database much since it's a small database.</li>\n<li>You might get back a response which could clearly be shown to contain every row in one or more tables, which is probably not what they want.</li>\n<li>Things which pass the above conditions are likely to be okay, so you can run them against the copy of the production database.</li>\n</ol>\n\n<p>Assuming your schema doesn't change much and is not particularly weird, writing the above is likely the quickest solution to your problem.</p>\n"
},
{
"answer_id": 15630,
"author": "Michael Ratanapintha",
"author_id": 1879,
"author_profile": "https://Stackoverflow.com/users/1879",
"pm_score": 2,
"selected": false,
"text": "<p>If your people are using the mysql(1) program to run queries, you can use the <a href=\"http://dev.mysql.com/doc/refman/5.1/en/mysql-tips.html\" rel=\"nofollow noreferrer\">safe-updates</a> option (aka i-am-a-dummy) to get you part of what you need. Its name is somewhat misleading; it not only prevents UPDATE and DELETE without a WHERE (which you're not worried about), but also adds an implicit LIMIT 1000 to SELECT statements, and aborts SELECTs that have joins and are estimated to consider over 1,000,000 tuples --- perfect for discouraging Cartesian joins.</p>\n"
},
{
"answer_id": 19462,
"author": "AdamGiles",
"author_id": 1264,
"author_profile": "https://Stackoverflow.com/users/1264",
"pm_score": 1,
"selected": false,
"text": "<p>...\"writing very complex ad-hoc SQL queries.... they are so busy\"</p>\n\n<p>Danger Will Robinson!</p>\n\n<p>Automate Automate Automate.</p>\n\n<p>Ideally, the ops team should not be put into a position where they have to write queries on the fly in a high stress situation – it’s a recipe for disaster! Better for them to build up a library of pre-written scripts that have undergone the appropriate testing to make sure it a) does what you want b) provides an audit trail c) has a possible ‘undo’ type function.</p>\n\n<p>Failing that, giving them a user ID that only has SELECT premissions might help :-)</p>\n"
},
{
"answer_id": 414391,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 0,
"selected": false,
"text": "<p>I'd start with some coding standards - for instance never use the type of join in your example - it often results in bad results (especially in SQL Server if you try to do an outer join that way, you will get bad results). require them to do explicit joins.</p>\n\n<p>If you have complex relationships, you might consider putting them in views and then writing the adhoc queries from the views. Then at least they will never make the mistake of getting the joins wrong.</p>\n"
},
{
"answer_id": 414414,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you just limit the amount of time a query can run for? I'm not sure about MySQL, but for SQL Server, even just the default query analyzer can restrict how long queries will run before they time out. Couple that with limited rights so they can only run SELECT queries, and you should be pretty much covered.</p>\n"
}
] | 2008/08/18 | [
"https://Stackoverflow.com/questions/15399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | My firm have a talented and smart operations staff who are working very hard. I'd like to give them a SQL-execution tool that helps them avoid common, easily-detected SQL mistakes that are easy to make when they are in a hurry. Can anyone suggest such a tool? Details follow.
Part of the operations team remit is writing very complex ad-hoc SQL queries. Not surprisingly, operators sometimes make mistakes in the queries they write because they are so busy.
Luckily, their queries are all SELECTs not data-changing SQL, and they are running on a copy of the database anyway. Still, we'd like to prevent errors in the SQL they run. For instance, sometimes the mistakes lead to long-running queries that slow down the duplicate system they're using and inconvenience others until we find the culprit query and kill it. Worse, occasionally the mistakes lead to apparently-correct answers that we don't catch until much later, with consequent embarrassment.
Our developers also make mistakes in complex code that they write, but they have Eclipse and various plugins (such as [FindBugs](http://findbugs.sourceforge.net/ "FindBugs")) that catch errors as they type. I'd like to give operators something similar - ideally it would see
```
SELECT U.NAME, C.NAME FROM USER U, COMPANY C WHERE U.NAME = 'ibell';
```
and before you executed, it would say "Hey, did you realise that's a Cartesian product? Are you sure you want to do that?" It doesn't have to be very smart - finding obviously missing join conditions and similar evident errors would be fine.
It looks like [TOAD](http://www.toadsoft.com/ "TOAD") should do this but I can't seem to find anything about such a feature. Are there other tools like TOAD that can provide this kind of semi-intelligent error correction?
Update: I forgot to mention that we're using MySQL. | If your people are using the mysql(1) program to run queries, you can use the [safe-updates](http://dev.mysql.com/doc/refman/5.1/en/mysql-tips.html) option (aka i-am-a-dummy) to get you part of what you need. Its name is somewhat misleading; it not only prevents UPDATE and DELETE without a WHERE (which you're not worried about), but also adds an implicit LIMIT 1000 to SELECT statements, and aborts SELECTs that have joins and are estimated to consider over 1,000,000 tuples --- perfect for discouraging Cartesian joins. |
15,470 | <p>I know this site is written using ASP.Net MVC and I do not see "/Home" in the url. This proves to me that it can be done. What special route and do I need?</p>
| [
{
"answer_id": 15474,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 5,
"selected": true,
"text": "<p>Just change \"Home\" to an empty string.</p>\n\n<pre><code>routes.MapRoute(\n \"Home\",\n \"\",\n new { action = Index, controller = Home }\n);\n</code></pre>\n"
},
{
"answer_id": 19037,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 3,
"selected": false,
"text": "<p>If you're running on IIS 7, you can simply delete the Default.aspx file that comes with ASP.NET MVC (assuming you're running on Preview 3 or higher). That file was needed due to an issue with Cassini that was fixed in .NET 3.5 SP1. For more details check out:</p>\n\n<p><a href=\"http://haacked.com/archive/2008/04/10/upcoming-changes-in-routing.aspx\" rel=\"noreferrer\">http://haacked.com/archive/2008/04/10/upcoming-changes-in-routing.aspx</a>\nand\n<a href=\"http://haacked.com/archive/2008/05/12/sp1-beta-and-its-effect-on-mvc.aspx\" rel=\"noreferrer\">http://haacked.com/archive/2008/05/12/sp1-beta-and-its-effect-on-mvc.aspx</a></p>\n"
},
{
"answer_id": 4699350,
"author": "Brandon Joyce",
"author_id": 54050,
"author_profile": "https://Stackoverflow.com/users/54050",
"pm_score": 3,
"selected": false,
"text": "<p>I actually like having all of my home controller methods to be at the root of the site. Like this: /about, /contact, etc. I guess I'm picky. I use a simple route constraint to do it. <a href=\"http://sonerdy.com/getting-rid-of-home-in-aspnet-mvc\" rel=\"nofollow\">Here is my blog post with a code sample.</a></p>\n"
},
{
"answer_id": 15564471,
"author": "prageeth",
"author_id": 2198134,
"author_profile": "https://Stackoverflow.com/users/2198134",
"pm_score": -1,
"selected": false,
"text": "<p>In IIS 7, you can simply delete the Default.aspx file that comes with ASP.NET MVC (assuming you're running on Preview 3 or higher). That file was needed due to an issue with Cassini that was fixed in .NET 3.5 SP1.</p>\n\n<p>For more details check out:</p>\n\n<p><a href=\"http://haacked.com/archive/2008/04/10/upcoming-changes-in-routing.aspx\" rel=\"nofollow\">Upcoming Changes In Routing</a> and <a href=\"http://haacked.com/archive/2008/05/12/sp1-beta-and-its-effect-on-mvc.aspx\" rel=\"nofollow\">.NET 3.5 SP1 Beta and Its Effect on MVC</a></p>\n"
},
{
"answer_id": 27425188,
"author": "SepehrM",
"author_id": 2550529,
"author_profile": "https://Stackoverflow.com/users/2550529",
"pm_score": 1,
"selected": false,
"text": "<p>I'd add </p>\n\n<pre><code>routes.MapRoute(\"NoIndex\", \"{action}\", new { controller = \"Home\", action = \"Index\" });\n</code></pre>\n\n<p>in RouteConfig.cs</p>\n"
},
{
"answer_id": 28389682,
"author": "Kraig McConaghy",
"author_id": 3578535,
"author_profile": "https://Stackoverflow.com/users/3578535",
"pm_score": 0,
"selected": false,
"text": "<p>This is what I did to get rid of Home. It will treat all routes with only one specifier as Home/Action and any with two as Controller/Action. The downside is now controller has to have an explicit index (/Controller != /Controller/Index), but it might help you or others.</p>\n\n<pre><code>routes.MapRoute(\n \"Default\",\n \"{action}\",\n new { controller = \"Home\", action = \"Index\" }\n);\n\nroutes.MapRoute(\n \"Actions\",\n \"{controller}/{action}\",\n new { }\n);\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/692/"
] | I know this site is written using ASP.Net MVC and I do not see "/Home" in the url. This proves to me that it can be done. What special route and do I need? | Just change "Home" to an empty string.
```
routes.MapRoute(
"Home",
"",
new { action = Index, controller = Home }
);
``` |
15,478 | <p>GDI+ DrawLines function has a clipping bug that can be reproduced by running the following c# code. When running the code, two line paths appear, that should be identical, because both of them are inside the clipping region. But when the clipping region is set, one of the line segment is not drawn. </p>
<pre><code>protected override void OnPaint(PaintEventArgs e)
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
Rectangle b = new Rectangle(70, 32, 20, 164);
e.Graphics.SetClip(b);
e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly
e.Graphics.TranslateTransform(80, 0);
e.Graphics.ResetClip();
e.Graphics.DrawLines(Pens.Red, points);
}
</code></pre>
<p>Setting the antials mode on the graphics object resolves this. But that is not a real solution.</p>
<p>Does anybody know of a workaround?</p>
| [
{
"answer_id": 15813,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "<p>What appears to be the matter with the code?</p>\n\n<p>OK, the question should be... what should the code do that it doesn't already.</p>\n\n<p>When I run the code, I see 2 red 'spikes' am I not ment to?</p>\n\n<p>You appear to draw the first spike within the clipped rectangle region verified by adding the the following after the declaration of teh Rectangle :</p>\n\n<p><code>e.Graphics.FillRectangle( new SolidBrush( Color.Black ), b );</code></p>\n\n<p>Then you perform a translation, reset the clip so at this point I assume the clientRectangle is being used as the appropriate clip region and then attempt to redarw the translated spike. Where's the bug?!?</p>\n"
},
{
"answer_id": 15914,
"author": "Forritarinn",
"author_id": 1873,
"author_profile": "https://Stackoverflow.com/users/1873",
"pm_score": 0,
"selected": false,
"text": "<p>The bug is that both line segments should be drawn identical but they are not because the spike that is drawn within the clipping region is completely within the clipping region and should not be clipped in any way but it is. This is a very annoying but that results in any software that uses drawlines heavily + clipping to look unprofessional because of gaps that can appear in the polygons.</p>\n"
},
{
"answer_id": 16914,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 2,
"selected": false,
"text": "<p>It appears that this is a known bug...</p>\n\n<p>The following code appears to function as you requested:</p>\n\n<pre><code>protected override void OnPaint(PaintEventArgs e)\n {\n PointF[] points = new PointF[] { new PointF(73.36f, 196), \n new PointF(75.44f, 32), \n new PointF(77.52f, 32), \n new PointF(79.6f, 196), \n new PointF(85.84f, 196) };\n\n e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n Rectangle b = new Rectangle(70, 32, 20, 165);\n e.Graphics.SetClip(b);\n e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly\n e.Graphics.TranslateTransform(80, 0);\n e.Graphics.ResetClip(); \n e.Graphics.DrawLines(Pens.Red, points);\n }\n</code></pre>\n\n<p>Note: I have AntiAlias'ed the line and extended your clipping region by 1</p>\n\n<p>it appears that the following work arounds might help (although not tested):</p>\n\n<ul>\n<li>The pen is more than one pixel thick</li>\n<li>The line is perfectly horizontal or vertical</li>\n<li>The clipping is against the window boundaries rather than a clip rectangle</li>\n</ul>\n\n<p>The following is a list of articles that might / or then again might not help:</p>\n\n<p><a href=\"http://www.tech-archive.net/pdf/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0350.pdf\" rel=\"nofollow noreferrer\">http://www.tech-archive.net/pdf/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0350.pdf</a>\n<a href=\"http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0368.html\" rel=\"nofollow noreferrer\">http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0368.html</a></p>\n\n<p>OR...</p>\n\n<p>the following is also possible:</p>\n\n<pre><code>protected override void OnPaint ( PaintEventArgs e )\n {\n PointF[] points = new PointF[] { new PointF(73.36f, 196), \n new PointF(75.44f, 32), \n new PointF(77.52f, 32), \n new PointF(79.6f, 196), \n new PointF(85.84f, 196) };\n\n Rectangle b = new Rectangle( 70, 32, 20, 164 );\n Region reg = new Region( b );\n e.Graphics.SetClip( reg, System.Drawing.Drawing2D.CombineMode.Union);\n e.Graphics.DrawLines( Pens.Red, points ); // clipped incorrectly\n e.Graphics.TranslateTransform( 80, 0 );\n e.Graphics.ResetClip();\n e.Graphics.DrawLines( Pens.Red, points );\n }\n</code></pre>\n\n<p>This effecivly clips using a region combined/unioned (I think) with the ClientRectangle of the canvas/Control. As the region is difned from the rectangle, the results should be what is expected. This code can be proven to work by adding</p>\n\n<pre><code>e.Graphics.FillRectangle( new SolidBrush( Color.Black ), b );\n</code></pre>\n\n<p>after the setClip() call. This clearly shows the black rectangle only appearing in the clipped region.</p>\n\n<p>This could be a valid workaround if Anti-Aliasing the line is not an option.</p>\n\n<p>Hope this helps</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873/"
] | GDI+ DrawLines function has a clipping bug that can be reproduced by running the following c# code. When running the code, two line paths appear, that should be identical, because both of them are inside the clipping region. But when the clipping region is set, one of the line segment is not drawn.
```
protected override void OnPaint(PaintEventArgs e)
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
Rectangle b = new Rectangle(70, 32, 20, 164);
e.Graphics.SetClip(b);
e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly
e.Graphics.TranslateTransform(80, 0);
e.Graphics.ResetClip();
e.Graphics.DrawLines(Pens.Red, points);
}
```
Setting the antials mode on the graphics object resolves this. But that is not a real solution.
Does anybody know of a workaround? | It appears that this is a known bug...
The following code appears to function as you requested:
```
protected override void OnPaint(PaintEventArgs e)
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
Rectangle b = new Rectangle(70, 32, 20, 165);
e.Graphics.SetClip(b);
e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly
e.Graphics.TranslateTransform(80, 0);
e.Graphics.ResetClip();
e.Graphics.DrawLines(Pens.Red, points);
}
```
Note: I have AntiAlias'ed the line and extended your clipping region by 1
it appears that the following work arounds might help (although not tested):
* The pen is more than one pixel thick
* The line is perfectly horizontal or vertical
* The clipping is against the window boundaries rather than a clip rectangle
The following is a list of articles that might / or then again might not help:
<http://www.tech-archive.net/pdf/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0350.pdf>
<http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.gdi/2004-08/0368.html>
OR...
the following is also possible:
```
protected override void OnPaint ( PaintEventArgs e )
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
Rectangle b = new Rectangle( 70, 32, 20, 164 );
Region reg = new Region( b );
e.Graphics.SetClip( reg, System.Drawing.Drawing2D.CombineMode.Union);
e.Graphics.DrawLines( Pens.Red, points ); // clipped incorrectly
e.Graphics.TranslateTransform( 80, 0 );
e.Graphics.ResetClip();
e.Graphics.DrawLines( Pens.Red, points );
}
```
This effecivly clips using a region combined/unioned (I think) with the ClientRectangle of the canvas/Control. As the region is difned from the rectangle, the results should be what is expected. This code can be proven to work by adding
```
e.Graphics.FillRectangle( new SolidBrush( Color.Black ), b );
```
after the setClip() call. This clearly shows the black rectangle only appearing in the clipped region.
This could be a valid workaround if Anti-Aliasing the line is not an option.
Hope this helps |
15,481 | <p>Sometimes a labeled break or continue can make code a lot more readable. </p>
<pre><code>OUTERLOOP: for ( ;/*stuff*/; ) {
//...lots of code
if ( isEnough() ) break OUTERLOOP;
//...more code
}
</code></pre>
<p>I was wondering what the common convention for the labels was. All caps? first cap? </p>
| [
{
"answer_id": 15501,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 4,
"selected": false,
"text": "<p>The convention is to avoid labels altogether.</p>\n\n<p>There are very, very few valid reasons to use a label for breaking out of a loop. Breaking out is ok, but you can remove the need to break at all by modifying your design a little. In the example you have given, you would extract the 'Lots of code' sections and put them in individual methods with meaningful names. </p>\n\n<pre><code>for ( ;/*stuff*/; ) \n{\n lotsOfCode();\n\n if ( !isEnough() )\n {\n moreCode();\n }\n}\n</code></pre>\n\n<hr>\n\n<p><em>Edit:</em> having seen the actual code in question (<a href=\"https://stackoverflow.com/questions/15851/refactoring-away-labeled-loops\">over here</a>), I think the use of labels is probably the best way to make the code readable. In most cases using labels is the wrong approach, in this instance, I think it is fine.</p>\n"
},
{
"answer_id": 15644,
"author": "JProgrammer",
"author_id": 1675,
"author_profile": "https://Stackoverflow.com/users/1675",
"pm_score": 0,
"selected": false,
"text": "<p>The convetion/best practise would still be not to use them at all and to refactor the code so that is more readable using extract as method.</p>\n"
},
{
"answer_id": 15658,
"author": "Craig",
"author_id": 1611,
"author_profile": "https://Stackoverflow.com/users/1611",
"pm_score": 5,
"selected": true,
"text": "<p>If you have to use them use capitals, this draws attention to them and singles them out from being mistakenly interpreted as \"Class\" names. Drawing attention to them has the additional benefit of catching someone's eye that will come along and refactor your code and remove them. ;)</p>\n"
},
{
"answer_id": 15663,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 0,
"selected": false,
"text": "<p>They are kind of the goto of Java - not sure if C# has them. I have never used them in practice, I can't think of a case where avoiding them wouldn't result in much more readable code. </p>\n\n<p>But if you have to- I think all caps is ok. Most people won't use labelled breaks, so when they see the code, the caps will jump out at them and will force them to realise what is going on. </p>\n"
},
{
"answer_id": 15665,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>I know, I should not use labels.</p>\n<p>But just assume, I have some code, that could gain a lot in readability from labeled breaks, how do I format them.</p>\n</blockquote>\n<p>Mo, your premise is wrong.\nThe question shouldn't be 'how do I format them?'</p>\n<p>Your question should be 'I have code that has a large amount of logic inside loops - how do I make it more readable?'</p>\n<p>The answer to that question is to move the code into individual, well named functions. Then you don't need to label the breaks at all.</p>\n"
},
{
"answer_id": 15894,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 2,
"selected": false,
"text": "<p>The convention I've most seen is simply camel case, like a method name...</p>\n\n<pre><code>myLabel:\n</code></pre>\n\n<p>but I've also seen labels prefixed with an underscore</p>\n\n<pre><code>_myLabel:\n</code></pre>\n\n<p>or with lab...</p>\n\n<pre><code>labSomething:\n</code></pre>\n\n<p>You can probably sense though from the other answers that you'll be hard-pushed to find a coding standard that says anything other than 'Don't use labels'. The answer then I guess is that you should use whatever style makes sense to you, as long as it's consistent.</p>\n"
},
{
"answer_id": 15939,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 5,
"selected": false,
"text": "<p>I don't understand where this \"don't use labels\" rule comes from. When doing non-trivial looping logic, the test to break or continue isn't always neatly at the end of the surrounding block.</p>\n\n<pre><code>outer_loop:\nfor (...) {\n // some code\n for (...) {\n // some code\n if (...)\n continue outer_loop;\n // more code\n }\n // more code\n}\n</code></pre>\n\n<p>Yes, cases like this do happen all the time. What are people suggesting I use instead? A boolean condition like this?</p>\n\n<pre><code>for (...) {\n // some code\n boolean continueOuterLoop = false;\n for (...) {\n // some code\n if (...) {\n continueOuterLoop = true;\n break;\n }\n // more code\n }\n if (continueOuterLoop)\n continue;\n // more code\n}\n</code></pre>\n\n<p><strong>Yuck!</strong> Refactoring it as a method doesn't alleviate that either:</p>\n\n<pre><code>boolean innerLoop (...) {\n for (...) {\n // some code\n if (...) {\n return true;\n }\n // more code\n }\n return false;\n}\n\nfor (...) {\n // some code\n if (innerLoop(...))\n continue;\n // more code\n}\n</code></pre>\n\n<p>Sure it's a little prettier, but it's still passing around a superfluous boolean. And if the inner loop modified local variables, refactoring it into a method isn't always the correct solution.</p>\n\n<p>So why are you all against labels? Give me some solid reasons, and practical alternatives for the above case.</p>\n"
},
{
"answer_id": 15944,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 1,
"selected": false,
"text": "<p>wrt <a href=\"https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15939\">sadie's code example</a>:</p>\n\n<p>You gave </p>\n\n<pre><code>outerloop:\nfor (...) {\n // some code\n for (...) {\n // some code\n if (...)\n continue outerloop;\n // more code\n }\n // more code\n}\n</code></pre>\n\n<p>As an example. You make a good point. My best guess would be:</p>\n\n<pre><code>public void lookMumNoLabels() {\n for (...) {\n // some code\n doMoreInnerCodeLogic(...);\n }\n}\n\nprivate void doMoreInnerCodeLogic(...) {\n for (...) {\n // some code\n if (...) return;\n }\n}\n</code></pre>\n\n<p>But there would be examples where that kind of refactoring doesn't sit correctly with whatever logic you're doing.</p>\n"
},
{
"answer_id": 17643,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 1,
"selected": false,
"text": "<p>As labels are so rarely useful, it appears, that there is no clear convention. The Java language specification has one example with labels and they are in non_cap.</p>\n\n<p>But since they are so rare, in my opinion it is best, to think twice whether they are really the right tool.</p>\n\n<p>And if they are the right tool, make them all caps so that other developers (or yourself later on) realize them as something unusual right away. (as Craig already pointed out)</p>\n"
},
{
"answer_id": 17756,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 3,
"selected": false,
"text": "<p>Sun's Java code style seem to prefer naming labels in the same way as variables, meaning camel case with the first letter in lower case.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] | Sometimes a labeled break or continue can make code a lot more readable.
```
OUTERLOOP: for ( ;/*stuff*/; ) {
//...lots of code
if ( isEnough() ) break OUTERLOOP;
//...more code
}
```
I was wondering what the common convention for the labels was. All caps? first cap? | If you have to use them use capitals, this draws attention to them and singles them out from being mistakenly interpreted as "Class" names. Drawing attention to them has the additional benefit of catching someone's eye that will come along and refactor your code and remove them. ;) |
15,486 | <p>So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.</p>
<p>Turns out the IList interface doesn't have a sort method built in. </p>
<p>I ended up using the <code>ArrayList.Adapter(list).Sort(new MyComparer())</code> method to solve the problem but it just seemed a bit "ghetto" to me.</p>
<p>I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.</p>
<p>So my question is, does anyone have an elegant solution to sorting an IList</p>
| [
{
"answer_id": 15491,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 3,
"selected": false,
"text": "<p>You're going to have to do something like that i think (convert it into a more concrete type).</p>\n\n<p>Maybe take it into a List of T rather than ArrayList, so that you get type safety and more options for how you implement the comparer.</p>\n"
},
{
"answer_id": 15492,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": -1,
"selected": false,
"text": "<p>Convert your <code>IList</code> into <code>List<T></code> or some other generic collection and then you can easily query/sort it using <code>System.Linq</code> namespace (it will supply bunch of extension methods)</p>\n"
},
{
"answer_id": 15494,
"author": "Brad Leach",
"author_id": 708,
"author_profile": "https://Stackoverflow.com/users/708",
"pm_score": 7,
"selected": true,
"text": "<p>How about using LINQ To Objects to sort for you?</p>\n\n<p>Say you have a <code>IList<Car></code>, and the car had an <code>Engine</code> property, I believe you could sort as follows:</p>\n\n<pre><code>from c in list\norderby c.Engine\nselect c;\n</code></pre>\n\n<p><em>Edit: You do need to be quick to get answers in here. As I presented a slightly different syntax to the other answers, I will leave my answer - however, the other answers presented are equally valid.</em></p>\n"
},
{
"answer_id": 15495,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": false,
"text": "<p>You can use LINQ:</p>\n\n<pre><code>using System.Linq;\n\nIList<Foo> list = new List<Foo>();\nIEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);\nIList<Foo> sortedList = sortedEnum.ToList();\n</code></pre>\n"
},
{
"answer_id": 16025,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 0,
"selected": false,
"text": "<p>Here's an example using the stronger typing. Not sure if it's necessarily the best way though.</p>\n\n<pre><code>static void Main(string[] args)\n{\n IList list = new List<int>() { 1, 3, 2, 5, 4, 6, 9, 8, 7 };\n List<int> stronglyTypedList = new List<int>(Cast<int>(list));\n stronglyTypedList.Sort();\n}\n\nprivate static IEnumerable<T> Cast<T>(IEnumerable list)\n{\n foreach (T item in list)\n {\n yield return item;\n }\n}\n</code></pre>\n\n<p>The Cast function is just a reimplementation of the extension method that comes with 3.5 written as a normal static method. It is quite ugly and verbose unfortunately.</p>\n"
},
{
"answer_id": 83241,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "<p>In VS2008, when I click on the service reference and select \"Configure Service Reference\", there is an option to choose how the client de-serializes lists returned from the service.</p>\n\n<p>Notably, I can choose between System.Array, System.Collections.ArrayList and System.Collections.Generic.List</p>\n"
},
{
"answer_id": 512755,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Found a good post on this and thought I'd share. <a href=\"http://foxsys.blogspot.com/search?q=IList+Sort\" rel=\"nofollow noreferrer\">Check it out HERE</a></p>\n\n<p>Basically.</p>\n\n<p>You can create the following class and IComparer Classes</p>\n\n<pre><code>public class Widget {\n public string Name = string.Empty;\n public int Size = 0;\n\n public Widget(string name, int size) {\n this.Name = name;\n this.Size = size;\n}\n}\n\npublic class WidgetNameSorter : IComparer<Widget> {\n public int Compare(Widget x, Widget y) {\n return x.Name.CompareTo(y.Name);\n}\n}\n\npublic class WidgetSizeSorter : IComparer<Widget> {\n public int Compare(Widget x, Widget y) {\n return x.Size.CompareTo(y.Size);\n}\n}\n</code></pre>\n\n<p>Then If you have an IList, you can sort it like this.</p>\n\n<pre><code>List<Widget> widgets = new List<Widget>();\nwidgets.Add(new Widget(\"Zeta\", 6));\nwidgets.Add(new Widget(\"Beta\", 3));\nwidgets.Add(new Widget(\"Alpha\", 9));\n\nwidgets.Sort(new WidgetNameSorter());\nwidgets.Sort(new WidgetSizeSorter());\n</code></pre>\n\n<p>But Checkout this site for more information... <a href=\"http://foxsys.blogspot.com/search?q=IList+Sort\" rel=\"nofollow noreferrer\">Check it out HERE</a></p>\n"
},
{
"answer_id": 1087089,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>using System.Linq;\n\nvar yourList = SomeDAO.GetRandomThings();\nyourList.ToList().Sort( (thing, randomThing) => thing.CompareThisProperty.CompareTo( randomThing.CompareThisProperty ) );\n</code></pre>\n\n<p>That's pretty !ghetto.</p>\n"
},
{
"answer_id": 3242024,
"author": "John",
"author_id": 239628,
"author_profile": "https://Stackoverflow.com/users/239628",
"pm_score": 1,
"selected": false,
"text": "<p>Found this thread while I was looking for a solution to the exact problem described in the original post. None of the answers met my situation entirely, however. Brody's answer was pretty close. Here is my situation and solution I found to it.</p>\n\n<p>I have two ILists of the same type returned by NHibernate and have emerged the two IList into one, hence the need for sorting.</p>\n\n<p>Like Brody said I implemented an ICompare on the object (ReportFormat) which is the type of my IList:</p>\n\n<pre><code> public class FormatCcdeSorter:IComparer<ReportFormat>\n {\n public int Compare(ReportFormat x, ReportFormat y)\n {\n return x.FormatCode.CompareTo(y.FormatCode);\n }\n }\n</code></pre>\n\n<p>I then convert the merged IList to an array of the same type:</p>\n\n<pre><code>ReportFormat[] myReports = new ReportFormat[reports.Count]; //reports is the merged IList\n</code></pre>\n\n<p>Then sort the array: </p>\n\n<pre><code>Array.Sort(myReports, new FormatCodeSorter());//sorting using custom comparer\n</code></pre>\n\n<p>Since one-dimensional array implements the interface <code>System.Collections.Generic.IList<T></code>, the array can be used just like the original IList.</p>\n"
},
{
"answer_id": 3691280,
"author": "Yoav",
"author_id": 445117,
"author_profile": "https://Stackoverflow.com/users/445117",
"pm_score": 0,
"selected": false,
"text": "<p>Is this a valid solution?</p>\n\n<pre><code> IList<string> ilist = new List<string>();\n ilist.Add(\"B\");\n ilist.Add(\"A\");\n ilist.Add(\"C\");\n\n Console.WriteLine(\"IList\");\n foreach (string val in ilist)\n Console.WriteLine(val);\n Console.WriteLine();\n\n List<string> list = (List<string>)ilist;\n list.Sort();\n Console.WriteLine(\"List\");\n foreach (string val in list)\n Console.WriteLine(val);\n Console.WriteLine();\n\n list = null;\n\n Console.WriteLine(\"IList again\");\n foreach (string val in ilist)\n Console.WriteLine(val);\n Console.WriteLine();\n</code></pre>\n\n<p>The result was:\nIList\nB\nA\nC</p>\n\n<p>List\nA\nB\nC</p>\n\n<p>IList again\nA\nB\nC</p>\n"
},
{
"answer_id": 4388250,
"author": "Bruno",
"author_id": 535044,
"author_profile": "https://Stackoverflow.com/users/535044",
"pm_score": 1,
"selected": false,
"text": "<p>Useful for grid sorting this method sorts list based on property names. As follow the example.</p>\n\n<pre><code> List<MeuTeste> temp = new List<MeuTeste>();\n\n temp.Add(new MeuTeste(2, \"ramster\", DateTime.Now));\n temp.Add(new MeuTeste(1, \"ball\", DateTime.Now));\n temp.Add(new MeuTeste(8, \"gimm\", DateTime.Now));\n temp.Add(new MeuTeste(3, \"dies\", DateTime.Now));\n temp.Add(new MeuTeste(9, \"random\", DateTime.Now));\n temp.Add(new MeuTeste(5, \"call\", DateTime.Now));\n temp.Add(new MeuTeste(6, \"simple\", DateTime.Now));\n temp.Add(new MeuTeste(7, \"silver\", DateTime.Now));\n temp.Add(new MeuTeste(4, \"inn\", DateTime.Now));\n\n SortList(ref temp, SortDirection.Ascending, \"MyProperty\");\n\n private void SortList<T>(\n ref List<T> lista\n , SortDirection sort\n , string propertyToOrder)\n {\n if (!string.IsNullOrEmpty(propertyToOrder)\n && lista != null\n && lista.Count > 0)\n {\n Type t = lista[0].GetType();\n\n if (sort == SortDirection.Ascending)\n {\n lista = lista.OrderBy(\n a => t.InvokeMember(\n propertyToOrder\n , System.Reflection.BindingFlags.GetProperty\n , null\n , a\n , null\n )\n ).ToList();\n }\n else\n {\n lista = lista.OrderByDescending(\n a => t.InvokeMember(\n propertyToOrder\n , System.Reflection.BindingFlags.GetProperty\n , null\n , a\n , null\n )\n ).ToList();\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 5037815,
"author": "David Mills",
"author_id": 29696,
"author_profile": "https://Stackoverflow.com/users/29696",
"pm_score": 6,
"selected": false,
"text": "<p>This question inspired me to write a blog post: <a href=\"http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/\" rel=\"noreferrer\">http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/</a></p>\n\n<p>I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList<T>, but the next best thing is to create your own extension method. It's not too hard to create a couple of methods that will allow you to sort an IList<T> as you would a List<T>. As a bonus you can overload the LINQ OrderBy extension method using the same technique, so that whether you're using List.Sort, IList.Sort, or IEnumerable.OrderBy, you can use the exact same syntax.</p>\n\n<pre><code>public static class SortExtensions\n{\n // Sorts an IList<T> in place.\n public static void Sort<T>(this IList<T> list, Comparison<T> comparison)\n {\n ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));\n }\n\n // Sorts in IList<T> in place, when T is IComparable<T>\n public static void Sort<T>(this IList<T> list) where T: IComparable<T>\n {\n Comparison<T> comparison = (l, r) => l.CompareTo(r);\n Sort(list, comparison);\n\n }\n\n // Convenience method on IEnumerable<T> to allow passing of a\n // Comparison<T> delegate to the OrderBy method.\n public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)\n {\n return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));\n }\n}\n\n// Wraps a generic Comparison<T> delegate in an IComparer to make it easy\n// to use a lambda expression for methods that take an IComparer or IComparer<T>\npublic class ComparisonComparer<T> : IComparer<T>, IComparer\n{\n private readonly Comparison<T> _comparison;\n\n public ComparisonComparer(Comparison<T> comparison)\n {\n _comparison = comparison;\n }\n\n public int Compare(T x, T y)\n {\n return _comparison(x, y);\n }\n\n public int Compare(object o1, object o2)\n {\n return _comparison((T)o1, (T)o2);\n }\n}\n</code></pre>\n\n<p>With these extensions, sort your IList just like you would a List:</p>\n\n<pre><code>IList<string> iList = new []\n{\n \"Carlton\", \"Alison\", \"Bob\", \"Eric\", \"David\"\n};\n\n// Use the custom extensions:\n\n// Sort in-place, by string length\niList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));\n\n// Or use OrderBy()\nIEnumerable<string> ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));\n</code></pre>\n\n<p>There's more info in the post: <a href=\"http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/\" rel=\"noreferrer\">http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/</a></p>\n"
},
{
"answer_id": 12211204,
"author": "Dhanasekar Murugesan",
"author_id": 1565396,
"author_profile": "https://Stackoverflow.com/users/1565396",
"pm_score": 2,
"selected": false,
"text": "<pre><code>try this **USE ORDER BY** :\n\n public class Employee\n {\n public string Id { get; set; }\n public string Name { get; set; }\n }\n\n private static IList<Employee> GetItems()\n {\n List<Employee> lst = new List<Employee>();\n\n lst.Add(new Employee { Id = \"1\", Name = \"Emp1\" });\n lst.Add(new Employee { Id = \"2\", Name = \"Emp2\" });\n lst.Add(new Employee { Id = \"7\", Name = \"Emp7\" });\n lst.Add(new Employee { Id = \"4\", Name = \"Emp4\" });\n lst.Add(new Employee { Id = \"5\", Name = \"Emp5\" });\n lst.Add(new Employee { Id = \"6\", Name = \"Emp6\" });\n lst.Add(new Employee { Id = \"3\", Name = \"Emp3\" });\n\n return lst;\n }\n\n**var lst = GetItems().AsEnumerable();\n\n var orderedLst = lst.OrderBy(t => t.Id).ToList();\n\n orderedLst.ForEach(emp => Console.WriteLine(\"Id - {0} Name -{1}\", emp.Id, emp.Name));**\n</code></pre>\n"
},
{
"answer_id": 39031496,
"author": "dana",
"author_id": 315689,
"author_profile": "https://Stackoverflow.com/users/315689",
"pm_score": 3,
"selected": false,
"text": "<p>The accepted answer by @DavidMills is quite good, but I think it can be improved upon. For one, there is no need to define the <code>ComparisonComparer<T></code> class when the framework already includes a static method <code>Comparer<T>.Create(Comparison<T>)</code>. This method can be used to create an <code>IComparison</code> on the fly.</p>\n<p>Also, it casts <code>IList<T></code> to <code>IList</code> which has the potential to be dangerous. In most cases that I have seen, <code>List<T></code> which implements <code>IList</code> is used behind the scenes to implement <code>IList<T></code>, but this is not guaranteed and can lead to brittle code.</p>\n<p>Lastly, the overloaded <code>List<T>.Sort()</code> method has 4 signatures and only 2 of them are implemented.</p>\n<ol>\n<li><code>List<T>.Sort()</code></li>\n<li><code>List<T>.Sort(Comparison<T>)</code></li>\n<li><code>List<T>.Sort(IComparer<T>)</code></li>\n<li><code>List<T>.Sort(Int32, Int32, IComparer<T>)</code></li>\n</ol>\n<p>The below class implements all 4 <code>List<T>.Sort()</code> signatures for the <code>IList<T></code> interface:</p>\n<pre><code>using System;\nusing System.Collections.Generic;\n\npublic static class IListExtensions\n{\n public static void Sort<T>(this IList<T> list)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort();\n }\n else\n {\n var copy = new List<T>(list);\n copy.Sort();\n Copy(copy, 0, list, 0, list.Count);\n }\n }\n\n public static void Sort<T>(this IList<T> list, Comparison<T> comparison)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort(comparison);\n }\n else\n {\n var copy = new List<T>(list);\n copy.Sort(comparison);\n Copy(copy, 0, list, 0, list.Count);\n }\n }\n\n public static void Sort<T>(this IList<T> list, IComparer<T> comparer)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort(comparer);\n }\n else\n {\n var copy = new List<T>(list);\n copy.Sort(comparer);\n Copy(copy, 0, list, 0, list.Count);\n }\n }\n\n public static void Sort<T>(this IList<T> list, int index, int count,\n IComparer<T> comparer)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort(index, count, comparer);\n }\n else\n {\n var range = new List<T>(count);\n for (int i = 0; i < count; i++)\n {\n range.Add(list[index + i]);\n }\n range.Sort(comparer);\n Copy(range, 0, list, index, count);\n }\n }\n\n private static void Copy<T>(IList<T> sourceList, int sourceIndex,\n IList<T> destinationList, int destinationIndex, int count)\n {\n for (int i = 0; i < count; i++)\n {\n destinationList[destinationIndex + i] = sourceList[sourceIndex + i];\n }\n }\n}\n</code></pre>\n<p>Usage:</p>\n<pre><code>class Foo\n{\n public int Bar;\n\n public Foo(int bar) { this.Bar = bar; }\n}\n\nvoid TestSort()\n{\n IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };\n IList<Foo> foos = new List<Foo>()\n {\n new Foo(1),\n new Foo(4),\n new Foo(5),\n new Foo(3),\n new Foo(2),\n };\n\n ints.Sort();\n foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));\n}\n</code></pre>\n<p>The idea here is to leverage the functionality of the underlying <code>List<T></code> to handle sorting whenever possible. Again, most <code>IList<T></code> implementations that I have seen use this. In the case when the underlying collection is a different type, fallback to creating a new instance of <code>List<T></code> with elements from the input list, use it to do the sorting, then copy the results back to the input list. This will work even if the input list does not implement the <code>IList</code> interface.</p>\n"
},
{
"answer_id": 58669695,
"author": "Momodu Deen Swarray",
"author_id": 10032850,
"author_profile": "https://Stackoverflow.com/users/10032850",
"pm_score": 0,
"selected": false,
"text": "<p>This looks MUCH MORE SIMPLE if you ask me. This works PERFECTLY for me.</p>\n\n<p>You could use Cast() to change it to IList then use OrderBy():</p>\n\n<pre><code> var ordered = theIList.Cast<T>().OrderBy(e => e);\n</code></pre>\n\n<p>WHERE T is the type eg. Model.Employee or Plugin.ContactService.Shared.Contact</p>\n\n<p>Then you can use a for loop and its DONE.</p>\n\n<pre><code> ObservableCollection<Plugin.ContactService.Shared.Contact> ContactItems= new ObservableCollection<Contact>();\n\n foreach (var item in ordered)\n {\n ContactItems.Add(item);\n }\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.
Turns out the IList interface doesn't have a sort method built in.
I ended up using the `ArrayList.Adapter(list).Sort(new MyComparer())` method to solve the problem but it just seemed a bit "ghetto" to me.
I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.
So my question is, does anyone have an elegant solution to sorting an IList | How about using LINQ To Objects to sort for you?
Say you have a `IList<Car>`, and the car had an `Engine` property, I believe you could sort as follows:
```
from c in list
orderby c.Engine
select c;
```
*Edit: You do need to be quick to get answers in here. As I presented a slightly different syntax to the other answers, I will leave my answer - however, the other answers presented are equally valid.* |
15,514 | <p>In my example below I'm using a <code>dijit.form.DateTextBox</code>:</p>
<pre><code><input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
</code></pre>
<p>So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying <code>The value entered is not valid.</code>. Even if I remove the <code>constraints="{datePattern:'MM/dd/yyyy'}"</code> it still validates. </p>
<p>Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.</p>
| [
{
"answer_id": 15532,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>My only suggestion is to programmatically remove the dojoType on the server-side or client-side. It is not possible to keep the dojoType and not have it validate. Unless you create your own type that has you logic in it.</p>\n"
},
{
"answer_id": 15677,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 4,
"selected": true,
"text": "<p>Try overriding the validate method in your markup.</p>\n\n<p>This will work (just tested):</p>\n\n<pre><code><input type=\"text\" name=\"startDate\" dojoType=\"dijit.form.DateTextBox\" \n constraints=\"{datePattern:'MM/dd/yyyy'}\" \n value='<c:out value=\"${sessionScope.adminMessageForm.startDate}\"/>'\n validate='return true;'\n/>\n</code></pre>\n"
},
{
"answer_id": 59751,
"author": "esarjeant",
"author_id": 644,
"author_profile": "https://Stackoverflow.com/users/644",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem, where the ValidationTextBox met all my needs but it was necessary to disable the validation routines until after the user had first pressed Submit.</p>\n\n<p>My solution was to clone this into a ValidationConditionalTextBox with a couple new methods:</p>\n\n<pre><code> enableValidator:function() {\n this.validatorOn = true;\n },\n\n disableValidator: function() {\n this.validatorOn = false;\n },\n</code></pre>\n\n<p>Then -- in the validator:function() I added a single check:</p>\n\n<pre><code> if (this.validatorOn)\n { ... }\n</code></pre>\n\n<p>Fairly straightforward, my default value for validatorOn is false (this appears right at the top of the javascript). When my form submits, simply call enableValidator(). You can view the full JavaScript here:</p>\n\n<p><a href=\"http://lilawnsprinklers.com/js/dijit/form/ValidationTextBox.js\" rel=\"nofollow noreferrer\">http://lilawnsprinklers.com/js/dijit/form/ValidationTextBox.js</a></p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700/"
] | In my example below I'm using a `dijit.form.DateTextBox`:
```
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
```
So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying `The value entered is not valid.`. Even if I remove the `constraints="{datePattern:'MM/dd/yyyy'}"` it still validates.
Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances. | Try overriding the validate method in your markup.
This will work (just tested):
```
<input type="text" name="startDate" dojoType="dijit.form.DateTextBox"
constraints="{datePattern:'MM/dd/yyyy'}"
value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>'
validate='return true;'
/>
``` |
15,593 | <p>I understand what <a href="http://msdn.microsoft.com/en-us/library/ms404247.aspx" rel="noreferrer">System.WeakReference</a> does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack. It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen. What's the canonical example of where you've really got to use a WeakReference? Aren't we trying to get <i>farther</i> away from this type of behavior and use of this class? </p>
| [
{
"answer_id": 15616,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "<p>I use it to implement a cache where unused entries are automatically garbage collected:</p>\n\n<pre><code>class Cache<TKey,TValue> : IEnumerable<KeyValuePair<TKey,TValue>>\n{ Dictionary<TKey,WeakReference> dict = new Dictionary<TKey,WeakReference>();\n\n public TValue this[TKey key]\n { get {lock(dict){ return getInternal(key);}}\n set {lock(dict){ setInteral(key,value);}} \n }\n\n void setInteral(TKey key, TValue val)\n { if (dict.ContainsKey(key)) dict[key].Target = val;\n else dict.Add(key,new WeakReference(val));\n } \n\n\n public void Clear() { dict.Clear(); }\n\n /// <summary>Removes any dead weak references</summary>\n /// <returns>The number of cleaned-up weak references</returns>\n public int CleanUp()\n { List<TKey> toRemove = new List<TKey>(dict.Count);\n foreach(KeyValuePair<TKey,WeakReference> kv in dict)\n { if (!kv.Value.IsAlive) toRemove.Add(kv.Key);\n }\n\n foreach (TKey k in toRemove) dict.Remove(k);\n return toRemove.Count;\n }\n\n public bool Contains(string key) \n { lock (dict) { return containsInternal(key); }\n }\n\n bool containsInternal(TKey key)\n { return (dict.ContainsKey(key) && dict[key].IsAlive);\n }\n\n public bool Exists(Predicate<TValue> match) \n { if (match==null) throw new ArgumentNullException(\"match\");\n\n lock (dict)\n { foreach (WeakReference weakref in dict.Values) \n { if ( weakref.IsAlive \n && match((TValue) weakref.Target)) return true;\n } \n }\n\n return false;\n }\n\n /* ... */\n }\n</code></pre>\n"
},
{
"answer_id": 15627,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 7,
"selected": true,
"text": "<p>One useful example is the guys who run DB4O object oriented database. There, WeakReferences are used as a kind of light cache: it will keep your objects in memory only as long as your application does, allowing you to put a real cache on top.</p>\n\n<p>Another use would be in the implementation of weak event handlers. Currently, one big source of memory leaks in .NET applications is forgetting to remove event handlers. E.g.</p>\n\n<pre><code>public MyForm()\n{\n MyApplication.Foo += someHandler;\n}\n</code></pre>\n\n<p>See the problem? In the above snippet, MyForm will be kept alive in memory forever as long as MyApplication is alive in memory. Create 10 MyForms, close them all, your 10 MyForms will still be in memory, kept alive by the event handler.</p>\n\n<p>Enter WeakReference. You can build a weak event handler using WeakReferences so that someHandler is a weak event handler to MyApplication.Foo, thus fixing your memory leaks!</p>\n\n<p>This isn't just theory. Dustin Campbell from the DidItWith.NET blog posted <a href=\"http://diditwith.net/PermaLink,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx\" rel=\"noreferrer\">an implementation of weak event handlers</a> using System.WeakReference.</p>\n"
},
{
"answer_id": 347508,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 2,
"selected": false,
"text": "<p>I use weak reference for state-keeping in mixins. Remember, mixins are static, so when you use a static object to attach state to a non-static one, you never know how long it will be required. So instead of keeping a <code>Dictionary<myobject, myvalue></code> I keep a <code>Dictionary<WeakReference,myvalue></code> to prevent the mixin from dragging things for too long.</p>\n\n<p>The only problem is that every time I do an access, I also check for dead references and remove them. Not that they hurt anyone, unless there are thousands, of course.</p>\n"
},
{
"answer_id": 12124101,
"author": "hIpPy",
"author_id": 58678,
"author_profile": "https://Stackoverflow.com/users/58678",
"pm_score": 0,
"selected": false,
"text": "<p>There are two reasons why you would use <code>WeakReference</code>. </p>\n\n<ol>\n<li><p><strong>Instead of global objects declared as static</strong>: Global objects are declared as static fields and static fields cannot be GC'ed (garbage-collected) until the <code>AppDomain</code> is GC'ed. So you risk out-of-memory exceptions. Instead, we can wrap the global object in a <code>WeakReference</code>. Even though the <code>WeakReference</code> itself is declared static, the object it points to will be GC'ed when memory is low. </p>\n\n<p>Basically, use <code>wrStaticObject</code> instead of <code>staticObject</code>.</p>\n\n<pre><code>class ThingsWrapper {\n //private static object staticObject = new object();\n private static WeakReference wrStaticObject \n = new WeakReference(new object());\n}\n</code></pre>\n\n<p>Simple app to prove that static object is garbage-collected when AppDomain is.</p>\n\n<pre><code>class StaticGarbageTest\n{\n public static void Main1()\n {\n var s = new ThingsWrapper();\n s = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\nclass ThingsWrapper\n{\n private static Thing staticThing = new Thing(\"staticThing\");\n private Thing privateThing = new Thing(\"privateThing\");\n ~ThingsWrapper()\n { Console.WriteLine(\"~ThingsWrapper\"); }\n}\nclass Thing\n{\n protected string name;\n public Thing(string name) {\n this.name = name;\n Console.WriteLine(\"Thing() \" + name);\n }\n public override string ToString() { return name; }\n ~Thing() { Console.WriteLine(\"~Thing() \" + name); }\n}\n</code></pre>\n\n<p>Note from the output below <code>staticThing</code> is GC'ed at the very end even after <code>ThingsWrapper</code> is - i.e. GC'ed when <code>AppDomain</code> is GC'ed.</p>\n\n<pre><code>Thing() staticThing\nThing() privateThing\n~Thing() privateThing\n~ThingsWrapper\n~Thing() staticThing\n</code></pre>\n\n<p>Instead we can wrap <code>Thing</code> in a <code>WeakReference</code>. As <code>wrStaticThing</code> can be GC'ed, we'll need a lazy-loaded method which I've left out for brevity. </p>\n\n<pre><code>class WeakReferenceTest\n{\n public static void Main1()\n {\n var s = new WeakReferenceThing();\n s = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n if (WeakReferenceThing.wrStaticThing.IsAlive)\n Console.WriteLine(\"WeakReference: {0}\", \n (Thing)WeakReferenceThing.wrStaticThing.Target);\n else \n Console.WriteLine(\"WeakReference is dead.\");\n }\n}\nclass WeakReferenceThing\n{\n public static WeakReference wrStaticThing;\n static WeakReferenceThing()\n { wrStaticThing = new WeakReference(new Thing(\"wrStaticThing\")); }\n ~WeakReferenceThing()\n { Console.WriteLine(\"~WeakReferenceThing\"); }\n //lazy-loaded method to new Thing\n}\n</code></pre>\n\n<p>Note from output below that <code>wrStaticThing</code> is GC'ed when GC thread is invoked.</p>\n\n<pre><code>Thing() wrStaticThing\n~Thing() wrStaticThing\n~WeakReferenceThing\nWeakReference is dead.\n</code></pre></li>\n<li><p><strong>For objects that are time-consuming to initialize</strong>: You do not want objects that are time-consusming to init to be GC'ed. You can either keep a static reference to avoid that (with cons from above point) or use <code>WeakReference</code>. </p></li>\n</ol>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1875/"
] | I understand what [System.WeakReference](http://msdn.microsoft.com/en-us/library/ms404247.aspx) does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack. It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen. What's the canonical example of where you've really got to use a WeakReference? Aren't we trying to get *farther* away from this type of behavior and use of this class? | One useful example is the guys who run DB4O object oriented database. There, WeakReferences are used as a kind of light cache: it will keep your objects in memory only as long as your application does, allowing you to put a real cache on top.
Another use would be in the implementation of weak event handlers. Currently, one big source of memory leaks in .NET applications is forgetting to remove event handlers. E.g.
```
public MyForm()
{
MyApplication.Foo += someHandler;
}
```
See the problem? In the above snippet, MyForm will be kept alive in memory forever as long as MyApplication is alive in memory. Create 10 MyForms, close them all, your 10 MyForms will still be in memory, kept alive by the event handler.
Enter WeakReference. You can build a weak event handler using WeakReferences so that someHandler is a weak event handler to MyApplication.Foo, thus fixing your memory leaks!
This isn't just theory. Dustin Campbell from the DidItWith.NET blog posted [an implementation of weak event handlers](http://diditwith.net/PermaLink,guid,aacdb8ae-7baa-4423-a953-c18c1c7940ab.aspx) using System.WeakReference. |
15,656 | <p>Another SSRS question here: <br />
We have a development, a QA, a Prod-Backup and a Production SSRS set of servers. <br />
On our production and prod-backup, SSRS will go to sleep if not used for a period of time. <br /><br />
This does not occur on our development or QA server.
<br />In the corporate environment we're in, we don't have physical (or even remote login) access to these machines, and have to work with a team of remote administrators to configure our SSRS application.<br />
<br /> We have asked that they fix, if possible, this issue. So far, they haven't been able to identify the issue, and I would like to know if any of my peers know the answer to this question. Thanks.</p>
| [
{
"answer_id": 15659,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>I vaguely recall having problems with SSRS on one machine when we changed the \"Enable HTTP Keep-Alives\" setting in IIS. Try toggling that checkbox (I don't remember whether it was checked or unchecked when it caused us problems).</p>\n"
},
{
"answer_id": 16497,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 2,
"selected": false,
"text": "<p>In IIS, check the settings on the application pool that SSRS is running in. On the properties pane->Performance tab you can set the amount of time the worker process needs to be idle for before it shuts down. You can also disable this entirely. </p>\n"
},
{
"answer_id": 10721575,
"author": "Lynn Crumbling",
"author_id": 656243,
"author_profile": "https://Stackoverflow.com/users/656243",
"pm_score": 5,
"selected": false,
"text": "<p>For anybody using the integrated webserver that is built into SQL Reporting Services (and hence IIS may not even be installed on the box), the setting to control this actually lives in:</p>\n\n<pre><code>C:\\Program Files\\Microsoft SQL Server\\\n MSRS10_50.MSSQLSERVER\\Reporting Services\\ReportServer\\rsreportserver.config\n</code></pre>\n\n<p>Your directory may be different; version 10_50 maps to SQL 2008 R2.</p>\n\n<p>You'll be looking for the setting called <code>RecycleTime</code>. <br />\nDefault is 720 (12 hours). Setting it to 0 will disable.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1580/"
] | Another SSRS question here:
We have a development, a QA, a Prod-Backup and a Production SSRS set of servers.
On our production and prod-backup, SSRS will go to sleep if not used for a period of time.
This does not occur on our development or QA server.
In the corporate environment we're in, we don't have physical (or even remote login) access to these machines, and have to work with a team of remote administrators to configure our SSRS application.
We have asked that they fix, if possible, this issue. So far, they haven't been able to identify the issue, and I would like to know if any of my peers know the answer to this question. Thanks. | For anybody using the integrated webserver that is built into SQL Reporting Services (and hence IIS may not even be installed on the box), the setting to control this actually lives in:
```
C:\Program Files\Microsoft SQL Server\
MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer\rsreportserver.config
```
Your directory may be different; version 10\_50 maps to SQL 2008 R2.
You'll be looking for the setting called `RecycleTime`.
Default is 720 (12 hours). Setting it to 0 will disable. |
15,674 | <p>When using Subversion (svn) for source control with multiple projects I've noticed that the revision number increases across all of my projects' directories. To illustrate my svn layout (using fictitious project names): </p>
<pre>
/NinjaProg/branches
/tags
/trunk
/StealthApp/branches
/tags
/trunk
/SnailApp/branches
/tags
/trunk
</pre>
<p>When I perform a commit to the trunk of the Ninja Program, let's say I get that it has been updated to revision 7. The next day let's say that I make a small change to the Stealth Application and it comes back as revision 8.</p>
<p>The question is this: <strong>Is it common accepted practice to, when maintaining multiple projects with one Subversion server, to have unrelated projects' revision number increase across all projects?</strong> Or am I doing it wrong and should be creating individual repositories for each project? Or is it something else entirely?</p>
<p><strong>EDIT:</strong> I delayed in flagging an answer because it had become clear that there are reasons for both approaches, and even though this question came first, I'd like to point to some other questions that are ultimately asking the same question: </p>
<p><a href="https://stackoverflow.com/questions/130447/should-i-store-all-projects-in-one-repository-or-mulitiple">Should I store all projects in one repository or mulitiple?</a></p>
<p><a href="https://stackoverflow.com/questions/252459/one-svn-repository-or-many">One SVN Repository or many?</a> </p>
| [
{
"answer_id": 15676,
"author": "John Downey",
"author_id": 200,
"author_profile": "https://Stackoverflow.com/users/200",
"pm_score": 2,
"selected": false,
"text": "<p>This is due to how subversion works. Each revision is really a snapshot of the repository identified by that revision number. If all your projects share a repository then it is unavoidable. Typically, in my experience, however you would setup separate repositories for completely unrelated projects. So short answer is no you are doing nothing wrong it is a common question surrounding subversion but it makes sense when you think about how it stores repository information.</p>\n"
},
{
"answer_id": 15679,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 1,
"selected": false,
"text": "<p>I store one project per repository, and like a previous <a href=\"https://stackoverflow.com/questions/15621/subversion-question#15651\">commenter</a> on this <a href=\"https://stackoverflow.com/questions/15621/subversion-question\">subversion question</a>, I mark shared projects as external, so that they are only in source control once.</p>\n\n<p>I'm just starting to add a CI build server (CruiseControl.NET), so I'll have to see how that all works out, but if my build scripts are right it should not be a problem.</p>\n\n<p>Other than appearance though, it is really a matter of preference (in my opinion).</p>\n"
},
{
"answer_id": 15680,
"author": "Daniel Fone",
"author_id": 1848,
"author_profile": "https://Stackoverflow.com/users/1848",
"pm_score": 2,
"selected": false,
"text": "<p>The revision number should really only be an identifier for a particular version. Whether it's sequential for a project or not shouldn't matter. That being said, I can understand that it's less than ideal.</p>\n\n<p>Most projects I've encountered have been setup in a single repository and the revision ids behave in this way. I don't know any SVN configuration option to change this behavior, and IMHO, maintaining multiple repositories seems like an unnecessary overhead.</p>\n"
},
{
"answer_id": 15684,
"author": "Barrett Conrad",
"author_id": 1227,
"author_profile": "https://Stackoverflow.com/users/1227",
"pm_score": 3,
"selected": false,
"text": "<p>I think it is highly recommended that you create separate repositories for each project. If for nothing else than to avoid the scenario you are talking about. </p>\n\n<p>With version control, especially Subversion, you can easily check out pieces of a repository into another working copy and then commit them back to their respective repositories. That allows you to keep them clearly separate and distinct while giving you a great deal of flexibility. Once you get into SVN a little more (I'm assuming you are new.) you can start using hooks and I might see where that could get difficult with you setup. If permission are important to you, a single repository might prove more difficult than necessary.</p>\n\n<p>Also, if you are concerned that it will take a lot of time to setup each repository look into the SVNParentPath variable for the Apache configuration file. (Again, I'm assuming you are using Apache.)</p>\n"
},
{
"answer_id": 16057,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 2,
"selected": false,
"text": "<p>Recommended to use separate repository per project. In my Apache conf.d directory I have subversion.conf that contains:</p>\n\n<pre><code><Location /svn>\n DAV svn\n SVNParentPath /var/www/svn\n\n AuthType Basic\n AuthName \"Subversion Repository\"\n AuthUserFile /var/www/svn/password\n Require valid-user\n</Location>\n</code></pre>\n\n<p>Then whenever I start a new project I just run:</p>\n\n<pre><code>svnadmin create /var/www/svn/myproject\n</code></pre>\n"
},
{
"answer_id": 16062,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 0,
"selected": false,
"text": "<p>One repository per project.</p>\n\n<p>Steven Murawski's comment about CC.NET is an interesting one. I would be interested to hear how it works if you need to specify several source control repositories.</p>\n"
},
{
"answer_id": 16162,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 2,
"selected": false,
"text": "<p>If having the revision numbers change based on other projects bothers you, then put the projects in separate repositories. That is the only way to make the revision numbers independent.</p>\n\n<p>To me, the big reason to use different repositories is to provide separate access control for users and/or using different hook scripts.</p>\n"
},
{
"answer_id": 16241,
"author": "Erlend Halvorsen",
"author_id": 1920,
"author_profile": "https://Stackoverflow.com/users/1920",
"pm_score": 2,
"selected": false,
"text": "<p>Hm, where I work we have all our projects in the same repository. I really don't see the benefit of separating them, doesn't that just create a lot of extra work -creating new repositories, granting access to people, etc? I guess separate repositories makes sense if the projects are completely unrelated, and you have, say, external customers that needs to have access to the repo.</p>\n"
},
{
"answer_id": 16278,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 2,
"selected": false,
"text": "<p>At my workplace, we have two repositories. One with public read access, and one for everything else. I'd use just one for everything, but we need different access rights for public/private projects.</p>\n\n<p>That said, I personally don't see the problem with the revision numbers incrementing on every update. The revision numbers could skip prime and even numbers and still do what its supposed to do. Make it easy to get to a specific revision.</p>\n"
},
{
"answer_id": 16784,
"author": "flipdoubt",
"author_id": 470,
"author_profile": "https://Stackoverflow.com/users/470",
"pm_score": 0,
"selected": false,
"text": "<p>@Daniel Fone: The SVN docs recommend one project per repository, so that is definitely the way the creators intended it to go. As you can have one server (apache or svnserve) maintain multiple repositories, I've never run into a problem of too much overhead. With <a href=\"http://www.visualsvn.com/server/\" rel=\"nofollow noreferrer\">VisualSVN Server</a>, installing an apache server and configuring multiple repositories is a snap. </p>\n"
},
{
"answer_id": 26792,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure the SVN docs actually recommend one project per repository. Mostly they talk about the upsides and downsides of each path. I happen to use three different repositories, one for 7 or 8 projects that are all related, making it very nice to be able to send out compatible copies of all the projects just by building from one revision (or verifying they're compatible by looking at the revision numbers on each). The second repository has another group of related projects and documents, while the third is a much smaller one. That lets us take advantage of the fact that the related projects can be managed by a single revision number, but that unrelated projects don't affect their repository. </p>\n"
},
{
"answer_id": 26836,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "<p>We just have one repository with everything in it, pretty much exactly like your example.</p>\n\n<p>I can't see anything wrong with this - the only requirement for the revision number is that it is</p>\n\n<ul>\n<li>Unique</li>\n<li>Atomic</li>\n<li>Bigger than it was at the last checkin</li>\n</ul>\n\n<p>It doesn't matter if it increases by 1 or 50 with each commit as far as I'm concerned.</p>\n\n<p>@grom:</p>\n\n<blockquote>\n <p>Then whenever I start a new project I just run:</p>\n \n <p><code>svnadmin create /var/www/svn/myproject</code></p>\n</blockquote>\n\n<p>I can see this working fine if you've only got 1 or 2 devs, but what happens if the people who are creating new projects don't have shell access on the SVN server to be able to create directories under /var/www ? </p>\n"
},
{
"answer_id": 230005,
"author": "James McMahon",
"author_id": 20774,
"author_profile": "https://Stackoverflow.com/users/20774",
"pm_score": 4,
"selected": true,
"text": "<p>I am surprised no has mentioned that this is discussed in Version Control with Subversion, which is available free online, <a href=\"http://svnbook.red-bean.com/en/1.5/svn.reposadmin.planning.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>I read up on the issue awhile back and it really seems like a matter of personal choice, there is a good blog post on the subject <a href=\"http://blogs.open.collab.net/svn/2007/04/single_reposito.html\" rel=\"nofollow noreferrer\">here</a>. EDIT: <em>Since the blog appears to be down, (<a href=\"http://replay.web.archive.org/20090228154135/http://blogs.open.collab.net/svn/2007/04/single_reposito.html\" rel=\"nofollow noreferrer\">archived version here</a>), here is some of what Mark Phippard had to say on the subject.</em></p>\n<blockquote>\n<p>These are some of the advantages of the single repository approach.</p>\n<ol>\n<li>Simplified administration. One set of hooks to deploy. One repository to backup. etc.</li>\n<li>Branch/tag flexibility. With the code all in one repository it makes it easier to create a branch or tag involving multiple projects.</li>\n<li>Move code easily. Perhaps you want to take a section of code from one project and use it in another, or turn it into a library for several projects. It is easy to move the code within the same repository and retain the history of the code in the process.</li>\n</ol>\n<p>Here are some of the drawbacks to the single repository approach, advantages to the multiple repository approach.</p>\n<ol>\n<li>Size. It might be easier to deal with many smaller repositories than one large one. For example, if you retire a project you can just archive the repository to media and remove it from the disk and free up the storage. Maybe you need to dump/load a repository for some reason, such as to take advantage of a new Subversion feature. This is easier to do and with less impact if it is a smaller repository. Even if you eventually want to do it to all of your repositories, it will have less impact to do them one at a time, assuming there is not a pressing need to do them all at once.</li>\n<li>Global revision number. Even though this should not be an issue, some people perceive it to be one and do not like to see the revision number advance on the repository and for inactive projects to have large gaps in their revision history.</li>\n<li>Access control. While Subversion's authz mechanism allows you to restrict access as needed to parts of the repository, it is still easier to do this at the repository level. If you have a project that only a select few individuals should access, this is easier to do with a single repository for that project.</li>\n<li>Administrative flexibility. If you have multiple repositories, then it is easier to implement different hook scripts based on the needs of the repository/projects. If you want uniform hook scripts, then a single repository might be better, but if each project wants its own commit email style then it is easier to have those projects in separate repositories</li>\n</ol>\n</blockquote>\n<p>When you really think about, the revision numbers in a multiple project repository are going to get high, but you are not going to run out. Keep in mind that you can view a history on a sub directory and quickly see all the revision numbers that pertain to a project.</p>\n"
},
{
"answer_id": 337108,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 0,
"selected": false,
"text": "<p>The revision-numbers have no semantic use. The only thing is, that they are in sequential order. If you dump your project and import it in another repository, your versions can get new revision-numbers. So <strong>NEVER</strong> use the revision-numbers to mark your releases or similar stuff. Make tags for releases (copies of the relevant revision).</p>\n"
},
{
"answer_id": 339837,
"author": "Ronald Conco",
"author_id": 16092,
"author_profile": "https://Stackoverflow.com/users/16092",
"pm_score": 0,
"selected": false,
"text": "<p>Had the same problem in my previous company, They use to have like 50 projects running in one repository and it was a nightmare to work on the same projects because of when doing svn updates others would curse....lol...</p>\n\n<p>One thing I have learned that always works out best, One project One Repo....you will never regret it.</p>\n"
},
{
"answer_id": 11707035,
"author": "ShaunOfTheLive",
"author_id": 1169994,
"author_profile": "https://Stackoverflow.com/users/1169994",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe it's best not to necessarily make one repo per \"project\", but rather one repo per \"solution\" (to use Visual Studio terms). If you have a bunch of \"projects\" in different folders but they're related to each other, then put them in the same repo.</p>\n"
},
{
"answer_id": 16148221,
"author": "jjthomas3rd",
"author_id": 1964446,
"author_profile": "https://Stackoverflow.com/users/1964446",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>When you really think about, the revision numbers in a multiple\n project repository are going to get high, but you are not going to run\n out. Keep in mind that you can view a history on a sub directory and\n quickly see all the revision numbers that pertain to a project.</p>\n</blockquote>\n\n<p>Actually if your building Microsoft code, and you use the svn revision numbers as a part of your version string then you could run out. Microsoft compiler will throw an error if any part of the version string is greater than 65535.... In our case we have a massive repository at revision 68876 and we just hit this wall.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] | When using Subversion (svn) for source control with multiple projects I've noticed that the revision number increases across all of my projects' directories. To illustrate my svn layout (using fictitious project names):
```
/NinjaProg/branches
/tags
/trunk
/StealthApp/branches
/tags
/trunk
/SnailApp/branches
/tags
/trunk
```
When I perform a commit to the trunk of the Ninja Program, let's say I get that it has been updated to revision 7. The next day let's say that I make a small change to the Stealth Application and it comes back as revision 8.
The question is this: **Is it common accepted practice to, when maintaining multiple projects with one Subversion server, to have unrelated projects' revision number increase across all projects?** Or am I doing it wrong and should be creating individual repositories for each project? Or is it something else entirely?
**EDIT:** I delayed in flagging an answer because it had become clear that there are reasons for both approaches, and even though this question came first, I'd like to point to some other questions that are ultimately asking the same question:
[Should I store all projects in one repository or mulitiple?](https://stackoverflow.com/questions/130447/should-i-store-all-projects-in-one-repository-or-mulitiple)
[One SVN Repository or many?](https://stackoverflow.com/questions/252459/one-svn-repository-or-many) | I am surprised no has mentioned that this is discussed in Version Control with Subversion, which is available free online, [here](http://svnbook.red-bean.com/en/1.5/svn.reposadmin.planning.html).
I read up on the issue awhile back and it really seems like a matter of personal choice, there is a good blog post on the subject [here](http://blogs.open.collab.net/svn/2007/04/single_reposito.html). EDIT: *Since the blog appears to be down, ([archived version here](http://replay.web.archive.org/20090228154135/http://blogs.open.collab.net/svn/2007/04/single_reposito.html)), here is some of what Mark Phippard had to say on the subject.*
>
> These are some of the advantages of the single repository approach.
>
>
> 1. Simplified administration. One set of hooks to deploy. One repository to backup. etc.
> 2. Branch/tag flexibility. With the code all in one repository it makes it easier to create a branch or tag involving multiple projects.
> 3. Move code easily. Perhaps you want to take a section of code from one project and use it in another, or turn it into a library for several projects. It is easy to move the code within the same repository and retain the history of the code in the process.
>
>
> Here are some of the drawbacks to the single repository approach, advantages to the multiple repository approach.
>
>
> 1. Size. It might be easier to deal with many smaller repositories than one large one. For example, if you retire a project you can just archive the repository to media and remove it from the disk and free up the storage. Maybe you need to dump/load a repository for some reason, such as to take advantage of a new Subversion feature. This is easier to do and with less impact if it is a smaller repository. Even if you eventually want to do it to all of your repositories, it will have less impact to do them one at a time, assuming there is not a pressing need to do them all at once.
> 2. Global revision number. Even though this should not be an issue, some people perceive it to be one and do not like to see the revision number advance on the repository and for inactive projects to have large gaps in their revision history.
> 3. Access control. While Subversion's authz mechanism allows you to restrict access as needed to parts of the repository, it is still easier to do this at the repository level. If you have a project that only a select few individuals should access, this is easier to do with a single repository for that project.
> 4. Administrative flexibility. If you have multiple repositories, then it is easier to implement different hook scripts based on the needs of the repository/projects. If you want uniform hook scripts, then a single repository might be better, but if each project wants its own commit email style then it is easier to have those projects in separate repositories
>
>
>
When you really think about, the revision numbers in a multiple project repository are going to get high, but you are not going to run out. Keep in mind that you can view a history on a sub directory and quickly see all the revision numbers that pertain to a project. |
15,700 | <p>I'm looking for a way to configure a DB connection at runtime; specifically using the Enterprise Library. I see that there's a *.Data.Configuration (or something close to this ... don't recall off the top of my head) assembly but am finding not much on the interwebs. Complicating matters is the fact that the API help is broken on Vista.</p>
<p>Now, I found this work-around:</p>
<pre><code>Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connection = new ConnectionStringSettings();
connection.Name = "Runtime Connection";
connection.ProviderName = "System.Data.OleDb";
connection.ConnectionString = "myconstring";
cfg.ConnectionStrings.ConnectionStrings.Add(connection);
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
var runtimeCon = DatabaseFactory.CreateDatabase("Runtime Connection");
</code></pre>
<p>And although it gives me what I want, it permanently edits the App.config. Sure I can go back and delete the changes, but I'd rather not go through this hassle.</p>
| [
{
"answer_id": 15704,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using a winforms app you could try using <a href=\"http://msdn.microsoft.com/en-us/library/aa221771(office.11).aspx\" rel=\"nofollow noreferrer\">UserProperties</a> to store this info. Another possible solution could be <a href=\"http://msdn.microsoft.com/en-us/library/2tw134k3.aspx\" rel=\"nofollow noreferrer\">custom configuration sections</a>.</p>\n"
},
{
"answer_id": 15714,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't want it saved, you do not need to execute the cfg.Save command. </p>\n\n<p>The Configuration object will store your changes until it isn't needed anymore.</p>\n"
},
{
"answer_id": 16372,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 0,
"selected": false,
"text": "<p>Nope, you must save in order for the EntLib (and, I suspect, any other tool) to see the changes.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1886/"
] | I'm looking for a way to configure a DB connection at runtime; specifically using the Enterprise Library. I see that there's a \*.Data.Configuration (or something close to this ... don't recall off the top of my head) assembly but am finding not much on the interwebs. Complicating matters is the fact that the API help is broken on Vista.
Now, I found this work-around:
```
Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringSettings connection = new ConnectionStringSettings();
connection.Name = "Runtime Connection";
connection.ProviderName = "System.Data.OleDb";
connection.ConnectionString = "myconstring";
cfg.ConnectionStrings.ConnectionStrings.Add(connection);
cfg.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
var runtimeCon = DatabaseFactory.CreateDatabase("Runtime Connection");
```
And although it gives me what I want, it permanently edits the App.config. Sure I can go back and delete the changes, but I'd rather not go through this hassle. | If you're using a winforms app you could try using [UserProperties](http://msdn.microsoft.com/en-us/library/aa221771(office.11).aspx) to store this info. Another possible solution could be [custom configuration sections](http://msdn.microsoft.com/en-us/library/2tw134k3.aspx). |
15,709 | <p>So for my text parsing in C# <a href="https://stackoverflow.com/questions/13963/best-method-of-textfile-parsing-in-c">question</a>, I got directed at YAML. I'm hitting a wall with this library I was recommended, so this is a quickie.</p>
<pre><code>heading:
name: A name
taco: Yes
age: 32
heading:
name: Another name
taco: No
age: 27
</code></pre>
<p>And so on. Is that valid?</p>
| [
{
"answer_id": 15723,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 2,
"selected": false,
"text": "<p>There appears to be a YAML validator called <a href=\"http://www.kuwata-lab.com/kwalify/\" rel=\"nofollow noreferrer\">Kwalify</a> which should give you the answer. You shoulda just gone with the String tokenizing, man. Writing parsers is fun :)</p>\n"
},
{
"answer_id": 15726,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 4,
"selected": false,
"text": "<p>Partially. YAML supports the notion of multiple consecutive \"documents\". If this is what you are trying to do here, then yes, it is correct - you have two documents (or document fragments). To make it more explicit, you should separate them with three dashes, like this:</p>\n\n<pre><code>---\nheading:\n name: A name\n taco: Yes\n age: 32\n---\nheading:\n name: Another name\n taco: No\n age: 27\n</code></pre>\n\n<p>On the other hand if you wish to make them part of the same document (so that deserializing them would result in a list with two elements), you should write it like the following. Take extra care with the indentation level:</p>\n\n<pre><code>- heading:\n name: A name\n taco: Yes\n age: 32\n- heading:\n name: Another name\n taco: No\n age: 27\n</code></pre>\n\n<p>In general YAML is concise and human readable / editable, but not really human writable, so you should always use libraries to generate it. Also, take care that there exists some breaking changes between different versions of YAML, which can bite you if you are using libraries in different languages which conform to different versions of the standard.</p>\n"
},
{
"answer_id": 15742,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 2,
"selected": false,
"text": "<p>Well, it appears YAML is gone out the window then. I want something both human writable <em>and</em> readable. Plus, this C# implementation...I have no idea <em>if</em> it's working or not, the documentation consists of a few one line code examples. It barfs on their own YAML files, and is an old student project. The only other C# YAML parser I've found uses the MS-PL which I'm not really comfortable using.</p>\n\n<p>I might just end up rolling my own format. Best practices be damned, all I want to do is associate a key with a value. </p>\n"
},
{
"answer_id": 29200,
"author": "Antoine Aubry",
"author_id": 2680,
"author_profile": "https://Stackoverflow.com/users/2680",
"pm_score": 2,
"selected": false,
"text": "<p>There is <a href=\"http://yamldotnet.wiki.sourceforge.net/\" rel=\"nofollow noreferrer\">another YAML library for .NET</a> which is under development. Right now it supports reading YAML streams. It has been tested on Windows and Mono. Write support is currently being implemented.</p>\n"
},
{
"answer_id": 361574,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>CodeProject has one at:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/recipes/yamlparser.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/recipes/yamlparser.aspx</a></p>\n\n<p>I haven't tried it too much, but it's worth a look.</p>\n"
},
{
"answer_id": 1298847,
"author": "Paul Tarjan",
"author_id": 90025,
"author_profile": "https://Stackoverflow.com/users/90025",
"pm_score": 1,
"selected": false,
"text": "<p>You can see the output in the online yaml parser :</p>\n\n<p><a href=\"http://yaml-online-parser.appspot.com/?yaml=heading%3A%0D%0A+name%3A+A+name%0D%0A+taco%3A+Yes%0D%0A+age%3A+32%0D%0A%0D%0Aheading%3A%0D%0A+name%3A+Another+name%0D%0A+taco%3A+No%0D%0A+age%3A+27%0D%0A&type=json\" rel=\"nofollow noreferrer\">http://yaml-online-parser.appspot.com/?yaml=heading%3A%0D%0A+name%3A+A+name%0D%0A+taco%3A+Yes%0D%0A+age%3A+32%0D%0A%0D%0Aheading%3A%0D%0A+name%3A+Another+name%0D%0A+taco%3A+No%0D%0A+age%3A+27%0D%0A&type=json</a></p>\n\n<p>As you can see, there is only one heading node created.</p>\n"
},
{
"answer_id": 5098143,
"author": "SeniorLee",
"author_id": 197018,
"author_profile": "https://Stackoverflow.com/users/197018",
"pm_score": 2,
"selected": false,
"text": "<p>Try <a href=\"http://yaml-online-parser.appspot.com/\" rel=\"nofollow\">this(Online YAML parser)</a>.</p>\n\n<p>You don't have to download anything or do something. Just go there, and copy & paste. That's it.</p>\n"
},
{
"answer_id": 18981813,
"author": "MrBackend",
"author_id": 2791256,
"author_profile": "https://Stackoverflow.com/users/2791256",
"pm_score": 0,
"selected": false,
"text": "<p>Just to make an explicit comment about it: You have a duplicate mapping key issue. A YAML processor will resolve this as a !!map, which prohibits duplicate keys. Not all processors enforce this constraint, though, so you might get an incorrect result if you pass an incorrect YAML stream to a processor.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So for my text parsing in C# [question](https://stackoverflow.com/questions/13963/best-method-of-textfile-parsing-in-c), I got directed at YAML. I'm hitting a wall with this library I was recommended, so this is a quickie.
```
heading:
name: A name
taco: Yes
age: 32
heading:
name: Another name
taco: No
age: 27
```
And so on. Is that valid? | Partially. YAML supports the notion of multiple consecutive "documents". If this is what you are trying to do here, then yes, it is correct - you have two documents (or document fragments). To make it more explicit, you should separate them with three dashes, like this:
```
---
heading:
name: A name
taco: Yes
age: 32
---
heading:
name: Another name
taco: No
age: 27
```
On the other hand if you wish to make them part of the same document (so that deserializing them would result in a list with two elements), you should write it like the following. Take extra care with the indentation level:
```
- heading:
name: A name
taco: Yes
age: 32
- heading:
name: Another name
taco: No
age: 27
```
In general YAML is concise and human readable / editable, but not really human writable, so you should always use libraries to generate it. Also, take care that there exists some breaking changes between different versions of YAML, which can bite you if you are using libraries in different languages which conform to different versions of the standard. |
15,716 | <p>I have created a UserControl that has a <code>ListView</code> in it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the <code>ListView</code> though the property, the <code>ListView</code> stays that way until I compile again and it reverts back to the default state. </p>
<p>How do I get my design changes to stick for the <code>ListView</code>?</p>
| [
{
"answer_id": 15717,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Just so I'm clear, you've done something like this, right?</p>\n\n<pre><code>public ListView MyListView { get { return this.listView1; } }\n</code></pre>\n\n<p>So then you are accessing (at design time) the MyListView property on your UserControl?</p>\n\n<p>I think if you want proper design-time support you're better off changing the \"Modifier\" property on the ListView itself (back on the original UserControl) to Public - that way you can modify the ListView directly on instances of the UserControl. I've had success doing that anyway.</p>\n"
},
{
"answer_id": 15803,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 4,
"selected": true,
"text": "<p>You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so:</p>\n\n<pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic ListView MyListView { get { return this.listView1; } }\n</code></pre>\n\n<p>This tells the designer's code generator to output code for it.</p>\n"
},
{
"answer_id": 15832,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/15716/design-problems-with-net-usercontrol#15803\">Fredrik</a> is right, basically, when you need to enable the designer to persist the property to page so it can be instantiated at run time. There is only one way to do this, and that is to write its values to the ASPX page, which is then picked up by the runtime.</p>\n\n<p>Otherwise, the control will simply revert to its default state each and every time.</p>\n\n<p>Always keep in the back of your mind that the Page (and its contents) and the code are completely seperate in ASP.NET, they are hooked up at run time. This means that you dont get the nice code-behind designer support like you do in a WinForms app (where the form is an instance of an object).</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788/"
] | I have created a UserControl that has a `ListView` in it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the `ListView` though the property, the `ListView` stays that way until I compile again and it reverts back to the default state.
How do I get my design changes to stick for the `ListView`? | You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so:
```
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ListView MyListView { get { return this.listView1; } }
```
This tells the designer's code generator to output code for it. |
15,729 | <p>As I browse through the site, I find a lot of terms that many developers just starting out (and even some advanced developers) may be unfamiliar with.</p>
<p>It would be great if people could post here with a term and definition that might be unknown to beginners or those from different programming backgrounds. </p>
<p>Some not-so-common terms I've seen are 'auto boxing', 'tuples', 'orthogonal code', 'domain driven design', 'test driven development', etc.</p>
<p>Code snippets would also be helpful where applicable..</p>
| [
{
"answer_id": 15717,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "<p>Just so I'm clear, you've done something like this, right?</p>\n\n<pre><code>public ListView MyListView { get { return this.listView1; } }\n</code></pre>\n\n<p>So then you are accessing (at design time) the MyListView property on your UserControl?</p>\n\n<p>I think if you want proper design-time support you're better off changing the \"Modifier\" property on the ListView itself (back on the original UserControl) to Public - that way you can modify the ListView directly on instances of the UserControl. I've had success doing that anyway.</p>\n"
},
{
"answer_id": 15803,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 4,
"selected": true,
"text": "<p>You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so:</p>\n\n<pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic ListView MyListView { get { return this.listView1; } }\n</code></pre>\n\n<p>This tells the designer's code generator to output code for it.</p>\n"
},
{
"answer_id": 15832,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/15716/design-problems-with-net-usercontrol#15803\">Fredrik</a> is right, basically, when you need to enable the designer to persist the property to page so it can be instantiated at run time. There is only one way to do this, and that is to write its values to the ASPX page, which is then picked up by the runtime.</p>\n\n<p>Otherwise, the control will simply revert to its default state each and every time.</p>\n\n<p>Always keep in the back of your mind that the Page (and its contents) and the code are completely seperate in ASP.NET, they are hooked up at run time. This means that you dont get the nice code-behind designer support like you do in a WinForms app (where the form is an instance of an object).</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] | As I browse through the site, I find a lot of terms that many developers just starting out (and even some advanced developers) may be unfamiliar with.
It would be great if people could post here with a term and definition that might be unknown to beginners or those from different programming backgrounds.
Some not-so-common terms I've seen are 'auto boxing', 'tuples', 'orthogonal code', 'domain driven design', 'test driven development', etc.
Code snippets would also be helpful where applicable.. | You need to decorate the ListView property with the DesignerSerializationVisibility attribute, like so:
```
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public ListView MyListView { get { return this.listView1; } }
```
This tells the designer's code generator to output code for it. |
15,732 | <p>I'm generating some xml files that needs to conform to an xsd file that was given to me. How should I verify they conform?</p>
| [
{
"answer_id": 15739,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 5,
"selected": false,
"text": "<p>Here's how to do it using <a href=\"http://xerces.apache.org/xerces2-j/\" rel=\"noreferrer\">Xerces2</a>. A tutorial for this, <a href=\"http://www.ibm.com/developerworks/edu/x-dw-xvalid-i.html\" rel=\"noreferrer\">here</a> (req. signup).</p>\n\n<p>Original attribution: blatantly copied from <a href=\"http://forums.sun.com/thread.jspa?messageID=3411478\" rel=\"noreferrer\">here</a>:</p>\n\n<pre><code>import org.apache.xerces.parsers.DOMParser;\nimport java.io.File;\nimport org.w3c.dom.Document;\n\npublic class SchemaTest {\n public static void main (String args[]) {\n File docFile = new File(\"memory.xml\");\n try {\n DOMParser parser = new DOMParser();\n parser.setFeature(\"http://xml.org/sax/features/validation\", true);\n parser.setProperty(\n \"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation\", \n \"memory.xsd\");\n ErrorChecker errors = new ErrorChecker();\n parser.setErrorHandler(errors);\n parser.parse(\"memory.xml\");\n } catch (Exception e) {\n System.out.print(\"Problem parsing the file.\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 15741,
"author": "Adam",
"author_id": 1366,
"author_profile": "https://Stackoverflow.com/users/1366",
"pm_score": 0,
"selected": false,
"text": "<p>Are you looking for a tool or a library?</p>\n\n<p>As far as libraries goes, pretty much the de-facto standard is <a href=\"http://xerces.apache.org\" rel=\"nofollow noreferrer\">Xerces2</a> which has both <a href=\"http://xerces.apache.org/xerces-c/\" rel=\"nofollow noreferrer\">C++</a> and <a href=\"http://xerces.apache.org/xerces2-j/\" rel=\"nofollow noreferrer\">Java</a> versions.</p>\n\n<p>Be fore warned though, it is a heavy weight solution. But then again, validating XML against XSD files is a rather heavy weight problem.</p>\n\n<p>As for a tool to do this for you, <a href=\"http://www.xmlfox.com/xml_editor.htm\" rel=\"nofollow noreferrer\">XMLFox</a> seems to be a decent freeware solution, but not having used it personally I can't say for sure.</p>\n"
},
{
"answer_id": 16054,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 9,
"selected": true,
"text": "<p>The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/Validator.html\" rel=\"noreferrer\">javax.xml.validation.Validator</a>.</p>\n\n<pre><code>import javax.xml.XMLConstants;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.*;\nimport java.net.URL;\nimport org.xml.sax.SAXException;\n//import java.io.File; // if you use File\nimport java.io.IOException;\n...\nURL schemaFile = new URL(\"http://host:port/filename.xsd\");\n// webapp example xsd: \n// URL schemaFile = new URL(\"http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\");\n// local file example:\n// File schemaFile = new File(\"/location/to/localfile.xsd\"); // etc.\nSource xmlFile = new StreamSource(new File(\"web.xml\"));\nSchemaFactory schemaFactory = SchemaFactory\n .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\ntry {\n Schema schema = schemaFactory.newSchema(schemaFile);\n Validator validator = schema.newValidator();\n validator.validate(xmlFile);\n System.out.println(xmlFile.getSystemId() + \" is valid\");\n} catch (SAXException e) {\n System.out.println(xmlFile.getSystemId() + \" is NOT valid reason:\" + e);\n} catch (IOException e) {}\n</code></pre>\n\n<p>The schema factory constant is the string <code>http://www.w3.org/2001/XMLSchema</code> which defines XSDs. The above code validates a WAR deployment descriptor against the URL <code>http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd</code> but you could just as easily validate against a local file.</p>\n\n<p>You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.</p>\n"
},
{
"answer_id": 158781,
"author": "KnomDeGuerre",
"author_id": 24233,
"author_profile": "https://Stackoverflow.com/users/24233",
"pm_score": -1,
"selected": false,
"text": "<p>I had to validate an XML against XSD just one time, so I tried XMLFox. I found it to be very confusing and weird. The help instructions didn't seem to match the interface.</p>\n\n<p>I ended up using LiquidXML Studio 2008 (v6) which was much easier to use and more immediately familiar (the UI is very similar to Visual Basic 2008 Express, which I use frequently). The drawback: the validation capability is not in the free version, so I had to use the 30 day trial.</p>\n"
},
{
"answer_id": 488685,
"author": "Todd",
"author_id": 53036,
"author_profile": "https://Stackoverflow.com/users/53036",
"pm_score": 2,
"selected": false,
"text": "<p>If you are generating XML files programatically, you may want to look at the <a href=\"http://xmlbeans.apache.org/\" rel=\"nofollow noreferrer\">XMLBeans </a>library. Using a command line tool, XMLBeans will automatically generate and package up a set of Java objects based on an XSD. You can then use these objects to build an XML document based on this schema.</p>\n\n<p>It has built-in support for schema validation, and can convert Java objects to an XML document and vice-versa.</p>\n\n<p><a href=\"http://www.castor.org/\" rel=\"nofollow noreferrer\">Castor</a> and <a href=\"http://java.sun.com/developer/technicalArticles/WebServices/jaxb/\" rel=\"nofollow noreferrer\">JAXB</a> are other Java libraries that serve a similar purpose to XMLBeans.</p>\n"
},
{
"answer_id": 690450,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 2,
"selected": false,
"text": "<p>One more answer: since you said you need to validate files you are <strong>generating</strong> (writing), you might want to validate content while you are writing, instead of first writing, then reading back for validation. You can probably do that with JDK API for Xml validation, if you use SAX-based writer: if so, just link in validator by calling 'Validator.validate(source, result)', where source comes from your writer, and result is where output needs to go.</p>\n\n<p>Alternatively if you use Stax for writing content (or a library that uses or can use stax), <a href=\"https://github.com/FasterXML/woodstox\" rel=\"nofollow noreferrer\">Woodstox</a> can also directly support validation when using XMLStreamWriter. Here's a <a href=\"http://www.cowtowncoder.com/blog/archives/2006/08/entry_17.html\" rel=\"nofollow noreferrer\">blog entry</a> showing how that is done:</p>\n"
},
{
"answer_id": 6690151,
"author": "chickeninabiscuit",
"author_id": 3966,
"author_profile": "https://Stackoverflow.com/users/3966",
"pm_score": 4,
"selected": false,
"text": "<p>We build our project using ant, so we can use the schemavalidate task to check our config files:</p>\n\n<pre><code><schemavalidate> \n <fileset dir=\"${configdir}\" includes=\"**/*.xml\" />\n</schemavalidate>\n</code></pre>\n\n<p>Now naughty config files will fail our build!</p>\n\n<p><a href=\"http://ant.apache.org/manual/Tasks/schemavalidate.html\" rel=\"noreferrer\">http://ant.apache.org/manual/Tasks/schemavalidate.html</a></p>\n"
},
{
"answer_id": 9826988,
"author": "juwens",
"author_id": 534812,
"author_profile": "https://Stackoverflow.com/users/534812",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a Linux-Machine you could use the free command-line tool SAXCount. I found this very usefull.</p>\n\n<pre><code>SAXCount -f -s -n my.xml\n</code></pre>\n\n<p>It validates against dtd and xsd.\n5s for a 50MB file.</p>\n\n<p>In debian squeeze it is located in the package \"libxerces-c-samples\".</p>\n\n<p>The definition of the dtd and xsd has to be in the xml! You can't config them separately.</p>\n"
},
{
"answer_id": 16518985,
"author": "Paulo Fidalgo",
"author_id": 1006863,
"author_profile": "https://Stackoverflow.com/users/1006863",
"pm_score": 3,
"selected": false,
"text": "<p>Using Java 7 you can follow the documentation provided in <a href=\"http://docs.oracle.com/javase/7/docs/api/javax/xml/validation/package-summary.html\" rel=\"nofollow noreferrer\">package description</a>.</p>\n<blockquote>\n<pre><code>// create a SchemaFactory capable of understanding WXS schemas\nSchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n\n// load a WXS schema, represented by a Schema instance\nSource schemaFile = new StreamSource(new File("mySchema.xsd"));\nSchema schema = factory.newSchema(schemaFile);\n\n// create a Validator instance, which can be used to validate an instance document\nValidator validator = schema.newValidator();\n\n// validate the DOM tree\ntry {\n validator.validate(new StreamSource(new File("instance.xml"));\n} catch (SAXException e) {\n // instance document is invalid!\n}\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 41225329,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 4,
"selected": false,
"text": "<p>Since this is a popular question, I will point out that java can also validate against "referred to" xsd's, for instance if the .xml file itself specifies XSD's in the header, using <code>xsi:schemaLocation</code> or <code>xsi:noNamespaceSchemaLocation</code> (or xsi for particular namespaces) <a href=\"http://www.ibm.com/developerworks/xml/library/x-javaxmlvalidapi/index.html\" rel=\"nofollow noreferrer\">ex</a>:</p>\n<pre><code><document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n xsi:noNamespaceSchemaLocation="http://www.example.com/document.xsd">\n ...\n</code></pre>\n<p>or schemaLocation (always a list of namespace to xsd mappings)</p>\n<pre><code><document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n xsi:schemaLocation="http://www.example.com/my_namespace http://www.example.com/document.xsd">\n ...\n</code></pre>\n<p>The other answers work here as well, because the .xsd files "map" to the namespaces declared in the .xml file, because they declare a namespace, and if matches up with the namespace in the .xml file, you're good. But sometimes it's convenient to be able to have a custom <a href=\"https://stackoverflow.com/a/2342859/32453\">resolver</a>...</p>\n<p>From the javadocs: "If you create a schema without specifying a URL, file, or source, then the Java language creates one that looks in the document being validated to find the schema it should use. For example:"</p>\n<pre><code>SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");\nSchema schema = factory.newSchema();\n</code></pre>\n<p>and this works for multiple namespaces, etc.\nThe problem with this approach is that the <code>xmlsns:xsi</code> is probably a network location, so it'll by default go out and hit the network with each and every validation, not always optimal.</p>\n<p>Here's an example that validates an XML file against any XSD's it references (even if it has to pull them from the network):</p>\n<pre><code> public static void verifyValidatesInternalXsd(String filename) throws Exception {\n InputStream xmlStream = new new FileInputStream(filename);\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setValidating(true);\n factory.setNamespaceAware(true);\n factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",\n "http://www.w3.org/2001/XMLSchema");\n DocumentBuilder builder = factory.newDocumentBuilder();\n builder.setErrorHandler(new RaiseOnErrorHandler());\n builder.parse(new InputSource(xmlStream));\n xmlStream.close();\n }\n\n public static class RaiseOnErrorHandler implements ErrorHandler {\n public void warning(SAXParseException e) throws SAXException {\n throw new RuntimeException(e);\n }\n public void error(SAXParseException e) throws SAXException {\n throw new RuntimeException(e);\n }\n public void fatalError(SAXParseException e) throws SAXException {\n throw new RuntimeException(e);\n }\n }\n</code></pre>\n<p>You can avoid pulling referenced XSD's from the network, even though the xml files reference url's, by specifying the xsd manually (see some other answers here) or by using an "XML catalog" <a href=\"https://stackoverflow.com/q/25698764/32453\">style resolver</a>. Spring apparently also <a href=\"https://stackoverflow.com/a/10768972/32453\">can intercept</a> the URL requests to serve local files for validations. Or you can set your own via <a href=\"https://docs.oracle.com/javase/7/docs/api/javax/xml/validation/SchemaFactory.html#setResourceResolver(org.w3c.dom.ls.LSResourceResolver)\" rel=\"nofollow noreferrer\">setResourceResolver</a>, ex:</p>\n<pre><code>Source xmlFile = new StreamSource(xmlFileLocation);\nSchemaFactory schemaFactory = SchemaFactory\n .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\nSchema schema = schemaFactory.newSchema();\nValidator validator = schema.newValidator();\nvalidator.setResourceResolver(new LSResourceResolver() {\n @Override\n public LSInput resolveResource(String type, String namespaceURI,\n String publicId, String systemId, String baseURI) {\n InputSource is = new InputSource(\n getClass().getResourceAsStream(\n "some_local_file_in_the_jar.xsd"));\n // or lookup by URI, etc...\n return new Input(is); // for class Input see \n // https://stackoverflow.com/a/2342859/32453\n }\n});\nvalidator.validate(xmlFile);\n</code></pre>\n<p>See also <a href=\"https://docs.oracle.com/javase/tutorial/jaxp/dom/validating.html\" rel=\"nofollow noreferrer\">here</a> for another tutorial.</p>\n<p>I believe the default is to use DOM parsing, you can do something similar with SAX parser that is validating <a href=\"https://blog.frankel.ch/use-local-resources-when-validating-xml/\" rel=\"nofollow noreferrer\">as well</a> <code>saxReader.setEntityResolver(your_resolver_here);</code></p>\n"
},
{
"answer_id": 47514401,
"author": "razvanone",
"author_id": 2148681,
"author_profile": "https://Stackoverflow.com/users/2148681",
"pm_score": 2,
"selected": false,
"text": "<p>With JAXB, you could use the code below:</p>\n\n<pre><code> @Test\npublic void testCheckXmlIsValidAgainstSchema() {\n logger.info(\"Validating an XML file against the latest schema...\");\n\n MyValidationEventCollector vec = new MyValidationEventCollector();\n\n validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);\n\n assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));\n}\n\nprivate void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class<?> rootClass) {\n try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {\n final JAXBContext jContext = JAXBContext.newInstance(rootClass);\n // Unmarshal the data from InputStream\n final Unmarshaller unmarshaller = jContext.createUnmarshaller();\n\n final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);\n unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));\n\n unmarshaller.setEventHandler(vec);\n\n unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate\n\n for (String validationError : vec.getValidationErrors()) {\n logger.trace(validationError);\n }\n } catch (final Exception e) {\n logger.error(\"The validation of the XML file \" + xmlFileName + \" failed: \", e);\n }\n}\n\nclass MyValidationEventCollector implements ValidationEventHandler {\n private final List<String> validationErrors;\n\n public MyValidationEventCollector() {\n validationErrors = new ArrayList<>();\n }\n\n public List<String> getValidationErrors() {\n return Collections.unmodifiableList(validationErrors);\n }\n\n @Override\n public boolean handleEvent(final ValidationEvent event) {\n String pattern = \"line {0}, column {1}, error message {2}\";\n String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),\n event.getMessage());\n if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {\n validationErrors.add(errorMessage);\n }\n return true; // you collect the validation errors in a List and handle them later\n }\n}\n</code></pre>\n"
},
{
"answer_id": 52645727,
"author": "jschnasse",
"author_id": 1485527,
"author_profile": "https://Stackoverflow.com/users/1485527",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Validate against online schemas</strong></p>\n\n<pre><code>Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(\"your.xml\"));\nSchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\nSchema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource(\"your.xsd\"));\nValidator validator = schema.newValidator();\nvalidator.validate(xmlFile);\n</code></pre>\n\n<p><strong>Validate against local schemas</strong></p>\n\n<p><a href=\"https://stackoverflow.com/a/48447453/1485527\">Offline XML Validation with Java</a></p>\n"
},
{
"answer_id": 58040690,
"author": "Loris Securo",
"author_id": 6245535,
"author_profile": "https://Stackoverflow.com/users/6245535",
"pm_score": 1,
"selected": false,
"text": "<p>Using <a href=\"https://github.com/FasterXML/woodstox\" rel=\"nofollow noreferrer\">Woodstox</a>, configure the StAX parser to validate against your schema and parse the XML.</p>\n\n<p>If exceptions are caught the XML is not valid, otherwise it is valid:</p>\n\n<pre><code>// create the XSD schema from your schema file\nXMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);\nXMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);\n\n// create the XML reader for your XML file\nWstxInputFactory inputFactory = new WstxInputFactory();\nXMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);\n\ntry {\n // configure the reader to validate against the schema\n xmlReader.validateAgainst(validationSchema);\n\n // parse the XML\n while (xmlReader.hasNext()) {\n xmlReader.next();\n }\n\n // no exceptions, the XML is valid\n\n} catch (XMLStreamException e) {\n\n // exceptions, the XML is not valid\n\n} finally {\n xmlReader.close();\n}\n</code></pre>\n\n<p><strong>Note</strong>: If you need to validate multiple files, you should try to reuse your <code>XMLInputFactory</code> and <code>XMLValidationSchema</code> in order to maximize the performance.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1650/"
] | I'm generating some xml files that needs to conform to an xsd file that was given to me. How should I verify they conform? | The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a [javax.xml.validation.Validator](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/validation/Validator.html).
```
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd:
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
Schema schema = schemaFactory.newSchema(schemaFile);
Validator validator = schema.newValidator();
validator.validate(xmlFile);
System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}
```
The schema factory constant is the string `http://www.w3.org/2001/XMLSchema` which defines XSDs. The above code validates a WAR deployment descriptor against the URL `http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd` but you could just as easily validate against a local file.
You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them. |
15,744 | <p>I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation?</p>
<blockquote>
<p>Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGme as a custom symbol, the only way to exclude it from compile is to remove this #define statement?</p>
</blockquote>
| [
{
"answer_id": 15749,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 1,
"selected": false,
"text": "<p>Well, defines are used often for compile time constants and macros. This can make your code a bit faster as there are really no function calls, the output values of the macros are determined at compile time. The #if's are very useful. The most simple example that I can think of is checking for a debug build to add in some extra logging or messaging, maybe even some debugging functions. You can also check different environment variables this way.</p>\n\n<p>Others with more C/C++ experience can add more I am sure.</p>\n"
},
{
"answer_id": 15757,
"author": "HS.",
"author_id": 1398,
"author_profile": "https://Stackoverflow.com/users/1398",
"pm_score": 1,
"selected": false,
"text": "<p>I often find myself defining some things that are done repetitively in certain functions. That makes the code much shorter and thus allows a better overview.</p>\n\n<p>But as always, try to find a good measure to not create a new language out of it. Might be a little hard to read for the occasional maintenance later on.</p>\n"
},
{
"answer_id": 15758,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 5,
"selected": true,
"text": "<p>In C# <code>#define</code> macros, like some of Bernard's examples, are not allowed. The only common use of <code>#define</code>/<code>#if</code>s in C# is for adding optional debug only code. For example:</p>\n\n<pre><code> static void Main(string[] args)\n {\n#if DEBUG\n //this only compiles if in DEBUG\n Console.WriteLine(\"DEBUG\")\n#endif \n#if !DEBUG\n //this only compiles if not in DEBUG\n Console.WriteLine(\"RELEASE\")\n#endif\n //This always compiles\n Console.ReadLine()\n }\n</code></pre>\n"
},
{
"answer_id": 15761,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<p>#define is used to define compile-time constants that you can use with #if to include or exclude bits of code.</p>\n\n<pre><code>#define USEFOREACH\n\n#if USEFOREACH\n foreach(var item in items)\n { \n#else\n for(int i=0; i < items.Length; ++i)\n { var item = items[i]; //take item\n#endif\n\n doSomethingWithItem(item);\n }\n</code></pre>\n"
},
{
"answer_id": 15767,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 0,
"selected": false,
"text": "<p>@Ed: When using C++, there is rarely any benefit for using #define over inline functions when creating macros. The idea of \"greater speed\" is a misconception. With inline functions you get the same speed, but you also get type safey, and no side-effects of preprocessor \"pasting\" due to the fact that parameters are evaluated before the function is called (for an example, try writing the ubiquitous MAX macro, and call it like this: MAX(x++, y).. you'll see what I'm getting at).</p>\n\n<p>I have never had to use #define in my C#, and I very rarely use it for anything other that platform and compiler version checking for conditional compilation in C++.</p>\n"
},
{
"answer_id": 15778,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Is #define the only thing that\n determines if the code is included\n when compiled? If I have #define\n DEBUGme as a custom symbol, the only\n way to exclude it from compile is to\n remove this #define statement?</p>\n</blockquote>\n\n<p>You can <a href=\"http://msdn.microsoft.com/en-us/library/wkxst87d(VS.80).aspx\" rel=\"nofollow noreferrer\">undefine</a> symbols as well</p>\n\n<pre><code>#if defined(DEBUG)\n#undef DEBUG\n#endif\n</code></pre>\n"
},
{
"answer_id": 15994,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps the most common usees of #define in C# is to differentiate between debug/release and different platforms (for example Windows and X-Box 360 in the XNA framework).</p>\n"
},
{
"answer_id": 16016,
"author": "Ali Parr",
"author_id": 1169,
"author_profile": "https://Stackoverflow.com/users/1169",
"pm_score": 1,
"selected": false,
"text": "<p>It's for conditional compilation, so you can include or remove bits of code based upon project attributes which tend to be:</p>\n\n<ul>\n<li>Intended platform (Windows/Linux/XB360/PS3/Iphone.... etc)</li>\n<li>Release or Debug (Generally logging, asserts etc are only included in a debug build)</li>\n</ul>\n\n<p>They can also be used to disable large parts of a system quickly,\nfor example, during development of a game, I might define </p>\n\n<pre><code>#define PLAYSOUNDS\n</code></pre>\n\n<p>and then wrap the final call to play a sound in:</p>\n\n<pre><code>#ifdef PLAYSOUNDS\n// Do lots of funk to play a sound\nreturn true;\n#else\nreturn true;\n</code></pre>\n\n<p>So it's very easy for me to turn on and off the playing of sounds for a build. (Typically I don't play sounds when debugging because it gets in the way of my personal music :) )\nThe benefit is that you're not introducing a branch through adding an if statement....</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888/"
] | I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation?
>
> Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGme as a custom symbol, the only way to exclude it from compile is to remove this #define statement?
>
>
> | In C# `#define` macros, like some of Bernard's examples, are not allowed. The only common use of `#define`/`#if`s in C# is for adding optional debug only code. For example:
```
static void Main(string[] args)
{
#if DEBUG
//this only compiles if in DEBUG
Console.WriteLine("DEBUG")
#endif
#if !DEBUG
//this only compiles if not in DEBUG
Console.WriteLine("RELEASE")
#endif
//This always compiles
Console.ReadLine()
}
``` |
15,774 | <p>I run an ASP.NET website solution with a few other projects in it. I've known that MSBuild projects are capable of this, but is it the best way? Are they easy to create? Is nAnt, CruiseControl.NET or any other solution better?</p>
<p>When I build the site (using <a href="http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx" rel="nofollow noreferrer">Web Deployment Projects</a>), can I automate part of the build so that it does not copy certain folders from the project into the Release folder? For instance, I have folders with local search indexes, images and other content part of the folder, but I never need or upload those when deploying the project. </p>
<p>I'm also looking toward this type of solution to automatically increment build and version numbers.</p>
| [
{
"answer_id": 15780,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 1,
"selected": false,
"text": "<p>CruiseControl.NET solves a different problem (continuous integration) ... however, I've had great success with NAnt for specifically what you're asking. There's a learning curve, but once you get proficient you'll wonder how you ever got along w/o it.</p>\n"
},
{
"answer_id": 15810,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 2,
"selected": false,
"text": "<p>You can set the Build Action/Copy to Output Directory property on individual files (select the file and hit F4 to open the properties window) to control what happens to them during build, but not for folders. This could probably be automated with a (pre) build task if you don't want to do it manually.</p>\n\n<p>Alternatively, you can exclude these folders from the project (right click and 'exclude from project'); they'll still be there (\"show all files\" in solution explorer), but they won't be included when building the project.</p>\n"
},
{
"answer_id": 15892,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to @Fredrik's tip about setting project items to \"Copy to Output Directory\", you can also specify a post-build action in the project's properties in the Build tab and include CMD commands like copy.exe and move.exe.</p>\n"
},
{
"answer_id": 16809,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 1,
"selected": false,
"text": "<p>We use FinalBuilder to automate a bunch of post build / pre build tasks. There's also a web interface so you can kick off builds (or push websites) by logging in to the web site and clicking a button.</p>\n\n<p><a href=\"http://www.finalbuilder.com/\" rel=\"nofollow noreferrer\">http://www.finalbuilder.com/</a></p>\n"
},
{
"answer_id": 16813,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<p>Can't you edit the Web Deployment project's MSBuild file for it to do what you want?</p>\n"
},
{
"answer_id": 32861,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 2,
"selected": false,
"text": "<p>MaseBase, you can use <a href=\"http://weblogs.asp.net/scottgu/archive/2005/11/06/429723.aspx\" rel=\"nofollow noreferrer\">Web Deployment Projects</a> to build and package Web Sites. We do that all the time for projects with a web application aspect. After you assign a WDP to a Web Site, you can open up the <strong>.wdproj</strong> file as plain-text XML file. At the end is a commented section of MSBuild targets that represent the sequence of events that fire during a build process.</p>\n\n<pre><code><!-- To modify your build process, add your task inside one of the targets below and uncomment it. \nOther similar extension points exist, see Microsoft.WebDeployment.targets.\n<Target Name=\"BeforeBuild\">\n</Target>\n<Target Name=\"BeforeMerge\">\n</Target>\n<Target Name=\"AfterMerge\">\n</Target>\n<Target Name=\"AfterBuild\">\n</Target>\n-->\n</code></pre>\n\n<p>You can uncomment the targets you want (e.g. \"AfterBuild\") and insert the necessary tasks there to carry out your repeated post-build activities.</p>\n"
},
{
"answer_id": 157767,
"author": "Chris",
"author_id": 40352,
"author_profile": "https://Stackoverflow.com/users/40352",
"pm_score": 4,
"selected": true,
"text": "<p>Here's an example of a Web Deployment Project scripting this sort of task in the .wdproj file:</p>\n\n<pre><code> <Target Name=\"AfterBuild\">\n <!-- ============================ Script Compression============================ -->\n <MakeDir Directories=\"$(OutputPath)\\compressed\" />\n <Exec Command=\"java -jar c:\\yuicompressor-2.2.5\\build\\yuicompressor-2.2.5.jar --charset UTF-8 styles.css -o compressed/styles.css\" WorkingDirectory=\"$(OutputPath)\" />\n <Exec Command=\"move /Y .\\compressed\\* .\\\" WorkingDirectory=\"$(OutputPath)\" />\n <RemoveDir Directories=\"$(OutputPath)\\sql\" />\n <Exec Command=\"c:\\7zip-4.4.2\\7za.exe a $(ZipName).zip $(OutputPath)\\*\" />\n </Target>\n</code></pre>\n\n<p>This would allow you to delete a folder.</p>\n\n<p>(I suspect that if you wanted to not have the folder copy over <em>at all</em>, the solution file would be the place to specify that, though I haven't had to use that.)</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888/"
] | I run an ASP.NET website solution with a few other projects in it. I've known that MSBuild projects are capable of this, but is it the best way? Are they easy to create? Is nAnt, CruiseControl.NET or any other solution better?
When I build the site (using [Web Deployment Projects](http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx)), can I automate part of the build so that it does not copy certain folders from the project into the Release folder? For instance, I have folders with local search indexes, images and other content part of the folder, but I never need or upload those when deploying the project.
I'm also looking toward this type of solution to automatically increment build and version numbers. | Here's an example of a Web Deployment Project scripting this sort of task in the .wdproj file:
```
<Target Name="AfterBuild">
<!-- ============================ Script Compression============================ -->
<MakeDir Directories="$(OutputPath)\compressed" />
<Exec Command="java -jar c:\yuicompressor-2.2.5\build\yuicompressor-2.2.5.jar --charset UTF-8 styles.css -o compressed/styles.css" WorkingDirectory="$(OutputPath)" />
<Exec Command="move /Y .\compressed\* .\" WorkingDirectory="$(OutputPath)" />
<RemoveDir Directories="$(OutputPath)\sql" />
<Exec Command="c:\7zip-4.4.2\7za.exe a $(ZipName).zip $(OutputPath)\*" />
</Target>
```
This would allow you to delete a folder.
(I suspect that if you wanted to not have the folder copy over *at all*, the solution file would be the place to specify that, though I haven't had to use that.) |
15,798 | <p>I need to validate an XML string (and not a file)
against a DTD description file. </p>
<p>How can that be done in <code>python</code>?</p>
| [
{
"answer_id": 15931,
"author": "Michael Twomey",
"author_id": 995,
"author_profile": "https://Stackoverflow.com/users/995",
"pm_score": 6,
"selected": true,
"text": "<p>Another good option is <a href=\"http://lxml.de/validation.html\" rel=\"noreferrer\">lxml's validation</a> which I find quite pleasant to use.</p>\n\n<p>A simple example taken from the lxml site:</p>\n\n<pre><code>from StringIO import StringIO\n\nfrom lxml import etree\n\ndtd = etree.DTD(StringIO(\"\"\"<!ELEMENT foo EMPTY>\"\"\"))\nroot = etree.XML(\"<foo/>\")\nprint(dtd.validate(root))\n# True\n\nroot = etree.XML(\"<foo>bar</foo>\")\nprint(dtd.validate(root))\n# False\nprint(dtd.error_log.filter_from_errors())\n# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content\n</code></pre>\n"
},
{
"answer_id": 270538,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>from the examples directory in the libxml2 python bindings:</p>\n\n<pre><code>#!/usr/bin/python -u\nimport libxml2\nimport sys\n\n# Memory debug specific\nlibxml2.debugMemory(1)\n\ndtd=\"\"\"<!ELEMENT foo EMPTY>\"\"\"\ninstance=\"\"\"<?xml version=\"1.0\"?>\n<foo></foo>\"\"\"\n\ndtd = libxml2.parseDTD(None, 'test.dtd')\nctxt = libxml2.newValidCtxt()\ndoc = libxml2.parseDoc(instance)\nret = doc.validateDtd(ctxt, dtd)\nif ret != 1:\n print \"error doing DTD validation\"\n sys.exit(1)\n\ndoc.freeDoc()\ndtd.freeDtd()\ndel dtd\ndel ctxt\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446497/"
] | I need to validate an XML string (and not a file)
against a DTD description file.
How can that be done in `python`? | Another good option is [lxml's validation](http://lxml.de/validation.html) which I find quite pleasant to use.
A simple example taken from the lxml site:
```
from StringIO import StringIO
from lxml import etree
dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>"""))
root = etree.XML("<foo/>")
print(dtd.validate(root))
# True
root = etree.XML("<foo>bar</foo>")
print(dtd.validate(root))
# False
print(dtd.error_log.filter_from_errors())
# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content
``` |
15,816 | <p>I use VNC to connect to a Linux workstation at work. At work I have a 20" monitor that runs at 1600x1200, while at home I use my laptop with its resolution of 1440x900.
If I set the vncserver to run at 1440x900 I miss out on a lot of space on my monitor, whereas if I set it to run at 1600x1200 it doesn't fit on the laptop's screen, and I have to scroll it all the time.</p>
<p>Is there any good way to resize a VNC session on the fly?</p>
<p>My VNC server is RealVNC E4.x (I don't remember the exact version) running on SuSE64.</p>
| [
{
"answer_id": 15824,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know there's no way to change the client's resolution just using VNC, as it is just a \"monitor mirroring\" application.</p>\n\n<p><a href=\"http://www.tightvnc.com/\" rel=\"nofollow noreferrer\">TightVNC</a> however (which is a VNC client and server application) can resize the screen on the client side, i.e. making everything a little smaller (similar to image resizing techniques in graphics programs). That should work if you don't use too small font sizes. VNC should theoretically be compatible between different VNC applications.</p>\n"
},
{
"answer_id": 15865,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": -1,
"selected": false,
"text": "<p>I think that depends on your window manager.</p>\n\n<p>I'm a windows user, so this might be a wrong guess, but: Isn't there something called <a href=\"http://de.wikipedia.org/wiki/X-Server\" rel=\"nofollow noreferrer\">X-Server</a> running on linux machines - at least on ones that might be interesting targets for VNC - that you can connect to with \"X-Clients\"?</p>\n\n<p>VNC just takes everything that's on the screen and \"tunnels it through your network\". If I'm not totally wrong then the \"X\" protocol should give you the chance to use your client's desktop resolution. </p>\n\n<p>Give <a href=\"http://de.wikipedia.org/wiki/X-Server\" rel=\"nofollow noreferrer\">X-Server</a> on Wikipedia a try, that might give you a rough overview.</p>\n"
},
{
"answer_id": 15926,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 5,
"selected": false,
"text": "<p>I think your best best is to run the VNC server with a different geometry on a different port. I would try based on the <a href=\"http://www.realvnc.com/products/free/4.1/man/vncserver.html\" rel=\"noreferrer\">man page</a></p>\n\n<blockquote>\n<pre><code>$vncserver :0 -geometry 1600x1200\n$vncserver :1 -geometry 1440x900\n</code></pre>\n</blockquote>\n\n<p>Then you can connect from work to one port and from home to another.</p>\n\n<p>Edit: Then use xmove to move windows between the two x-servers.</p>\n"
},
{
"answer_id": 15952,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure about linux, but under windows, tightvnc will detect and adapt to resolution changes on the server. </p>\n\n<p>So you should be able to VNC into the workstation, do the equivalent of right-click on desktop, properties, set resolution to whatever, and have your client vnc window resize itself accordingly.</p>\n"
},
{
"answer_id": 16126,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>On the other hand, if there's a way to\n move an existing window from one\n X-server to another, that might solve\n the problem.</p>\n</blockquote>\n\n<p>I think you can use <a href=\"http://ubuntuforums.org/showthread.php?t=202589\" rel=\"nofollow noreferrer\">xmove</a> to move windows between two separate x-servers. So if it works, this should at least give you a way to do what you want albeit not as easily as changing the resolution.</p>\n"
},
{
"answer_id": 1083668,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 8,
"selected": true,
"text": "<p>Real VNC server 4.4 includes support for Xrandr, which allows resizing the VNC. Start the server with:</p>\n\n<pre><code>vncserver -geometry 1600x1200 -randr 1600x1200,1440x900,1024x768\n</code></pre>\n\n<p>Then resize with:</p>\n\n<pre><code>xrandr -s 1600x1200\nxrandr -s 1440x900\nxrandr -s 1024x768\n</code></pre>\n"
},
{
"answer_id": 3839759,
"author": "Tijs",
"author_id": 463917,
"author_profile": "https://Stackoverflow.com/users/463917",
"pm_score": 6,
"selected": false,
"text": "<p>Found out that the vnc4server (4.1.1) shipped with Ubuntu (10.04) is patched to also support changing the resolution on the fly via xrandr. Unfortunately the feature was hard to find because it is undocumented. So here it is...</p>\n\n<p>Start the server with multiple 'geometry' instances, like:</p>\n\n<pre><code>vnc4server -geometry 1280x1024 -geometry 800x600\n</code></pre>\n\n<p>From a terminal in a vncviewer (with: 'allow dymanic desktop resizing' enabled) use xrandr to view the available modes:</p>\n\n<pre><code>xrandr\n</code></pre>\n\n<p>to change the resulution, for example use:</p>\n\n<pre><code>xrandr -s 800x600\n</code></pre>\n\n<p>Thats it.</p>\n"
},
{
"answer_id": 6560690,
"author": "nhed",
"author_id": 652904,
"author_profile": "https://Stackoverflow.com/users/652904",
"pm_score": 3,
"selected": false,
"text": "<p>Adding to Nathan's (accepted) answer:</p>\n\n<p>I wanted to cycle through the list of resolutions but didnt see anything for it:</p>\n\n<pre><code>function vncNextRes()\n{\n xrandr -s $(($(xrandr | grep '^*'|sed 's@^\\*\\([0-9]*\\).*$@\\1@')+1)) > /dev/null 2>&1 || \\\n xrandr -s 0\n}\n</code></pre>\n\n<p>It gets the current index, steps to the next one and cycles back to 0 on error (i.e. end)</p>\n\n<h2><br></h2>\n\n<p><strong>EDIT</strong></p>\n\n<p>Modified to match a later version of xrandr (\"*\" is on end of line and no leading resolution identifier).</p>\n\n<pre><code>function vncNextRes()\n{\n xrandr -s $(($(xrandr 2>/dev/null | grep -n '\\* *$'| sed 's@:.*@@')-2)) || \\\n xrandr -s 0\n}\n</code></pre>\n"
},
{
"answer_id": 8388065,
"author": "Peter",
"author_id": 391313,
"author_profile": "https://Stackoverflow.com/users/391313",
"pm_score": 5,
"selected": false,
"text": "<p>I'm running <a href=\"http://sourceforge.net/apps/mediawiki/tigervnc/index.php?title=Welcome_to_TigerVNC\" rel=\"noreferrer\">TigerVNC</a> on my Linux server, which has basic <strong>randr</strong> support. \nI just start vncserver without any -randr or multiple -geometry options.</p>\n\n<p>When I run xrandr in a terminal, it displays all the available screen resolutions:</p>\n\n<pre><code>bash> xrandr\n SZ: Pixels Physical Refresh\n 0 1920 x 1200 ( 271mm x 203mm ) 60\n 1 1920 x 1080 ( 271mm x 203mm ) 60\n 2 1600 x 1200 ( 271mm x 203mm ) 60\n 3 1680 x 1050 ( 271mm x 203mm ) 60\n 4 1400 x 1050 ( 271mm x 203mm ) 60\n 5 1360 x 768 ( 271mm x 203mm ) 60\n 6 1280 x 1024 ( 271mm x 203mm ) 60\n 7 1280 x 960 ( 271mm x 203mm ) 60\n 8 1280 x 800 ( 271mm x 203mm ) 60\n 9 1280 x 720 ( 271mm x 203mm ) 60\n*10 1024 x 768 ( 271mm x 203mm ) *60\n 11 800 x 600 ( 271mm x 203mm ) 60\n 12 640 x 480 ( 271mm x 203mm ) 60\nCurrent rotation - normal\nCurrent reflection - none\nRotations possible - normal\nReflections possible - none\n</code></pre>\n\n<p>I can then easily switch to another resolution (f.e. switch to 1360x768):</p>\n\n<pre><code>bash> xrandr -s 5\n</code></pre>\n\n<p>I'm using TightVnc viewer as the client and it automatically adapts to the new resolution.</p>\n"
},
{
"answer_id": 11648533,
"author": "inukaze",
"author_id": 983309,
"author_profile": "https://Stackoverflow.com/users/983309",
"pm_score": 0,
"selected": false,
"text": "<p>I have a simple idea, something like this:</p>\n\n<pre><code>#!/bin/sh\n\necho `xrandr --current | grep current | awk '{print $8}'` >> RES1\necho `xrandr --current | grep current | awk '{print $10}'` >> RES2\ncat RES2 | sed -i 's/,//g' RES2\n\nP1RES=$(cat RES1)\nP2RES=$(cat RES2)\nrm RES1 RES2\necho \"$P1RES\"'x'\"$P2RES\" >> RES\nRES=$(cat RES)\n\n# Play The Game\n\n# Finish The Game with Lower Resolution\n\nxrandr -s $RES\n</code></pre>\n\n<p>Well, I need a better solution for all display devices under Linux and Similars S.O</p>\n"
},
{
"answer_id": 23974330,
"author": "Hammad Khan",
"author_id": 777982,
"author_profile": "https://Stackoverflow.com/users/777982",
"pm_score": 5,
"selected": false,
"text": "<p>Interestingly no one answered this. In TigerVNC, when you are logged into the session. Go to <code>System > Preference > Display</code> from the top menu bar ( I was using Cent OS as my remote Server). Click on the resolution drop down, there are various settings available including 1080p. Select the one that you like. It will change on the fly.</p>\n\n<p><img src=\"https://i.stack.imgur.com/UUAgd.png\" alt=\"enter image description here\"></p>\n\n<p><strong>Make sure you Apply the new setting when a dialog is prompted. Otherwise it will revert back to the previous setting just like in Windows</strong></p>\n"
},
{
"answer_id": 28777978,
"author": "Kashyap",
"author_id": 496289,
"author_profile": "https://Stackoverflow.com/users/496289",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps the most ignorant answer I've posted but here goes: Use TigerVNC client/viewer and check <code>'Resize remote session to local window'</code> under Screen tab of options.</p>\n\n<p>I don't know what the $%#@ TigerVNC client tells remote vncserver or xrandr or Xvnc or gnome or ... but it resizes when I change the TigerVNC Client window.</p>\n\n<p>My setup:</p>\n\n<ul>\n<li>Tiger VNC Server running on CentOS 6. Hosting GNOME desktop. (Works with RHEL 6.6 too)</li>\n<li>Windows some version with Tiger VNC Client.</li>\n</ul>\n\n<p>With this the resolution changes to fit the size of the client window no matter what it is, and it's not <code>zooming</code>, it's actual resolution change (I can see the new resolution in xrandr output).</p>\n\n<p>I tried all I could to add a new resolution to the xrandr, but to no avail, always end up with <code>'xrandr: Failed to get size of gamma for output default'</code> error.</p>\n\n<p>Versions with which it works for me right now (although I've not had issues with ANY versions in the past, I just install the latest using <code>yum install gnome-* tigervnc-server</code> and works fine):</p>\n\n<pre><code>OS: RHEL 6.6 (Santiago)\nVNC Server:\nName : tigervnc-server\nArch : x86_64\nVersion : 1.1.0\nRelease : 16.el6\n\n# May be this is relevant..\n$ xrandr --version\nxrandr program version 1.4.0\nServer reports RandR version 1.4\n$ \n\n# I start the server using vncserver -geometry 800x600\n# Xvnc is started by vncserver with following args:\n/usr/bin/Xvnc :1 -desktop plabb13.sgdcelab.sabre.com:1 (sg219898) -auth /login/sg219898/.Xauthority \n-geometry 800x600 -rfbwait 30000 -rfbauth /login/sg219898/.vnc/passwd -rfbport 5901 -fp catalogue:/e\ntc/X11/fontpath.d -pn\n\n\n# I'm running GNOME (installed using sudo yum install gnome-*)\nName : gnome-desktop\nArch : x86_64\nVersion : 2.28.2\nRelease : 11.el6\n\nName : gnome-session\nArch : x86_64\nVersion : 2.28.0\nRelease : 22.el6\n\nConnect using Tiger 32-bit VNC Client v1.3.1 on Windows 7.\n</code></pre>\n"
},
{
"answer_id": 38630417,
"author": "omiday",
"author_id": 6648502,
"author_profile": "https://Stackoverflow.com/users/6648502",
"pm_score": 5,
"selected": false,
"text": "<p>As this question comes up first on Google I thought I'd share a solution using TigerVNC which is the default these days.</p>\n\n<p><code>xrandr</code> allows selecting the display modes (a.k.a resolutions) however\ndue to modelines being <a href=\"https://github.com/TigerVNC/tigervnc/blob/master/unix/xserver/hw/vnc/xvnc.c\" rel=\"noreferrer\">hard\ncoded</a>\nany additional modeline such as \"2560x1600\" or \"1600x900\" would need to\nbe <a href=\"https://marc.info/?l=tigervnc-users&m=130721748515934&w=2\" rel=\"noreferrer\">added into the\ncode</a>. I\nthink the developers who wrote the code are much smarter and the hard\ncoded list is just a sample of values. It leads to the conclusion that\nthere must be a way to add custom modelines and <code>man xrandr</code> confirms\nit.</p>\n\n<p>With that background if the goal is to share a VNC session between two\ncomputers with the above resolutions and assuming that the VNC server is\nthe computer with the resolution of \"1600x900\":</p>\n\n<ol>\n<li><p>Start a VNC session with a geometry matching the physical display:</p>\n\n<pre><code>$ vncserver -geometry 1600x900 :1\n</code></pre></li>\n<li><p>On the \"2560x1600\" computer start the VNC viewer (I prefer\nRemmina) and connect to the remote VNC\nsession:</p>\n\n<pre><code>host:5901\n</code></pre></li>\n<li><p>Once inside the VNC session start up a terminal window.</p></li>\n<li><p>Confirm that the new geometry is available in the VNC session:</p>\n\n<pre><code>$ xrandr\nScreen 0: minimum 32 x 32, current 1600 x 900, maximum 32768 x 32768\nVNC-0 connected 1600x900+0+0 0mm x 0mm\n 1600x900 60.00 +\n 1920x1200 60.00 \n 1920x1080 60.00 \n 1600x1200 60.00 \n 1680x1050 60.00 \n 1400x1050 60.00 \n 1360x768 60.00 \n 1280x1024 60.00 \n 1280x960 60.00 \n 1280x800 60.00 \n 1280x720 60.00 \n 1024x768 60.00 \n 800x600 60.00 \n 640x480 60.00 \n</code></pre>\n\n<p>and you'll notice the screen being quite small.</p></li>\n<li><p>List the modeline (see xrandr article in ArchLinux wiki) for\nthe \"2560x1600\" resolution:</p>\n\n<pre><code>$ cvt 2560 1600\n# 2560x1600 59.99 Hz (CVT 4.10MA) hsync: 99.46 kHz; pclk: 348.50 MHz\nModeline \"2560x1600_60.00\" 348.50 2560 2760 3032 3504 1600 1603 1609 1658 -hsync +vsync\n</code></pre>\n\n<p>or if the monitor is old get the GTF timings:</p>\n\n<pre><code>$ gtf 2560 1600 60\n# 2560x1600 @ 60.00 Hz (GTF) hsync: 99.36 kHz; pclk: 348.16 MHz\nModeline \"2560x1600_60.00\" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync\n</code></pre></li>\n<li><p>Add the new modeline to the current VNC session:</p>\n\n<pre><code>$ xrandr --newmode \"2560x1600_60.00\" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync\n</code></pre></li>\n<li><p>In the above <code>xrandr</code> output look for the display name on the second\nline:</p>\n\n<pre><code>VNC-0 connected 1600x900+0+0 0mm x 0mm\n</code></pre></li>\n<li><p>Bind the new modeline to the current VNC virtual monitor:</p>\n\n<pre><code>$ xrandr --addmode VNC-0 \"2560x1600_60.00\"\n</code></pre></li>\n<li><p>Use it:</p>\n\n<pre><code>$ xrandr -s \"2560x1600_60.00\"\n</code></pre></li>\n</ol>\n"
},
{
"answer_id": 39777101,
"author": "Nicholas Sushkin",
"author_id": 789544,
"author_profile": "https://Stackoverflow.com/users/789544",
"pm_score": 2,
"selected": false,
"text": "<p>Solution by @omiday worked for me in Xvnc TigerVNC 1.1.0, so I condensed it into a single bash function <strong>vncsize x y</strong>. Use it like this: <strong>vncsize 1400 1000</strong>. It works for any VNC output name, "default" or "VNC-0".</p>\n<pre><code>function vncsize {\n local x=$1 y=$2\n local mode\n if mode=$(cvt "$x" "$y" 2>/dev/null)\n then\n if [[ $mode =~ "Modeline (.*)$" ]]\n then\n local newMode=${BASH_REMATCH[1]//\\"/}\n local modeName=${newMode%% *}\n local newSize=( ${modeName//[\\"x_]/ } )\n local screen=$(xrandr -q|grep connected|cut -d' ' -f1)\n xrandr --newmode $newMode\n xrandr --addmode "$screen" "$modeName"\n xrandr --size "${newSize[0]}x${newSize[1]}" &&\n return 0\n else\n echo "Unable to parse modeline for ($x $y) from $mode"\n return 2\n fi\n else\n echo "\\`$x $y' is not a valid X Y pair"\n return 1\n fi\n}\n</code></pre>\n"
},
{
"answer_id": 47251869,
"author": "Will Berger",
"author_id": 8928866,
"author_profile": "https://Stackoverflow.com/users/8928866",
"pm_score": 4,
"selected": false,
"text": "<p>Guys this is really simple.</p>\n\n<p>login via <code>ssh</code> into your pi</p>\n\n<p>execute </p>\n\n<pre><code>vncserver -geometry 1200x1600\n</code></pre>\n\n<p>This will generate a new session <code>:1</code></p>\n\n<p>connect with your vnc client at <code>ipaddress:1</code></p>\n\n<p>Thats it.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] | I use VNC to connect to a Linux workstation at work. At work I have a 20" monitor that runs at 1600x1200, while at home I use my laptop with its resolution of 1440x900.
If I set the vncserver to run at 1440x900 I miss out on a lot of space on my monitor, whereas if I set it to run at 1600x1200 it doesn't fit on the laptop's screen, and I have to scroll it all the time.
Is there any good way to resize a VNC session on the fly?
My VNC server is RealVNC E4.x (I don't remember the exact version) running on SuSE64. | Real VNC server 4.4 includes support for Xrandr, which allows resizing the VNC. Start the server with:
```
vncserver -geometry 1600x1200 -randr 1600x1200,1440x900,1024x768
```
Then resize with:
```
xrandr -s 1600x1200
xrandr -s 1440x900
xrandr -s 1024x768
``` |
15,828 | <p>Is there a free or open source library to read Excel files (.xls) directly from a C# program? </p>
<p>It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.</p>
| [
{
"answer_id": 15835,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 1,
"selected": false,
"text": "<p>you could write an excel spreadsheet that loads a given excel spreadsheet and saves it as csv (rather than doing it manually).</p>\n\n<p>then you could automate that from c#.</p>\n\n<p>and once its in csv, the c# program can grok that.</p>\n\n<p>(also, if someone asks you to program in excel, it's best to pretend you don't know how)</p>\n\n<p>(edit: ah yes, rob and ryan are both right)</p>\n"
},
{
"answer_id": 15836,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "<p>I know that people have been making an Excel \"extension\" for this purpose.<br>\nYou more or less make a button in Excel that says \"Export to Program X\", and then export and send off the data in a format the program can read.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms186213.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms186213.aspx</a> should be a good place to start.</p>\n\n<p>Good luck</p>\n"
},
{
"answer_id": 15837,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "<p>Forgive me if I am off-base here, but isn't this what the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=C41BD61E-3060-4F71-A6B4-01FEBA508E52&displaylang=en\" rel=\"nofollow noreferrer\">Office PIA's</a> are for?</p>\n"
},
{
"answer_id": 15839,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 6,
"selected": false,
"text": "<p>If it is just simple data contained in the Excel file you can read the data via ADO.NET. See the connection strings listed here:</p>\n\n<p><a href=\"http://www.connectionstrings.com/?carrier=excel2007\" rel=\"noreferrer\">http://www.connectionstrings.com/?carrier=excel2007</a>\nor \n<a href=\"http://www.connectionstrings.com/?carrier=excel2007\" rel=\"noreferrer\">http://www.connectionstrings.com/?carrier=excel</a></p>\n\n<p>-Ryan</p>\n\n<p>Update: then you can just read the worksheet via something like <code>select * from [Sheet1$]</code></p>\n"
},
{
"answer_id": 15842,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 2,
"selected": false,
"text": "<p>Not free, but with the latest Office there's a <em>very</em> nice automation .Net API. (there has been an API for a long while but was nasty COM) You can do everything you want / need in code all while the Office app remains a hidden background process.</p>\n"
},
{
"answer_id": 15858,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 1,
"selected": false,
"text": "<p>Just did a quick demo project that required managing some excel files. The .NET component from GemBox software was adequate for my needs. It has a free version with a few limitations.</p>\n\n<p><a href=\"http://www.gemboxsoftware.com/GBSpreadsheet.htm\" rel=\"nofollow noreferrer\">http://www.gemboxsoftware.com/GBSpreadsheet.htm</a></p>\n"
},
{
"answer_id": 15970,
"author": "hitec",
"author_id": 120,
"author_profile": "https://Stackoverflow.com/users/120",
"pm_score": 4,
"selected": false,
"text": "<p>Here's some code I wrote in C# using .NET 1.1 a few years ago. Not sure if this would be exactly what you need (and may not be my best code :)).</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.OleDb;\n\nnamespace ExportExcelToAccess\n{\n /// <summary>\n /// Summary description for ExcelHelper.\n /// </summary>\n public sealed class ExcelHelper\n {\n private const string CONNECTION_STRING = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\\\"Excel 8.0;HDR=Yes;\\\";\";\n\n public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)\n {\n OleDbConnection objConnection = new OleDbConnection();\n objConnection = new OleDbConnection(CONNECTION_STRING.Replace(\"<FILENAME>\", fullFileName));\n DataSet dsImport = new DataSet();\n\n try\n {\n objConnection.Open();\n\n DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);\n\n if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )\n {\n //raise exception if needed\n }\n\n if( (null != sheetName) && (0 != sheetName.Length))\n {\n if( !CheckIfSheetNameExists(sheetName, dtSchema) )\n {\n //raise exception if needed\n }\n }\n else\n {\n //Reading the first sheet name from the Excel file.\n sheetName = dtSchema.Rows[0][\"TABLE_NAME\"].ToString();\n }\n\n new OleDbDataAdapter(\"SELECT * FROM [\" + sheetName + \"]\", objConnection ).Fill(dsImport);\n }\n catch (Exception)\n {\n //raise exception if needed\n }\n finally\n {\n // Clean up.\n if(objConnection != null)\n {\n objConnection.Close();\n objConnection.Dispose();\n }\n }\n\n\n return dsImport.Tables[0];\n #region Commented code for importing data from CSV file.\n // string strConnectionString = \"Provider=Microsoft.Jet.OLEDB.4.0;\" +\"Data Source=\" + System.IO.Path.GetDirectoryName(fullFileName) +\";\" +\"Extended Properties=\\\"Text;HDR=YES;FMT=Delimited\\\"\";\n //\n // System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);\n // new System.Data.OleDb.OleDbDataAdapter(\"SELECT * FROM \" + System.IO.Path.GetFileName(fullFileName).Replace(\".\", \"#\"), conText).Fill(dsImport);\n // return dsImport.Tables[0];\n\n #endregion\n }\n\n /// <summary>\n /// This method checks if the user entered sheetName exists in the Schema Table\n /// </summary>\n /// <param name=\"sheetName\">Sheet name to be verified</param>\n /// <param name=\"dtSchema\">schema table </param>\n private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)\n {\n foreach(DataRow dataRow in dtSchema.Rows)\n {\n if( sheetName == dataRow[\"TABLE_NAME\"].ToString() )\n {\n return true;\n } \n }\n return false;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 16051,
"author": "Robin Robinson",
"author_id": 1629,
"author_profile": "https://Stackoverflow.com/users/1629",
"pm_score": 8,
"selected": true,
"text": "<pre><code>var fileName = string.Format(\"{0}\\\\fileNameHere\", Directory.GetCurrentDirectory());\nvar connectionString = string.Format(\"Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;\", fileName);\n\nvar adapter = new OleDbDataAdapter(\"SELECT * FROM [workSheetNameHere$]\", connectionString);\nvar ds = new DataSet();\n\nadapter.Fill(ds, \"anyNameHere\");\n\nDataTable data = ds.Tables[\"anyNameHere\"];\n</code></pre>\n\n<p>This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables: </p>\n\n<pre><code>var data = ds.Tables[\"anyNameHere\"].AsEnumerable();\n</code></pre>\n\n<p>as this lets me use LINQ to search and build structs from the fields.</p>\n\n<pre><code>var query = data.Where(x => x.Field<string>(\"phoneNumber\") != string.Empty).Select(x =>\n new MyContact\n {\n firstName= x.Field<string>(\"First Name\"),\n lastName = x.Field<string>(\"Last Name\"),\n phoneNumber =x.Field<string>(\"Phone Number\"),\n });\n</code></pre>\n"
},
{
"answer_id": 17921,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 5,
"selected": false,
"text": "<p>The ADO.NET approach is quick and easy, but it has a few quirks which you should be aware of, especially regarding how DataTypes are handled.</p>\n\n<p>This excellent article will help you avoid some common pitfalls:\n<a href=\"http://blog.lab49.com/archives/196\" rel=\"noreferrer\">http://blog.lab49.com/archives/196</a></p>\n"
},
{
"answer_id": 17930,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 3,
"selected": false,
"text": "<p>I did a lot of reading from Excel files in C# a while ago, and we used two approaches:</p>\n\n<ul>\n<li>The COM API, where you access Excel's objects directly and manipulate them through methods and properties</li>\n<li>The ODBC driver that allows to use Excel like a database.</li>\n</ul>\n\n<p>The latter approach was <strong>much</strong> faster: reading a big table with 20 columns and 200 lines would take 30 seconds via COM, and half a second via ODBC. So I would recommend the database approach if all you need is the data.</p>\n\n<p>Cheers,</p>\n\n<p>Carl</p>\n"
},
{
"answer_id": 43236,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 4,
"selected": false,
"text": "<p>While you did specifically ask for .xls, implying the older file formats, for the OpenXML formats (e.g. xlsx) I highly recommend the OpenXML SDK (<a href=\"http://msdn.microsoft.com/en-us/library/bb448854.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/bb448854.aspx</a>)</p>\n"
},
{
"answer_id": 43451,
"author": "Jason Von Ruden",
"author_id": 2062,
"author_profile": "https://Stackoverflow.com/users/2062",
"pm_score": 2,
"selected": false,
"text": "<p>I recommend the FileHelpers Library which is a free and easy to use .NET library to import/export data from EXCEL, fixed length or delimited records in files, strings or streams + More.</p>\n\n<p><strong>The Excel Data Link Documentation Section</strong>\n<a href=\"http://filehelpers.sourceforge.net/example_exceldatalink.html\" rel=\"nofollow noreferrer\">http://filehelpers.sourceforge.net/example_exceldatalink.html</a></p>\n"
},
{
"answer_id": 43494,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 2,
"selected": false,
"text": "<p>Lately, partly to get better at LINQ.... I've been using Excel's automation API to save the file as XML Spreadsheet and then get process that file using LINQ to XML. </p>\n"
},
{
"answer_id": 43534,
"author": "Dmitry Shechtman",
"author_id": 3583,
"author_profile": "https://Stackoverflow.com/users/3583",
"pm_score": 5,
"selected": false,
"text": "<p>This is what I used for Excel 2003:</p>\n\n<pre><code>Dictionary<string, string> props = new Dictionary<string, string>();\nprops[\"Provider\"] = \"Microsoft.Jet.OLEDB.4.0\";\nprops[\"Data Source\"] = repFile;\nprops[\"Extended Properties\"] = \"Excel 8.0\";\n\nStringBuilder sb = new StringBuilder();\nforeach (KeyValuePair<string, string> prop in props)\n{\n sb.Append(prop.Key);\n sb.Append('=');\n sb.Append(prop.Value);\n sb.Append(';');\n}\nstring properties = sb.ToString();\n\nusing (OleDbConnection conn = new OleDbConnection(properties))\n{\n conn.Open();\n DataSet ds = new DataSet();\n string columns = String.Join(\",\", columnNames.ToArray());\n using (OleDbDataAdapter da = new OleDbDataAdapter(\n \"SELECT \" + columns + \" FROM [\" + worksheet + \"$]\", conn))\n {\n DataTable dt = new DataTable(tableName);\n da.Fill(dt);\n ds.Tables.Add(dt);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 261566,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://koogra.sourceforge.net/\" rel=\"nofollow noreferrer\">Koogra</a> is an open-source component written in C# that reads and writes Excel files.</p>\n"
},
{
"answer_id": 458051,
"author": "Joe Erickson",
"author_id": 56710,
"author_profile": "https://Stackoverflow.com/users/56710",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.spreadsheetgear.com/\" rel=\"nofollow noreferrer\">SpreadsheetGear for .NET</a> is an Excel compatible spreadsheet component for .NET. You can see what our customers say about performance on the right hand side of our <a href=\"http://www.spreadsheetgear.com/products/spreadsheetgear.net.aspx\" rel=\"nofollow noreferrer\">product page</a>. You can try it yourself with the free, fully-functional <a href=\"https://www.spreadsheetgear.com/downloads/register.aspx\" rel=\"nofollow noreferrer\">evaluation</a>.</p>\n"
},
{
"answer_id": 848634,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>ExcelMapper is an open source tool (<a href=\"http://code.google.com/p/excelmapper/\" rel=\"noreferrer\">http://code.google.com/p/excelmapper/</a>) that can be used to read Excel worksheets as Strongly Typed Objects. It supports both xls and xlsx formats.</p>\n"
},
{
"answer_id": 1320733,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 0,
"selected": false,
"text": "<p>I just used <a href=\"http://code.google.com/p/excellibrary/\" rel=\"nofollow noreferrer\">ExcelLibrary</a> to load an .xls spreadsheet into a DataSet. Worked great for me.</p>\n"
},
{
"answer_id": 1495949,
"author": "liya",
"author_id": 121735,
"author_profile": "https://Stackoverflow.com/users/121735",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.smartxls.com\" rel=\"nofollow noreferrer\">SmartXLS</a> is another excel spreadsheet component which support most features of excel Charts,formulas engines, and can read/write the excel2007 openxml format.</p>\n"
},
{
"answer_id": 1501792,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://excelpackage.codeplex.com/\" rel=\"nofollow noreferrer\">Excel Package</a> is an open-source (GPL) component for reading/writing Excel 2007 files. I used it on a small project, and the API is straightforward. Works with XLSX only (Excel 200&), not with XLS.</p>\n\n<p>The source code also seems well-organized and easy to get around (if you need to expand functionality or fix minor issues as I did).</p>\n\n<p>At first, I tried the ADO.Net (Excel connection string) approach, but it was fraught with nasty hacks -- for instance if <em>second</em> row contains a number, it will return ints for all fields in the column below and quietly drop any data that doesn't fit.</p>\n"
},
{
"answer_id": 2405759,
"author": "user289261",
"author_id": 289261,
"author_profile": "https://Stackoverflow.com/users/289261",
"pm_score": 2,
"selected": false,
"text": "<p>You can try using this open source solution that makes dealing with Excel a lot more cleaner.</p>\n\n<p><a href=\"http://excelwrapperdotnet.codeplex.com/\" rel=\"nofollow noreferrer\">http://excelwrapperdotnet.codeplex.com/</a></p>\n"
},
{
"answer_id": 3578025,
"author": "John R",
"author_id": 432177,
"author_profile": "https://Stackoverflow.com/users/432177",
"pm_score": 2,
"selected": false,
"text": "<p>SpreadsheetGear is awesome. Yes it's an expense, but compared to twiddling with these other solutions, it's worth the cost. It is fast, reliable, very comprehensive, and I have to say after using this product in my fulltime software job for over a year and a half, their customer support is fantastic!</p>\n"
},
{
"answer_id": 3665991,
"author": "Michał Pawłowski",
"author_id": 287737,
"author_profile": "https://Stackoverflow.com/users/287737",
"pm_score": 4,
"selected": false,
"text": "<p>How about Excel Data Reader? </p>\n\n<p><a href=\"http://exceldatareader.codeplex.com/\" rel=\"noreferrer\">http://exceldatareader.codeplex.com/</a></p>\n\n<p>I've used in it anger, in a production environment, to pull large amounts of data from a variety of Excel files into SQL Server Compact. It works very well and it's rather robust.</p>\n"
},
{
"answer_id": 4902204,
"author": "JP Negri",
"author_id": 316958,
"author_profile": "https://Stackoverflow.com/users/316958",
"pm_score": 0,
"selected": false,
"text": "<p>Excel Data Reader is the way to go!</p>\n\n<p>It´s Open Source, at <a href=\"http://exceldatareader.codeplex.com/\" rel=\"nofollow\">http://exceldatareader.codeplex.com/</a> and actively developed.</p>\n\n<p>We been using it for reading Tabular (and sometimes not so tabular) worksheets for a couple of years now (In a financial application).</p>\n\n<p>Works like a charm to read unit test data from human-readable sheets.</p>\n\n<p>Just avoid the feature of trying to return DateTime's, as, for Excel, DateTime's are just double numbers.</p>\n"
},
{
"answer_id": 5631836,
"author": "Bonnie Cornell",
"author_id": 703481,
"author_profile": "https://Stackoverflow.com/users/703481",
"pm_score": 2,
"selected": false,
"text": "<p>The .NET component Excel Reader .NET may satisfy your requirement. It's good enought for reading XLSX and XLS files. So try it from:</p>\n\n<blockquote>\n <p><a href=\"http://www.devtriogroup.com/ExcelReader/Default.aspx\" rel=\"nofollow\">http://www.devtriogroup.com/ExcelReader</a></p>\n</blockquote>\n"
},
{
"answer_id": 5742568,
"author": "Marcel Toth",
"author_id": 702199,
"author_profile": "https://Stackoverflow.com/users/702199",
"pm_score": 2,
"selected": false,
"text": "<p>The solution that we used, needed to:</p>\n\n<ul>\n<li>Allow <strong>Reading/Writing</strong> of Excel produced files</li>\n<li>Be <strong>Fast</strong> in performance (not like using COMs)</li>\n<li>Be MS Office <strong>Independent</strong> (needed to be usable without clients having MS Office installed)</li>\n<li>Be <strong>Free</strong> or <strong>Open Source</strong> (but actively developed)</li>\n</ul>\n\n<p>There are several choices, but we found <strong>NPoi</strong> (.NET port of Java's long existing <strong>Poi</strong> open source project) to be the best:\n<a href=\"http://npoi.codeplex.com/\" rel=\"nofollow\">http://npoi.codeplex.com/</a></p>\n\n<p>It also allows working with .doc and .ppt file formats</p>\n"
},
{
"answer_id": 6756362,
"author": "VBK",
"author_id": 853096,
"author_profile": "https://Stackoverflow.com/users/853096",
"pm_score": 0,
"selected": false,
"text": "<p>If you have multiple tables in the same worksheet you can give each table an object name and read the table using the OleDb method as shown here: <a href=\"http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/\" rel=\"nofollow\">http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/</a></p>\n"
},
{
"answer_id": 7396934,
"author": "cless",
"author_id": 126624,
"author_profile": "https://Stackoverflow.com/users/126624",
"pm_score": 2,
"selected": false,
"text": "<p>If it's just tabular data. I would recommend file data helpers by Marcos Melli which can be downloaded <a href=\"http://filehelpers.sourceforge.net/\" rel=\"nofollow\">here</a>.</p>\n"
},
{
"answer_id": 7425567,
"author": "Balena",
"author_id": 945938,
"author_profile": "https://Stackoverflow.com/users/945938",
"pm_score": 1,
"selected": false,
"text": "<p><code>Take.io</code> Spreadsheet will do this work for you, and at no charge. Just take a look at <a href=\"https://bitbucket.org/guibv/takeio.spreadsheet/\" rel=\"nofollow\">this</a>.</p>\n"
},
{
"answer_id": 9580450,
"author": "Lizzy",
"author_id": 1242112,
"author_profile": "https://Stackoverflow.com/users/1242112",
"pm_score": 3,
"selected": false,
"text": "<p>I want to show a simple method to read xls/xlsx file with .NET. I hope that the following will be helpful for you.</p>\n\n<pre>\n private DataTable ReadExcelToTable(string path) \n {\n\n //Connection String\n\n string connstring = \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" + path + \";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';\"; \n //the same name \n //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=\" + path + //\";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';\"; \n\n using(OleDbConnection conn = new OleDbConnection(connstring))\n {\n conn.Open();\n //Get All Sheets Name\n DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,new object[]{null,null,null,\"Table\"}); \n\n //Get the First Sheet Name\n string firstSheetName = sheetsName.Rows[0][2].ToString(); \n\n //Query String \n string sql = string.Format(\"SELECT * FROM [{0}]\",firstSheetName); \n OleDbDataAdapter ada =new OleDbDataAdapter(sql,connstring);\n DataSet set = new DataSet();\n ada.Fill(set);\n return set.Tables[0]; \n }\n }</pre>\n\n<p>Code is from article: <a href=\"http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/uploadfile/d2dcfc/read-excel-file-with-net/</a>. You can get more details from it.</p>\n"
},
{
"answer_id": 12002438,
"author": "Doctor Rudolf",
"author_id": 563688,
"author_profile": "https://Stackoverflow.com/users/563688",
"pm_score": 1,
"selected": false,
"text": "<p>We use <a href=\"http://closedxml.codeplex.com/\" rel=\"nofollow\">ClosedXML</a> in rather large systems.</p>\n\n<ul>\n<li>Free</li>\n<li>Easy to install</li>\n<li>Straight forward coding</li>\n<li><strong>Very</strong> responsive support</li>\n<li>Developer team is <strong>extremly</strong> open to new suggestions. Often new features and bug fixes are implemented within the same week</li>\n</ul>\n"
},
{
"answer_id": 13089551,
"author": "DeeDee",
"author_id": 646628,
"author_profile": "https://Stackoverflow.com/users/646628",
"pm_score": 2,
"selected": false,
"text": "<p>Late to the party, but I'm a fan of <a href=\"http://code.google.com/p/linqtoexcel/\" rel=\"nofollow\">LinqToExcel</a></p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] | Is there a free or open source library to read Excel files (.xls) directly from a C# program?
It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step. | ```
var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory());
var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "anyNameHere");
DataTable data = ds.Tables["anyNameHere"];
```
This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables:
```
var data = ds.Tables["anyNameHere"].AsEnumerable();
```
as this lets me use LINQ to search and build structs from the fields.
```
var query = data.Where(x => x.Field<string>("phoneNumber") != string.Empty).Select(x =>
new MyContact
{
firstName= x.Field<string>("First Name"),
lastName = x.Field<string>("Last Name"),
phoneNumber =x.Field<string>("Phone Number"),
});
``` |
15,838 | <p>Can the performance of this sequential search algorithm (taken from
<a href="http://books.google.co.uk/books?id=to6M9_dbjosC&dq=the+practice+of+programming&pg=PP1&ots=3YH6Ggq0_a&sig=F2-ajdO37xA4iRec2sCyQF55Jjc&hl=en&sa=X&oi=book_result&resnum=1&ct=result" rel="noreferrer">The Practice of Programming</a>) be improved using any of C's native utilities, e.g. if I set the i variable to be a register variable ?</p>
<pre><code>int lookup(char *word, char*array[])
{
int i
for (i = 0; array[i] != NULL; i++)
if (strcmp(word, array[i]) == 0)
return i;
return -1;
}
</code></pre>
| [
{
"answer_id": 15846,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, but only very slightly. A much bigger performance improvement can be achieved by using better algorithms (for example keeping the list sorted and doing a binary search).</p>\n\n<p>In general optimizing a given algorithm only gets you so far. Choosing a better algorithm (even if it's not completely optimized) can give you a considerable (order of magnitude) performance improvement.</p>\n"
},
{
"answer_id": 15849,
"author": "HS.",
"author_id": 1398,
"author_profile": "https://Stackoverflow.com/users/1398",
"pm_score": 2,
"selected": false,
"text": "<p>I think, it will not make much of a difference. The compiler will already optimize it in that direction.</p>\n\n<p>Besides, the variable i does not have much impact, word stays constant throughout the function and the rest is too large to fit in any register. It is only a matter how large the cache is and if the whole array might fit in there.</p>\n\n<p>String comparisons are rather expensive computationally.</p>\n\n<p>Can you perhaps use some kind of hashing for the array before searching?</p>\n"
},
{
"answer_id": 15876,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 1,
"selected": false,
"text": "<p>If you're reading TPOP, you will next see how they make this search many times faster with different data structures and algorithms.</p>\n\n<p>But you can make things a bit faster by replacing things like</p>\n\n<pre><code>for (i = 0; i < n; ++i)\n foo(a[i]);\n</code></pre>\n\n<p>with</p>\n\n<pre><code>char **p = a;\nfor (i = 0; i < n; ++i)\n foo(*p);\n ++p;\n</code></pre>\n\n<p>If there is a known value at the end of the array (e.g. NULL) you can eliminate the loop counter:</p>\n\n<pre><code>for (p = a; *p != NULL; ++p)\n foo(*p)\n</code></pre>\n\n<p>Good luck, that's a great book!</p>\n"
},
{
"answer_id": 15915,
"author": "popopome",
"author_id": 1556,
"author_profile": "https://Stackoverflow.com/users/1556",
"pm_score": 2,
"selected": false,
"text": "<p>There is well-known technique as sentinal method.\nTo use sentinal method, you must know about the length of \"array[]\".\nYou can remove \"array[i] != NULL\" comparing by using sentinal.</p>\n\n<pre><code>int lookup(char *word, char*array[], int array_len)\n{\n int i = 0;\n array[array_len] = word;\n for (;; ++i)\n if (strcmp(word, array[i]) == 0) \n break;\n array[array_len] = NULL;\n return (i != array_len) ? i : -1;\n}\n</code></pre>\n"
},
{
"answer_id": 16094,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "<p>To optimize that code the best bet would be to rewrite the strcmp routine since you are only checking for equality and don't need to evaluate the entire word.</p>\n\n<p>Other than that you can't do much else. You can't sort as it appears you are looking for text within a larger text. Binary search won't work either since the text is unlikely to be sorted.</p>\n\n<p>My 2p (C-psuedocode):</p>\n\n<pre><code>wrd_end = wrd_ptr + wrd_len;\narr_end = arr_ptr - wrd_len;\nwhile (arr_ptr < arr_end)\n{\n wrd_beg = wrd_ptr; arr_beg = arr_ptr;\n while (wrd_ptr == arr_ptr)\n {\n wrd_ptr++; arr_ptr++;\n if (wrd_ptr == wrd_en)\n return wrd_beg;\n }\n wrd_ptr++;\n}\n</code></pre>\n"
},
{
"answer_id": 17209,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 0,
"selected": false,
"text": "<p>Realistically, setting I to be a register variable won't do anything that the compiler wouldn't do already.</p>\n\n<p>If you are willing to spend some time upfront preprocessing the reference array, you should google \"The World's Fastest Scrabble Program\" and implement that. Spoiler: it's a DAG optimized for character lookups.</p>\n"
},
{
"answer_id": 71698,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 0,
"selected": false,
"text": "<p>Mark Harrison: Your for loop will never terminate! (++p is indented, but is not actually within the for :-)</p>\n\n<p>Also, switching between pointers and indexing will generally have no effect on performance, nor will adding register keywords (as mat already mentions) -- the compiler is smart enough to apply these transformations where appropriate, and if you tell it enough about your cpu arch, it will do a better job of these than manual psuedo-micro-optimizations. </p>\n"
},
{
"answer_id": 252622,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 0,
"selected": false,
"text": "<p>A faster way to match strings would be to store them Pascal style. If you don't need more than 255 characters per string, store them roughly like this, with the count in the first byte:</p>\n\n<pre><code>char s[] = \"\\x05Hello\";\n</code></pre>\n\n<p>Then you can do:</p>\n\n<pre><code>for(i=0; i<len; ++i) {\n s_len = strings[i][0];\n if(\n s_len == match_len\n && strings[i][s_len] == match[s_len-1]\n && 0 == memcmp(strings[i]+1, match, s_len-1)\n ) {\n return 1;\n }\n}\n</code></pre>\n\n<p>And to get really fast, add memory prefetch hints for string start + 64, + 128 and the start of the next string. But that's just crazy. :-)</p>\n"
},
{
"answer_id": 252650,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 0,
"selected": false,
"text": "<p>Another fast way to do it is to get your compiler to use a SSE2 optimized memcmp. Use fixed-length char arrays and align so the string starts on a 64-byte alignment. Then I believe you can get the good memcmp functions if you pass const char match[64] instead of const char *match into the function, or strncpy match into a 64,128,256,whatever byte array.</p>\n\n<p>Thinking a bit more about this, these SSE2 match functions might be part of packages like Intel's and AMD's accelerator libraries. Check them out.</p>\n"
},
{
"answer_id": 20116661,
"author": "alchak",
"author_id": 3016771,
"author_profile": "https://Stackoverflow.com/users/3016771",
"pm_score": -1,
"selected": false,
"text": "<pre><code>/* there is no more quick */\nint lookup(char *word, char*array[])\n{\n int i;\n for(i=0; *(array++) != NULL;i++)\n if (strcmp(word, *array) == 0)\n return i;\n return -1;\n}\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] | Can the performance of this sequential search algorithm (taken from
[The Practice of Programming](http://books.google.co.uk/books?id=to6M9_dbjosC&dq=the+practice+of+programming&pg=PP1&ots=3YH6Ggq0_a&sig=F2-ajdO37xA4iRec2sCyQF55Jjc&hl=en&sa=X&oi=book_result&resnum=1&ct=result)) be improved using any of C's native utilities, e.g. if I set the i variable to be a register variable ?
```
int lookup(char *word, char*array[])
{
int i
for (i = 0; array[i] != NULL; i++)
if (strcmp(word, array[i]) == 0)
return i;
return -1;
}
``` | Yes, but only very slightly. A much bigger performance improvement can be achieved by using better algorithms (for example keeping the list sorted and doing a binary search).
In general optimizing a given algorithm only gets you so far. Choosing a better algorithm (even if it's not completely optimized) can give you a considerable (order of magnitude) performance improvement. |
15,851 | <p>After I was convinced that labeled breaks/continues are a total "nono" over <a href="https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501">here</a>, I need help to remove the label out of my code.</p>
<p>I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.</p>
<p>I hope, the code-fragment is basically understandable… </p>
<pre><code>vectorLoop:
for( int idx = 0; idx < vectorLength; idx++) {
if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;
matrixLoop:
for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
}
setValueInVector( v, idx );
}
</code></pre>
<p>Please convince me, that there is a more readable/better version without the labels.</p>
| [
{
"answer_id": 15855,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "<p>Easily, my good man.</p>\n\n<pre><code>for( int idx = 0; idx < vectorLength; idx++) {\n if( conditionAtVectorPosition( v, idx ) ) continue;\n\n for( rowIdx = 0; rowIdx < n; rowIdx++ ) {\n if( anotherConditionAtVector( v, rowIdx ) ) continue;\n if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) break;\n }\n if( !conditionAtMatrixRowCol( m, rowIdx, idx ) )\n setValueInVector( v, idx );\n}\n</code></pre>\n\n<p>EDIT: Quite correct you are Anders. I've edited my solution to take that into account as well.</p>\n"
},
{
"answer_id": 15869,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 1,
"selected": false,
"text": "<p>@Patrick you are assuming calling setValueInVector( v, idx ); at the end of the second loop is OK. If the code is to be identical, logically, it must be rewritten to somethng like this:</p>\n\n<pre>for( int idx = 0; idx </pre>\n"
},
{
"answer_id": 15870,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>Does this work for you? I extracted the inner loop into a method CheckedEntireMatrix (you can name it better than me) - Also my java is a bit rusty.. but I think it gets the message across</p>\n\n<pre><code>for( int idx = 0; idx < vectorLength; idx++) {\n if( conditionAtVectorPosition( v, idx ) \n || !CheckedEntireMatrix(v)) continue;\n\n setValueInVector( v, idx );\n}\n\nprivate bool CheckedEntireMatrix(Vector v)\n{\n for( rowIdx = 0; rowIdx < n; rowIdx++ ) {\n if( anotherConditionAtVector( v, rowIdx ) ) continue;\n if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) return false;\n } \n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 15901,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 0,
"selected": false,
"text": "<p>Gishu has the right idea :</p>\n\n<pre><code>for( int idx = 0; idx < vectorLength; idx++) {\n if (!conditionAtVectorPosition( v, idx ) \n && checkedRow(v, idx))\n setValueInVector( v, idx );\n}\n\nprivate boolean checkedRow(Vector v, int idx) {\n for( rowIdx = 0; rowIdx < n; rowIdx++ ) {\n if( anotherConditionAtVector( v, rowIdx ) ) continue;\n if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) return false;\n } \n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 15903,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not too sure to understand the first continue.\nI would copy Gishu and write something like ( sorry if there are some mistakes ) :</p>\n\n<pre><code>for( int idx = 0; idx < vectorLength; idx++) {\n if( !conditionAtVectorPosition( v, idx ) && CheckedEntireMatrix(v))\n setValueInVector( v, idx );\n}\n\ninline bool CheckedEntireMatrix(Vector v) {\n for(rowIdx = 0; rowIdx < n; rowIdx++)\n if ( !anotherConditionAtVector(v,rowIdx) && conditionAtMatrixRowCol(m,rowIdx,idx) ) \n return false;\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 15908,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "<p>From reading your code. </p>\n\n<ul>\n<li>I noticed your eliminating the invalid vector positions at conditionAtVectorPosition then you remove the invalid rows at anotherConditionAtVector. </li>\n<li>It seems that checking rows at anotherConditionAtVector is redundant since whatever the value of idx is, anotherConditionAtVector only depends on the row index (assuming anotherConditionAtVector has no side effects). </li>\n</ul>\n\n<p>So you can do this:</p>\n\n<ul>\n<li>Get the valid positions first using conditionAtVectorPosition (these are the valid columns).</li>\n<li>Then get the valid rows using anotherConditionAtVector.</li>\n<li>Finally, use conditionAtMatrixRowCol using the valid columns and rows.</li>\n</ul>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 15946,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 6,
"selected": true,
"text": "<p>Looking at the solutions presented so far:</p>\n\n<ul>\n<li><p>They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself</p></li>\n<li><p>Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything.</p></li>\n<li><p>Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly.</p></li>\n<li><p>Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it's executed.</p></li>\n</ul>\n\n<p>All of which makes me believe that, at least in the case of this question as phrased, the label is the correct solution and doesn't need to be refactored away. Certainly there are cases where labels are used incorrectly and should be refactored away. I just don't think it should be treated as some unbreakable rule.</p>\n"
},
{
"answer_id": 15981,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 1,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/15851/refactoring-away-labeled-loops#15946\">Sadie</a>:</p>\n\n<blockquote>\n <p>They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself</p>\n</blockquote>\n\n<p>Externalizing the second loop outside the algorithm is not necessarily less readable. If the method name is well chosen, it can improve readability.</p>\n\n<blockquote>\n <p>Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything.</p>\n</blockquote>\n\n<p>I have a different point of view: some of them are broken because it is hard to figure out the behavior of the original algorithm.</p>\n\n<blockquote>\n <p>Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly.</p>\n</blockquote>\n\n<p>The performance penalty is minor. However I agree that running a test twice is not a nice solution.</p>\n\n<blockquote>\n <p>Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it's executed.</p>\n</blockquote>\n\n<p>I don't see the point. Yep, it doesn't change the behavior, like... refactoring?</p>\n\n<blockquote>\n <p>Certainly there are cases where labels are used incorrectly and should be refactored away. I just don't think it should be treated as some unbreakable rule.</p>\n</blockquote>\n\n<p>I totally agree. But as you have pointed out, some of us have difficulties while refactoring this example. Even if the initial example is readable, it is hard to maintain.</p>\n"
},
{
"answer_id": 16014,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 1,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/15851?sort=newest#15981\">Nicolas</a></p>\n\n<blockquote>\n <blockquote>\n <p>Some of them are broken, or were before they were edited. Most damning is the fact that \n people are having to think quite hard about how to write the code without labels and not \n break anything.</p>\n </blockquote>\n \n <p>I have a different point of view: some of them are broken because it is hard to figure out \n the behavior of the original algorithm.</p>\n</blockquote>\n\n<p>I realise that it's subjective, but I don't have any trouble reading the original algorithm. It's shorter and clearer than the proposed replacements.</p>\n\n<p>What all the refactorings in this thread do is emulate the behaviour of a label using other language features - as if you were porting the code to a language that didn't have labels.</p>\n"
},
{
"answer_id": 16048,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 1,
"selected": false,
"text": "<blockquote><blockquote>Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly.</blockquote>\n\nThe performance penalty is minor. However I agree that running a test twice is not a nice solution.</blockquote>\n\n<p>I believe the question was how to remove the labels, not how to optimize the algorithm. It appeared to me that the original poster was unaware of how to use 'continue' and 'break' keywords without labels, but of course, my assumptions may be wrong. </p>\n\n<p>When it comes to performance, the post does not give any information about the implementation of the other functions, so for all I know they might as well be downloading the results via FTP as consisting of simple calculations inlined by the compiler.</p>\n\n<p>That being said, doing the same test twice is not optimal—in theory.</p>\n\n<p>EDIT: On a second thought, the example is actually not a horrible use of labels. I agree that <a href=\"http://en.wikipedia.org/wiki/Goto#Criticism_of_goto_usage\" rel=\"nofollow noreferrer\">\"goto is a no-no\"</a>, but not because of code like this. The use of labels here does not actually affect the readability of the code in a significant way. Of course, they are not required and can easily be omitted, but not using them simply because \"using labels is bad\" is not a good argument in this case. After all, removing the labels does not make the code much easier to read, as others have already commented.</p>\n"
},
{
"answer_id": 16512,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 1,
"selected": false,
"text": "<p>This question was not about optimizing the algorithm - but thanks anyway ;-) </p>\n\n<p>At the time I wrote it, I considered the labeled continue as a readable solution.</p>\n\n<p>I asked SO a <a href=\"https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501\">question</a> about the convention (having the label in all caps or not) for labels in Java.</p>\n\n<p>Basically every answer told me \"do not use them - there is always a better way! refactor!\". So I posted this question to ask for a more readable (and therefore better?) solution.</p>\n\n<p>Until now, I am not completely convinced by the alternatives presented so far.</p>\n\n<p>Please don't get me wrong. Labels are evil most of the time. </p>\n\n<p>But in my case, the conditional tests are pretty simple and the algorithm is taken from a mathematical paper and therefore very likely to not change in the near future. So I prefer having all the relevant parts visible at once instead of having to scroll to another method named something like checkMatrixAtRow(x).</p>\n\n<p>Especially at more complex mathematical algorithms, I find it pretty hard to find \"good\" function-names - but I guess that is yet another question</p>\n"
},
{
"answer_id": 17408,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 1,
"selected": false,
"text": "<p>I think that labelled loops are so uncommon that you can pick whatever method of labelling works for you - what you have there makes your intentions with the continues perfectly clear.</p>\n\n<hr>\n\n<p><em>After leading the charge to suggest refactoring the loops in the original question and now seeing the code in question, I think you've got a very readable loop there.</em></p>\n\n<p><em>What I had imagined was a very different chunk of code - putting the actual example up, I can see it is much cleaner than I had thought.</em></p>\n\n<p><em>My apologies for the misunderstanding.</em></p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] | After I was convinced that labeled breaks/continues are a total "nono" over [here](https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501), I need help to remove the label out of my code.
I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.
I hope, the code-fragment is basically understandable…
```
vectorLoop:
for( int idx = 0; idx < vectorLength; idx++) {
if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;
matrixLoop:
for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
}
setValueInVector( v, idx );
}
```
Please convince me, that there is a more readable/better version without the labels. | Looking at the solutions presented so far:
* They all look less readable than the original, in that they involve spending more code on the mechanism of the code rather than on the algorithm itself
* Some of them are broken, or were before they were edited. Most damning is the fact that people are having to think quite hard about how to write the code without labels and not break anything.
* Some come with a performance penalty of running the same test twice, which may not always be trivial. The alternative to that is storing and passing round booleans, which gets ugly.
* Refactoring the relevant part of the code into a method is effectively a no-op: it rearranges how the code is laid out in the file, but has no effect on how it's executed.
All of which makes me believe that, at least in the case of this question as phrased, the label is the correct solution and doesn't need to be refactored away. Certainly there are cases where labels are used incorrectly and should be refactored away. I just don't think it should be treated as some unbreakable rule. |
15,899 | <p>I have a <code>XmlDocument</code> in java, created with the <code>Weblogic XmlDocument</code> parser.</p>
<p>I want to replace the content of a tag in this <code>XMLDocument</code> with my own data, or insert the tag if it isn't there.</p>
<pre><code><customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
</code></pre>
<p>For example I want to insert a URL in the location tag:</p>
<pre><code><location>http://something</location>
</code></pre>
<p>but otherwise leave the XML as is.</p>
<p>Currently I use a <code>XMLCursor</code>:</p>
<pre><code> XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
</code></pre>
<p>I tried to find a "quick" <code>xquery</code> way to do this since the <code>XmlDocument</code> has an <code>execQuery</code> method, but didn't find it very easy. </p>
<p>Do anyone have a better way than this? It seems a bit elaborate.</p>
| [
{
"answer_id": 15961,
"author": "alanl",
"author_id": 1464,
"author_profile": "https://Stackoverflow.com/users/1464",
"pm_score": 0,
"selected": false,
"text": "<p>You should be able to do this with <code>query</code></p>\n\n<p>try </p>\n\n<pre><code> fn:replace(string,pattern,replace)\n</code></pre>\n\n<p>I am new to xquery myself and I have found it to be a painful query language to work with, but it does work quiet well once you get over the initial learning curve. </p>\n\n<p>I do still wish there was an easier way which was as efficient? </p>\n"
},
{
"answer_id": 15967,
"author": "Olly",
"author_id": 1174,
"author_profile": "https://Stackoverflow.com/users/1174",
"pm_score": 2,
"selected": false,
"text": "<p>How about an object oriented approach? You could deserialise the XML to an object, set the location value on the object, then serialise back to XML.</p>\n\n<p><a href=\"http://xstream.codehaus.org/tutorial.html\" rel=\"nofollow noreferrer\">XStream</a> makes this really easy.</p>\n\n<p>For example, you would define the main object, which in your case is CustomData (I'm using public fields to keep the example simple):</p>\n\n<pre><code>public class CustomData {\n public String tag1;\n public String tag2;\n public String location;\n public String tag3;\n}\n</code></pre>\n\n<p>Then you initialize XStream:</p>\n\n<pre><code>XStream xstream = new XStream();\n// if you need to output the main tag in lowercase, use the following line\nxstream.alias(\"customdata\", CustomData.class); \n</code></pre>\n\n<p>Now you can construct an object from XML, set the location field on the object and regenerate the XML:</p>\n\n<pre><code>CustomData d = (CustomData)xstream.fromXML(xml);\nd.location = \"http://stackoverflow.com\";\nxml = xstream.toXML(d);\n</code></pre>\n\n<p>How does that sound?</p>\n"
},
{
"answer_id": 16019,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 4,
"selected": true,
"text": "<p>How about an XPath based approach? I like this approach as the logic is super-easy to understand. The code is pretty much self-documenting.</p>\n\n<p>If your xml document is available to you as an org.w3c.dom.Document object (as most parsers return), then you could do something like the following:</p>\n\n<pre><code>// get the list of customdata nodes\nNodeList customDataNodeSet = findNodes(document, \"//customdata\" );\n\nfor (int i=0 ; i < customDataNodeSet.getLength() ; i++) {\n Node customDataNode = customDataNodeSet.item( i );\n\n // get the location nodes (if any) within this one customdata node\n NodeList locationNodeSet = findNodes(customDataNode, \"location\" );\n\n if (locationNodeSet.getLength() > 0) {\n // replace\n locationNodeSet.item( 0 ).setTextContent( \"http://stackoverflow.com/\" );\n }\n else {\n // insert\n Element newLocationNode = document.createElement( \"location\" );\n newLocationNode.setTextContent(\"http://stackoverflow.com/\" );\n customDataNode.appendChild( newLocationNode );\n }\n}\n</code></pre>\n\n<p>And here's the helper method findNodes that does the XPath search.</p>\n\n<pre><code>private NodeList findNodes( Object obj, String xPathString )\n throws XPathExpressionException {\n\n XPath xPath = XPathFactory.newInstance().newXPath();\n XPathExpression expression = xPath.compile( xPathString );\n return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );\n}\n</code></pre>\n"
},
{
"answer_id": 16375,
"author": "Olly",
"author_id": 1174,
"author_profile": "https://Stackoverflow.com/users/1174",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't know the schema the XStream solution probably isn't the way to go. At least XStream is on your radar now, might come in handy in the future!</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86/"
] | I have a `XmlDocument` in java, created with the `Weblogic XmlDocument` parser.
I want to replace the content of a tag in this `XMLDocument` with my own data, or insert the tag if it isn't there.
```
<customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
```
For example I want to insert a URL in the location tag:
```
<location>http://something</location>
```
but otherwise leave the XML as is.
Currently I use a `XMLCursor`:
```
XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
```
I tried to find a "quick" `xquery` way to do this since the `XmlDocument` has an `execQuery` method, but didn't find it very easy.
Do anyone have a better way than this? It seems a bit elaborate. | How about an XPath based approach? I like this approach as the logic is super-easy to understand. The code is pretty much self-documenting.
If your xml document is available to you as an org.w3c.dom.Document object (as most parsers return), then you could do something like the following:
```
// get the list of customdata nodes
NodeList customDataNodeSet = findNodes(document, "//customdata" );
for (int i=0 ; i < customDataNodeSet.getLength() ; i++) {
Node customDataNode = customDataNodeSet.item( i );
// get the location nodes (if any) within this one customdata node
NodeList locationNodeSet = findNodes(customDataNode, "location" );
if (locationNodeSet.getLength() > 0) {
// replace
locationNodeSet.item( 0 ).setTextContent( "http://stackoverflow.com/" );
}
else {
// insert
Element newLocationNode = document.createElement( "location" );
newLocationNode.setTextContent("http://stackoverflow.com/" );
customDataNode.appendChild( newLocationNode );
}
}
```
And here's the helper method findNodes that does the XPath search.
```
private NodeList findNodes( Object obj, String xPathString )
throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile( xPathString );
return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );
}
``` |
15,949 | <p>I have a tomcat instance setup but the database connection I have configured in <code>context.xml</code> keeps dying after periods of inactivity.</p>
<p>When I check the logs I get the following error:</p>
<p>com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was68051 seconds
ago. The last packet sent successfully to the server was 68051 seconds
ago, which is longer than the server configured value of
'wait_timeout'. You should consider either expiring and/or testing
connection validity before use in your application, increasing the
server configured values for client timeouts, or using the Connector/J
connection property 'autoReconnect=true' to avoid this problem.</p>
<p>Here is the configuration in context.xml:</p>
<pre><code><Resource name="dataSourceName"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="username"
password="********"
removeAbandoned = "true"
logAbandoned = "true"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/databasename?autoReconnect=true&amp;useEncoding=true&amp;characterEncoding=UTF-8" />
</code></pre>
<p>I am using <code>autoReconnect=true</code> like the error says to do, but the connection keeps dying. I have never seen this happen before.</p>
<p>I have also verified that all database connections are being closed properly.</p>
| [
{
"answer_id": 16168,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html\" rel=\"noreferrer\">Tomcat Documentation</a></p>\n\n<p>DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components:</p>\n\n<pre><code>* Jakarta-Commons DBCP\n* Jakarta-Commons Collections\n* Jakarta-Commons Pool\n</code></pre>\n\n<p>This attribute may help you out.</p>\n\n<pre><code>removeAbandonedTimeout=\"60\"\n</code></pre>\n\n<p>I'm using the same connection pooling stuff and I'm setting these properties to prevent the same thing it's just not configured through tomcat.\nBut if the first thing doesn't work try these.</p>\n\n<pre><code>testWhileIdle=true\ntimeBetweenEvictionRunsMillis=300000\n</code></pre>\n"
},
{
"answer_id": 16751,
"author": "abyx",
"author_id": 573,
"author_profile": "https://Stackoverflow.com/users/573",
"pm_score": 0,
"selected": false,
"text": "<p>I do not know whether the above answer does basically the same thing, but some of our systems use the DB connection about once a week and I've seen that we provide a -Otimeout flag or something of that sort to mysql to set the connection timeout.</p>\n"
},
{
"answer_id": 74086,
"author": "Sindri Traustason",
"author_id": 1113,
"author_profile": "https://Stackoverflow.com/users/1113",
"pm_score": 2,
"selected": false,
"text": "<p>Just to clarify what is actually causing this. MySQL by default terminates open connections after 8 hours of inactivity. However the database connection pool will retain connections for longer than that.</p>\n\n<p>So by setting timeBetweenEvictionRunsMillis=300000 you are instructing the connection pool to run through connections and evict and close idle ones every 5 minutes.</p>\n"
},
{
"answer_id": 528106,
"author": "Ophir",
"author_id": 17634,
"author_profile": "https://Stackoverflow.com/users/17634",
"pm_score": 1,
"selected": false,
"text": "<p>The removeAbandoned option is deprecated as of DBCP 1.2 (though <a href=\"http://commons.apache.org/dbcp/apidocs/org/apache/commons/dbcp/AbandonedConfig.html\" rel=\"nofollow noreferrer\">still present</a> in the 1.3 branch). <a href=\"http://mail-archives.apache.org/mod_mbox/commons-user/200604.mbox/%[email protected]%3E\" rel=\"nofollow noreferrer\">Here</a>'s a non-official explanation.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22/"
] | I have a tomcat instance setup but the database connection I have configured in `context.xml` keeps dying after periods of inactivity.
When I check the logs I get the following error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was68051 seconds
ago. The last packet sent successfully to the server was 68051 seconds
ago, which is longer than the server configured value of
'wait\_timeout'. You should consider either expiring and/or testing
connection validity before use in your application, increasing the
server configured values for client timeouts, or using the Connector/J
connection property 'autoReconnect=true' to avoid this problem.
Here is the configuration in context.xml:
```
<Resource name="dataSourceName"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="username"
password="********"
removeAbandoned = "true"
logAbandoned = "true"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/databasename?autoReconnect=true&useEncoding=true&characterEncoding=UTF-8" />
```
I am using `autoReconnect=true` like the error says to do, but the connection keeps dying. I have never seen this happen before.
I have also verified that all database connections are being closed properly. | [Tomcat Documentation](http://tomcat.apache.org/tomcat-5.5-doc/jndi-datasource-examples-howto.html)
DBCP uses the Jakarta-Commons Database Connection Pool. It relies on number of Jakarta-Commons components:
```
* Jakarta-Commons DBCP
* Jakarta-Commons Collections
* Jakarta-Commons Pool
```
This attribute may help you out.
```
removeAbandonedTimeout="60"
```
I'm using the same connection pooling stuff and I'm setting these properties to prevent the same thing it's just not configured through tomcat.
But if the first thing doesn't work try these.
```
testWhileIdle=true
timeBetweenEvictionRunsMillis=300000
``` |
15,954 | <p>How can a <code>sdbm</code> hash function (such as <a href="http://www.cse.yorku.ca/~oz/hash.html" rel="nofollow noreferrer">this</a>) be implemented in C# ?</p>
| [
{
"answer_id": 15971,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 2,
"selected": false,
"text": "<p>You can take the C code almost without changes:</p>\n\n<pre><code>uint sdbm( string str )\n{\n uint hash = 0;\n foreach( char ch in str )\n {\n hash = ch + (hash << 6) + (hash << 16) - hash;\n }\n return hash;\n}\n</code></pre>\n\n<p>Or did you think of something more sophisticated?</p>\n"
},
{
"answer_id": 15972,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "<p>I don't have a C compiler set up so I can't test to see if it performs the same, but I <em>think</em> the following is correct:</p>\n\n<pre><code>private static ulong SBDM(string str)\n{\n ulong hash = 0;\n\n foreach (char c in str)\n {\n hash = c + (hash << 6) + (hash << 16) - hash;\n }\n\n return hash;\n}\n</code></pre>\n\n<p>If you just need to get a hash of the string and it doesn't matter too much what the implementation is you can always do the <code>String.GetHashCode()</code>;</p>\n"
},
{
"answer_id": 18111,
"author": "Christo",
"author_id": 1658,
"author_profile": "https://Stackoverflow.com/users/1658",
"pm_score": 0,
"selected": false,
"text": "<p>The result from the hash differs between the C++ and C# implementation. I figured out that str parameter needs to be passed as a byte array.</p>\n\n<pre><code>private uint sdbm(byte[] str)\n{\n uint hash = 0;\n\n foreach (char ch in str)\n hash = ch + (hash << 6) + (hash << 16) - hash;\n\n return hash;\n}\n</code></pre>\n\n<p>Call the method by converting the value to be hashed with the <code>BitConverter.GetBytes</code> method.</p>\n\n<pre><code>uint Hash = sdbm(BitConverter.GetBytes(myID));\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658/"
] | How can a `sdbm` hash function (such as [this](http://www.cse.yorku.ca/~oz/hash.html)) be implemented in C# ? | You can take the C code almost without changes:
```
uint sdbm( string str )
{
uint hash = 0;
foreach( char ch in str )
{
hash = ch + (hash << 6) + (hash << 16) - hash;
}
return hash;
}
```
Or did you think of something more sophisticated? |
15,979 | <p>I use solr to search for documents and when trying to search for documents using this query "<code>id:*</code>", I get this query parser exception telling that it cannot parse the query with * or ? as the first character. </p>
<pre><code>HTTP Status 400 - org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
type Status report
message org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
description The request sent by the client was syntactically incorrect (org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery).
</code></pre>
<p>Is there any patch for getting this to work with just * ? Or is it very costly to do such a query?</p>
| [
{
"answer_id": 16661,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 1,
"selected": false,
"text": "<p>I'm assuming with id:* you're just trying to match all documents, right?</p>\n\n<p>I've never used solr before, but in my Lucene experience, when ingesting data, we've added a hidden field to every document, then when we need to return every record we do a search for the string constant in that field that's the same for every record.</p>\n\n<p>If you can't add a field like that in your situation, you could use a RegexQuery with a regex that would match anything that could be found in the id field.</p>\n\n<p>Edit: actually answering the question. I've never heard of a patch to get that to work, but I would be surprised if it could even be made to work reasonably well. See <a href=\"https://stackoverflow.com/questions/8532/with-lucene-why-do-i-get-a-too-many-clauses-error-if-i-do-a-prefix-search\">this question</a> for a reason why unconstrained PrefixQuery's can cause a problem.</p>\n"
},
{
"answer_id": 17458,
"author": "cnu",
"author_id": 1448,
"author_profile": "https://Stackoverflow.com/users/1448",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, I have been using a workaround for this. I append a character to the id, eg: A1, A2, etc.</p>\n\n<p>With such values in the field, it is possible to search using the query <code>id:A*</code></p>\n\n<p>But would love to find whether a true solution exists.</p>\n"
},
{
"answer_id": 23095,
"author": "Joe Shaw",
"author_id": 156,
"author_profile": "https://Stackoverflow.com/users/156",
"pm_score": 3,
"selected": false,
"text": "<p>Lucene doesn't allow you to start WildcardQueries with an asterisk by default, because those are incredibly expensive queries and will be very, very, very slow on large indexes.</p>\n\n<p>If you're using the Lucene QueryParser, call setAllowLeadingWildcard(true) on it to enable it.</p>\n\n<p>If you want all of the documents with a certain field set, you are much better off querying or walking the index programmatically than using QueryParser. You should really only use QueryParser to parse user input.</p>\n"
},
{
"answer_id": 23554,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": false,
"text": "<pre><code>id:[a* TO z*] id:[0* TO 9*] etc.\n</code></pre>\n\n<p>I just did this in lukeall on my index and it worked, therefore it should work in Solr which uses the standard query parser. I don't actually use Solr.</p>\n\n<p>In base Lucene there's a fine reason for why you'd never query for every document, it's because to query for a document you must use a <code>new indexReader(\"DirectoryName\")</code> and apply a query to it. Therefore you could totally skip applying a query to it and use the <code>indexReader</code> methods <code>numDocs()</code> to get a count of all the documents, and <code>document(int n)</code> to retrieve any of the documents.</p>\n"
},
{
"answer_id": 74475,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 4,
"selected": false,
"text": "<p>If you want all documents, do a query on *:*</p>\n\n<p>If you want all documents with a certain field (e.g. id) try id:[* TO *]</p>\n"
},
{
"answer_id": 104416,
"author": "Mark B",
"author_id": 13070,
"author_profile": "https://Stackoverflow.com/users/13070",
"pm_score": 2,
"selected": false,
"text": "<p>If you are just trying to get all documents, Solr does support the *:* query. It's the only time I know of that Solr will let you begin a query with an *. I'm sure you've probably seen this as the default query in the Solr admin page.</p>\n\n<p>If you are trying to do a more specific query with an * as the first character, like say id:*456 then one of the best ways I've seen is to index that field twice. Once normally (field name: id), and once with all the characters reversed (field name: reverse_id). Then you could essentially do the query id:<em>456 by sending the query reverse_id:654</em> instead. Hope that makes sense.</p>\n\n<p>You can also search the Solr user group mailing list at <a href=\"http://www.mail-archive.com/[email protected]/\" rel=\"nofollow noreferrer\">http://www.mail-archive.com/[email protected]/</a> where questions like this come up quite often.</p>\n"
},
{
"answer_id": 6899858,
"author": "Daniel Rijkhof",
"author_id": 648458,
"author_profile": "https://Stackoverflow.com/users/648458",
"pm_score": 2,
"selected": false,
"text": "<p>The following Solr issue is a request to be able to configure the default lucene query parser.\n<a href=\"https://issues.apache.org/jira/browse/SOLR-218\" rel=\"nofollow\">https://issues.apache.org/jira/browse/SOLR-218</a></p>\n\n<p>In this issue you can find the following description how to 'patch' Solr. This modification would allow you to start queries with a *.</p>\n\n<blockquote>\n <p>Jonas Salk: I've basically updated only one Java file: SolrQueryParser.java.</p>\n</blockquote>\n\n<pre><code>public SolrQueryParser(IndexSchema schema, String defaultField) { \n ... \n setAllowLeadingWildcard(true); \n setLowercaseExpandedTerms(true); \n ... \n}\n\n ...\n\npublic SolrQueryParser(QParser parser, String defaultField, Analyzer analyzer) {\n ... \n setAllowLeadingWildcard(true); \n setLowercaseExpandedTerms(true);\n ... \n}\n</code></pre>\n\n<p>I'm not sure if setLowercaseExpandedTerms is needed...</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | I use solr to search for documents and when trying to search for documents using this query "`id:*`", I get this query parser exception telling that it cannot parse the query with \* or ? as the first character.
```
HTTP Status 400 - org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
type Status report
message org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery
description The request sent by the client was syntactically incorrect (org.apache.lucene.queryParser.ParseException: Cannot parse 'id:*': '*' or '?' not allowed as first character in WildcardQuery).
```
Is there any patch for getting this to work with just \* ? Or is it very costly to do such a query? | If you want all documents, do a query on \*:\*
If you want all documents with a certain field (e.g. id) try id:[\* TO \*] |
15,995 | <p>Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and * that we see in the examples?</p>
<p>Refer <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196" rel="noreferrer">Fate of reduce() in Python 3000</a> by GvR</p>
| [
{
"answer_id": 16049,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 2,
"selected": false,
"text": "<p>Not sure if this is what you are after but you can <a href=\"http://www.google.com/codesearch\" rel=\"nofollow noreferrer\">search source code on Google</a>.</p>\n\n<p>Follow the link for a search on <a href=\"http://www.google.com/codesearch?q=function%3Areduce()+lang%3Apython&hl=en&btnG=Search+Code\" rel=\"nofollow noreferrer\">'function:reduce() lang:python'</a> on Google Code search</p>\n\n<p>At first glance the following projects use <code>reduce()</code></p>\n\n<ul>\n<li>MoinMoin</li>\n<li>Zope</li>\n<li>Numeric</li>\n<li>ScientificPython</li>\n</ul>\n\n<p>etc. etc. but then these are hardly surprising since they are huge projects.</p>\n\n<p>The functionality of reduce can be done using function recursion which I guess Guido thought was more explicit.</p>\n\n<p>Update:</p>\n\n<p>Since Google's Code Search was discontinued on 15-Jan-2012, besides reverting to regular Google searches, there's something called <a href=\"http://icodesnip.com/\" rel=\"nofollow noreferrer\">Code Snippets Collection</a> that looks promising. A number of other resources are mentioned in answers this (closed) question <a href=\"https://stackoverflow.com/questions/7778034/replacement-for-google-code-search\">Replacement for Google Code Search?</a>.</p>\n\n<p>Update 2 (29-May-2017):</p>\n\n<p>A good source for Python examples (in open-source code) is the <a href=\"http://nullege.com/\" rel=\"nofollow noreferrer\">Nullege search engine</a>.</p>\n"
},
{
"answer_id": 16091,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 1,
"selected": false,
"text": "<p>I have an old Python implementation of <a href=\"http://examples.oreilly.com/upt2/split/pipegrep\" rel=\"nofollow noreferrer\">pipegrep</a> that uses reduce and the glob module to build a list of files to process:</p>\n\n<pre><code>files = []\nfiles.extend(reduce(lambda x, y: x + y, map(glob.glob, args)))\n</code></pre>\n\n<p>I found it handy at the time, but it's really not necessary, as something similar is just as good, and probably more readable</p>\n\n<pre><code>files = []\nfor f in args:\n files.extend(glob.glob(f))\n</code></pre>\n"
},
{
"answer_id": 16198,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 3,
"selected": false,
"text": "<p>@Blair Conrad: You could also implement your glob/reduce using sum, like so:</p>\n\n<pre><code>files = sum([glob.glob(f) for f in args], [])\n</code></pre>\n\n<p>This is less verbose than either of your two examples, is perfectly Pythonic, and is still only one line of code.</p>\n\n<p>So to answer the original question, I personally try to avoid using reduce because it's never really necessary and I find it to be less clear than other approaches. However, some people get used to reduce and come to prefer it to list comprehensions (especially Haskell programmers). But if you're not already thinking about a problem in terms of reduce, you probably don't need to worry about using it.</p>\n"
},
{
"answer_id": 21247,
"author": "Tomi Kyöstilä",
"author_id": 616,
"author_profile": "https://Stackoverflow.com/users/616",
"pm_score": 2,
"selected": false,
"text": "<p>After grepping my code, it seems the only thing I've used reduce for is calculating the factorial:</p>\n\n<pre><code>reduce(operator.mul, xrange(1, x+1) or (1,))\n</code></pre>\n"
},
{
"answer_id": 41660,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 4,
"selected": false,
"text": "<p>The usage of <code>reduce</code> that I found in my code involved the situation where I had some class structure for logic expression and I needed to convert a list of these expression objects to a conjunction of the expressions. I already had a function <code>make_and</code> to create a conjunction given two expressions, so I wrote <code>reduce(make_and,l)</code>. (I knew the list wasn't empty; otherwise it would have been something like <code>reduce(make_and,l,make_true)</code>.)</p>\n\n<p>This is exactly the reason that (some) functional programmers like <code>reduce</code> (or <em>fold</em> functions, as such functions are typically called). There are often already many binary functions like <code>+</code>, <code>*</code>, <code>min</code>, <code>max</code>, concatenation and, in my case, <code>make_and</code> and <code>make_or</code>. Having a <code>reduce</code> makes it trivial to lift these operations to lists (or trees or whatever you got, for fold functions in general).</p>\n\n<p>Of course, if certain instantiations (such as <code>sum</code>) are often used, then you don't want to keep writing <code>reduce</code>. However, instead of defining the <code>sum</code> with some for-loop, you <em>can</em> just as easily define it with <code>reduce</code>.</p>\n\n<p>Readability, as mentioned by others, is indeed an issue. You could argue, however, that only reason why people find <code>reduce</code> less \"clear\" is because it is not a function that many people know and/or use.</p>\n"
},
{
"answer_id": 280242,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 6,
"selected": false,
"text": "<p>The other uses I've found for it besides + and * were with and and or, but now we have <code>any</code> and <code>all</code> to replace those cases. </p>\n\n<p><code>foldl</code> and <code>foldr</code> do come up in Scheme a lot... </p>\n\n<p>Here's some cute usages:</p>\n\n<p><b>Flatten a list</b></p>\n\n<p>Goal: turn <code>[[1, 2, 3], [4, 5], [6, 7, 8]]</code> into <code>[1, 2, 3, 4, 5, 6, 7, 8]</code>.</p>\n\n<pre><code>reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])\n</code></pre>\n\n<p><b>List of digits to a number</b></p>\n\n<p>Goal: turn <code>[1, 2, 3, 4, 5, 6, 7, 8]</code> into <code>12345678</code>.</p>\n\n<p>Ugly, slow way:</p>\n\n<pre><code>int(\"\".join(map(str, [1,2,3,4,5,6,7,8])))\n</code></pre>\n\n<p>Pretty <code>reduce</code> way:</p>\n\n<pre><code>reduce(lambda a,d: 10*a+d, [1,2,3,4,5,6,7,8], 0)\n</code></pre>\n"
},
{
"answer_id": 282206,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 6,
"selected": false,
"text": "<p><code>reduce()</code> can be used to find <a href=\"https://stackoverflow.com/questions/147515/least-common-multiple-for-3-or-more-numbers#147539\">Least common multiple for 3 or more numbers</a>:</p>\n<pre><code>#!/usr/bin/env python\nfrom math import gcd\nfrom functools import reduce\n\ndef lcm(*args):\n return reduce(lambda a,b: a * b // gcd(a, b), args)\n</code></pre>\n<p>Example:</p>\n<pre><code>>>> lcm(100, 23, 98)\n112700\n>>> lcm(*range(1, 20))\n232792560\n</code></pre>\n"
},
{
"answer_id": 282678,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 5,
"selected": false,
"text": "<p><code>reduce()</code> could be used to resolve dotted names (where <code>eval()</code> is too unsafe to use):</p>\n\n<pre><code>>>> import __main__\n>>> reduce(getattr, \"os.path.abspath\".split('.'), __main__)\n<function abspath at 0x009AB530>\n</code></pre>\n"
},
{
"answer_id": 2701826,
"author": "ben",
"author_id": 309368,
"author_profile": "https://Stackoverflow.com/users/309368",
"pm_score": 2,
"selected": false,
"text": "<p>I'm writing a compose function for a language, so I construct the composed function using reduce along with my apply operator.</p>\n\n<p>In a nutshell, compose takes a list of functions to compose into a single function. If I have a complex operation that is applied in stages, I want to put it all together like so:</p>\n\n<pre><code>complexop = compose(stage4, stage3, stage2, stage1)\n</code></pre>\n\n<p>This way, I can then apply it to an expression like so:</p>\n\n<pre><code>complexop(expression)\n</code></pre>\n\n<p>And I want it to be equivalent to:</p>\n\n<pre><code>stage4(stage3(stage2(stage1(expression))))\n</code></pre>\n\n<p>Now, to build my internal objects, I want it to say:</p>\n\n<pre><code>Lambda([Symbol('x')], Apply(stage4, Apply(stage3, Apply(stage2, Apply(stage1, Symbol('x'))))))\n</code></pre>\n\n<p>(The Lambda class builds a user-defined function, and Apply builds a function application.)</p>\n\n<p>Now, reduce, unfortunately, folds the wrong way, so I wound up using, roughly:</p>\n\n<pre><code>reduce(lambda x,y: Apply(y, x), reversed(args + [Symbol('x')]))\n</code></pre>\n\n<p>To figure out what reduce produces, try these in the REPL:</p>\n\n<pre><code>reduce(lambda x, y: (x, y), range(1, 11))\nreduce(lambda x, y: (y, x), reversed(range(1, 11)))\n</code></pre>\n"
},
{
"answer_id": 3272453,
"author": "ssoler",
"author_id": 170912,
"author_profile": "https://Stackoverflow.com/users/170912",
"pm_score": 5,
"selected": false,
"text": "<p>Find the intersection of N given lists:</p>\n\n<pre><code>input_list = [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]]\n\nresult = reduce(set.intersection, map(set, input_list))\n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>result = set([3, 4, 5])\n</code></pre>\n\n<p>via: <a href=\"https://stackoverflow.com/questions/642763/python-intersection-of-two-lists\">Python - Intersection of two lists</a></p>\n"
},
{
"answer_id": 12026042,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "<p>You could replace <code>value = json_obj['a']['b']['c']['d']['e']</code> with:</p>\n\n<pre><code>value = reduce(dict.__getitem__, 'abcde', json_obj)\n</code></pre>\n\n<p>If you already have the path <code>a/b/c/..</code> as a list. For example, <a href=\"https://stackoverflow.com/a/11919150/4279\">Change values in dict of nested dicts using items in a list</a>.</p>\n"
},
{
"answer_id": 12171466,
"author": "Chris X",
"author_id": 1567046,
"author_profile": "https://Stackoverflow.com/users/1567046",
"pm_score": 4,
"selected": false,
"text": "<p>I think reduce is a silly command. Hence:</p>\n\n<pre><code>reduce(lambda hold,next:hold+chr(((ord(next.upper())-65)+13)%26+65),'znlorabggbbhfrshy','')\n</code></pre>\n"
},
{
"answer_id": 12310900,
"author": "tborg",
"author_id": 1116899,
"author_profile": "https://Stackoverflow.com/users/1116899",
"pm_score": 2,
"selected": false,
"text": "<p>Reduce isn't limited to scalar operations; it can also be used to sort things into buckets. (This is what I use reduce for most often).</p>\n\n<p>Imagine a case in which you have a list of objects, and you want to re-organize it hierarchically based on properties stored flatly in the object. In the following example, I produce a list of metadata objects related to articles in an XML-encoded newspaper with the <code>articles</code> function. <code>articles</code> generates a list of XML elements, and then maps through them one by one, producing objects that hold some interesting info about them. On the front end, I'm going to want to let the user browse the articles by section/subsection/headline. So I use <code>reduce</code> to take the list of articles and return a single dictionary that reflects the section/subsection/article hierarchy.</p>\n\n<pre><code>from lxml import etree\nfrom Reader import Reader\n\nclass IssueReader(Reader):\n def articles(self):\n arts = self.q('//div3') # inherited ... runs an xpath query against the issue\n subsection = etree.XPath('./ancestor::div2/@type')\n section = etree.XPath('./ancestor::div1/@type')\n header_text = etree.XPath('./head//text()')\n return map(lambda art: {\n 'text_id': self.id,\n 'path': self.getpath(art)[0],\n 'subsection': (subsection(art)[0] or '[none]'),\n 'section': (section(art)[0] or '[none]'),\n 'headline': (''.join(header_text(art)) or '[none]')\n }, arts)\n\n def by_section(self):\n arts = self.articles()\n\n def extract(acc, art): # acc for accumulator\n section = acc.get(art['section'], False)\n if section:\n subsection = acc.get(art['subsection'], False)\n if subsection:\n subsection.append(art)\n else:\n section[art['subsection']] = [art]\n else:\n acc[art['section']] = {art['subsection']: [art]}\n return acc\n\n return reduce(extract, arts, {})\n</code></pre>\n\n<p>I give both functions here because I think it shows how map and reduce can complement each other nicely when dealing with objects. The same thing could have been accomplished with a for loop, ... but spending some serious time with a functional language has tended to make me think in terms of map and reduce.</p>\n\n<p>By the way, if anybody has a better way to set properties like I'm doing in <code>extract</code>, where the parents of the property you want to set might not exist yet, please let me know.</p>\n"
},
{
"answer_id": 15541396,
"author": "Sidharth C. Nadhan",
"author_id": 2094708,
"author_profile": "https://Stackoverflow.com/users/2094708",
"pm_score": 2,
"selected": false,
"text": "<p>reduce can be used to get the list with the maximum nth element</p>\n\n<pre><code>reduce(lambda x,y: x if x[2] > y[2] else y,[[1,2,3,4],[5,2,5,7],[1,6,0,2]])\n</code></pre>\n\n<p>would return [5, 2, 5, 7] as it is the list with max 3rd element +</p>\n"
},
{
"answer_id": 21144816,
"author": "beardc",
"author_id": 386279,
"author_profile": "https://Stackoverflow.com/users/386279",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Function composition</strong>: If you already have a list of functions that you'd like to apply in succession, such as:</p>\n\n<pre><code>color = lambda x: x.replace('brown', 'blue')\nspeed = lambda x: x.replace('quick', 'slow')\nwork = lambda x: x.replace('lazy', 'industrious')\nfs = [str.lower, color, speed, work, str.title]\n</code></pre>\n\n<p>Then you can apply them all consecutively with:</p>\n\n<pre><code>>>> call = lambda s, func: func(s)\n>>> s = \"The Quick Brown Fox Jumps Over the Lazy Dog\"\n>>> reduce(call, fs, s)\n'The Slow Blue Fox Jumps Over The Industrious Dog'\n</code></pre>\n\n<p>In this case, method chaining may be more readable. But sometimes it isn't possible, and this kind of composition may be more readable and maintainable than a <code>f1(f2(f3(f4(x))))</code> kind of syntax.</p>\n"
},
{
"answer_id": 21956185,
"author": "lessthanl0l",
"author_id": 3285376,
"author_profile": "https://Stackoverflow.com/users/3285376",
"pm_score": 0,
"selected": false,
"text": "<p>Using reduce() to find out if a list of dates are consecutive:</p>\n\n<pre><code>from datetime import date, timedelta\n\n\ndef checked(d1, d2):\n \"\"\"\n We assume the date list is sorted.\n If d2 & d1 are different by 1, everything up to d2 is consecutive, so d2\n can advance to the next reduction.\n If d2 & d1 are not different by 1, returning d1 - 1 for the next reduction\n will guarantee the result produced by reduce() to be something other than\n the last date in the sorted date list.\n\n Definition 1: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider consecutive\n Definition 2: 1/1/14, 1/2/14, 1/2/14, 1/3/14 is consider not consecutive\n\n \"\"\"\n #if (d2 - d1).days == 1 or (d2 - d1).days == 0: # for Definition 1\n if (d2 - d1).days == 1: # for Definition 2\n return d2\n else:\n return d1 + timedelta(days=-1)\n\n# datelist = [date(2014, 1, 1), date(2014, 1, 3),\n# date(2013, 12, 31), date(2013, 12, 30)]\n\n# datelist = [date(2014, 2, 19), date(2014, 2, 19), date(2014, 2, 20),\n# date(2014, 2, 21), date(2014, 2, 22)]\n\ndatelist = [date(2014, 2, 19), date(2014, 2, 21),\n date(2014, 2, 22), date(2014, 2, 20)]\n\ndatelist.sort()\n\nif datelist[-1] == reduce(checked, datelist):\n print \"dates are consecutive\"\nelse:\n print \"dates are not consecutive\"\n</code></pre>\n"
},
{
"answer_id": 21956201,
"author": "lessthanl0l",
"author_id": 3285376,
"author_profile": "https://Stackoverflow.com/users/3285376",
"pm_score": 1,
"selected": false,
"text": "<p>Let say that there are some yearly statistic data stored a list of Counters.\nWe want to find the MIN/MAX values in each month across the different years. \nFor example, for January it would be 10. And for February it would be 15. \nWe need to store the results in a new Counter.</p>\n\n<pre><code>from collections import Counter\n\nstat2011 = Counter({\"January\": 12, \"February\": 20, \"March\": 50, \"April\": 70, \"May\": 15,\n \"June\": 35, \"July\": 30, \"August\": 15, \"September\": 20, \"October\": 60,\n \"November\": 13, \"December\": 50})\n\nstat2012 = Counter({\"January\": 36, \"February\": 15, \"March\": 50, \"April\": 10, \"May\": 90,\n \"June\": 25, \"July\": 35, \"August\": 15, \"September\": 20, \"October\": 30,\n \"November\": 10, \"December\": 25})\n\nstat2013 = Counter({\"January\": 10, \"February\": 60, \"March\": 90, \"April\": 10, \"May\": 80,\n \"June\": 50, \"July\": 30, \"August\": 15, \"September\": 20, \"October\": 75,\n \"November\": 60, \"December\": 15})\n\nstat_list = [stat2011, stat2012, stat2013]\n\nprint reduce(lambda x, y: x & y, stat_list) # MIN\nprint reduce(lambda x, y: x | y, stat_list) # MAX\n</code></pre>\n"
},
{
"answer_id": 23764928,
"author": "Aleksei astynax Pirogov",
"author_id": 590667,
"author_profile": "https://Stackoverflow.com/users/590667",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import os\n\nfiles = [\n # full filenames\n \"var/log/apache/errors.log\",\n \"home/kane/images/avatars/crusader.png\",\n \"home/jane/documents/diary.txt\",\n \"home/kane/images/selfie.jpg\",\n \"var/log/abc.txt\",\n \"home/kane/.vimrc\",\n \"home/kane/images/avatars/paladin.png\",\n]\n\n# unfolding of plain filiname list to file-tree\nfs_tree = ({}, # dict of folders\n []) # list of files\nfor full_name in files:\n path, fn = os.path.split(full_name)\n reduce(\n # this fucction walks deep into path\n # and creates placeholders for subfolders\n lambda d, k: d[0].setdefault(k, # walk deep\n ({}, [])), # or create subfolder storage\n path.split(os.path.sep),\n fs_tree\n )[1].append(fn)\n\nprint fs_tree\n#({'home': (\n# {'jane': (\n# {'documents': (\n# {},\n# ['diary.txt']\n# )},\n# []\n# ),\n# 'kane': (\n# {'images': (\n# {'avatars': (\n# {},\n# ['crusader.png',\n# 'paladin.png']\n# )},\n# ['selfie.jpg']\n# )},\n# ['.vimrc']\n# )},\n# []\n# ),\n# 'var': (\n# {'log': (\n# {'apache': (\n# {},\n# ['errors.log']\n# )},\n# ['abc.txt']\n# )},\n# [])\n#},\n#[])\n</code></pre>\n"
},
{
"answer_id": 24061830,
"author": "JulienD",
"author_id": 2197181,
"author_profile": "https://Stackoverflow.com/users/2197181",
"pm_score": 1,
"selected": false,
"text": "<p>I have objects representing some kind of overlapping intervals (genomic exons), and redefined their intersection using <code>__and__</code>:\n</p>\n\n<pre><code>class Exon:\n def __init__(self):\n ...\n def __and__(self,other):\n ...\n length = self.length + other.length # (e.g.)\n return self.__class__(...length,...)\n</code></pre>\n\n<p>Then when I have a collection of them (for instance, in the same gene), I use\n</p>\n\n<pre><code>intersection = reduce(lambda x,y: x&y, exons)\n</code></pre>\n"
},
{
"answer_id": 24321770,
"author": "Jian",
"author_id": 1205529,
"author_profile": "https://Stackoverflow.com/users/1205529",
"pm_score": 3,
"selected": false,
"text": "<p><code>reduce</code> can be used to support chained attribute lookups:</p>\n\n<pre><code>reduce(getattr, ('request', 'user', 'email'), self)\n</code></pre>\n\n<p>Of course, this is equivalent to</p>\n\n<pre><code>self.request.user.email\n</code></pre>\n\n<p>but it's useful when your code needs to accept an arbitrary list of attributes.</p>\n\n<p>(Chained attributes of arbitrary length are common when dealing with Django models.)</p>\n"
},
{
"answer_id": 24322230,
"author": "Jian",
"author_id": 1205529,
"author_profile": "https://Stackoverflow.com/users/1205529",
"pm_score": 3,
"selected": false,
"text": "<p><code>reduce</code> is useful when you need to find the union or intersection of a sequence of <code>set</code>-like objects. </p>\n\n<pre><code>>>> reduce(operator.or_, ({1}, {1, 2}, {1, 3})) # union\n{1, 2, 3}\n>>> reduce(operator.and_, ({1}, {1, 2}, {1, 3})) # intersection\n{1}\n</code></pre>\n\n<p>(Apart from actual <code>set</code>s, an example of these are <a href=\"https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects\" rel=\"noreferrer\">Django's Q objects</a>.)</p>\n\n<p>On the other hand, if you're dealing with <code>bool</code>s, you should use <code>any</code> and <code>all</code>:</p>\n\n<pre><code>>>> any((True, False, True))\nTrue\n</code></pre>\n"
},
{
"answer_id": 32611847,
"author": "deddu",
"author_id": 2168258,
"author_profile": "https://Stackoverflow.com/users/2168258",
"pm_score": 1,
"selected": false,
"text": "<pre><code>def dump(fname,iterable):\n with open(fname,'w') as f:\n reduce(lambda x, y: f.write(unicode(y,'utf-8')), iterable)\n</code></pre>\n"
},
{
"answer_id": 33895037,
"author": "MatthewRock",
"author_id": 2373609,
"author_profile": "https://Stackoverflow.com/users/2373609",
"pm_score": 2,
"selected": false,
"text": "<p>I just found useful usage of <code>reduce</code>: <em>splitting string without removing the delimiter</em>. <a href=\"http://programmaticallyspeaking.com/split-on-separator-but-keep-the-separator-in-python.html\" rel=\"nofollow\">The code is entirely from Programatically Speaking blog.</a> Here's the code:</p>\n\n<pre><code>reduce(lambda acc, elem: acc[:-1] + [acc[-1] + elem] if elem == \"\\n\" else acc + [elem], re.split(\"(\\n)\", \"a\\nb\\nc\\n\"), [])\n</code></pre>\n\n<p>Here's the result:</p>\n\n<pre><code>['a\\n', 'b\\n', 'c\\n', '']\n</code></pre>\n\n<p>Note that it handles edge cases that popular answer in SO doesn't. For more in-depth explanation, I am redirecting you to original blog post.</p>\n"
},
{
"answer_id": 34625496,
"author": "bjmc",
"author_id": 845210,
"author_profile": "https://Stackoverflow.com/users/845210",
"pm_score": 2,
"selected": false,
"text": "<p>I used <code>reduce</code> <a href=\"https://github.com/kvesteri/sqlalchemy-searchable/commit/16ad8578029842ef13c39a3f406b7c462b0b9467#diff-9c140f1f7440a51eeab99543dee3587aR189\" rel=\"nofollow\">to concatenate a list of PostgreSQL search vectors</a> with the <code>||</code> operator in sqlalchemy-searchable:</p>\n\n<pre><code>vectors = (self.column_vector(getattr(self.table.c, column_name))\n for column_name in self.indexed_columns)\nconcatenated = reduce(lambda x, y: x.op('||')(y), vectors)\ncompiled = concatenated.compile(self.conn)\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/15995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] | Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and \* that we see in the examples?
Refer [Fate of reduce() in Python 3000](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) by GvR | The other uses I've found for it besides + and \* were with and and or, but now we have `any` and `all` to replace those cases.
`foldl` and `foldr` do come up in Scheme a lot...
Here's some cute usages:
**Flatten a list**
Goal: turn `[[1, 2, 3], [4, 5], [6, 7, 8]]` into `[1, 2, 3, 4, 5, 6, 7, 8]`.
```
reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])
```
**List of digits to a number**
Goal: turn `[1, 2, 3, 4, 5, 6, 7, 8]` into `12345678`.
Ugly, slow way:
```
int("".join(map(str, [1,2,3,4,5,6,7,8])))
```
Pretty `reduce` way:
```
reduce(lambda a,d: 10*a+d, [1,2,3,4,5,6,7,8], 0)
``` |
16,007 | <p>Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.</p>
<pre><code>if (System.IO.Directory.Exists(photosLocation))
{
string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
if (files.Length > 0)
{
// TODO: return the url of the first file found;
}
}
</code></pre>
| [
{
"answer_id": 16031,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>So far as I know there's no single function which does this (maybe you were looking for the inverse of <a href=\"http://msdn.microsoft.com/en-us/library/ms524632.aspx\" rel=\"nofollow noreferrer\">MapPath</a>?). I'd love to know if such a function exists. Until then, I would just take the filename(s) returned by GetFiles, remove the path, and prepend the URL root. This can be done generically.</p>\n"
},
{
"answer_id": 16032,
"author": "Robin Robinson",
"author_id": 1629,
"author_profile": "https://Stackoverflow.com/users/1629",
"pm_score": -1,
"selected": false,
"text": "<p>I think this should work. It might be off on the slashes. Not sure if they are needed or not.</p>\n\n<pre><code>string url = Request.ApplicationPath + \"/\" + photosLocation + \"/\" + files[0];\n</code></pre>\n"
},
{
"answer_id": 16039,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 5,
"selected": true,
"text": "<p>As far as I know, there's no method to do what you want; at least not directly. I'd store the <code>photosLocation</code> as a path relative to the application; for example: <code>\"~/Images/\"</code>. This way, you could use MapPath to get the physical location, and <code>ResolveUrl</code> to get the URL (with a bit of help from <code>System.IO.Path</code>):</p>\n\n<pre><code>string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);\nif (Directory.Exists(photosLocationPath))\n{\n string[] files = Directory.GetFiles(photosLocationPath, \"*.jpg\");\n if (files.Length > 0)\n {\n string filenameRelative = photosLocation + Path.GetFilename(files[0]) \n return Page.ResolveUrl(filenameRelative);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 16040,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe this is not the best way, but it works.</p>\n\n<pre><code>// Here is your path\nString p = photosLocation + \"whatever.jpg\";\n\n// Here is the page address\nString pa = Page.Request.Url.AbsoluteUri;\n\n// Take the page name \nString pn = Page.Request.Url.LocalPath;\n\n// Here is the server address \nString sa = pa.Replace(pn, \"\");\n\n// Take the physical location of the page \nString pl = Page.Request.PhysicalPath;\n\n// Replace the backslash with slash in your path \npl = pl.Replace(\"\\\\\", \"/\"); \np = p.Replace(\"\\\\\", \"/\");\n\n// Root path \nString rp = pl.Replace(pn, \"\");\n\n// Take out same path \nString final = p.Replace(rp, \"\");\n\n// So your picture's address is \nString path = sa + final;\n</code></pre>\n\n<p>Edit: Ok, somebody marked as not helpful. Some explanation: take the physical path of the current page, split it into two parts: server and directory (like c:\\inetpub\\whatever.com\\whatever) and page name (like /Whatever.aspx). The image's physical path should contain the server's path, so \"substract\" them, leaving only the image's path relative to the server's (like: \\design\\picture.jpg). Replace the backslashes with slashes and append it to the server's url.</p>\n"
},
{
"answer_id": 16188,
"author": "Andy Rose",
"author_id": 1762,
"author_profile": "https://Stackoverflow.com/users/1762",
"pm_score": 3,
"selected": false,
"text": "<p>I've accepted Fredriks answer as it appears to solve the problem with the least amount of effort however the Request object doesn't appear to conatin the ResolveUrl method.\nThis can be accessed through the Page object or an Image control object:</p>\n\n<pre><code>myImage.ImageUrl = Page.ResolveUrl(photoURL);\nmyImage.ImageUrl = myImage.ResolveUrl(photoURL);\n</code></pre>\n\n<p>An alternative, if you are using a static class as I am, is to use the VirtualPathUtility:</p>\n\n<pre><code>myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);\n</code></pre>\n"
},
{
"answer_id": 6872552,
"author": "fireydude",
"author_id": 869290,
"author_profile": "https://Stackoverflow.com/users/869290",
"pm_score": 0,
"selected": false,
"text": "<p>The simple solution seems to be to have a temporary location within the website that you can access easily with URL and then you can move files to the physical location when you need to save them.</p>\n"
},
{
"answer_id": 8985747,
"author": "NxtWhat",
"author_id": 1166821,
"author_profile": "https://Stackoverflow.com/users/1166821",
"pm_score": 2,
"selected": false,
"text": "<p>This worked for me:</p>\n\n<pre><code>HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + \"ImageName\";\n</code></pre>\n"
},
{
"answer_id": 12897607,
"author": "Rafael Herscovici",
"author_id": 572771,
"author_profile": "https://Stackoverflow.com/users/572771",
"pm_score": 4,
"selected": false,
"text": "<p>this is what i use:</p>\n\n<pre><code>private string MapURL(string path)\n{\n string appPath = Server.MapPath(\"/\").ToLower();\n return string.Format(\"/{0}\", path.ToLower().Replace(appPath, \"\").Replace(@\"\\\", \"/\"));\n }\n</code></pre>\n"
},
{
"answer_id": 13101286,
"author": "Ross Presser",
"author_id": 864696,
"author_profile": "https://Stackoverflow.com/users/864696",
"pm_score": 4,
"selected": false,
"text": "<p>The problem with all these answers is that they do not take virtual directories into account.</p>\n\n<p>Consider:</p>\n\n<pre><code>Site named \"tempuri.com/\" rooted at c:\\domains\\site\nvirtual directory \"~/files\" at c:\\data\\files\nvirtual directory \"~/files/vip\" at c:\\data\\VIPcust\\files\n</code></pre>\n\n<p>So:</p>\n\n<pre><code>Server.MapPath(\"~/files/vip/readme.txt\") \n = \"c:\\data\\VIPcust\\files\\readme.txt\"\n</code></pre>\n\n<p>But there is <em>no</em> way to do this:</p>\n\n<pre><code>MagicResolve(\"c:\\data\\VIPcust\\files\\readme.txt\") \n = \"http://tempuri.com/files/vip/readme.txt\"\n</code></pre>\n\n<p>because there is no way to get a complete list of virtual directories.</p>\n"
},
{
"answer_id": 13452579,
"author": "adripanico",
"author_id": 1552386,
"author_profile": "https://Stackoverflow.com/users/1552386",
"pm_score": 0,
"selected": false,
"text": "<p>For get the left part of the URL:</p>\n\n<pre><code>?HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)\n\"http://localhost:1714\"\n</code></pre>\n\n<p>For get the application (web) name:</p>\n\n<pre><code>?HttpRuntime.AppDomainAppVirtualPath\n\"/\"\n</code></pre>\n\n<p>With this, you are available to add your relative path after that obtaining the complete URL.</p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1762/"
] | Basically I have some code to check a specific directory to see if an image is there and if so I want to assign a URL to the image to an ImageControl.
```
if (System.IO.Directory.Exists(photosLocation))
{
string[] files = System.IO.Directory.GetFiles(photosLocation, "*.jpg");
if (files.Length > 0)
{
// TODO: return the url of the first file found;
}
}
``` | As far as I know, there's no method to do what you want; at least not directly. I'd store the `photosLocation` as a path relative to the application; for example: `"~/Images/"`. This way, you could use MapPath to get the physical location, and `ResolveUrl` to get the URL (with a bit of help from `System.IO.Path`):
```
string photosLocationPath = HttpContext.Current.Server.MapPath(photosLocation);
if (Directory.Exists(photosLocationPath))
{
string[] files = Directory.GetFiles(photosLocationPath, "*.jpg");
if (files.Length > 0)
{
string filenameRelative = photosLocation + Path.GetFilename(files[0])
return Page.ResolveUrl(filenameRelative);
}
}
``` |
16,096 | <p>In WPF, how would I apply multiple styles to a <code>FrameworkElement</code>? For instance, I have a control which already has a style. I also have a separate style which I would like to add to it without blowing away the first one. The styles have different TargetTypes, so I can't just extend one with the other.</p>
| [
{
"answer_id": 16108,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 5,
"selected": false,
"text": "<p>But you can extend from another.. take a look at the BasedOn property</p>\n\n<pre><code><Style TargetType=\"TextBlock\">\n <Setter Property=\"Margin\" Value=\"3\" />\n</Style>\n\n<Style x:Key=\"AlwaysVerticalStyle\" TargetType=\"TextBlock\" \n BasedOn=\"{StaticResource {x:Type TextBlock}}\">\n <Setter Property=\"VerticalAlignment\" Value=\"Top\" />\n</Style>\n</code></pre>\n"
},
{
"answer_id": 69379,
"author": "Greg",
"author_id": 11013,
"author_profile": "https://Stackoverflow.com/users/11013",
"pm_score": 1,
"selected": false,
"text": "<p>if you are not touching any specific properties, you can get all base and common properties to the style which's target type would be FrameworkElement. then, you can create specific flavours for each target types you need, without need of copying all those common properties again.</p>\n"
},
{
"answer_id": 167308,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 8,
"selected": true,
"text": "<p><strong>I think the simple answer is that you can't do (at least in this version of WPF) what you are trying to do.</strong></p>\n\n<p><em>That is, for any particular element only one Style can be applied.</em></p>\n\n<p>However, as others have stated above, maybe you can use <code>BasedOn</code> to help you out. Check out the following piece of loose xaml. In it you will see that I have a base style that is setting a property that exists on the base class of the element that I want to apply two styles to. And, in the second style which is based on the base style, I set another property.</p>\n\n<p><strong>So, the idea here ... is if you can somehow separate the properties that you want to set ... according the inheritance hierarchy of the element you want to set multiple styles on ... you might have a workaround.</strong></p>\n\n<pre><code><Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Page.Resources>\n <Style x:Key=\"baseStyle\" TargetType=\"FrameworkElement\">\n <Setter Property=\"HorizontalAlignment\" Value=\"Left\"/>\n </Style>\n <Style TargetType=\"Button\" BasedOn=\"{StaticResource baseStyle}\">\n <Setter Property=\"Content\" Value=\"Hello World\"/>\n </Style>\n </Page.Resources>\n <Grid>\n <Button Width=\"200\" Height=\"50\"/>\n </Grid>\n</Page>\n</code></pre>\n\n<p><br>\nHope this helps.</p>\n\n<p><strong>Note:</strong></p>\n\n<p>One thing in particular to note. If you change the <code>TargetType</code> in the second style (in first set of xaml above) to <code>ButtonBase</code>, the two Styles do not get applied. However, check out the following xaml below to get around that restriction. Basically, it means you need to give the Style a key and reference it with that key.</p>\n\n<pre><code><Page xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Page.Resources>\n <Style x:Key=\"baseStyle\" TargetType=\"FrameworkElement\">\n <Setter Property=\"HorizontalAlignment\" Value=\"Left\"/>\n </Style>\n <Style x:Key=\"derivedStyle\" TargetType=\"ButtonBase\" BasedOn=\"{StaticResource baseStyle}\">\n <Setter Property=\"Content\" Value=\"Hello World\"/>\n </Style>\n </Page.Resources>\n <Grid>\n <Button Width=\"200\" Height=\"50\" Style=\"{StaticResource derivedStyle}\"/>\n </Grid>\n</Page>\n</code></pre>\n"
},
{
"answer_id": 204311,
"author": "Dave",
"author_id": 28197,
"author_profile": "https://Stackoverflow.com/users/28197",
"pm_score": 1,
"selected": false,
"text": "<p>You can probably get something similar if applying this to a collection of items by the use of a StyleSelector, i have used this to approach a similar problem in using different styles on TreeViewItems depending on the bound object type in the tree. You may have to modify the class below slightly to adjust to your particular approach but hopefully this will get you started</p>\n\n<pre><code>public class MyTreeStyleSelector : StyleSelector\n{\n public Style DefaultStyle\n {\n get;\n set;\n }\n\n public Style NewStyle\n {\n get;\n set;\n }\n\n public override Style SelectStyle(object item, DependencyObject container)\n {\n ItemsControl ctrl = ItemsControl.ItemsControlFromItemContainer(container);\n\n //apply to only the first element in the container (new node)\n if (item == ctrl.Items[0])\n {\n return NewStyle;\n }\n else\n {\n //otherwise use the default style\n return DefaultStyle;\n }\n }\n}\n</code></pre>\n\n<p>You then apply this as so</p>\n\n<pre>\n <TreeView>\n <TreeView.ItemContainerStyleSelector\n <myassembly:MyTreeStyleSelector DefaultStyle=\"{StaticResource DefaultItemStyle}\"\n NewStyle=\"{StaticResource NewItemStyle}\" />\n </TreeView.ItemContainerStyleSelector>\n </TreeView>\n</pre>\n"
},
{
"answer_id": 410430,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>WPF/XAML doesn't provide this functionality natively, but it does provide the extensibility to allow you to do what you want.</p>\n\n<p>We ran into the same need, and ended up creating our own XAML Markup Extension (which we called \"MergedStylesExtension\") to allow us to create a new Style from two other styles (which, if needed, could probably be used multiple times in a row to inherit from even more styles).</p>\n\n<p>Due to a WPF/XAML bug, we need to use property element syntax to use it, but other than that it seems to work ok. E.g.,</p>\n\n<pre><code><Button\n Content=\"This is an example of a button using two merged styles\">\n <Button.Style>\n <ext:MergedStyles\n BasedOn=\"{StaticResource FirstStyle}\"\n MergeStyle=\"{StaticResource SecondStyle}\"/>\n </Button.Style>\n</Button>\n</code></pre>\n\n<p>I recently wrote about it here:\n<a href=\"http://swdeveloper.wordpress.com/2009/01/03/wpf-xaml-multiple-style-inheritance-and-markup-extensions/\" rel=\"noreferrer\">http://swdeveloper.wordpress.com/2009/01/03/wpf-xaml-multiple-style-inheritance-and-markup-extensions/</a></p>\n"
},
{
"answer_id": 1866600,
"author": "Wilka",
"author_id": 1367,
"author_profile": "https://Stackoverflow.com/users/1367",
"pm_score": 6,
"selected": false,
"text": "<p>Bea Stollnitz had <a href=\"http://web.archive.org/web/20101125040337/http://bea.stollnitz.com/blog/?p=384\" rel=\"nofollow noreferrer\">a good blog post</a> about using a markup extension for this, under the heading "How can I set multiple styles in WPF?"</p>\n<p>That blog is dead now, so I'm reproducing the post here:</p>\n<blockquote>\n<p>WPF and Silverlight both offer the ability to derive a Style from\nanother Style through the “BasedOn” property. This feature enables\ndevelopers to organize their styles using a hierarchy similar to class\ninheritance. Consider the following styles:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><Style TargetType="Button" x:Key="BaseButtonStyle">\n <Setter Property="Margin" Value="10" />\n</Style>\n<Style TargetType="Button" x:Key="RedButtonStyle" BasedOn="{StaticResource BaseButtonStyle}">\n <Setter Property="Foreground" Value="Red" />\n</Style>\n</code></pre>\n<p>With this syntax, a Button that uses RedButtonStyle will have its\nForeground property set to Red and its Margin property set to 10.</p>\n<p>This feature has been around in WPF for a long time, and it’s new in\nSilverlight 3.</p>\n<p>What if you want to set more than one style on an element? Neither WPF\nnor Silverlight provide a solution for this problem out of the box.\nFortunately there are ways to implement this behavior in WPF, which I\nwill discuss in this blog post.</p>\n<p>WPF and Silverlight use markup extensions to provide properties with\nvalues that require some logic to obtain. Markup extensions are easily\nrecognizable by the presence of curly brackets surrounding them in\nXAML. For example, the {Binding} markup extension contains logic to\nfetch a value from a data source and update it when changes occur; the\n{StaticResource} markup extension contains logic to grab a value from\na resource dictionary based on a key. Fortunately for us, WPF allows\nusers to write their own custom markup extensions. This feature is not\nyet present in Silverlight, so the solution in this blog is only\napplicable to WPF.</p>\n<p><a href=\"https://swdeveloper.wordpress.com/2009/01/03/wpf-xaml-multiple-style-inheritance-and-markup-extensions/\" rel=\"nofollow noreferrer\">Others</a>\nhave written great solutions to merge two styles using markup\nextensions. However, I wanted a solution that provided the ability to\nmerge an unlimited number of styles, which is a little bit trickier.</p>\n<p>Writing a markup extension is straightforward. The first step is to\ncreate a class that derives from MarkupExtension, and use the\nMarkupExtensionReturnType attribute to indicate that you intend the\nvalue returned from your markup extension to be of type Style.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[MarkupExtensionReturnType(typeof(Style))]\npublic class MultiStyleExtension : MarkupExtension\n{\n}\n</code></pre>\n<h3>Specifying inputs to the markup extension</h3>\n<p>We’d like to give users of our markup extension a simple way to\nspecify the styles to be merged. There are essentially two ways in\nwhich the user can specify inputs to a markup extension. The user can\nset properties or pass parameters to the constructor. Since in this\nscenario the user needs the ability to specify an unlimited number of\nstyles, my first approach was to create a constructor that takes any\nnumber of strings using the “params” keyword:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public MultiStyleExtension(params string[] inputResourceKeys)\n{\n}\n</code></pre>\n<p>My goal was to be able to write the inputs as follows:</p>\n<pre class=\"lang-cs prettyprint-override\"><code><Button Style="{local:MultiStyle BigButtonStyle, GreenButtonStyle}" … />\n</code></pre>\n<p>Notice the comma separating the different style keys. Unfortunately,\ncustom markup extensions don’t support an unlimited number of\nconstructor parameters, so this approach results in a compile error.\nIf I knew in advance how many styles I wanted to merge, I could have\nused the same XAML syntax with a constructor taking the desired number\nof strings:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public MultiStyleExtension(string inputResourceKey1, string inputResourceKey2)\n{\n}\n</code></pre>\n<p>As a workaround, I decided to have the constructor parameter take a\nsingle string that specifies the style names separated by spaces. The\nsyntax isn’t too bad:</p>\n<p><Button Style="{local:MultiStyle BigButtonStyle GreenButtonStyle}"\n… /></p>\n<pre class=\"lang-cs prettyprint-override\"><code>private string[] resourceKeys;\n\npublic MultiStyleExtension(string inputResourceKeys)\n{\n if (inputResourceKeys == null)\n {\n throw new ArgumentNullException("inputResourceKeys");\n }\n\n this.resourceKeys = inputResourceKeys.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n\n if (this.resourceKeys.Length == 0)\n {\n throw new ArgumentException("No input resource keys specified.");\n }\n}\n</code></pre>\n<h3>Calculating the output of the markup extension</h3>\n<p>To calculate the output of a markup extension, we need to override a\nmethod from MarkupExtension called “ProvideValue”. The value returned\nfrom this method will be set in the target of the markup extension.</p>\n<p>I started by creating an extension method for Style that knows how to\nmerge two styles. The code for this method is quite simple:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static void Merge(this Style style1, Style style2)\n{\n if (style1 == null)\n {\n throw new ArgumentNullException("style1");\n }\n if (style2 == null)\n {\n throw new ArgumentNullException("style2");\n }\n\n if (style1.TargetType.IsAssignableFrom(style2.TargetType))\n {\n style1.TargetType = style2.TargetType;\n }\n\n if (style2.BasedOn != null)\n {\n Merge(style1, style2.BasedOn);\n }\n\n foreach (SetterBase currentSetter in style2.Setters)\n {\n style1.Setters.Add(currentSetter);\n }\n\n foreach (TriggerBase currentTrigger in style2.Triggers)\n {\n style1.Triggers.Add(currentTrigger);\n }\n\n // This code is only needed when using DynamicResources.\n foreach (object key in style2.Resources.Keys)\n {\n style1.Resources[key] = style2.Resources[key];\n }\n}\n</code></pre>\n<p>With the logic above, the first style is modified to include all\ninformation from the second. If there are conflicts (e.g. both styles\nhave a setter for the same property), the second style wins. Notice\nthat aside from copying styles and triggers, I also took into account\nthe TargetType and BasedOn values as well as any resources the second\nstyle may have. For the TargetType of the merged style, I used\nwhichever type is more derived. If the second style has a BasedOn\nstyle, I merge its hierarchy of styles recursively. If it has\nresources, I copy them over to the first style. If those resources are\nreferred to using {StaticResource}, they’re statically resolved before\nthis merge code executes, and therefore it isn’t necessary to move\nthem. I added this code in case we’re using DynamicResources.</p>\n<p>The extension method shown above enables the following syntax:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>style1.Merge(style2);\n</code></pre>\n<p>This syntax is useful provided that I have instances of both styles\nwithin ProvideValue. Well, I don’t. All I get from the constructor is\na list of string keys for those styles. If there was support for\nparams in the constructor parameters, I could have used the following\nsyntax to get the actual style instances:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><Button Style="{local:MultiStyle {StaticResource BigButtonStyle}, {StaticResource GreenButtonStyle}}" … />\n</code></pre>\n<pre class=\"lang-cs prettyprint-override\"><code>public MultiStyleExtension(params Style[] styles)\n{\n}\n</code></pre>\n<p>But that doesn’t work. And even if the params limitation didn’t exist,\nwe would probably hit another limitation of markup extensions, where\nwe would have to use property-element syntax instead of attribute\nsyntax to specify the static resources, which is verbose and\ncumbersome (I explain this bug better in a <a href=\"http://web.archive.org/web/20101125040337/http://www.beacosta.com/blog/?p=36\" rel=\"nofollow noreferrer\">previous blog\npost</a>).\nAnd even if both those limitations didn’t exist, I would still rather\nwrite the list of styles using just their names – it is shorter and\nsimpler to read than a StaticResource for each one.</p>\n<p>The solution is to create a StaticResourceExtension using code. Given\na style key of type string and a service provider, I can use\nStaticResourceExtension to retrieve the actual style instance. Here is\nthe syntax:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Style currentStyle = new StaticResourceExtension(currentResourceKey).ProvideValue(serviceProvider)\n</code></pre>\n<p>as Style;</p>\n<p>Now we have all the pieces needed to write the ProvideValue method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public override object ProvideValue(IServiceProvider serviceProvider)\n{\n Style resultStyle = new Style();\n\n foreach (string currentResourceKey in resourceKeys)\n {\n Style currentStyle = new StaticResourceExtension(currentResourceKey).ProvideValue(serviceProvider)\n</code></pre>\n<p>as Style;</p>\n<pre><code> if (currentStyle == null)\n {\n throw new InvalidOperationException("Could not find style with resource key " + currentResourceKey + ".");\n }\n\n resultStyle.Merge(currentStyle);\n }\n return resultStyle;\n}\n</code></pre>\n<p>Here is a complete example of the usage of the MultiStyle markup\nextension:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><Window.Resources>\n <Style TargetType="Button" x:Key="SmallButtonStyle">\n <Setter Property="Width" Value="120" />\n <Setter Property="Height" Value="25" />\n <Setter Property="FontSize" Value="12" />\n </Style>\n\n <Style TargetType="Button" x:Key="GreenButtonStyle">\n <Setter Property="Foreground" Value="Green" />\n </Style>\n\n <Style TargetType="Button" x:Key="BoldButtonStyle">\n <Setter Property="FontWeight" Value="Bold" />\n </Style>\n</Window.Resources>\n\n<Button Style="{local:MultiStyle SmallButtonStyle GreenButtonStyle BoldButtonStyle}" Content="Small, green, bold" />\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/YTzpK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YTzpK.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n"
},
{
"answer_id": 12730626,
"author": "Shahar Prish",
"author_id": 594571,
"author_profile": "https://Stackoverflow.com/users/594571",
"pm_score": 2,
"selected": false,
"text": "<p>This is possible by creating a helper class to use and wrap your styles. CompoundStyle mentioned <a href=\"http://socialeboladev.wordpress.com/2012/10/04/using-multiple-styles-on-elements-in-xaml-windows-8wp7/\" rel=\"nofollow\">here</a> shows how to do it. There are multiple ways, but the easiest is to do the following:</p>\n\n<pre><code><TextBlock Text=\"Test\"\n local:CompoundStyle.StyleKeys=\"headerStyle,textForMessageStyle,centeredStyle\"/>\n</code></pre>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 20179478,
"author": "hillin",
"author_id": 1383540,
"author_profile": "https://Stackoverflow.com/users/1383540",
"pm_score": 1,
"selected": false,
"text": "<p>Sometimes you can approach this by nesting panels. Say you have a Style which changes Foreground and another changes FontSize, you can apply the latter one on a TextBlock, and put it in a Grid which its Style is the first one. This might help and might be the easiest way in some cases, though it won't solve all the problems.</p>\n"
},
{
"answer_id": 21568120,
"author": "Sérgio Henrique",
"author_id": 3273517,
"author_profile": "https://Stackoverflow.com/users/3273517",
"pm_score": 1,
"selected": false,
"text": "<p>When you override SelectStyle you can get GroupBy property via reflection like below:</p>\n\n<pre><code> public override Style SelectStyle(object item, DependencyObject container)\n {\n\n PropertyInfo p = item.GetType().GetProperty(\"GroupBy\", BindingFlags.NonPublic | BindingFlags.Instance);\n\n PropertyGroupDescription propertyGroupDescription = (PropertyGroupDescription)p.GetValue(item);\n\n if (propertyGroupDescription != null && propertyGroupDescription.PropertyName == \"Title\" )\n {\n return this.TitleStyle;\n }\n\n if (propertyGroupDescription != null && propertyGroupDescription.PropertyName == \"Date\")\n {\n return this.DateStyle;\n }\n\n return null;\n }\n</code></pre>\n"
},
{
"answer_id": 46163919,
"author": "google dev",
"author_id": 7206675,
"author_profile": "https://Stackoverflow.com/users/7206675",
"pm_score": 2,
"selected": false,
"text": "<p>Use <code>AttachedProperty</code> to set multiple styles like following code:</p>\n<pre><code>public static class Css\n{\n\n public static string GetClass(DependencyObject element)\n {\n if (element == null)\n throw new ArgumentNullException("element");\n\n return (string)element.GetValue(ClassProperty);\n }\n\n public static void SetClass(DependencyObject element, string value)\n {\n if (element == null)\n throw new ArgumentNullException("element");\n\n element.SetValue(ClassProperty, value);\n }\n\n\n public static readonly DependencyProperty ClassProperty =\n DependencyProperty.RegisterAttached("Class", typeof(string), typeof(Css), \n new PropertyMetadata(null, OnClassChanged));\n\n private static void OnClassChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n var ui = d as FrameworkElement;\n Style newStyle = new Style();\n\n if (e.NewValue != null)\n {\n var names = e.NewValue as string;\n var arr = names.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n foreach (var name in arr)\n {\n Style style = ui.FindResource(name) as Style;\n foreach (var setter in style.Setters)\n {\n newStyle.Setters.Add(setter);\n }\n foreach (var trigger in style.Triggers)\n {\n newStyle.Triggers.Add(trigger);\n }\n }\n }\n ui.Style = newStyle;\n }\n}\n</code></pre>\n<p>Usage: (Point the <em>xmlns:local="clr-namespace:style_a_class_like_css"</em> to the right namespace)</p>\n<pre><code><Window x:Class="MainWindow"\n xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"\n xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"\n xmlns:d="http://schemas.microsoft.com/expression/blend/2008"\n xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"\n xmlns:local="clr-namespace:style_a_class_like_css"\n mc:Ignorable="d"\n Title="MainWindow" Height="150" Width="325">\n <Window.Resources>\n\n <Style TargetType="TextBlock" x:Key="Red" >\n <Setter Property="Foreground" Value="Red"/>\n </Style>\n\n <Style TargetType="TextBlock" x:Key="Green" >\n <Setter Property="Foreground" Value="Green"/>\n </Style>\n \n <Style TargetType="TextBlock" x:Key="Size18" >\n <Setter Property="FontSize" Value="18"/>\n <Setter Property="Margin" Value="6"/>\n </Style>\n\n <Style TargetType="TextBlock" x:Key="Bold" >\n <Setter Property="FontWeight" Value="Bold"/>\n </Style>\n\n </Window.Resources>\n <StackPanel>\n \n <Button Content="Button" local:Css.Class="Red Bold" Width="75"/>\n <Button Content="Button" local:Css.Class="Red Size18" Width="75"/>\n <Button Content="Button" local:Css.Class="Green Size18 Bold" Width="75"/>\n\n </StackPanel>\n</Window>\n</code></pre>\n<p>Result:</p>\n<p><a href=\"https://i.stack.imgur.com/255Jp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/255Jp.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 54497999,
"author": "JamesHoux",
"author_id": 1402498,
"author_profile": "https://Stackoverflow.com/users/1402498",
"pm_score": 0,
"selected": false,
"text": "<p><strong>If you are trying to apply a unique style to just one single element</strong> as an addition to a base style, there is a completely different way to do this that is IMHO much better for readable and maintainable code.</p>\n\n<p>It's extremely common to need to tweak parameters per individual element. Defining dictionary styles just for use on one-element is extremely cumbersome to maintain or make sense of. To avoid creating styles just for one-off element tweaks, read my answer to my own question here here:</p>\n\n<p><a href=\"https://stackoverflow.com/a/54497665/1402498\">https://stackoverflow.com/a/54497665/1402498</a></p>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | In WPF, how would I apply multiple styles to a `FrameworkElement`? For instance, I have a control which already has a style. I also have a separate style which I would like to add to it without blowing away the first one. The styles have different TargetTypes, so I can't just extend one with the other. | **I think the simple answer is that you can't do (at least in this version of WPF) what you are trying to do.**
*That is, for any particular element only one Style can be applied.*
However, as others have stated above, maybe you can use `BasedOn` to help you out. Check out the following piece of loose xaml. In it you will see that I have a base style that is setting a property that exists on the base class of the element that I want to apply two styles to. And, in the second style which is based on the base style, I set another property.
**So, the idea here ... is if you can somehow separate the properties that you want to set ... according the inheritance hierarchy of the element you want to set multiple styles on ... you might have a workaround.**
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="baseStyle" TargetType="FrameworkElement">
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
<Style TargetType="Button" BasedOn="{StaticResource baseStyle}">
<Setter Property="Content" Value="Hello World"/>
</Style>
</Page.Resources>
<Grid>
<Button Width="200" Height="50"/>
</Grid>
</Page>
```
Hope this helps.
**Note:**
One thing in particular to note. If you change the `TargetType` in the second style (in first set of xaml above) to `ButtonBase`, the two Styles do not get applied. However, check out the following xaml below to get around that restriction. Basically, it means you need to give the Style a key and reference it with that key.
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Page.Resources>
<Style x:Key="baseStyle" TargetType="FrameworkElement">
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
<Style x:Key="derivedStyle" TargetType="ButtonBase" BasedOn="{StaticResource baseStyle}">
<Setter Property="Content" Value="Hello World"/>
</Style>
</Page.Resources>
<Grid>
<Button Width="200" Height="50" Style="{StaticResource derivedStyle}"/>
</Grid>
</Page>
``` |
16,100 | <p>What's the best way to convert a string to an enumeration value in C#?</p>
<p>I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.</p>
<p>In an ideal world, I could do something like this:</p>
<pre><code>StatusEnum MyStatus = StatusEnum.Parse("Active");
</code></pre>
<p>but that isn't a valid code.</p>
| [
{
"answer_id": 16103,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 7,
"selected": false,
"text": "<p>You're looking for <a href=\"https://msdn.microsoft.com/en-us/library/aa328348.aspx\" rel=\"noreferrer\">Enum.Parse</a>.</p>\n\n<pre><code>SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), \"EnumValue\");\n</code></pre>\n"
},
{
"answer_id": 16104,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 12,
"selected": true,
"text": "<p>In .NET Core and .NET Framework ≥4.0 <a href=\"https://msdn.microsoft.com/en-us/library/dd783499%28v=vs.110%29.aspx\" rel=\"noreferrer\">there is a generic parse method</a>:</p>\n<pre><code>Enum.TryParse("Active", out StatusEnum myStatus);\n</code></pre>\n<p>This also includes C#7's new inline <code>out</code> variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the <code>myStatus</code> variable.</p>\n<p>If you have access to C#7 and the latest .NET this is the best way.</p>\n<h2>Original Answer</h2>\n<p>In .NET it's rather ugly (until 4 or above):</p>\n<pre><code>StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);\n</code></pre>\n<p>I tend to simplify this with:</p>\n<pre><code>public static T ParseEnum<T>(string value)\n{\n return (T) Enum.Parse(typeof(T), value, true);\n}\n</code></pre>\n<p>Then I can do:</p>\n<pre><code>StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");\n</code></pre>\n<p>One option suggested in the comments is to add an extension, which is simple enough:</p>\n<pre><code>public static T ToEnum<T>(this string value)\n{\n return (T) Enum.Parse(typeof(T), value, true);\n}\n\nStatusEnum MyStatus = "Active".ToEnum<StatusEnum>();\n</code></pre>\n<p>Finally, you may want to have a default enum to use if the string cannot be parsed:</p>\n<pre><code>public static T ToEnum<T>(this string value, T defaultValue) \n{\n if (string.IsNullOrEmpty(value))\n {\n return defaultValue;\n }\n\n T result;\n return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;\n}\n</code></pre>\n<p>Which makes this the call:</p>\n<pre><code>StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);\n</code></pre>\n<p>However, I would be careful adding an extension method like this to <code>string</code> as (without namespace control) it will appear on all instances of <code>string</code> whether they hold an enum or not (so <code>1234.ToString().ToEnum(StatusEnum.None)</code> would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do.</p>\n"
},
{
"answer_id": 16107,
"author": "tags2k",
"author_id": 192,
"author_profile": "https://Stackoverflow.com/users/192",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/aa328348.aspx\" rel=\"noreferrer\">Enum.Parse</a> is your friend:</p>\n\n<pre><code>StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), \"Active\");\n</code></pre>\n"
},
{
"answer_id": 16112,
"author": "brendan",
"author_id": 225,
"author_profile": "https://Stackoverflow.com/users/225",
"pm_score": 5,
"selected": false,
"text": "<pre><code>object Enum.Parse(System.Type enumType, string value, bool ignoreCase);\n</code></pre>\n\n<p>So if you had an enum named mood it would look like this:</p>\n\n<pre><code> enum Mood\n {\n Angry,\n Happy,\n Sad\n } \n\n // ...\n Mood m = (Mood) Enum.Parse(typeof(Mood), \"Happy\", true);\n Console.WriteLine(\"My mood is: {0}\", m.ToString());</code></pre>\n"
},
{
"answer_id": 16131,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "<pre><code>// str.ToEnum<EnumType>()\nT static ToEnum<T>(this string str) \n{ \n return (T) Enum.Parse(typeof(T), str);\n}\n</code></pre>\n"
},
{
"answer_id": 38711,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 8,
"selected": false,
"text": "<p>Note that the performance of <code>Enum.Parse()</code> is not ideal, because it is implemented via reflection. (The same is true of <code>Enum.ToString()</code>, which goes the other way.)</p>\n<p>If you need to convert strings to Enums in performance-sensitive code, your best bet is to create a <code>Dictionary<String,YourEnum></code> at startup and use that to do your conversions.</p>\n"
},
{
"answer_id": 12199994,
"author": "gap",
"author_id": 438205,
"author_profile": "https://Stackoverflow.com/users/438205",
"pm_score": 4,
"selected": false,
"text": "<p>We couldn't assume perfectly valid input, and went with this variation of @Keith's answer:</p>\n\n<pre><code>public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct\n{\n TEnum tmp; \n if (!Enum.TryParse<TEnum>(value, true, out tmp))\n {\n tmp = new TEnum();\n }\n return tmp;\n}\n</code></pre>\n"
},
{
"answer_id": 19431735,
"author": "jite.gs",
"author_id": 2891293,
"author_profile": "https://Stackoverflow.com/users/2891293",
"pm_score": 3,
"selected": false,
"text": "<p>Parses string to TEnum without try/catch and without TryParse() method from .NET 4.5</p>\n\n<pre><code>/// <summary>\n/// Parses string to TEnum without try/catch and .NET 4.5 TryParse()\n/// </summary>\npublic static bool TryParseToEnum<TEnum>(string probablyEnumAsString_, out TEnum enumValue_) where TEnum : struct\n{\n enumValue_ = (TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0);\n if(!Enum.IsDefined(typeof(TEnum), probablyEnumAsString_))\n return false;\n\n enumValue_ = (TEnum) Enum.Parse(typeof(TEnum), probablyEnumAsString_);\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 20394856,
"author": "Erwin Mayer",
"author_id": 541420,
"author_profile": "https://Stackoverflow.com/users/541420",
"pm_score": 9,
"selected": false,
"text": "<p>Use <a href=\"http://msdn.microsoft.com/query/dev12.query?appId=Dev12IDEF1&l=EN-US&k=k%28System.Enum.TryParse%60%601%29;k%28SolutionItemsProject%29;k%28TargetFrameworkMoniker-.NETFramework,Version=v4.5%29;k%28DevLang-csharp%29&rd=true\" rel=\"noreferrer\"><code>Enum.TryParse<T>(String, T)</code></a> (≥ .NET 4.0):</p>\n\n<pre><code>StatusEnum myStatus;\nEnum.TryParse(\"Active\", out myStatus);\n</code></pre>\n\n<p>It can be simplified even further with C# 7.0's <a href=\"https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/\" rel=\"noreferrer\">parameter type inlining</a>:</p>\n\n<pre><code>Enum.TryParse(\"Active\", out StatusEnum myStatus);\n</code></pre>\n"
},
{
"answer_id": 21674259,
"author": "Foyzul Karim",
"author_id": 326597,
"author_profile": "https://Stackoverflow.com/users/326597",
"pm_score": 5,
"selected": false,
"text": "<p>You can use <a href=\"https://en.wikipedia.org/wiki/Extension_method#Extension_methods\">extension methods</a> now:</p>\n\n<pre><code>public static T ToEnum<T>(this string value, bool ignoreCase = true)\n{\n return (T) Enum.Parse(typeof (T), value, ignoreCase);\n}\n</code></pre>\n\n<p>And you can call them by the below code (here, <code>FilterType</code> is an enum type):</p>\n\n<pre><code>FilterType filterType = type.ToEnum<FilterType>();\n</code></pre>\n"
},
{
"answer_id": 27378161,
"author": "Nelly",
"author_id": 3181564,
"author_profile": "https://Stackoverflow.com/users/3181564",
"pm_score": 4,
"selected": false,
"text": "<p>You can extend the accepted answer with a default value to avoid exceptions:</p>\n\n<pre><code>public static T ParseEnum<T>(string value, T defaultValue) where T : struct\n{\n try\n {\n T enumValue;\n if (!Enum.TryParse(value, true, out enumValue))\n {\n return defaultValue;\n }\n return enumValue;\n }\n catch (Exception)\n {\n return defaultValue;\n }\n}\n</code></pre>\n\n<p>Then you call it like:</p>\n\n<pre><code>StatusEnum MyStatus = EnumUtil.ParseEnum(\"Active\", StatusEnum.None);\n</code></pre>\n\n<p>If the default value is not an enum the Enum.TryParse would fail and throw an exception which is catched.</p>\n\n<p>After years of using this function in our code on many places maybe it's good to add the information that this operation costs performance!</p>\n"
},
{
"answer_id": 31157772,
"author": "Patrik Lindström",
"author_id": 648076,
"author_profile": "https://Stackoverflow.com/users/648076",
"pm_score": 2,
"selected": false,
"text": "<p>I used class (strongly-typed version of Enum with parsing and performance improvements). I found it on GitHub, and it should work for .NET 3.5 too. It has some memory overhead since it buffers a dictionary.</p>\n\n<pre><code>StatusEnum MyStatus = Enum<StatusEnum>.Parse(\"Active\");\n</code></pre>\n\n<p>The blogpost is <em><a href=\"http://damieng.com/blog/2010/10/17/enums-better-syntax-improved-performance-and-tryparse-in-net-3-5\" rel=\"nofollow\">Enums – Better syntax, improved performance and TryParse in NET 3.5</a></em>.</p>\n\n<p>And code:\n<a href=\"https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs\" rel=\"nofollow\">https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs</a></p>\n"
},
{
"answer_id": 32064171,
"author": "Rae Lee",
"author_id": 5113582,
"author_profile": "https://Stackoverflow.com/users/5113582",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static T ParseEnum<T>(string value) //function declaration \n{\n return (T) Enum.Parse(typeof(T), value);\n}\n\nImportance imp = EnumUtil.ParseEnum<Importance>(\"Active\"); //function call\n</code></pre>\n\n<p>====================A Complete Program====================</p>\n\n<pre><code>using System;\n\nclass Program\n{\n enum PetType\n {\n None,\n Cat = 1,\n Dog = 2\n }\n\n static void Main()\n {\n\n // Possible user input:\n string value = \"Dog\";\n\n // Try to convert the string to an enum:\n PetType pet = (PetType)Enum.Parse(typeof(PetType), value);\n\n // See if the conversion succeeded:\n if (pet == PetType.Dog)\n {\n Console.WriteLine(\"Equals dog.\");\n }\n }\n}\n-------------\nOutput\n\nEquals dog.\n</code></pre>\n"
},
{
"answer_id": 32897493,
"author": "alhpe",
"author_id": 2998185,
"author_profile": "https://Stackoverflow.com/users/2998185",
"pm_score": 3,
"selected": false,
"text": "<p>I like the extension method solution..</p>\n\n<pre><code>namespace System\n{\n public static class StringExtensions\n {\n\n public static bool TryParseAsEnum<T>(this string value, out T output) where T : struct\n {\n T result;\n\n var isEnum = Enum.TryParse(value, out result);\n\n output = isEnum ? result : default(T);\n\n return isEnum;\n }\n }\n}\n</code></pre>\n\n<p>Here below my implementation with tests.</p>\n\n<pre><code>using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert;\nusing static System.Console;\n\nprivate enum Countries\n {\n NorthAmerica,\n Europe,\n Rusia,\n Brasil,\n China,\n Asia,\n Australia\n }\n\n [TestMethod]\n public void StringExtensions_On_TryParseAsEnum()\n {\n var countryName = \"Rusia\";\n\n Countries country;\n var isCountry = countryName.TryParseAsEnum(out country);\n\n WriteLine(country);\n\n IsTrue(isCountry);\n AreEqual(Countries.Rusia, country);\n\n countryName = \"Don't exist\";\n\n isCountry = countryName.TryParseAsEnum(out country);\n\n WriteLine(country);\n\n IsFalse(isCountry);\n AreEqual(Countries.NorthAmerica, country); // the 1rst one in the enumeration\n }\n</code></pre>\n"
},
{
"answer_id": 34267134,
"author": "Timo",
"author_id": 543814,
"author_profile": "https://Stackoverflow.com/users/543814",
"pm_score": 5,
"selected": false,
"text": "<p><strong>BEWARE:</strong></p>\n\n<pre><code>enum Example\n{\n One = 1,\n Two = 2,\n Three = 3\n}\n</code></pre>\n\n<p><code>Enum.(Try)Parse()</code> <strong>accepts multiple, comma-separated arguments, and combines them with binary 'or' <code>|</code></strong>. You cannot disable this and in my opinion you almost never want it.</p>\n\n<pre><code>var x = Enum.Parse(\"One,Two\"); // x is now Three\n</code></pre>\n\n<p>Even if <code>Three</code> was not defined, <code>x</code> would still get int value <code>3</code>. That's even worse: Enum.Parse() can give you a value that is not even defined for the enum!</p>\n\n<p>I would not want to experience the consequences of users, willingly or unwillingly, triggering this behavior.</p>\n\n<p>Additionally, as mentioned by others, performance is less than ideal for large enums, namely linear in the number of possible values.</p>\n\n<p>I suggest the following:</p>\n\n<pre><code> public static bool TryParse<T>(string value, out T result)\n where T : struct\n {\n var cacheKey = \"Enum_\" + typeof(T).FullName;\n\n // [Use MemoryCache to retrieve or create&store a dictionary for this enum, permanently or temporarily.\n // [Implementation off-topic.]\n var enumDictionary = CacheHelper.GetCacheItem(cacheKey, CreateEnumDictionary<T>, EnumCacheExpiration);\n\n return enumDictionary.TryGetValue(value.Trim(), out result);\n }\n\n private static Dictionary<string, T> CreateEnumDictionary<T>()\n {\n return Enum.GetValues(typeof(T))\n .Cast<T>()\n .ToDictionary(value => value.ToString(), value => value, StringComparer.OrdinalIgnoreCase);\n }\n</code></pre>\n"
},
{
"answer_id": 37970592,
"author": "Koray",
"author_id": 1266873,
"author_profile": "https://Stackoverflow.com/users/1266873",
"pm_score": 2,
"selected": false,
"text": "<p>For performance this might help:</p>\n\n<pre><code> private static Dictionary<Type, Dictionary<string, object>> dicEnum = new Dictionary<Type, Dictionary<string, object>>();\n public static T ToEnum<T>(this string value, T defaultValue)\n {\n var t = typeof(T);\n Dictionary<string, object> dic;\n if (!dicEnum.ContainsKey(t))\n {\n dic = new Dictionary<string, object>();\n dicEnum.Add(t, dic);\n foreach (var en in Enum.GetValues(t))\n dic.Add(en.ToString(), en);\n }\n else\n dic = dicEnum[t];\n if (!dic.ContainsKey(value))\n return defaultValue;\n else\n return (T)dic[value];\n }\n</code></pre>\n"
},
{
"answer_id": 39857622,
"author": "isxaker",
"author_id": 364429,
"author_profile": "https://Stackoverflow.com/users/364429",
"pm_score": 2,
"selected": false,
"text": "<p>I found that here the case with enum values that have EnumMember value was not considered. So here we go:</p>\n\n<pre><code>using System.Runtime.Serialization;\n\npublic static TEnum ToEnum<TEnum>(this string value, TEnum defaultValue) where TEnum : struct\n{\n if (string.IsNullOrEmpty(value))\n {\n return defaultValue;\n }\n\n TEnum result;\n var enumType = typeof(TEnum);\n foreach (var enumName in Enum.GetNames(enumType))\n {\n var fieldInfo = enumType.GetField(enumName);\n var enumMemberAttribute = ((EnumMemberAttribute[]) fieldInfo.GetCustomAttributes(typeof(EnumMemberAttribute), true)).FirstOrDefault();\n if (enumMemberAttribute?.Value == value)\n {\n return Enum.TryParse(enumName, true, out result) ? result : defaultValue;\n }\n }\n\n return Enum.TryParse(value, true, out result) ? result : defaultValue;\n}\n</code></pre>\n\n<p>And example of that enum:</p>\n\n<pre><code>public enum OracleInstanceStatus\n{\n Unknown = -1,\n Started = 1,\n Mounted = 2,\n Open = 3,\n [EnumMember(Value = \"OPEN MIGRATE\")]\n OpenMigrate = 4\n}\n</code></pre>\n"
},
{
"answer_id": 40796886,
"author": "Brian Rice",
"author_id": 1027031,
"author_profile": "https://Stackoverflow.com/users/1027031",
"pm_score": 3,
"selected": false,
"text": "<p>Super simple code using TryParse:</p>\n\n<pre><code>var value = \"Active\";\n\nStatusEnum status;\nif (!Enum.TryParse<StatusEnum>(value, out status))\n status = StatusEnum.Unknown;\n</code></pre>\n"
},
{
"answer_id": 42111987,
"author": "Bartosz Gawron",
"author_id": 6888393,
"author_profile": "https://Stackoverflow.com/users/6888393",
"pm_score": 2,
"selected": false,
"text": "<p>You have to use Enum.Parse to get the object value from Enum, after that you have to change the object value to specific enum value. Casting to enum value can be do by using Convert.ChangeType. Please have a look on following code snippet</p>\n\n<pre><code>public T ConvertStringValueToEnum<T>(string valueToParse){\n return Convert.ChangeType(Enum.Parse(typeof(T), valueToParse, true), typeof(T));\n}\n</code></pre>\n"
},
{
"answer_id": 52588251,
"author": "AmirReza-Farahlagha",
"author_id": 7059557,
"author_profile": "https://Stackoverflow.com/users/7059557",
"pm_score": 2,
"selected": false,
"text": "<p>Try this sample:</p>\n\n<pre><code> public static T GetEnum<T>(string model)\n {\n var newModel = GetStringForEnum(model);\n\n if (!Enum.IsDefined(typeof(T), newModel))\n {\n return (T)Enum.Parse(typeof(T), \"None\", true);\n }\n\n return (T)Enum.Parse(typeof(T), newModel.Result, true);\n }\n\n private static Task<string> GetStringForEnum(string model)\n {\n return Task.Run(() =>\n {\n Regex rgx = new Regex(\"[^a-zA-Z0-9 -]\");\n var nonAlphanumericData = rgx.Matches(model);\n if (nonAlphanumericData.Count < 1)\n {\n return model;\n }\n foreach (var item in nonAlphanumericData)\n {\n model = model.Replace((string)item, \"\");\n }\n return model;\n });\n }\n</code></pre>\n\n<p>In this sample you can send every string, and set your <code>Enum</code>. If your <code>Enum</code> had data that you wanted, return that as your <code>Enum</code> type.</p>\n"
},
{
"answer_id": 56251256,
"author": "AHMED RABEE",
"author_id": 1294770,
"author_profile": "https://Stackoverflow.com/users/1294770",
"pm_score": 1,
"selected": false,
"text": "<pre><code> <Extension()>\n Public Function ToEnum(Of TEnum)(ByVal value As String, ByVal defaultValue As TEnum) As TEnum\n If String.IsNullOrEmpty(value) Then\n Return defaultValue\n End If\n\n Return [Enum].Parse(GetType(TEnum), value, True)\n End Function\n</code></pre>\n"
},
{
"answer_id": 56251321,
"author": "AHMED RABEE",
"author_id": 1294770,
"author_profile": "https://Stackoverflow.com/users/1294770",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public TEnum ToEnum<TEnum>(this string value, TEnum defaultValue){\nif (string.IsNullOrEmpty(value))\n return defaultValue;\n\nreturn Enum.Parse(typeof(TEnum), value, true);}\n</code></pre>\n"
},
{
"answer_id": 59076571,
"author": "JCisar",
"author_id": 1179562,
"author_profile": "https://Stackoverflow.com/users/1179562",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure when this was added but on the Enum class there is now a </p>\n\n<p><code>Parse<TEnum>(stringValue)</code></p>\n\n<p>Used like so with example in question:</p>\n\n<p><code>var MyStatus = Enum.Parse<StatusEnum >(\"Active\")</code></p>\n\n<p>or ignoring casing by:</p>\n\n<p><code>var MyStatus = Enum.Parse<StatusEnum >(\"active\", true)</code></p>\n\n<p>Here is the decompiled methods this uses:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> [NullableContext(0)]\n public static TEnum Parse<TEnum>([Nullable(1)] string value) where TEnum : struct\n {\n return Enum.Parse<TEnum>(value, false);\n }\n\n [NullableContext(0)]\n public static TEnum Parse<TEnum>([Nullable(1)] string value, bool ignoreCase) where TEnum : struct\n {\n TEnum result;\n Enum.TryParse<TEnum>(value, ignoreCase, true, out result);\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 59897419,
"author": "Joel Wiklund",
"author_id": 583037,
"author_profile": "https://Stackoverflow.com/users/583037",
"pm_score": 2,
"selected": false,
"text": "<p>If the property name is different from what you want to call it (i.e. language differences) you can do like this:</p>\n\n<p>MyType.cs</p>\n\n<pre><code>using System;\nusing System.Runtime.Serialization;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Converters;\n\n[JsonConverter(typeof(StringEnumConverter))]\npublic enum MyType\n{\n [EnumMember(Value = \"person\")]\n Person,\n [EnumMember(Value = \"annan_deltagare\")]\n OtherPerson,\n [EnumMember(Value = \"regel\")]\n Rule,\n}\n</code></pre>\n\n<p>EnumExtensions.cs</p>\n\n<pre><code>using System;\nusing Newtonsoft.Json;\nusing Newtonsoft.Json.Converters;\n\npublic static class EnumExtensions\n{\n public static TEnum ToEnum<TEnum>(this string value) where TEnum : Enum\n {\n var jsonString = $\"'{value.ToLower()}'\";\n return JsonConvert.DeserializeObject<TEnum>(jsonString, new StringEnumConverter());\n }\n\n public static bool EqualsTo<TEnum>(this string strA, TEnum enumB) where TEnum : Enum\n {\n TEnum enumA;\n try\n {\n enumA = strA.ToEnum<TEnum>();\n }\n catch\n {\n return false;\n }\n return enumA.Equals(enumB);\n }\n}\n</code></pre>\n\n<p>Program.cs</p>\n\n<pre><code>public class Program\n{\n static public void Main(String[] args) \n { \n var myString = \"annan_deltagare\";\n var myType = myString.ToEnum<MyType>();\n var isEqual = myString.EqualsTo(MyType.OtherPerson);\n //Output: true\n } \n}\n</code></pre>\n"
},
{
"answer_id": 62345657,
"author": "MBWise",
"author_id": 2454604,
"author_profile": "https://Stackoverflow.com/users/2454604",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to use a default value when null or empty (e.g. when retrieving from config file and the value does not exist) and throw an exception when the string or number does not match any of the enum values. Beware of caveat in Timo's answer though (<a href=\"https://stackoverflow.com/a/34267134/2454604\">https://stackoverflow.com/a/34267134/2454604</a>).</p>\n\n<pre><code> public static T ParseEnum<T>(this string s, T defaultValue, bool ignoreCase = false) \n where T : struct, IComparable, IConvertible, IFormattable//If C# >=7.3: struct, System.Enum \n {\n if ((s?.Length ?? 0) == 0)\n {\n return defaultValue;\n }\n\n var valid = Enum.TryParse<T>(s, ignoreCase, out T res);\n\n if (!valid || !Enum.IsDefined(typeof(T), res))\n {\n throw new InvalidOperationException(\n $\"'{s}' is not a valid value of enum '{typeof(T).FullName}'!\");\n }\n return res;\n }\n</code></pre>\n"
},
{
"answer_id": 66977781,
"author": "Felipe Augusto",
"author_id": 8104755,
"author_profile": "https://Stackoverflow.com/users/8104755",
"pm_score": -1,
"selected": false,
"text": "<p>First of all, you need to decorate your enum, like this:</p>\n<pre><code> public enum Store : short\n{\n [Description("Rio Big Store")]\n Rio = 1\n}\n</code></pre>\n<p>in .net 5, i create this extension method:</p>\n<pre><code>//The class also needs to be static, ok?\npublic static string GetDescription(this System.Enum enumValue)\n {\n FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());\n\n DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(\n typeof(DescriptionAttribute), false);\n\n if (attributes != null && attributes.Length > 0) return attributes[0].Description;\n else return enumValue.ToString();\n }\n</code></pre>\n<p>now you have an extension methods to use in any Enums</p>\n<p>Like this:</p>\n<pre><code>var Desc = Store.Rio.GetDescription(); //Store is your Enum\n</code></pre>\n"
},
{
"answer_id": 69637069,
"author": "Jordan Ryder",
"author_id": 2088676,
"author_profile": "https://Stackoverflow.com/users/2088676",
"pm_score": 4,
"selected": false,
"text": "<p>At some point a generic version of Parse was added. For me this was preferable because I didn't need to "try" to parse and I also want the result inline without generating an output variable.</p>\n<pre><code>ColorEnum color = Enum.Parse<ColorEnum>("blue");\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.enum.parse?view=net-5.0#System_Enum_Parse__1_System_String_\" rel=\"noreferrer\">MS Documentation: Parse</a></p>\n"
},
{
"answer_id": 71249113,
"author": "Bloggrammer",
"author_id": 12476466,
"author_profile": "https://Stackoverflow.com/users/12476466",
"pm_score": 3,
"selected": false,
"text": "<p>Most of the answers here require you to always pass in the default value of the enum each time you call on the extension method. If you don't want to go by that approach, you can implement it like below:</p>\n<pre><code> public static TEnum ToEnum<TEnum>(this string value) where TEnum : struct\n {\n if (string.IsNullOrWhiteSpace(value))\n return default(TEnum);\n\n return Enum.TryParse(value, true, out TEnum result) ? result : default(TEnum);\n\n }\n</code></pre>\n<p><strong>Using default literal (available from C# 7.1)</strong></p>\n<pre><code> public static TEnum ToEnum<TEnum>(this string value, TEnum defaultValue = default) where TEnum : struct\n {\n if (string.IsNullOrWhiteSpace(value))\n return defaultValue ;\n\n return Enum.TryParse(value, true, out TEnum result) ? result : defaultValue ;\n\n }\n</code></pre>\n<p><strong>Better still:</strong></p>\n<pre><code>public static TEnum ToEnum<TEnum>(this string value) where TEnum : struct\n{\n if (string.IsNullOrWhiteSpace(value))\n return default;\n\n return Enum.TryParse(value, true, out TEnum result) ? result : default;\n\n}\n</code></pre>\n"
},
{
"answer_id": 72832417,
"author": "shvets",
"author_id": 7432218,
"author_profile": "https://Stackoverflow.com/users/7432218",
"pm_score": 0,
"selected": false,
"text": "<p>I started to use this approach. Performance seems to be ok however it requires a bit of boilerplate code setup.</p>\n<pre><code>public enum StatusType {\n Success,\n Pending,\n Rejected\n}\n\nstatic class StatusTypeMethods {\n\n public static StatusType GetEnum(string type) {\n switch (type) {\n case nameof(StatusType.Success): return StatusType.Success;\n case nameof(StatusType.Pending): return StatusType.Pending;\n case nameof(StatusType.Rejected): return StatusType.Rejected;\n default:\n throw new ArgumentOutOfRangeException(nameof(type), type, null);\n };\n }\n}\n</code></pre>\n<p>And later on, you can use it like this:</p>\n<pre><code>StatusType = StatusType.GetEnum("Success");\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/203/"
] | What's the best way to convert a string to an enumeration value in C#?
I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the corresponding enumeration value.
In an ideal world, I could do something like this:
```
StatusEnum MyStatus = StatusEnum.Parse("Active");
```
but that isn't a valid code. | In .NET Core and .NET Framework ≥4.0 [there is a generic parse method](https://msdn.microsoft.com/en-us/library/dd783499%28v=vs.110%29.aspx):
```
Enum.TryParse("Active", out StatusEnum myStatus);
```
This also includes C#7's new inline `out` variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the `myStatus` variable.
If you have access to C#7 and the latest .NET this is the best way.
Original Answer
---------------
In .NET it's rather ugly (until 4 or above):
```
StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
```
I tend to simplify this with:
```
public static T ParseEnum<T>(string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
```
Then I can do:
```
StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
```
One option suggested in the comments is to add an extension, which is simple enough:
```
public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
```
Finally, you may want to have a default enum to use if the string cannot be parsed:
```
public static T ToEnum<T>(this string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
```
Which makes this the call:
```
StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);
```
However, I would be careful adding an extension method like this to `string` as (without namespace control) it will appear on all instances of `string` whether they hold an enum or not (so `1234.ToString().ToEnum(StatusEnum.None)` would be valid but nonsensical) . It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do. |
16,110 | <p>I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents. </p>
<p>The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome. </p>
<p>The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.</p>
<p><strong>Edit:</strong> The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again.</p>
| [
{
"answer_id": 16119,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>OK, are you sure that is wise? I am picturing two scenarios here:</p>\n\n<ol>\n<li>There is a default button on the form, which is \"clicked\" when enter is pushed\".</li>\n<li>There is no default button, and you want the user to have to press enter, regardless.</li>\n</ol>\n\n<p>Both of these raise the same questions:</p>\n\n<ul>\n<li>Is there any validation that is taking place on the text?</li>\n<li>Why not create a user control to encapsulate this logic?</li>\n<li>If you know the enter button is being pushed and consumed fine, how are you having problems with <em>TextBoxName.Text = string.Empty</em> ?</li>\n</ul>\n\n<p>Also, as a polite note, can you please try and break up your question a bit? One big block is a bit of a pain to read..</p>\n"
},
{
"answer_id": 16130,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 3,
"selected": true,
"text": "<p>Hook into the KeyPress event on the TextBox, and when it encounters the Enter key, run your hardware setting code, and then highlight the full text of the textbox again (see below) - Windows will take care of clearing the text with the next keystroke for you.</p>\n\n<pre><code>TextBox1.Select(0, TextBox1.Text.Length);\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1629/"
] | I have a user that want to be able to select a textbox and have the current text selected so that he doesn't have to highlight it all in order to change the contents.
The contents need to be handle when enter is pushed. That part I think I have figured out but any suggestions would be welcome.
The part I need help with is that once enter has been pushed, any entry into the textbox should clear the contents again.
**Edit:** The textbox controls an piece of RF hardware. What the user wants to be able to do is enter a setting and press enter. The setting is sent to the hardware. Without doing anything else the user wants to be able to type in a new setting and press enter again. | Hook into the KeyPress event on the TextBox, and when it encounters the Enter key, run your hardware setting code, and then highlight the full text of the textbox again (see below) - Windows will take care of clearing the text with the next keystroke for you.
```
TextBox1.Select(0, TextBox1.Text.Length);
``` |
16,155 | <p><strong>Is there a way in PHP to overwrite a method declared by one interface in an interface extending that interface?</strong></p>
<p>The Example:</p>
<p>I'm probably doing something wrong, but here is what I have:</p>
<pre><code>interface iVendor{
public function __construct($vendors_no = null);
public function getName();
public function getVendors_no();
public function getZip();
public function getCountryCode();
public function setName($name);
public function setVendors_no($vendors_no);
public function setZip($zip);
public function setCountryCode($countryCode);
}
interface iShipper extends iVendor{
public function __construct($vendors_no = null, $shipment = null);
public function getTransitTime($shipment = null);
public function getTransitCost($shipment = null);
public function getCurrentShipment();
public function setCurrentShipment($shipment);
public function getStatus($shipment = null);
}
</code></pre>
<p>Normally in PHP, when you extend something, you can overwrite any method contained therein (right?). However, when one interface extends another, it won't let you. Unless I'm thinking about this wrong... When I implement the iShipper interface, I don't have to make the Shipper object extend the Vendor object (that implements the iVendor interface). I just say:</p>
<pre><code>class FedEx implements iShipper{}
</code></pre>
<p>and make FedEx implement all of the methods from iVendor and iShipper. However, I need the <code>__construct</code> functions in iVendor and iShipper to be unique. I know I could take out the <code>$shipment = null</code>, but then it wouldn't be as convenient to create Shippers (by just passing in the vendors_no and the shipment while instantiating).</p>
<p>Anyone know how to make this work? My fallback is to have to set the shipment by calling <code>$shipper->setShipment($shipment);</code> on the Shipper after I instantiate it, but I'm hoping for a way to get around having to do that...</p>
<p><em>A little more explanation for the curious:</em><br>
<em>The FedEx Object has methods that go to the FedEx site (using cURL) and gets an estimate for the Shipment in question. I have a UPS Object, a BAXGlobal Object, a Conway Object, etc. Each one has COMPLETELY different methods for actually getting the shipping estimate, but all the system needs to know is that they are a "shipper" and that the methods listed in the interface are callable on them (so it can treat them all exactly the same, and loop through them in a "shippers" array calling <code>getTransitX()</code> to find the best shipper for a shipment).</em> </p>
<p><em>Each "Shipper" is also a "Vendor" though, and is treated as such in other parts of the system (getting and putting in the DB, etc. Our data design is a pile of crap, so FedEx is stored right alongside companies like Dunder Mifflin in the "Vendors" table, which means it gets to have all the properties of every other Vendor, but needs the extra properties and methods supplied by iShipper).</em></p>
| [
{
"answer_id": 16245,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/16155/making-one-interface-overwrite-a-method-it-inherits-from-another-interface-in-p#16196\">@cmcculloh</a> Yeah, in Java you don't define constructors in Interfaces. This allows you to both extend interfaces and also have a class that implements multiple interfaces (both allowed, and very useful in many cases) without worrying about having to satisfy a particular constructor.</p>\n\n<p><em>EDIT:</em></p>\n\n<p><em>Here's my new model:</em></p>\n\n<p><em>A. Each interface no longer has a constructor method.</em><br>\n<em>B. All Shippers (UPS, FedEx, etc) now implement iShipper (which extends iVendor) and extend the abstract class Shipper (which has all common non-abstract methods for shippers defined in it, getName(), getZip() etc).</em><br>\n<em>C. Each Shipper has it's own unique _construct method which overwrites the abstract __construct($vendors_no = null, $shipment = null) method contained in Shipper (I don't remember why I'm allowing those to be optional now though. I'd have to go back through my documentation...).</em></p>\n\n<p>So:</p>\n\n<pre><code>interface iVendor{\n public function getName();\n public function getVendors_no();\n public function getZip();\n public function getCountryCode();\n public function setName($name);\n public function setVendors_no($vendors_no);\n public function setZip($zip);\n public function setCountryCode($countryCode);\n}\n\ninterface iShipper extends iVendor{\n public function getTransitTime($shipment = null);\n public function getTransitCost($shipment = null);\n public function getCurrentShipment();\n public function setCurrentShipment($shipment);\n public function getStatus($shipment = null);\n}\n\nabstract class Shipper implements iShipper{ \n abstract public function __construct($vendors_no = null, $shipment = null); \n //a bunch of non-abstract common methods... \n}\n\nclass FedEx extends Shipper implements iShipper{ \n public function __construct($vendors_no = null, $shipment = null){\n //a bunch of setup code...\n }\n //all my FedEx specific methods...\n}\n</code></pre>\n\n<p><em>Thanks for the help!</em><br>\n<em>ps. since I have now added this to \"your\" answer, if there is something about it you don't like/think should be different, feel free to change it...</em></p>\n"
},
{
"answer_id": 16409,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 0,
"selected": false,
"text": "<p>You could drop off the constructor and just put them in each individual class. Then what you have is each class has its own __construct, which is probably the same depending on if it is a shipper or vendor. If you want to only have those constructs defined once I don't think you want to go down that route. </p>\n\n<p>What I think you want to do is make an abstract class that implements vendor, and one that implements shipper. There you could define the constructors differently. </p>\n\n<pre><code>abstract class Vendor implements iVendor {\n public function __construct() {\n whatever();\n }\n}\n\nabstract class Shipper implements iShipper {\n public function __construct() {\n something();\n }\n}\n</code></pre>\n"
}
] | 2008/08/19 | [
"https://Stackoverflow.com/questions/16155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] | **Is there a way in PHP to overwrite a method declared by one interface in an interface extending that interface?**
The Example:
I'm probably doing something wrong, but here is what I have:
```
interface iVendor{
public function __construct($vendors_no = null);
public function getName();
public function getVendors_no();
public function getZip();
public function getCountryCode();
public function setName($name);
public function setVendors_no($vendors_no);
public function setZip($zip);
public function setCountryCode($countryCode);
}
interface iShipper extends iVendor{
public function __construct($vendors_no = null, $shipment = null);
public function getTransitTime($shipment = null);
public function getTransitCost($shipment = null);
public function getCurrentShipment();
public function setCurrentShipment($shipment);
public function getStatus($shipment = null);
}
```
Normally in PHP, when you extend something, you can overwrite any method contained therein (right?). However, when one interface extends another, it won't let you. Unless I'm thinking about this wrong... When I implement the iShipper interface, I don't have to make the Shipper object extend the Vendor object (that implements the iVendor interface). I just say:
```
class FedEx implements iShipper{}
```
and make FedEx implement all of the methods from iVendor and iShipper. However, I need the `__construct` functions in iVendor and iShipper to be unique. I know I could take out the `$shipment = null`, but then it wouldn't be as convenient to create Shippers (by just passing in the vendors\_no and the shipment while instantiating).
Anyone know how to make this work? My fallback is to have to set the shipment by calling `$shipper->setShipment($shipment);` on the Shipper after I instantiate it, but I'm hoping for a way to get around having to do that...
*A little more explanation for the curious:*
*The FedEx Object has methods that go to the FedEx site (using cURL) and gets an estimate for the Shipment in question. I have a UPS Object, a BAXGlobal Object, a Conway Object, etc. Each one has COMPLETELY different methods for actually getting the shipping estimate, but all the system needs to know is that they are a "shipper" and that the methods listed in the interface are callable on them (so it can treat them all exactly the same, and loop through them in a "shippers" array calling `getTransitX()` to find the best shipper for a shipment).*
*Each "Shipper" is also a "Vendor" though, and is treated as such in other parts of the system (getting and putting in the DB, etc. Our data design is a pile of crap, so FedEx is stored right alongside companies like Dunder Mifflin in the "Vendors" table, which means it gets to have all the properties of every other Vendor, but needs the extra properties and methods supplied by iShipper).* | [@cmcculloh](https://stackoverflow.com/questions/16155/making-one-interface-overwrite-a-method-it-inherits-from-another-interface-in-p#16196) Yeah, in Java you don't define constructors in Interfaces. This allows you to both extend interfaces and also have a class that implements multiple interfaces (both allowed, and very useful in many cases) without worrying about having to satisfy a particular constructor.
*EDIT:*
*Here's my new model:*
*A. Each interface no longer has a constructor method.*
*B. All Shippers (UPS, FedEx, etc) now implement iShipper (which extends iVendor) and extend the abstract class Shipper (which has all common non-abstract methods for shippers defined in it, getName(), getZip() etc).*
*C. Each Shipper has it's own unique \_construct method which overwrites the abstract \_\_construct($vendors\_no = null, $shipment = null) method contained in Shipper (I don't remember why I'm allowing those to be optional now though. I'd have to go back through my documentation...).*
So:
```
interface iVendor{
public function getName();
public function getVendors_no();
public function getZip();
public function getCountryCode();
public function setName($name);
public function setVendors_no($vendors_no);
public function setZip($zip);
public function setCountryCode($countryCode);
}
interface iShipper extends iVendor{
public function getTransitTime($shipment = null);
public function getTransitCost($shipment = null);
public function getCurrentShipment();
public function setCurrentShipment($shipment);
public function getStatus($shipment = null);
}
abstract class Shipper implements iShipper{
abstract public function __construct($vendors_no = null, $shipment = null);
//a bunch of non-abstract common methods...
}
class FedEx extends Shipper implements iShipper{
public function __construct($vendors_no = null, $shipment = null){
//a bunch of setup code...
}
//all my FedEx specific methods...
}
```
*Thanks for the help!*
*ps. since I have now added this to "your" answer, if there is something about it you don't like/think should be different, feel free to change it...* |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.