qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
187,453
<p>Would it suppose any difference regarding overhead to write an import loading all the types within one package (<code>import java.*</code>); than just a specific type (i.e. <code>import java.lang.ClassLoader</code>)? Would the second one be a more advisable way to use than the other one?</p>
[ { "answer_id": 187487, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 7, "selected": false, "text": "java.lang.reflect.Array\njava.sql.Array\n java.lang.reflect.* java.sql.*" }, { "answer_id": 187789, "author": "Juan Carlos Blanco Martínez", "author_id": 94303, "author_profile": "https://Stackoverflow.com/users/94303", "pm_score": 4, "selected": false, "text": "package P;\n\npublic class A {\n public static class B {}\n}\n import P.*;\n import P.A.*;\n" }, { "answer_id": 188645, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 5, "selected": false, "text": "import a.*;\nimport b.*;\n...\nFoo f;\n import a.*;\n import a.X;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/94303/" ]
187,455
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
[ { "answer_id": 187463, "author": "Trent", "author_id": 9083, "author_profile": "https://Stackoverflow.com/users/9083", "pm_score": 9, "selected": true, "text": "len(myArray)\n myArray = [1, 2, 3]\nlen(myArray)\n 3\n" }, { "answer_id": 187493, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 2, "selected": false, "text": "myArray.__len__()\n" }, { "answer_id": 188867, "author": "Jeremy Brown", "author_id": 21776, "author_profile": "https://Stackoverflow.com/users/21776", "pm_score": 5, "selected": false, "text": "len __len__ obj.__len__()" }, { "answer_id": 31467803, "author": "Evan Young", "author_id": 4946606, "author_profile": "https://Stackoverflow.com/users/4946606", "pm_score": 2, "selected": false, "text": "for tempVar in arrayName: tempVar+=1\n len(arrayName)" }, { "answer_id": 31937513, "author": "user2993689", "author_id": 2993689, "author_profile": "https://Stackoverflow.com/users/2993689", "pm_score": 4, "selected": false, "text": "import numpy as np\na = np.arange(10).reshape(2, 5)\nprint len(a) == 2\n import numpy as np\nlen(a) == np.shape(a)[0]\n import numpy as np\nsize = 1\nfor dim in np.shape(a): size *= dim\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
187,465
<p>Any ideas how i can best drive a USB POS printer from c#. POS printers are usually serial, TCP/IP or USB based. I know how to accomplish serial and TCP/IP but have no idea about communications through USB in C#. I know that there is a layer available from Microsoft called POS.NET, but I want to try and avoid using this. Any ideas or any C# libraries that people can recomend would be really appreciated. Thanks</p>
[ { "answer_id": 187504, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": " [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_FlushQueue( SafeFileHandle HidDeviceObject ); \n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_FreePreparsedData( ref IntPtr PreparsedData ); \n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_GetAttributes( SafeFileHandle HidDeviceObject\n , ref HIDD_ATTRIBUTES Attributes ); \n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_GetFeature( SafeFileHandle HidDeviceObject\n , ref Byte lpReportBuffer\n , Int32 ReportBufferLength ); \n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_GetInputReport( SafeFileHandle HidDeviceObject\n ,ref Byte lpReportBuffer\n ,Int32 ReportBufferLength ); \n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern void HidD_GetHidGuid( ref System.Guid HidGuid );\n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_GetNumInputBuffers( SafeFileHandle HidDeviceObject\n , ref Int32 NumberBuffers ); \n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_GetPreparsedData( SafeFileHandle HidDeviceObject\n ,ref IntPtr PreparsedData );\n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_SetFeature( SafeFileHandle HidDeviceObject\n , ref Byte lpReportBuffer\n , Int32 ReportBufferLength );\n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_SetNumInputBuffers( SafeFileHandle HidDeviceObject\n ,Int32 NumberBuffers );\n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Boolean \n HidD_SetOutputReport( SafeFileHandle HidDeviceObject\n ,ref Byte lpReportBuffer\n ,Int32 ReportBufferLength );\n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Int32 \n HidP_GetCaps( IntPtr PreparsedData, ref HIDP_CAPS Capabilities );\n\n [ DllImport( \"hid.dll\", SetLastError=true ) ]\n public static extern Int32 \n HidP_GetValueCaps( Int16 ReportType\n , ref Byte ValueCaps\n , ref Int16 ValueCapsLength\n , IntPtr PreparsedData );\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20339/" ]
187,482
<p>I'd like to use the newer <code>&lt;button&gt;</code> tag in an ASP.NET website which, among other things, allows CSS-styled text and embedding a graphic inside the button. The asp:Button control renders as <code>&lt;input type="button"&gt;</code>, is there any way to make a preexisting control render to <code>&lt;button&gt;</code>?</p> <p>From what I've read there is an incompatibility with IE posting the button's markup instead of the value attribute when the button is located within a <code>&lt;form&gt;</code>, but in ASP.NET it will be using the onclick event to fire __doPostBack anyway, so I don't think that this would be a problem.</p> <p>Are there any reasons why I shouldn't use this? If not, how would you go about supporting it with asp:Button, or a new server control based on it? I would prefer to not write my own server control if that can be avoided.</p> <hr> <p>At first the <code>&lt;button runat="server"&gt;</code> solution worked, but I immediately ran into a situation where it needs to have a CommandName property, which the HtmlButton control doesn't have. It looks like I'm going to need to create a control inherited from Button after all. </p> <p>What do I need to do in order to override the render method and make it render what I want?</p> <hr> <p><strong>UPDATE</strong></p> <p>DanHerbert's reply has made me interested in finding a solution to this again, so I've spent some more time working on it. </p> <p>First, there's a far easier way of overloading the TagName:</p> <pre><code>public ModernButton() : base(HtmlTextWriterTag.Button) { } </code></pre> <p>The problem with Dan's solution as it stands is the innerhtml of the tag is placed into the value property, which causes a validation error on postback. A related problem is, even if you render the value property correctly, IE's braindead implementation of the <code>&lt;button&gt;</code> tag posts the innerhtml instead of the value anyway. So, any implementation of this needs to override the AddAttributesToRender method in order to correctly render the value property, and also provide some sort of workaround for IE so it doesn't completely screw up the postback.</p> <p>The IE problem may be insurmountable if you want to take advantage of the CommandName/CommandArgument properties for a databound control. Hopefully someone can suggest a workaround for this.</p> <p>I have made progress on the rendering:</p> <p><a href="http://gist.github.com/69841" rel="noreferrer">ModernButton.cs</a></p> <p>This renders as a proper html <code>&lt;button&gt;</code> with the correct value, but it doesn't work with the ASP.Net PostBack system. I've written some of what I need to provide the <code>Command</code> event, but it doesn't fire.</p> <p>When inspecting this button side-by-side with a regular asp:Button, they look the same other than the differences I need. So I'm not sure how ASP.Net is wiring up the <code>Command</code> event in this case.</p> <p>An additional problem is, nested server controls aren't rendered (as you can see with the ParseChildren(false) attribute). It's pretty easy to inject literal html text into the control during render, but how do you allow support for nested server controls?</p>
[ { "answer_id": 573990, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 5, "selected": false, "text": "Button TagName TagKey Button Button [ParseChildren(false)]\n[PersistChildren(true)]\npublic class ModernButton : Button\n{\n protected override string TagName\n {\n get { return \"button\"; }\n }\n\n protected override HtmlTextWriterTag TagKey\n {\n get { return HtmlTextWriterTag.Button; }\n }\n\n // Create a new implementation of the Text property which\n // will be ignored by the parent class, giving us the freedom\n // to use this property as we please.\n public new string Text\n {\n get { return ViewState[\"NewText\"] as string; }\n set { ViewState[\"NewText\"] = HttpUtility.HtmlDecode(value); }\n }\n\n protected override void OnPreRender(System.EventArgs e)\n {\n base.OnPreRender(e);\n // I wasn't sure what the best way to handle 'Text' would\n // be. Text is treated as another control which gets added\n // to the end of the button's control collection in this \n //implementation\n LiteralControl lc = new LiteralControl(this.Text);\n Controls.Add(lc);\n\n // Add a value for base.Text for the parent class\n // If the following line is omitted, the 'value' \n // attribute will be blank upon rendering\n base.Text = UniqueID;\n }\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n RenderChildren(writer);\n }\n}\n <uc:ModernButton runat=\"server\" \n ID=\"btnLogin\" \n OnClick=\"btnLogin_Click\" \n Text=\"Purplemonkeydishwasher\">\n <img src=\"../someUrl/img.gif\" alt=\"img\" />\n <asp:Label ID=\"Label1\" runat=\"server\" Text=\"Login\" />\n</uc:ModernButton>\n // This code probably won't work too well \"as is\"\n// since there is nothing being defined about these\n// controls, but you get the idea.\nbtnLogin.Controls.Add(new Label());\nbtnLogin.Controls.Add(new Table());\n" }, { "answer_id": 975539, "author": "David Andersson", "author_id": 120521, "author_profile": "https://Stackoverflow.com/users/120521", "pm_score": 1, "selected": false, "text": "<button/> name <button type=\"submit\" name=\"ctl02\" value=\"Content\" class=\"btn \">\n <span>Content</span>\n</button>\n name name" }, { "answer_id": 1171539, "author": "Philippe", "author_id": 27219, "author_profile": "https://Stackoverflow.com/users/27219", "pm_score": 5, "selected": false, "text": "<button id=\"btnSubmit\" runat=\"server\" class=\"myButton\" \n onserverclick=\"btnSubmit_Click\">Hello</button>\n" }, { "answer_id": 31879094, "author": "Daniel Liuzzi", "author_id": 88709, "author_profile": "https://Stackoverflow.com/users/88709", "pm_score": 6, "selected": true, "text": "<button class=\"btn btn-default\">\n <span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></span>\n Search\n</button>\n <input> <button> <asp:LinkButton runat=\"server\" ID=\"uxSearch\" CssClass=\"btn btn-default\">\n <span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></span>\n Search\n</asp:LinkButton>\n <a id=\"uxSearch\" class=\"btn btn-default\" href=\"javascript:__doPostBack(&#39;uxSearch&#39;,&#39;&#39;)\">\n <span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></span>\n Search\n</a>\n Command CommandName CommandArgument <a> <button> <button runat=\"server\" id=\"uxSearch\" class=\"btn btn-default\">\n <span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></span>\n Search\n</button>\n <button onclick=\"__doPostBack('uxSearch','')\" id=\"uxSearch\" class=\"btn btn-default\">\n <span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></span>\n Search\n</button>\n <button> Command CommandName CommandArgument ServerClick using System.Web.UI;\nusing System.Web.UI.WebControls;\n\nnamespace ModernControls\n{\n [ParseChildren]\n public class ModernButton : Button\n {\n public new string Text\n {\n get { return (string)ViewState[\"NewText\"] ?? \"\"; }\n set { ViewState[\"NewText\"] = value; }\n }\n\n public string Value\n {\n get { return base.Text; }\n set { base.Text = value; }\n }\n\n protected override HtmlTextWriterTag TagKey\n {\n get { return HtmlTextWriterTag.Button; }\n }\n\n protected override void AddParsedSubObject(object obj)\n {\n var literal = obj as LiteralControl;\n if (literal == null) return;\n Text = literal.Text;\n }\n\n protected override void RenderContents(HtmlTextWriter writer)\n {\n writer.Write(Text);\n }\n }\n}\n PersistChildren TagName Text OnPreRender AddParsedSubObject RenderContents Value using Value Text value Text value <button> <%@ Register TagPrefix=\"mc\" Namespace=\"ModernControls\" %>\n\n<mc:ModernButton runat=\"server\" ID=\"uxSearch\" Value=\"Foo\" CssClass=\"btn btn-default\" >\n <span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></span>\n Search\n</mc:ModernButton>\n <button type=\"submit\" name=\"uxSearch\" value=\"Foo\" id=\"uxSearch\" class=\"btn btn-default\">\n <span class=\"glyphicon glyphicon-search\" aria-hidden=\"true\"></span>\n Search\n</button>\n <button> Command CommandName CommandArgument" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1249/" ]
187,495
<p>In my program, how can I read the properties set in AssemblyInfo.cs:</p> <pre><code>[assembly: AssemblyTitle("My Product")] [assembly: AssemblyDescription("...")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Radeldudel inc.")] [assembly: AssemblyProduct("My Product")] [assembly: AssemblyCopyright("Copyright @ me 2008")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] </code></pre> <p>I'd like to display some of these values to the user of my program, so I'd like to know how to load them from the main program and from komponent assemblies I'm using.</p>
[ { "answer_id": 187529, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 7, "selected": true, "text": "typeof(MyTypeInAssembly).Assembly\n object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false);\n\nAssemblyProductAttribute attribute = null;\nif (attributes.Length > 0)\n{\n attribute = attributes[0] as AssemblyProductAttribute;\n}\n attribute.Product" }, { "answer_id": 874889, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "using System.Runtime.InteropServices;\nusing System.Reflection;\n\nobject[] customAttributes = this.GetType().Assembly.GetCustomAttributes(false);\n foreach (object attribute in customAttributes)\n{\n string assemblyGuid = string.Empty; \n\n if (attribute.GetType() == typeof(GuidAttribute))\n {\n assemblyGuid = ((GuidAttribute) attribute).Value;\n break;\n }\n}\n" }, { "answer_id": 20077072, "author": "dmihailescu", "author_id": 376495, "author_profile": "https://Stackoverflow.com/users/376495", "pm_score": 4, "selected": false, "text": "public static T GetAssemblyAttribute<T>(this System.Reflection.Assembly ass) where T : Attribute\n{\n object[] attributes = ass.GetCustomAttributes(typeof(T), false);\n if (attributes == null || attributes.Length == 0)\n return null;\n return attributes.OfType<T>().SingleOrDefault();\n}\n var attr = targetAssembly.GetAssemblyAttribute<AssemblyDescriptionAttribute>();\nif(attr != null)\n Console.WriteLine(\"{0} Assembly Description:{1}\", Environment.NewLine, attr.Description);\n" }, { "answer_id": 28447667, "author": "Kavindu Dodanduwa", "author_id": 3197055, "author_profile": "https://Stackoverflow.com/users/3197055", "pm_score": 3, "selected": false, "text": "Assembly.LoadFrom(path) c# get assembly attributes CustomAttributes using System;\nusing System.Reflection;\n\nnamespace MetaGetter\n{\n class Program\n {\n static void Main(string[] args)\n {\n Assembly assembly = Assembly.LoadFrom(\"Path to assembly\");\n\n foreach (CustomAttributeData attributedata in assembly.CustomAttributes)\n {\n Console.WriteLine(\" Name : {0}\",attributedata.AttributeType.Name);\n\n foreach (CustomAttributeTypedArgument argumentset in attributedata.ConstructorArguments)\n {\n Console.WriteLine(\" >> Value : {0} \\n\" ,argumentset.Value);\n }\n }\n\n Console.ReadKey();\n }\n }\n}\n Name : AssemblyTitleAttribute\n >> Value : \"My Product\"\n" }, { "answer_id": 40285188, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 2, "selected": false, "text": "public static string Title\n{\n get\n {\n return GetCustomAttribute<AssemblyTitleAttribute>(a => a.Title);\n }\n}\n using System;\nusing System.Reflection;\nusing System.Runtime.CompilerServices;\n\n\n\nnamespace Extensions\n{\n\n\n public static class AssemblyInfo\n {\n\n\n private static Assembly m_assembly;\n\n static AssemblyInfo()\n {\n m_assembly = Assembly.GetEntryAssembly();\n }\n\n\n public static void Configure(Assembly ass)\n {\n m_assembly = ass;\n }\n\n\n public static T GetCustomAttribute<T>() where T : Attribute\n {\n object[] customAttributes = m_assembly.GetCustomAttributes(typeof(T), false);\n if (customAttributes.Length != 0)\n {\n return (T)((object)customAttributes[0]);\n }\n return default(T);\n }\n\n public static string GetCustomAttribute<T>(Func<T, string> getProperty) where T : Attribute\n {\n T customAttribute = GetCustomAttribute<T>();\n if (customAttribute != null)\n {\n return getProperty(customAttribute);\n }\n return null;\n }\n\n public static int GetCustomAttribute<T>(Func<T, int> getProperty) where T : Attribute\n {\n T customAttribute = GetCustomAttribute<T>();\n if (customAttribute != null)\n {\n return getProperty(customAttribute);\n }\n return 0;\n }\n\n\n\n public static Version Version\n {\n get\n {\n return m_assembly.GetName().Version;\n }\n }\n\n\n public static string Title\n {\n get\n {\n return GetCustomAttribute<AssemblyTitleAttribute>(\n delegate(AssemblyTitleAttribute a)\n {\n return a.Title;\n }\n );\n }\n }\n\n public static string Description\n {\n get\n {\n return GetCustomAttribute<AssemblyDescriptionAttribute>(\n delegate(AssemblyDescriptionAttribute a)\n {\n return a.Description;\n }\n );\n }\n }\n\n\n public static string Product\n {\n get\n {\n return GetCustomAttribute<AssemblyProductAttribute>(\n delegate(AssemblyProductAttribute a)\n {\n return a.Product;\n }\n );\n }\n }\n\n\n public static string Copyright\n {\n get\n {\n return GetCustomAttribute<AssemblyCopyrightAttribute>(\n delegate(AssemblyCopyrightAttribute a)\n {\n return a.Copyright;\n }\n );\n }\n }\n\n\n\n public static string Company\n {\n get\n {\n return GetCustomAttribute<AssemblyCompanyAttribute>(\n delegate(AssemblyCompanyAttribute a)\n {\n return a.Company;\n }\n );\n }\n }\n\n\n public static string InformationalVersion\n {\n get\n {\n return GetCustomAttribute<AssemblyInformationalVersionAttribute>(\n delegate(AssemblyInformationalVersionAttribute a)\n {\n return a.InformationalVersion;\n }\n );\n }\n }\n\n\n\n public static int ProductId\n {\n get\n {\n return GetCustomAttribute<AssemblyProductIdAttribute>(\n delegate(AssemblyProductIdAttribute a)\n {\n return a.ProductId;\n }\n );\n }\n }\n\n\n public static string Location\n {\n get\n {\n return m_assembly.Location;\n }\n }\n\n }\n\n}\n" }, { "answer_id": 50062061, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 3, "selected": false, "text": "internal static class AssemblyInfo\n{\n public static string Company { get { return GetExecutingAssemblyAttribute<AssemblyCompanyAttribute>(a => a.Company); } }\n public static string Product { get { return GetExecutingAssemblyAttribute<AssemblyProductAttribute>(a => a.Product); } }\n public static string Copyright { get { return GetExecutingAssemblyAttribute<AssemblyCopyrightAttribute>(a => a.Copyright); } }\n public static string Trademark { get { return GetExecutingAssemblyAttribute<AssemblyTrademarkAttribute>(a => a.Trademark); } }\n public static string Title { get { return GetExecutingAssemblyAttribute<AssemblyTitleAttribute>(a => a.Title); } }\n public static string Description { get { return GetExecutingAssemblyAttribute<AssemblyDescriptionAttribute>(a => a.Description); } }\n public static string Configuration { get { return GetExecutingAssemblyAttribute<AssemblyConfigurationAttribute>(a => a.Configuration); } }\n public static string FileVersion { get { return GetExecutingAssemblyAttribute<AssemblyFileVersionAttribute>(a => a.Version); } }\n\n public static Version Version { get { return Assembly.GetExecutingAssembly().GetName().Version; } }\n public static string VersionFull { get { return Version.ToString(); } }\n public static string VersionMajor { get { return Version.Major.ToString(); } }\n public static string VersionMinor { get { return Version.Minor.ToString(); } }\n public static string VersionBuild { get { return Version.Build.ToString(); } }\n public static string VersionRevision { get { return Version.Revision.ToString(); } }\n\n private static string GetExecutingAssemblyAttribute<T>(Func<T, string> value) where T : Attribute\n {\n T attribute = (T)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(T));\n return value.Invoke(attribute);\n }\n}\n internal class ApplicationData\n{\n\n DirectoryInfo roamingDataFolder;\n DirectoryInfo localDataFolder;\n DirectoryInfo appDataFolder;\n\n public ApplicationData()\n {\n appDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyInfo.Product,\"Data\"));\n roamingDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),AssemblyInfo.Product));\n localDataFolder = new DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AssemblyInfo.Product));\n\n if (!roamingDataFolder.Exists) \n roamingDataFolder.Create();\n\n if (!localDataFolder.Exists)\n localDataFolder.Create();\n if (!appDataFolder.Exists)\n appDataFolder.Create();\n\n }\n\n /// <summary>\n /// Gets the roaming application folder location.\n /// </summary>\n /// <value>The roaming data directory.</value>\n public DirectoryInfo RoamingDataFolder => roamingDataFolder;\n\n\n /// <summary>\n /// Gets the local application folder location.\n /// </summary>\n /// <value>The local data directory.</value>\n public DirectoryInfo LocalDataFolder => localDataFolder;\n\n /// <summary>\n /// Gets the local data folder location.\n /// </summary>\n /// <value>The local data directory.</value>\n public DirectoryInfo AppDataFolder => appDataFolder;\n}\n" }, { "answer_id": 54101934, "author": "glopes", "author_id": 628228, "author_profile": "https://Stackoverflow.com/users/628228", "pm_score": 2, "selected": false, "text": "Attribute var attribute = Attribute.GetCustomAttribute(assembly, typeof(AssemblyTitleAttribute))\n inherit null" }, { "answer_id": 58189887, "author": "Randall Deetz", "author_id": 1096739, "author_profile": "https://Stackoverflow.com/users/1096739", "pm_score": 2, "selected": false, "text": "string company = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false)).Company;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ]
187,505
<p>I have few different applications among which I'd like to share a C# enum. I can't quite figure out how to share an enum declaration between a regular application and a WCF service. </p> <p>Here's the situation. I have 2 lightweight C# destop apps and a WCF webservice that all need to share enum values. </p> <p>Client 1 has </p> <pre><code> Method1( MyEnum e, string sUserId ); </code></pre> <p>Client 2 has </p> <pre><code>Method2( MyEnum e, string sUserId ); </code></pre> <p>Webservice has </p> <pre><code>ServiceMethod1( MyEnum e, string sUserId, string sSomeData); </code></pre> <p>My initial though was to create a library called Common.dll to encapsulate the enum and then just reference that library in all of the projects where the enum is needed. However, WCF makes things difficult because you need to markup the enum for it to be an integral part of the service. Like this: </p> <pre><code>[ServiceContract] [ServiceKnownType(typeof(MyEnum))] public interface IMyService { [OperationContract] ServiceMethod1( MyEnum e, string sUserId, string sSomeData); } [DataContract] public enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue }; </code></pre> <p>So .... Is there a way to share an enum among a WCF service and other applictions? </p>
[ { "answer_id": 189029, "author": "Keith G", "author_id": 5208, "author_profile": "https://Stackoverflow.com/users/5208", "pm_score": 5, "selected": false, "text": "using Common; \n\n[ServiceContract]\n[ServiceKnownType(typeof(MyEnum))]\npublic interface IMyService\n{\n [OperationContract]\n ServiceMethod1( MyEnum e, string sUserId, string sSomeData);\n}\n [DataContract]\npublic enum MyEnum{ [EnumMember] red, [EnumMember] green, [EnumMember] blue };\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5208/" ]
187,506
<p>I'm involved with updating an Access solution. It has a good amount of VBA, a number of queries, a small amount of tables, and a few forms for data entry &amp; report generation. It's an ideal candidate for Access.</p> <p>I want to make changes to the table design, the VBA, the queries, and the forms. How can I track my changes with version control? (we use Subversion, but this goes for any flavor) I can stick the entire mdb in subversion, but that will be storing a binary file, and I won't be able to tell that I just changed one line of VBA code.</p> <p>I thought about copying the VBA code to separate files, and saving those, but I could see those quickly getting out of sync with what's in the database.</p>
[ { "answer_id": 211210, "author": "Oliver", "author_id": 28828, "author_profile": "https://Stackoverflow.com/users/28828", "pm_score": 9, "selected": true, "text": "OpenAccessProject() OpenCurrentDatabase() ' Usage:\n' CScript decompose.vbs <input file> <path>\n\n' Converts all modules, classes, forms and macros from an Access Project file (.adp) <input file> to\n' text and saves the results in separate files to <path>. Requires Microsoft Access.\n'\n\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Bitte den Dateinamen angeben!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sExportpath\nIf (WScript.Arguments.Count = 1) then\n sExportpath = \"\"\nelse\n sExportpath = WScript.Arguments(1)\nEnd If\n\n\nexportModulesTxt sADPFilename, sExportpath\n\nIf (Err <> 0) and (Err.Description <> NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction exportModulesTxt(sADPFilename, sExportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n If (sExportpath = \"\") then\n sExportpath = myPath & \"\\Source\\\"\n End If\n sStubADPFilename = sExportpath & myName & \"_stub.\" & myType\n\n WScript.Echo \"copy stub to \" & sStubADPFilename & \"...\"\n On Error Resume Next\n fso.CreateFolder(sExportpath)\n On Error Goto 0\n fso.CopyFile sADPFilename, sStubADPFilename\n\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" & sStubADPFilename & \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sStubADPFilename\n Else\n oApplication.OpenCurrentDatabase sStubADPFilename\n End If\n\n oApplication.Visible = false\n\n dim dctDelete\n Set dctDelete = CreateObject(\"Scripting.Dictionary\")\n WScript.Echo \"exporting...\"\n Dim myObj\n For Each myObj In oApplication.CurrentProject.AllForms\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acForm, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".form\"\n oApplication.DoCmd.Close acForm, myObj.fullname\n dctDelete.Add \"FO\" & myObj.fullname, acForm\n Next\n For Each myObj In oApplication.CurrentProject.AllModules\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acModule, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".bas\"\n dctDelete.Add \"MO\" & myObj.fullname, acModule\n Next\n For Each myObj In oApplication.CurrentProject.AllMacros\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acMacro, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".mac\"\n dctDelete.Add \"MA\" & myObj.fullname, acMacro\n Next\n For Each myObj In oApplication.CurrentProject.AllReports\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acReport, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".report\"\n dctDelete.Add \"RE\" & myObj.fullname, acReport\n Next\n\n WScript.Echo \"deleting...\"\n dim sObjectname\n For Each sObjectname In dctDelete\n WScript.Echo \" \" & Mid(sObjectname, 3)\n oApplication.DoCmd.DeleteObject dctDelete(sObjectname), Mid(sObjectname, 3)\n Next\n\n oApplication.CloseCurrentDatabase\n oApplication.CompactRepair sStubADPFilename, sStubADPFilename & \"_\"\n oApplication.Quit\n\n fso.CopyFile sStubADPFilename & \"_\", sStubADPFilename\n fso.DeleteFile sStubADPFilename & \"_\"\n\n\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf & \"----------------------------------------------------------------------------------------------------------------------------------------\" & vbCrLf & _\n \"From \" & Err.source & \":\" & vbCrLf & _\n \" Description: \" & Err.Description & vbCrLf & _\n \" Code: \" & Err.Number & vbCrLf\n getErr = strError\nEnd Function\n cscript decompose.vbs youraccessapplication.adp\n ' Usage:\n' WScript compose.vbs <file> <path>\n\n' Converts all modules, classes, forms and macros in a directory created by \"decompose.vbs\"\n' and composes then into an Access Project file (.adp). This overwrites any existing Modules with the\n' same names without warning!!!\n' Requires Microsoft Access.\n\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\n\nConst acCmdCompileAndSaveAllModules = &H7E\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Please enter the file name!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sPath\nIf (WScript.Arguments.Count = 1) then\n sPath = \"\"\nelse\n sPath = WScript.Arguments(1)\nEnd If\n\n\nimportModulesTxt sADPFilename, sPath\n\nIf (Err <> 0) and (Err.Description <> NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction importModulesTxt(sADPFilename, sImportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n ' Build file and pathnames\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n ' if no path was given as argument, use a relative directory\n If (sImportpath = \"\") then\n sImportpath = myPath & \"\\Source\\\"\n End If\n sStubADPFilename = sImportpath & myName & \"_stub.\" & myType\n\n ' check for existing file and ask to overwrite with the stub\n if (fso.FileExists(sADPFilename)) Then\n WScript.StdOut.Write sADPFilename & \" exists. Overwrite? (y/n) \"\n dim sInput\n sInput = WScript.StdIn.Read(1)\n if (sInput <> \"y\") Then\n WScript.Quit\n end if\n\n fso.CopyFile sADPFilename, sADPFilename & \".bak\"\n end if\n\n fso.CopyFile sStubADPFilename, sADPFilename\n\n ' launch MSAccess\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" & sADPFilename & \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sADPFilename\n Else\n oApplication.OpenCurrentDatabase sADPFilename\n End If\n oApplication.Visible = false\n\n Dim folder\n Set folder = fso.GetFolder(sImportpath)\n\n ' load each file from the import path into the stub\n Dim myFile, objectname, objecttype\n for each myFile in folder.Files\n objecttype = fso.GetExtensionName(myFile.Name)\n objectname = fso.GetBaseName(myFile.Name)\n WScript.Echo \" \" & objectname & \" (\" & objecttype & \")\"\n\n if (objecttype = \"form\") then\n oApplication.LoadFromText acForm, objectname, myFile.Path\n elseif (objecttype = \"bas\") then\n oApplication.LoadFromText acModule, objectname, myFile.Path\n elseif (objecttype = \"mac\") then\n oApplication.LoadFromText acMacro, objectname, myFile.Path\n elseif (objecttype = \"report\") then\n oApplication.LoadFromText acReport, objectname, myFile.Path\n end if\n\n next\n\n oApplication.RunCommand acCmdCompileAndSaveAllModules\n oApplication.Quit\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf & \"----------------------------------------------------------------------------------------------------------------------------------------\" & vbCrLf & _\n \"From \" & Err.source & \":\" & vbCrLf & _\n \" Description: \" & Err.Description & vbCrLf & _\n \" Code: \" & Err.Number & vbCrLf\n getErr = strError\nEnd Function\n cscript compose.vbs youraccessapplication.adp\n" }, { "answer_id": 1849498, "author": "DaveParillo", "author_id": 167483, "author_profile": "https://Stackoverflow.com/users/167483", "pm_score": 4, "selected": false, "text": "CurrentProject ' Writes database componenets to a series of text files\n' @author Arvin Meyer\n' @date June 02, 1999\nFunction DocDatabase(oApp)\n Dim dbs \n Dim cnt \n Dim doc \n Dim i\n Dim prefix\n Dim dctDelete\n Dim docName\n\n Const acQuery = 1\n\n Set dctDelete = CreateObject(\"Scripting.Dictionary\")\n\n Set dbs = oApp.CurrentDb() ' use CurrentDb() to refresh Collections\n Set cnt = dbs.Containers(\"Forms\")\n prefix = oApp.CurrentProject.Path & \"\\\"\n For Each doc In cnt.Documents\n oApp.SaveAsText acForm, doc.Name, prefix & doc.Name & \".frm\"\n dctDelete.Add \"frm_\" & doc.Name, acForm\n Next\n\n Set cnt = dbs.Containers(\"Reports\")\n For Each doc In cnt.Documents\n oApp.SaveAsText acReport, doc.Name, prefix & doc.Name & \".rpt\"\n dctDelete.Add \"rpt_\" & doc.Name, acReport\n Next\n\n Set cnt = dbs.Containers(\"Scripts\")\n For Each doc In cnt.Documents\n oApp.SaveAsText acMacro, doc.Name, prefix & doc.Name & \".vbs\"\n dctDelete.Add \"vbs_\" & doc.Name, acMacro\n Next\n\n Set cnt = dbs.Containers(\"Modules\")\n For Each doc In cnt.Documents\n oApp.SaveAsText acModule, doc.Name, prefix & doc.Name & \".bas\"\n dctDelete.Add \"bas_\" & doc.Name, acModule\n Next\n\n For i = 0 To dbs.QueryDefs.Count - 1\n oApp.SaveAsText acQuery, dbs.QueryDefs(i).Name, prefix & dbs.QueryDefs(i).Name & \".txt\"\n dctDelete.Add \"qry_\" & dbs.QueryDefs(i).Name, acQuery\n Next\n\n WScript.Echo \"deleting \" & dctDelete.Count & \" objects.\"\n For Each docName In dctDelete\n WScript.Echo \" \" & Mid(docName, 5)\n oApp.DoCmd.DeleteObject dctDelete(docName), Mid(docName, 5)\n Next\n\n Set doc = Nothing\n Set cnt = Nothing\n Set dbs = Nothing\n Set dctDelete = Nothing\n\nEnd Function\n" }, { "answer_id": 9740061, "author": "JKK", "author_id": 1058864, "author_profile": "https://Stackoverflow.com/users/1058864", "pm_score": 3, "selected": false, "text": "NoSaveCTIWhenDisabled =1\n '(to extract for importing to source control)\ncscript compose.vbs database.accdb \n\n'(to rebuild from extracted files saved from an earlier date)\ncscript decompose.vbs database.accdb C:\\SControl\\Source\\\n" }, { "answer_id": 21149015, "author": "JBickford", "author_id": 118346, "author_profile": "https://Stackoverflow.com/users/118346", "pm_score": 0, "selected": false, "text": "Dim def\nSet stream = fso.CreateTextFile(sExportpath & \"\\\" & myName & \".queries.txt\")\n For Each def In oApplication.CurrentDb.QueryDefs\n\n WScript.Echo \" Exporting Queries to Text...\"\n stream.WriteLine(\"Name: \" & def.Name)\n stream.WriteLine(def.SQL)\n stream.writeline \"--------------------------\"\n stream.writeline \" \"\n\n Next\nstream.Close\n" }, { "answer_id": 26253820, "author": "Daniel Hillebrand", "author_id": 4031178, "author_profile": "https://Stackoverflow.com/users/4031178", "pm_score": 1, "selected": false, "text": "' Usage:\n' CScript decompose.vbs <input file> <path>\n\n' Converts all modules, classes, forms and macros from an Access Project file (.adp) <input file> to\n' text and saves the results in separate files to <path>. Requires Microsoft Access.\n'\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\nconst acQuery = 1\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Bitte den Dateinamen angeben!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sExportpath\nIf (WScript.Arguments.Count = 1) then\n sExportpath = \"\"\nelse\n sExportpath = WScript.Arguments(1)\nEnd If\n\n\nexportModulesTxt sADPFilename, sExportpath\n\nIf (Err <> 0) and (Err.Description <> NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction exportModulesTxt(sADPFilename, sExportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n If (sExportpath = \"\") then\n sExportpath = myPath & \"\\Source\\\"\n End If\n sStubADPFilename = sExportpath & myName & \"_stub.\" & myType\n\n WScript.Echo \"copy stub to \" & sStubADPFilename & \"...\"\n On Error Resume Next\n fso.CreateFolder(sExportpath)\n On Error Goto 0\n fso.CopyFile sADPFilename, sStubADPFilename\n\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" & sStubADPFilename & \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sStubADPFilename\n Else\n oApplication.OpenCurrentDatabase sStubADPFilename\n End If\n\n oApplication.Visible = false\n\n dim dctDelete\n Set dctDelete = CreateObject(\"Scripting.Dictionary\")\n WScript.Echo \"exporting...\"\n Dim myObj\n\n For Each myObj In oApplication.CurrentProject.AllForms\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acForm, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".form\"\n oApplication.DoCmd.Close acForm, myObj.fullname\n dctDelete.Add \"FO\" & myObj.fullname, acForm\n Next\n For Each myObj In oApplication.CurrentProject.AllModules\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acModule, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".bas\"\n dctDelete.Add \"MO\" & myObj.fullname, acModule\n Next\n For Each myObj In oApplication.CurrentProject.AllMacros\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acMacro, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".mac\"\n dctDelete.Add \"MA\" & myObj.fullname, acMacro\n Next\n For Each myObj In oApplication.CurrentProject.AllReports\n WScript.Echo \" \" & myObj.fullname\n oApplication.SaveAsText acReport, myObj.fullname, sExportpath & \"\\\" & myObj.fullname & \".report\"\n dctDelete.Add \"RE\" & myObj.fullname, acReport\n Next\n For Each myObj In oApplication.CurrentDb.QueryDefs\n if not left(myObj.name,3) = \"~sq\" then 'exclude queries defined by the forms. Already included in the form itself\n WScript.Echo \" \" & myObj.name\n oApplication.SaveAsText acQuery, myObj.name, sExportpath & \"\\\" & myObj.name & \".query\"\n oApplication.DoCmd.Close acQuery, myObj.name\n dctDelete.Add \"FO\" & myObj.name, acQuery\n end if\n Next\n\n WScript.Echo \"deleting...\"\n dim sObjectname\n For Each sObjectname In dctDelete\n WScript.Echo \" \" & Mid(sObjectname, 3)\n oApplication.DoCmd.DeleteObject dctDelete(sObjectname), Mid(sObjectname, 3)\n Next\n\n oApplication.CloseCurrentDatabase\n oApplication.CompactRepair sStubADPFilename, sStubADPFilename & \"_\"\n oApplication.Quit\n\n fso.CopyFile sStubADPFilename & \"_\", sStubADPFilename\n fso.DeleteFile sStubADPFilename & \"_\"\n\n\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf & \"----------------------------------------------------------------------------------------------------------------------------------------\" & vbCrLf & _\n \"From \" & Err.source & \":\" & vbCrLf & _\n \" Description: \" & Err.Description & vbCrLf & _\n \" Code: \" & Err.Number & vbCrLf\n getErr = strError\nEnd Function\n ' Usage:\n' WScript compose.vbs <file> <path>\n\n' Converts all modules, classes, forms and macros in a directory created by \"decompose.vbs\"\n' and composes then into an Access Project file (.adp). This overwrites any existing Modules with the\n' same names without warning!!!\n' Requires Microsoft Access.\n\nOption Explicit\n\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\nconst acQuery = 1\n\nConst acCmdCompileAndSaveAllModules = &H7E\n\n' BEGIN CODE\nDim fso\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\n\ndim sADPFilename\nIf (WScript.Arguments.Count = 0) then\n MsgBox \"Bitte den Dateinamen angeben!\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd if\nsADPFilename = fso.GetAbsolutePathName(WScript.Arguments(0))\n\nDim sPath\nIf (WScript.Arguments.Count = 1) then\n sPath = \"\"\nelse\n sPath = WScript.Arguments(1)\nEnd If\n\n\nimportModulesTxt sADPFilename, sPath\n\nIf (Err <> 0) and (Err.Description <> NULL) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction importModulesTxt(sADPFilename, sImportpath)\n Dim myComponent\n Dim sModuleType\n Dim sTempname\n Dim sOutstring\n\n ' Build file and pathnames\n dim myType, myName, myPath, sStubADPFilename\n myType = fso.GetExtensionName(sADPFilename)\n myName = fso.GetBaseName(sADPFilename)\n myPath = fso.GetParentFolderName(sADPFilename)\n\n ' if no path was given as argument, use a relative directory\n If (sImportpath = \"\") then\n sImportpath = myPath & \"\\Source\\\"\n End If\n sStubADPFilename = sImportpath & myName & \"_stub.\" & myType\n\n ' check for existing file and ask to overwrite with the stub\n if (fso.FileExists(sADPFilename)) Then\n WScript.StdOut.Write sADPFilename & \" existiert bereits. Überschreiben? (j/n) \"\n dim sInput\n sInput = WScript.StdIn.Read(1)\n if (sInput <> \"j\") Then\n WScript.Quit\n end if\n\n fso.CopyFile sADPFilename, sADPFilename & \".bak\"\n end if\n\n fso.CopyFile sStubADPFilename, sADPFilename\n\n ' launch MSAccess\n WScript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n WScript.Echo \"opening \" & sADPFilename & \" ...\"\n If (Right(sStubADPFilename,4) = \".adp\") Then\n oApplication.OpenAccessProject sADPFilename\n Else\n oApplication.OpenCurrentDatabase sADPFilename\n End If\n oApplication.Visible = false\n\n Dim folder\n Set folder = fso.GetFolder(sImportpath)\n\n ' load each file from the import path into the stub\n Dim myFile, objectname, objecttype\n for each myFile in folder.Files\n objecttype = fso.GetExtensionName(myFile.Name)\n objectname = fso.GetBaseName(myFile.Name)\n WScript.Echo \" \" & objectname & \" (\" & objecttype & \")\"\n\n if (objecttype = \"form\") then\n oApplication.LoadFromText acForm, objectname, myFile.Path\n elseif (objecttype = \"bas\") then\n oApplication.LoadFromText acModule, objectname, myFile.Path\n elseif (objecttype = \"mac\") then\n oApplication.LoadFromText acMacro, objectname, myFile.Path\n elseif (objecttype = \"report\") then\n oApplication.LoadFromText acReport, objectname, myFile.Path\n elseif (objecttype = \"query\") then\n oApplication.LoadFromText acQuery, objectname, myFile.Path\n end if\n\n next\n\n oApplication.RunCommand acCmdCompileAndSaveAllModules\n oApplication.Quit\nEnd Function\n\nPublic Function getErr()\n Dim strError\n strError = vbCrLf & \"----------------------------------------------------------------------------------------------------------------------------------------\" & vbCrLf & _\n \"From \" & Err.source & \":\" & vbCrLf & _\n \" Description: \" & Err.Description & vbCrLf & _\n \" Code: \" & Err.Number & vbCrLf\n getErr = strError\nEnd Function\n" }, { "answer_id": 35501159, "author": "Jakub M.", "author_id": 4863744, "author_profile": "https://Stackoverflow.com/users/4863744", "pm_score": 2, "selected": false, "text": "' Usage:\n' cscript decompose.vbs <input file> <path>\n\n' Converts all modules, classes, forms and macros from an Access Project file (.adp) <input file> to\n' text and saves the results in separate files to <path>. Requires Microsoft Access.\nOption Explicit\n\nConst acForm = 2\nConst acModule = 5\nConst acMacro = 4\nConst acReport = 3\nConst acQuery = 1\nConst acExportTable = 0\n\n' BEGIN CODE\nDim fso, relDoc, ACCDBFilename, sExportpath\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nSet relDoc = CreateObject(\"Microsoft.XMLDOM\")\n\nIf (Wscript.Arguments.Count = 0) Then\n MsgBox \"Please provide the .accdb database file\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd If\nACCDBFilename = fso.GetAbsolutePathName(Wscript.Arguments(0))\n\nIf (Wscript.Arguments.Count = 1) Then\n sExportpath = \"\"\nElse\n sExportpath = Wscript.Arguments(1)\nEnd If\n\n\nexportModulesTxt ACCDBFilename, sExportpath\n\nIf (Err <> 0) And (Err.Description <> Null) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\nFunction exportModulesTxt(ACCDBFilename, sExportpath)\n Dim myComponent, sModuleType, sTempname, sOutstring\n Dim myType, myName, myPath, hasRelations\n myType = fso.GetExtensionName(ACCDBFilename)\n myName = fso.GetBaseName(ACCDBFilename)\n myPath = fso.GetParentFolderName(ACCDBFilename)\n\n 'if no path was given as argument, use a relative directory\n If (sExportpath = \"\") Then\n sExportpath = myPath & \"\\Source\"\n End If\n 'On Error Resume Next\n fso.DeleteFolder (sExportpath)\n fso.CreateFolder (sExportpath)\n On Error GoTo 0\n\n Wscript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n Wscript.Echo \"Opening \" & ACCDBFilename & \" ...\"\n If (Right(ACCDBFilename, 4) = \".adp\") Then\n oApplication.OpenAccessProject ACCDBFilename\n Else\n oApplication.OpenCurrentDatabase ACCDBFilename\n End If\n oApplication.Visible = False\n\n Wscript.Echo \"exporting...\"\n Dim myObj\n For Each myObj In oApplication.CurrentProject.AllForms\n Wscript.Echo \"Exporting FORM \" & myObj.FullName\n oApplication.SaveAsText acForm, myObj.FullName, sExportpath & \"\\\" & myObj.FullName & \".form.txt\"\n oApplication.DoCmd.Close acForm, myObj.FullName\n Next\n For Each myObj In oApplication.CurrentProject.AllModules\n Wscript.Echo \"Exporting MODULE \" & myObj.FullName\n oApplication.SaveAsText acModule, myObj.FullName, sExportpath & \"\\\" & myObj.FullName & \".module.txt\"\n Next\n For Each myObj In oApplication.CurrentProject.AllMacros\n Wscript.Echo \"Exporting MACRO \" & myObj.FullName\n oApplication.SaveAsText acMacro, myObj.FullName, sExportpath & \"\\\" & myObj.FullName & \".macro.txt\"\n Next\n For Each myObj In oApplication.CurrentProject.AllReports\n Wscript.Echo \"Exporting REPORT \" & myObj.FullName\n oApplication.SaveAsText acReport, myObj.FullName, sExportpath & \"\\\" & myObj.FullName & \".report.txt\"\n Next\n For Each myObj In oApplication.CurrentDb.QueryDefs\n Wscript.Echo \"Exporting QUERY \" & myObj.Name\n oApplication.SaveAsText acQuery, myObj.Name, sExportpath & \"\\\" & myObj.Name & \".query.txt\"\n Next\n For Each myObj In oApplication.CurrentDb.TableDefs\n If Not Left(myObj.Name, 4) = \"MSys\" Then\n Wscript.Echo \"Exporting TABLE \" & myObj.Name\n oApplication.ExportXml acExportTable, myObj.Name, , sExportpath & \"\\\" & myObj.Name & \".table.txt\"\n 'put the file path as a second parameter if you want to export the table data as well, instead of ommiting it and passing it into a third parameter for structure only\n End If\n Next\n\n hasRelations = False\n relDoc.appendChild relDoc.createElement(\"Relations\")\n For Each myObj In oApplication.CurrentDb.Relations 'loop though all the relations\n If Not Left(myObj.Name, 4) = \"MSys\" Then\n Dim relName, relAttrib, relTable, relFoTable, fld\n hasRelations = True\n\n relDoc.ChildNodes(0).appendChild relDoc.createElement(\"Relation\")\n Set relName = relDoc.createElement(\"Name\")\n relName.Text = myObj.Name\n relDoc.ChildNodes(0).LastChild.appendChild relName\n\n Set relAttrib = relDoc.createElement(\"Attributes\")\n relAttrib.Text = myObj.Attributes\n relDoc.ChildNodes(0).LastChild.appendChild relAttrib\n\n Set relTable = relDoc.createElement(\"Table\")\n relTable.Text = myObj.Table\n relDoc.ChildNodes(0).LastChild.appendChild relTable\n\n Set relFoTable = relDoc.createElement(\"ForeignTable\")\n relFoTable.Text = myObj.ForeignTable\n relDoc.ChildNodes(0).LastChild.appendChild relFoTable\n\n Wscript.Echo \"Exporting relation \" & myObj.Name & \" between tables \" & myObj.Table & \" -> \" & myObj.ForeignTable\n\n For Each fld In myObj.Fields 'in case the relationship works with more fields\n Dim lf, ff\n relDoc.ChildNodes(0).LastChild.appendChild relDoc.createElement(\"Field\")\n\n Set lf = relDoc.createElement(\"Name\")\n lf.Text = fld.Name\n relDoc.ChildNodes(0).LastChild.LastChild.appendChild lf\n\n Set ff = relDoc.createElement(\"ForeignName\")\n ff.Text = fld.ForeignName\n relDoc.ChildNodes(0).LastChild.LastChild.appendChild ff\n\n Wscript.Echo \" Involving fields \" & fld.Name & \" -> \" & fld.ForeignName\n Next\n End If\n Next\n If hasRelations Then\n relDoc.InsertBefore relDoc.createProcessingInstruction(\"xml\", \"version='1.0'\"), relDoc.ChildNodes(0)\n relDoc.Save sExportpath & \"\\relations.rel.txt\"\n Wscript.Echo \"Relations successfuly saved in file relations.rel.txt\"\n End If\n\n oApplication.CloseCurrentDatabase\n oApplication.Quit\n\nEnd Function\n cscript decompose.vbs <path to file to decompose> <folder to store text files> oApplication.ExportXML acExportTable, myObj.Name, , sExportpath & \"\\\" & myObj.Name & \".table.txt\" oApplication.ExportXML acExportTable, myObj.Name, sExportpath & \"\\\" & myObj.Name & \".table.txt\" ' Usage:\n' cscript compose.vbs <file> <path>\n\n' Reads all modules, classes, forms, macros, queries, tables and their relationships in a directory created by \"decompose.vbs\"\n' and composes then into an Access Database file (.accdb).\n' Requires Microsoft Access.\nOption Explicit\n\nConst acForm = 2\nConst acModule = 5\nConst acMacro = 4\nConst acReport = 3\nConst acQuery = 1\nConst acStructureOnly = 0 'change 0 to 1 if you want import StructureAndData instead of StructureOnly\nConst acCmdCompileAndSaveAllModules = &H7E\n\nDim fso, relDoc, ACCDBFilename, sPath\nSet fso = CreateObject(\"Scripting.FileSystemObject\")\nSet relDoc = CreateObject(\"Microsoft.XMLDOM\")\n\nIf (Wscript.Arguments.Count = 0) Then\n MsgBox \"Please provide the .accdb database file\", vbExclamation, \"Error\"\n Wscript.Quit()\nEnd If\n\nACCDBFilename = fso.GetAbsolutePathName(Wscript.Arguments(0))\nIf (Wscript.Arguments.Count = 1) Then\n sPath = \"\"\nElse\n sPath = Wscript.Arguments(1)\nEnd If\n\n\nimportModulesTxt ACCDBFilename, sPath\n\nIf (Err <> 0) And (Err.Description <> Null) Then\n MsgBox Err.Description, vbExclamation, \"Error\"\n Err.Clear\nEnd If\n\n\nFunction importModulesTxt(ACCDBFilename, sImportpath)\n Dim myComponent, sModuleType, sTempname, sOutstring\n\n ' Build file and pathnames\n Dim myType, myName, myPath\n myType = fso.GetExtensionName(ACCDBFilename)\n myName = fso.GetBaseName(ACCDBFilename)\n myPath = fso.GetParentFolderName(ACCDBFilename)\n\n ' if no path was given as argument, use a relative directory\n If (sImportpath = \"\") Then\n sImportpath = myPath & \"\\Source\\\"\n End If\n\n ' check for existing file and ask to overwrite with the stub\n If fso.FileExists(ACCDBFilename) Then\n Wscript.StdOut.Write ACCDBFilename & \" already exists. Overwrite? (y/n) \"\n Dim sInput\n sInput = Wscript.StdIn.Read(1)\n If (sInput <> \"y\") Then\n Wscript.Quit\n Else\n If fso.FileExists(ACCDBFilename & \".bak\") Then\n fso.DeleteFile (ACCDBFilename & \".bak\")\n End If\n fso.MoveFile ACCDBFilename, ACCDBFilename & \".bak\"\n End If\n End If\n\n Wscript.Echo \"starting Access...\"\n Dim oApplication\n Set oApplication = CreateObject(\"Access.Application\")\n Wscript.Echo \"Opening \" & ACCDBFilename\n If (Right(ACCDBFilename, 4) = \".adp\") Then\n oApplication.CreateAccessProject ACCDBFilename\n Else\n oApplication.NewCurrentDatabase ACCDBFilename\n End If\n oApplication.Visible = False\n\n Dim folder\n Set folder = fso.GetFolder(sImportpath)\n\n 'load each file from the import path into the stub\n Dim myFile, objectname, objecttype\n For Each myFile In folder.Files\n objectname = fso.GetBaseName(myFile.Name) 'get rid of .txt extension\n objecttype = fso.GetExtensionName(objectname)\n objectname = fso.GetBaseName(objectname)\n\n Select Case objecttype\n Case \"form\"\n Wscript.Echo \"Importing FORM from file \" & myFile.Name\n oApplication.LoadFromText acForm, objectname, myFile.Path\n Case \"module\"\n Wscript.Echo \"Importing MODULE from file \" & myFile.Name\n oApplication.LoadFromText acModule, objectname, myFile.Path\n Case \"macro\"\n Wscript.Echo \"Importing MACRO from file \" & myFile.Name\n oApplication.LoadFromText acMacro, objectname, myFile.Path\n Case \"report\"\n Wscript.Echo \"Importing REPORT from file \" & myFile.Name\n oApplication.LoadFromText acReport, objectname, myFile.Path\n Case \"query\"\n Wscript.Echo \"Importing QUERY from file \" & myFile.Name\n oApplication.LoadFromText acQuery, objectname, myFile.Path\n Case \"table\"\n Wscript.Echo \"Importing TABLE from file \" & myFile.Name\n oApplication.ImportXml myFile.Path, acStructureOnly\n Case \"rel\"\n Wscript.Echo \"Found RELATIONSHIPS file \" & myFile.Name & \" ... opening, it will be processed after everything else has been imported\"\n relDoc.Load (myFile.Path)\n End Select\n Next\n\n If relDoc.readyState Then\n Wscript.Echo \"Preparing to build table dependencies...\"\n Dim xmlRel, xmlField, accessRel, relTable, relName, relFTable, relAttr, i\n For Each xmlRel In relDoc.SelectNodes(\"/Relations/Relation\") 'loop through every Relation node inside .xml file\n relName = xmlRel.SelectSingleNode(\"Name\").Text\n relTable = xmlRel.SelectSingleNode(\"Table\").Text\n relFTable = xmlRel.SelectSingleNode(\"ForeignTable\").Text\n relAttr = xmlRel.SelectSingleNode(\"Attributes\").Text\n\n 'remove any possible conflicting relations or indexes\n On Error Resume Next\n oApplication.CurrentDb.Relations.Delete (relName)\n oApplication.CurrentDb.TableDefs(relTable).Indexes.Delete (relName)\n oApplication.CurrentDb.TableDefs(relFTable).Indexes.Delete (relName)\n On Error GoTo 0\n\n Wscript.Echo \"Creating relation \" & relName & \" between tables \" & relTable & \" -> \" & relFTable\n Set accessRel = oApplication.CurrentDb.CreateRelation(relName, relTable, relFTable, relAttr) 'create the relationship object\n\n For Each xmlField In xmlRel.SelectNodes(\"Field\") 'in case the relationship works with more fields\n accessRel.Fields.Append accessRel.CreateField(xmlField.SelectSingleNode(\"Name\").Text)\n accessRel.Fields(xmlField.SelectSingleNode(\"Name\").Text).ForeignName = xmlField.SelectSingleNode(\"ForeignName\").Text\n Wscript.Echo \" Involving fields \" & xmlField.SelectSingleNode(\"Name\").Text & \" -> \" & xmlField.SelectSingleNode(\"ForeignName\").Text\n Next\n\n oApplication.CurrentDb.Relations.Append accessRel 'append the newly created relationship to the database\n Wscript.Echo \" Relationship added\"\n Next\n End If\n\n oApplication.RunCommand acCmdCompileAndSaveAllModules\n oApplication.Quit\nEnd Function\n cscript compose.vbs <path to file which should be created> <folder with text files> const acStructureOnly = 0 const acStructureOnly = 1" }, { "answer_id": 46453438, "author": "CTristan", "author_id": 1410257, "author_profile": "https://Stackoverflow.com/users/1410257", "pm_score": 0, "selected": false, "text": "' Converts all modules, classes, forms and macros from an Access file (.mdb) <input file> to\n' text and saves the results in separate files to <path>. Requires Microsoft Access.\nOption Explicit\n\nConst acQuery = 1\nConst acForm = 2\nConst acModule = 5\nConst acMacro = 4\nConst acReport = 3\nConst acCmdCompactDatabase = 4\nConst TemporaryFolder = 2\n\nDim strMDBFileName : strMDBFileName = SelectDatabaseFile\nDim strExportPath : strExportPath = SelectExportFolder\nCreateExportFolders(strExportPath)\nDim objProgressWindow\nDim strOverallProgress\nCreateProgressWindow objProgressWindow\nDim strTempMDBFileName\nCopyToTempDatabase strMDBFileName, strTempMDBFileName, strOverallProgress\nDim objAccess\nDim objDatabase\nOpenAccessDatabase objAccess, objDatabase, strTempMDBFileName, strOverallProgress\nExportQueries objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportForms objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportReports objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportMacros objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nExportModules objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress\nobjAccess.CloseCurrentDatabase\nobjAccess.Quit\nDeleteTempDatabase strTempMDBFileName, strOverallProgress\nobjProgressWindow.Quit\nMsgBox \"Successfully exported database.\"\n\nPrivate Function SelectDatabaseFile()\n MsgBox \"Please select the Access database to export.\"\n Dim objFileOpen : Set objFileOpen = CreateObject(\"SAFRCFileDlg.FileOpen\")\n If objFileOpen.OpenFileOpenDlg Then\n SelectDatabaseFile = objFileOpen.FileName\n Else\n WScript.Quit()\n End If\nEnd Function\n\nPrivate Function SelectExportFolder()\n Dim objShell : Set objShell = CreateObject(\"Shell.Application\")\n SelectExportFolder = objShell.BrowseForFolder(0, \"Select folder to export the database to:\", 0, \"\").self.path & \"\\\"\nEnd Function\n\nPrivate Sub CreateExportFolders(strExportPath)\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n MsgBox \"Existing folders from a previous Access export under \" & strExportPath & \" will be deleted!\"\n If objFileSystem.FolderExists(strExportPath & \"Queries\\\") Then\n objFileSystem.DeleteFolder strExportPath & \"Queries\", true\n End If\n objFileSystem.CreateFolder(strExportPath & \"Queries\\\")\n If objFileSystem.FolderExists(strExportPath & \"Forms\\\") Then\n objFileSystem.DeleteFolder strExportPath & \"Forms\", true\n End If\n objFileSystem.CreateFolder(strExportPath & \"Forms\\\")\n If objFileSystem.FolderExists(strExportPath & \"Reports\\\") Then\n objFileSystem.DeleteFolder strExportPath & \"Reports\", true\n End If\n objFileSystem.CreateFolder(strExportPath & \"Reports\\\")\n If objFileSystem.FolderExists(strExportPath & \"Macros\\\") Then\n objFileSystem.DeleteFolder strExportPath & \"Macros\", true\n End If\n objFileSystem.CreateFolder(strExportPath & \"Macros\\\")\n If objFileSystem.FolderExists(strExportPath & \"Modules\\\") Then\n objFileSystem.DeleteFolder strExportPath & \"Modules\", true\n End If\n objFileSystem.CreateFolder(strExportPath & \"Modules\\\")\nEnd Sub\n\nPrivate Sub CreateProgressWindow(objProgressWindow)\n Set objProgressWindow = CreateObject (\"InternetExplorer.Application\")\n objProgressWindow.Navigate \"about:blank\"\n objProgressWindow.ToolBar = 0\n objProgressWindow.StatusBar = 0\n objProgressWindow.Width = 320\n objProgressWindow.Height = 240\n objProgressWindow.Visible = 1\n objProgressWindow.Document.Title = \"Access export in progress\"\nEnd Sub\n\nPrivate Sub CopyToTempDatabase(strMDBFileName, strTempMDBFileName, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Copying to temporary database...<br/>\"\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n strTempMDBFileName = objFileSystem.GetSpecialFolder(TemporaryFolder) & \"\\\" & objFileSystem.GetBaseName(strMDBFileName) & \"_temp.mdb\"\n objFileSystem.CopyFile strMDBFileName, strTempMDBFileName\nEnd Sub\n\nPrivate Sub OpenAccessDatabase(objAccess, objDatabase, strTempMDBFileName, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Compacting temporary database...<br/>\"\n Set objAccess = CreateObject(\"Access.Application\")\n objAccess.Visible = false\n CompactAccessDatabase objAccess, strTempMDBFileName\n strOverallProgress = strOverallProgress & \"Opening temporary database...<br/>\"\n objAccess.OpenCurrentDatabase strTempMDBFileName\n Set objDatabase = objAccess.CurrentDb\nEnd Sub\n\n' Sometimes the Compact Database command errors out, and it's not serious if the database isn't compacted first.\nPrivate Sub CompactAccessDatabase(objAccess, strTempMDBFileName)\n On Error Resume Next\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n objAccess.DbEngine.CompactDatabase strTempMDBFileName, strTempMDBFileName & \"_\"\n objFileSystem.CopyFile strTempMDBFileName & \"_\", strTempMDBFileName\n objFileSystem.DeleteFile strTempMDBFileName & \"_\"\nEnd Sub\n\nPrivate Sub ExportQueries(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Exporting Queries (Step 1 of 5)...<br/>\"\n Dim counter\n For counter = 0 To objDatabase.QueryDefs.Count - 1\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter + 1 & \" of \" & objDatabase.QueryDefs.Count\n objAccess.SaveAsText acQuery, objDatabase.QueryDefs(counter).Name, strExportPath & \"Queries\\\" & Clean(objDatabase.QueryDefs(counter).Name) & \".sql\"\n Next\nEnd Sub\n\nPrivate Sub ExportForms(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Exporting Forms (Step 2 of 5)...<br/>\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Forms\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter & \" of \" & objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acForm, objDocument.Name, strExportPath & \"Forms\\\" & Clean(objDocument.Name) & \".form\"\n objAccess.DoCmd.Close acForm, objDocument.Name\n Next\nEnd Sub\n\nPrivate Sub ExportReports(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Exporting Reports (Step 3 of 5)...<br/>\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Reports\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter & \" of \" & objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acReport, objDocument.Name, strExportPath & \"Reports\\\" & Clean(objDocument.Name) & \".report\"\n Next\nEnd Sub\n\nPrivate Sub ExportMacros(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Exporting Macros (Step 4 of 5)...<br/>\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Scripts\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter & \" of \" & objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acMacro, objDocument.Name, strExportPath & \"Macros\\\" & Clean(objDocument.Name) & \".macro\"\n Next\nEnd Sub\n\nPrivate Sub ExportModules(objAccess, objDatabase, objProgressWindow, strExportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Exporting Modules (Step 5 of 5)...<br/>\"\n Dim counter : counter = 1\n Dim objContainer : Set objContainer = objDatabase.Containers(\"Modules\")\n Dim objDocument\n For Each objDocument In objContainer.Documents\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter & \" of \" & objContainer.Documents.Count\n counter = counter + 1\n objAccess.SaveAsText acModule, objDocument.Name, strExportPath & \"Modules\\\" & Clean(objDocument.Name) & \".module\"\n Next\nEnd Sub\n\nPrivate Sub DeleteTempDatabase(strTempMDBFileName, strOverallProgress)\n On Error Resume Next\n strOverallProgress = strOverallProgress & \"Deleting temporary database...<br/>\"\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n objFileSystem.DeleteFile strTempMDBFileName, true\nEnd Sub\n\n' Windows doesn't like certain characters, so we have to filter those out of the name when exporting\nPrivate Function Clean(strInput)\n Dim objRegexp : Set objRegexp = New RegExp\n objRegexp.IgnoreCase = True\n objRegexp.Global = True\n objRegexp.Pattern = \"[\\\\/:*?\"\"<>|]\"\n Dim strOutput\n If objRegexp.Test(strInput) Then\n strOutput = objRegexp.Replace(strInput, \"\")\n MsgBox strInput & \" is being exported as \" & strOutput\n Else\n strOutput = strInput\n End If\n Clean = strOutput\nEnd Function\n ' Imports all of the queries, forms, reports, macros, and modules from text\n' files to an Access file (.mdb). Requires Microsoft Access.\nOption Explicit\n\nconst acQuery = 1\nconst acForm = 2\nconst acModule = 5\nconst acMacro = 4\nconst acReport = 3\nconst acCmdCompileAndSaveAllModules = &H7E\n\nDim strMDBFilename : strMDBFilename = SelectDatabaseFile\nCreateBackup strMDBFilename\nDim strImportPath : strImportPath = SelectImportFolder\nDim objAccess\nDim objDatabase\nOpenAccessDatabase objAccess, objDatabase, strMDBFilename\nDim objProgressWindow\nDim strOverallProgress\nCreateProgressWindow objProgressWindow\nImportQueries objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportForms objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportReports objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportMacros objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nImportModules objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress\nobjAccess.CloseCurrentDatabase\nobjAccess.Quit\nobjProgressWindow.Quit\nMsgBox \"Successfully imported objects into the database.\"\n\nPrivate Function SelectDatabaseFile()\n MsgBox \"Please select the Access database to import the objects from. ALL EXISTING OBJECTS WITH THE SAME NAME WILL BE OVERWRITTEN!\"\n Dim objFileOpen : Set objFileOpen = CreateObject( \"SAFRCFileDlg.FileOpen\" )\n If objFileOpen.OpenFileOpenDlg Then\n SelectDatabaseFile = objFileOpen.FileName\n Else\n WScript.Quit()\n End If\nEnd Function\n\nPrivate Function SelectImportFolder()\n Dim objShell : Set objShell = WScript.CreateObject(\"Shell.Application\")\n SelectImportFolder = objShell.BrowseForFolder(0, \"Select folder to import the database objects from:\", 0, \"\").self.path & \"\\\"\nEnd Function\n\nPrivate Sub CreateBackup(strMDBFilename)\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n objFileSystem.CopyFile strMDBFilename, strMDBFilename & \".bak\"\nEnd Sub\n\nPrivate Sub OpenAccessDatabase(objAccess, objDatabase, strMDBFileName)\n Set objAccess = CreateObject(\"Access.Application\")\n objAccess.OpenCurrentDatabase strMDBFilename\n objAccess.Visible = false\n Set objDatabase = objAccess.CurrentDb\nEnd Sub\n\nPrivate Sub CreateProgressWindow(ByRef objProgressWindow)\n Set objProgressWindow = CreateObject (\"InternetExplorer.Application\")\n objProgressWindow.Navigate \"about:blank\"\n objProgressWindow.ToolBar = 0\n objProgressWindow.StatusBar = 0\n objProgressWindow.Width = 320\n objProgressWindow.Height = 240\n objProgressWindow.Visible = 1\n objProgressWindow.Document.Title = \"Access import in progress\"\nEnd Sub\n\nPrivate Sub ImportQueries(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = \"Importing Queries (Step 1 of 5)...<br/>\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath & \"Queries\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strQueryName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter + 1 & \" of \" & folder.Files.Count\n strQueryName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acQuery, strQueryName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportForms(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Importing Forms (Step 2 of 5)...<br/>\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath & \"Forms\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strFormName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter + 1 & \" of \" & folder.Files.Count\n strFormName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acForm, strFormName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportReports(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Importing Reports (Step 3 of 5)...<br/>\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath & \"Reports\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strReportName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter + 1 & \" of \" & folder.Files.Count\n strReportName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acReport, strReportName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportMacros(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Importing Macros (Step 4 of 5)...<br/>\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath & \"Macros\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strMacroName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter + 1 & \" of \" & folder.Files.Count\n strMacroName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acMacro, strMacroName, file.Path\n counter = counter + 1\n Next\nEnd Sub\n\nPrivate Sub ImportModules(objAccess, objDatabase, objProgressWindow, strImportPath, strOverallProgress)\n strOverallProgress = strOverallProgress & \"Importing Modules (Step 5 of 5)...<br/>\"\n Dim counter : counter = 0\n Dim folder : Set folder = objFileSystem.GetFolder(strImportPath & \"Modules\\\")\n Dim objFileSystem : Set objFileSystem = CreateObject(\"Scripting.FileSystemObject\")\n Dim file\n Dim strModuleName\n For Each file in folder.Files\n objProgressWindow.Document.Body.InnerHTML = strOverallProgress & counter + 1 & \" of \" & folder.Files.Count\n strModuleName = objFileSystem.GetBaseName(file.Name)\n objAccess.LoadFromText acModule, strModuleName, file.Path\n counter = counter + 1\n Next\n\n ' We need to compile the database whenever any module code changes.\n If Not objAccess.IsCompiled Then\n objAccess.RunCommand acCmdCompileAndSaveAllModules\n End If\nEnd Sub\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1753/" ]
187,515
<p>I have two arrays. One contains <code>id=&gt;count</code> and the other contains <code>id=&gt;name</code>. I'm trying to produce a single array that is <code>name=&gt;count</code>. Any suggestions on a straightforward way to do this?</p> <p>I have looked at the <a href="http://us2.php.net/manual/en/ref.array.php" rel="nofollow noreferrer">Array Functions in the PHP Manual</a> and didn't see anything that stood out as doing what I want, so I'm guessing I'll need a combination of functions, but I'm having trouble coming up with something that's not convoluted.</p>
[ { "answer_id": 187533, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 3, "selected": true, "text": "foreach($countA as $id => $count)\n{\n $newArray[$nameA[$id]] = $count;\n}\n" }, { "answer_id": 187534, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 2, "selected": false, "text": "$countArray = array(0 => 1, 1 => 5);\n$namesArray = array(0 => \"Bob\", 1 => \"Alice\");\n\n$assocArray = array_combine($namesArray, $countArray);\n $assocArray = array();\nforeach($namesArray as $id => $name) {\n $assocArray[$name] = (array_key_exists($id, $countArray)) ? $countArray[$id] : 0;\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
187,526
<p>I'd like to be able to run my aliases from my .bashrc in the "Run Application" dialog that comes up when you hit Alt+F2 in Ubuntu/Gnome.</p> <p>Does anyone know how to do this?</p>
[ { "answer_id": 198830, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 3, "selected": true, "text": ".bashrc xterm -e 'bash -c \"unzip -l %f; sleep 5\"' rm -rf ~/.local/share/applications/ xterm-usercreated.desktop [Desktop Entry]\nEncoding=UTF-8\nName=xterm\nMimeType=application/zip;\nExec=xterm -e 'bash -c \"unzip -l %f; sleep 5\"' %f\nType=Application\nTerminal=false\nNoDisplay=true\n [Desktop Entry]\nType=Application\nEncoding=UTF-8\nName=XTerm\nGenericName=\nComment=XTerm: terminal emulator for X\nIcon=/usr/share/pixmaps/xterm-color_32x32.xpm\nExec=xterm\nTerminal=false\nCategories=X-Debian-Applications-Terminal-Emulators;\n [Desktop Entry] \nType=Application \nEncoding=UTF-8 \nName=xtermz \nExec=xterm -e 'bash -c \"unzip -l %f; sleep 5\"' %f \nTerminal=false \nCategories=X-Local-WTF \n xdg-desktop-menu xdg-icon-resource xdg-utils .desktop .desktop xdg-desktop-menu install" }, { "answer_id": 2753932, "author": "Nostoc", "author_id": 330870, "author_profile": "https://Stackoverflow.com/users/330870", "pm_score": 1, "selected": false, "text": "sudo ln -s ~/bin/MyShellScript.sh /usr/bin/MyShortcutName" }, { "answer_id": 10000461, "author": "plinio", "author_id": 1311320, "author_profile": "https://Stackoverflow.com/users/1311320", "pm_score": 2, "selected": false, "text": "ln -s <YOUR_ALIAS_PATCH> <ALIAS_NAME>" }, { "answer_id": 17927472, "author": "gzS", "author_id": 2603364, "author_profile": "https://Stackoverflow.com/users/2603364", "pm_score": 1, "selected": false, "text": "$ cat my/local/path/terminal\n#! /bin/bash\ngnome-terminal\n $ cat my/local/path/myAlias\n#! /bin/bash\nCMD=\"$*\"\neval \"$CMD\"\n" }, { "answer_id": 25629268, "author": "VinGarcia", "author_id": 2905274, "author_profile": "https://Stackoverflow.com/users/2905274", "pm_score": 0, "selected": false, "text": "echo -e '#!/usr/bin/bash\\n~/bin/$@' > ~/temp\nsudo cp ~/temp /usr/local/bin/my\nrm ~/temp\n my script.sh\n" }, { "answer_id": 33537689, "author": "Jason Eisner", "author_id": 5026802, "author_profile": "https://Stackoverflow.com/users/5026802", "pm_score": 1, "selected": false, "text": "#!/bin/bash -i\neval \"$@\"\n b foo arg1 arg2\n foo arg1 arg2\n" }, { "answer_id": 33930536, "author": "maxkoryukov", "author_id": 1115187, "author_profile": "https://Stackoverflow.com/users/1115187", "pm_score": 2, "selected": false, "text": "mkdir ~/bin #actually, need to run this line just once\ncd ~/bin\nln -s /bin/any/your/application.sh YOUR_ALIAS_NAME\n calc mkdir ~/bin\ncd ~/bin\nln -s /usr/bin/gnome-calculator calc\n ~/bin #create the file:\necho '#!/bin/sh\nfirefox --private-window' > ~/bin/pfx\n#make my script executable:\nchmod 755 ~/bin/pfx\n .profile .profile ~/bin $PATH bin bin" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26510/" ]
187,531
<p>I have a package that I just made and I have an "old-mode" that basically makes it work like it worked before: importing everything into the current namespace. One of the nice things about having this as a package is that we no longer have to do that. Anyway, what I would like to do is have it so that whenever anyone does:</p> <pre><code>use Foo qw(:oldmode); </code></pre> <p>I throw a warning that this is deprecated and that they should either import only what they need or just access functions with Foo->fun();</p> <p>Any ideas on how to do this?</p>
[ { "answer_id": 187541, "author": "moritz", "author_id": 14132, "author_profile": "https://Stackoverflow.com/users/14132", "pm_score": 4, "selected": false, "text": "sub import package Foo use Foo package Foo;\nuse Exporter;\n\nsub import {\n warn \"called with paramters '@_'\";\n\n # do the real import work\n goto &{Exporter->can('import')};\n}\n import goto &{Exporter->can('import')}" }, { "answer_id": 187625, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": true, "text": "use Mod qw<:oldmode>; package Foo;\nuse base qw<Exporter>;\nuse Carp qw<carp>;\n...\nsub import { \n #if ( grep { $_ eq ':oldmode' } @_ ) { # Perl 5.8\n if ( @_ ~~ ':oldmode' ) { # Perl 5.10 \n carp( 'import called with :oldmode!' );\n }\n goto &{Exporter->can( 'import' )};\n}\n $Exporter::ExportLevel Foo->export_to_level( 1, @_ );" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12448/" ]
187,537
<p>Is there a case insensitive version of the <a href="http://docs.jquery.com/Selectors/contains" rel="noreferrer">:contains</a> jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?</p>
[ { "answer_id": 187557, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 8, "selected": true, "text": "jQuery.extend(\n jQuery.expr[':'], { \n Contains : \"jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0\" \n});\n jQuery.expr[':'].Contains = function(a,i,m){\n return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;\n};\n (a.textContent || a.innerText || \"\") \n jQuery(a).text()\n jQuery.expr[\":\"].Contains = jQuery.expr.createPseudo(function(arg) {\n return function( elem ) {\n return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;\n };\n});\n" }, { "answer_id": 783874, "author": "user95227", "author_id": 95227, "author_profile": "https://Stackoverflow.com/users/95227", "pm_score": 5, "selected": false, "text": "jQuery.expr[':'].Contains = function(a,i,m){\n return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;\n};\n" }, { "answer_id": 994213, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "jQuery.expr[':'].contains = function(a,i,m){\n return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;\n};\n" }, { "answer_id": 4936066, "author": "montrealmike", "author_id": 454375, "author_profile": "https://Stackoverflow.com/users/454375", "pm_score": 7, "selected": false, "text": "$.extend($.expr[':'], {\n 'containsi': function(elem, i, match, array)\n {\n return (elem.textContent || elem.innerText || '').toLowerCase()\n .indexOf((match[3] || \"\").toLowerCase()) >= 0;\n }\n});\n :containsi :contains" }, { "answer_id": 11326196, "author": "Brock Adams", "author_id": 331508, "author_profile": "https://Stackoverflow.com/users/331508", "pm_score": 4, "selected": false, "text": "jQuery.extend (\n jQuery.expr[':'].containsCI = function (a, i, m) {\n //-- faster than jQuery(a).text()\n var sText = (a.textContent || a.innerText || \"\"); \n var zRegExp = new RegExp (m[3], 'i');\n return zRegExp.test (sText);\n }\n);\n $(\"p:containsCI('\\\\bup\\\\b')\") $(\"p:containsCI('(?:Red|Blue) state')\") $(\"p:containsCI('^\\\\s*Stocks?')\")" }, { "answer_id": 12113443, "author": "seagullJS", "author_id": 1593862, "author_profile": "https://Stackoverflow.com/users/1593862", "pm_score": 5, "selected": false, "text": "jQuery.expr[\":\"].icontains = jQuery.expr.createPseudo(function (arg) { \n return function (elem) { \n return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0; \n }; \n});\n" }, { "answer_id": 16776915, "author": "ErickBest", "author_id": 2290703, "author_profile": "https://Stackoverflow.com/users/2290703", "pm_score": 4, "selected": false, "text": "$.extend($.expr[\":\"], {\n\"MyCaseInsensitiveContains\": function(elem, i, match, array) {\nreturn (elem.textContent || elem.innerText || \"\").toLowerCase().indexOf((match[3] || \"\").toLowerCase()) >= 0;\n}\n});\n" }, { "answer_id": 34719928, "author": "Umesh Patil", "author_id": 1200323, "author_profile": "https://Stackoverflow.com/users/1200323", "pm_score": 3, "selected": false, "text": " $.expr[\":\"].contains = $.expr.createPseudo(function(arg) {\n return function( elem ) {\n return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;\n };\n });\n $(\"#searchTextBox\").keypress(function() {\n if($(\"#searchTextBox\").val().length > 0){\n $(\".rows\").css(\"display\",\"none\");\n var userSerarchField = $(\"#searchTextBox\").val();\n $(\".rows:contains('\"+ userSerarchField +\"')\").css(\"display\",\"block\");\n } else {\n $(\".rows\").css(\"display\",\"block\");\n } \n });\n" }, { "answer_id": 36392273, "author": "shao.lo", "author_id": 820013, "author_profile": "https://Stackoverflow.com/users/820013", "pm_score": 0, "selected": false, "text": "// This doesn't catch flac or Flac\n$('div.story span.Quality:not(:contains(\"FLAC\"))').css(\"background-color\", 'yellow');\n $('div.story span.Quality:not([data*=\"flac\"])').css(\"background-color\", 'yellow');\n $('div.story span.Quality').contents().filter(function()\n{\n return !/flac/i.test(this.nodeValue);\n}).parent().css(\"background-color\", 'yellow');\n" }, { "answer_id": 50006690, "author": "Howard", "author_id": 1040634, "author_profile": "https://Stackoverflow.com/users/1040634", "pm_score": 2, "selected": false, "text": "$.expr[':'].icontains = function(el, i, m) { // checks for substring (case insensitive)\n var search = m[3];\n if (!search) return false;\n\n var pattern = new RegExp(search, 'i');\n return pattern.test($(el).text());\n};\n" }, { "answer_id": 59730613, "author": "劉鎮瑲", "author_id": 7786739, "author_profile": "https://Stackoverflow.com/users/7786739", "pm_score": 0, "selected": false, "text": "$(\"elementsYouNeed\") .filter() .filter() $(\"elementsYouNeed\") .toLowerCase() .filter() var subString =\"string you want to match\".toLowerCase();\n\nvar matchObjects = $(\"elementsYouNeed\").filter(function () {return $(this).text().toLowerCase().indexOf(subString) > -1;});\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238/" ]
187,550
<p>I have a lot of Java source code that requires custom pre-processing. I'd like rid of it but that's not feasible right now so I'm stuck with it. Given that I have an unfortunate problem that shouldn't have existed in the first place, how do I solve it using maven? </p> <p>(For the full story, I'm replacing a python-based build system with a maven one, so one improvement at a time please. Fixing the non-standard source code is harder, and will come later.)</p> <p>Is it possible using any existing Maven plugins to actually alter the source files during compile time? (Obviously leaving the original, unprocessed code alone)</p> <p>To be clear, by preprocessing I mean preprocessing in the same sense as antenna or a C compiler would preprocess the code, and by custom I mean that it's completely proprietary and looks nothing at all like C or antenna preprocessing.</p>
[ { "answer_id": 189299, "author": "Travis B. Hartwell", "author_id": 10873, "author_profile": "https://Stackoverflow.com/users/10873", "pm_score": 4, "selected": true, "text": " <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-antrun-plugin</artifactId>\n <executions>\n <execution>\n <id>process-sources</id>\n <phase>process-sources</phase>\n <configuration>\n <tasks>\n <!-- Put the code to run the program here -->\n </tasks>\n </configuration>\n <goals>\n <goal>run</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n</build>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
187,552
<p>What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python?</p> <p>Thus far I've tried</p> <pre><code>target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) </code></pre> <p>This gives me data but its garbled or wont play in mp3 players.</p>
[ { "answer_id": 187563, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "target target = open(target_path, \"wb\")\n" }, { "answer_id": 3193428, "author": "Boiler", "author_id": 385355, "author_profile": "https://Stackoverflow.com/users/385355", "pm_score": 2, "selected": false, "text": "urllib.urlretrieve(stream_url, target_path);\n" }, { "answer_id": 50496223, "author": "never_comment", "author_id": 8452041, "author_profile": "https://Stackoverflow.com/users/8452041", "pm_score": 1, "selected": false, "text": "import urllib.request\n\nurllib.request.urlretrieve(stream_url, target_path)\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2906/" ]
187,555
<p>I have a flash program that loads movie clips dynamically and sometimes they want to use more than the space that I give them. Ideally I'd like to force them to only show content in borders I give them. The reason I want this is that my program has a user interface that sometimes gets covered up by this behavior. I'd like to avoid rewriting my program to have these loaded movies be on the first level but that's looking like my only option. Any suggestions?</p>
[ { "answer_id": 188666, "author": "defmeta", "author_id": 10875, "author_profile": "https://Stackoverflow.com/users/10875", "pm_score": 0, "selected": false, "text": "private function onClipLoaded(clipRef:MovieClip) {\n if (clipRef.width > myViewArea.width) {\n var scaleRatio:Number = myViewArea.width / clipRef.width;\n with (clipRef) {\n scaleX = scaleRatio;\n scaleY = scaleRatio;\n }\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12261/" ]
187,560
<p>I am migrating a site from SharePoint 2 to 3 (in fact, from SharePoint Portal Server 2003 to Microsoft Office SharePoint Server 2007). There are a handful of 3rd party web parts and since this is a migration, not an in-place upgrade, I need to install these web parts on the new farm.</p> <p>How do I do this, given that I have the packaged up web parts as provided by the SharePoint Configuration Analyzer in the form of cab files? Can I simply deploy these cab files somehow, even though they are not packaged as solutions? Or do I need to pull the cab files apart and repackage them as solutions? Or do I need to get new versions of the web parts, written for SharePoint 3, and maybe edit the pages that use them?</p>
[ { "answer_id": 188684, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 3, "selected": true, "text": "STSADM -o addwppack -filename <filename.CAB>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3142/" ]
187,567
<p>I used Visual Studio's Application Wizard to create a skeleton MFC program with a multi-document interface. When I start this program, it automatically creates a child frame, which I don't want it to do - I need the main frame's client area to be empty until the user chooses to open a file.</p> <p>The debugger tells me that a CChildFrame object is created when the application class's InitInstance() function calls ProcessShellCommand(), but what is a good entry point for me to override this behaviour?</p>
[ { "answer_id": 187931, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 3, "selected": true, "text": "if (!ProcessShellCommand(cmdInfo))\n if (cmdInfo.m_nShellCommand != CCommandLineInfo::FileNew && !ProcessShellCommand(cmdInfo))\n" }, { "answer_id": 190286, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 3, "selected": false, "text": "// Parse command line for standard shell commands, DDE, file open\nCCommandLineInfo cmdInfo;\nParseCommandLine(cmdInfo);\n\nif ( cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew )\n{\n cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing ;\n}\n\n// Dispatch commands specified on the command line\nif (!ProcessShellCommand(cmdInfo))\n return FALSE;\n" }, { "answer_id": 2251383, "author": "Jatin Zaveri", "author_id": 271787, "author_profile": "https://Stackoverflow.com/users/271787", "pm_score": 1, "selected": false, "text": " CCommandLineInfo cmdInfo;\nParseCommandLine(cmdInfo);\n\n// Dispatch commands specified on the command line. Will return FALSE if\n// app was launched with /RegServer, /Register, /Unregserver or /Unregister.\nif (!ProcessShellCommand(cmdInfo))\n return; \n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
187,576
<p>I am developing a little app that retrieves an XML file, located on a remote server (<code>http://example.com/myfile.xml</code>) This file is relatively big, and it contains a big list of geolocations with other information that I need to use for my app. So I read this file remotely once and insert it into a little SqlCE file (<code>database.sdf</code>)</p> <p>So If I need to be accessing geolocation #1, I ll just make a SELECT statement into this DATABASE instead of loading the whole XML file every time.</p> <p>But I would like to know if its possible to do this without using .sdf files?</p> <p>What is the most efficient way (fastest)?</p> <p>Saving the big XML file once locally and load if every time I start my app to load it in a data set? this is would make the app a bit long to load every time</p> <p>Saving the big XML file once locally and reading the nodes one by one to look for geolocation #1?</p> <p>Or is it possible to retrieve geolocation #1 from the remote XML directly(<code>http://example.com/myfile.xml</code>) without reading the whole file?</p>
[ { "answer_id": 187909, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": ".proto .proto .proto" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12067/" ]
187,583
<p>I have one std::list&lt;> container and these threads:</p> <ul> <li><p>One writer thread which adds elements indefinitely.</p></li> <li><p>One reader/writer thread which reads and removes elements while available.</p></li> <li><p>Several reader threads which access the SIZE of the container (by using the size() method)</p></li> </ul> <p>There is a normal mutex which protects the access to the list from the first two threads. My question is, do the size reader threads need to acquire this mutex too? should I use a read/write mutex?</p> <p>I'm in a windows environment using Visual C++ 6.</p> <p><strong>Update</strong>: It looks like the answer is not clear yet. To sum up the main doubt: Do I still need to protect the SIZE reader threads even if they only call size() (which returns a simple variable) taking into account that I don't need the exact value (i.e. I can assume a +/- 1 variation)? How a race condition could make my size() call return an invalid value (i.e. one totally unrelated to the good one)?</p> <p><strong>Answer</strong>: In general, the reader threads must be protected to avoid race conditions. Nevertheless, in my opinion, some of the questions stated above in the update haven't been answered yet.</p> <p>Thanks in advance! </p> <p>Thank you all for your answers!</p>
[ { "answer_id": 242721, "author": "Tal", "author_id": 11287, "author_profile": "https://Stackoverflow.com/users/11287", "pm_score": 1, "selected": false, "text": "volatile unsigned int ContainerSize = 0;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11441/" ]
187,587
<p>I'm looking for the equivalent of the Unix 'tail' command that will allow me to watch the output of a log file while it is being written to.</p>
[ { "answer_id": 187826, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 4, "selected": false, "text": "---------- T.TXT: 15\n tail.bat REM tail.bat\nREM\nREM Usage: tail.bat <file> <number-of-lines> \nREM\nREM Examples: tail.bat myfile.txt 10\nREM tail.bat \"C:\\My File\\With\\Spaces.txt\" 10\n\n@ECHO OFF\nfor /f \"tokens=2-3 delims=:\" %%f in ('find /c /v \"\" %1') do (\n for %%F in (%%f %%g) do set nbLines=%%F )\nset /a nbSkippedLines=%nbLines%-%2\nfor /f \"usebackq skip=%nbSkippedLines% delims=\" %%d in (%1) do echo %%d\n" }, { "answer_id": 188126, "author": "Alex", "author_id": 26564, "author_profile": "https://Stackoverflow.com/users/26564", "pm_score": 9, "selected": false, "text": "Get-Content filenamehere -Wait -Tail 30\n" }, { "answer_id": 841695, "author": "ismail", "author_id": 35060, "author_profile": "https://Stackoverflow.com/users/35060", "pm_score": 3, "selected": false, "text": "Windows Server 2003 Resource Kit Tools" }, { "answer_id": 841713, "author": "Uberfuzzy", "author_id": 314, "author_profile": "https://Stackoverflow.com/users/314", "pm_score": 2, "selected": false, "text": "type cat cat tail tail" }, { "answer_id": 841787, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 4, "selected": false, "text": "Get-Content <file> -Wait\n" }, { "answer_id": 1307475, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "@echo off\nSETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION\nrem tail.bat -d <lines> <file>\nrem tail.bat -f <file>\n\nrem ****** MAIN ******\nIF \"%1\"==\"-d\" GOTO displayfile\nIF \"%1\"==\"-f\" GOTO followfile\n\nGOTO end\n\nrem ************\nrem Show Last n lines of file\nrem ************\n\n:displayfile\nSET skiplines=%2\nSET sourcefile=%3\n\nrem *** Get the current line count of file ***\nFOR /F \"usebackq tokens=3,3 delims= \" %%l IN (`find /c /v \"\" %sourcefile%`) DO (call SET find_lc=%%l)\n\nrem *** Calculate the lines to skip\nSET /A skiplines=%find_lc%-!skiplines!\n\nrem *** Display to screen line needed\nmore +%skiplines% %sourcefile%\n\nGOTO end\n\nrem ************\nrem Show Last n lines of file & follow output\nrem ************\n\n:followfile\nSET skiplines=0\nSET findend_lc=0\nSET sourcefile=%2\n\n:followloop\nrem *** Get the current line count of file ***\nFOR /F \"usebackq tokens=3,3 delims= \" %%l IN (`find /c /v \"\" %sourcefile%`) DO (call SET find_lc=%%l)\nFOR /F \"usebackq tokens=3,3 delims= \" %%l IN (`find /c /v \"\" %sourcefile%`) DO (call SET findend_lc=%%l)\n\nrem *** Calculate the lines to skip\nSET /A skiplines=%findend_lc%-%find_lc%\nSET /A skiplines=%find_lc%-%skiplines%\n\nrem *** Display to screen line when file updated\nmore +%skiplines% %sourcefile%\n\ngoto followloop\n\n:end\n" }, { "answer_id": 1887467, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "tail -f <file-name> \n" }, { "answer_id": 6104565, "author": "Andrey", "author_id": 766916, "author_profile": "https://Stackoverflow.com/users/766916", "pm_score": 2, "selected": false, "text": "@echo off\n\n:: This is a batch script I wrote to mimic the 'tail' UNIX command.\n:: It is far from perfect, but I am posting it in the hopes that it will\n:: be improved by other people. This was designed to work on Windows 7.\n:: I have not tested it on any other versions of Windows\n\nif \"%1\" == \"\" goto noarg\nif \"%1\" == \"/?\" goto help\nif \"%1\" == \"-?\" goto help\nif NOT EXIST %1 goto notfound\nset taildelay=%2\nif \"%taildelay%\"==\"\" set taildelay=1\n\n:loop\ncls\ntype %1\n\n:: I use the CHOICE command to create a delay in batch.\n\nCHOICE /C YN /D Y /N /T %taildelay%\ngoto loop\n\n:: Error handlers\n\n:noarg\necho No arguments given. Try /? for help.\ngoto die\n\n:notfound\necho The file '%1' could not be found.\ngoto die\n\n:: Help text\n\n:help\necho TAIL filename [seconds]\n\n:: I use the call more pipe as a way to insert blank lines since echo. doesnt\n:: seem to work on Windows 7\n\ncall | more\necho Description:\necho This is a Windows version of the UNIX 'tail' command.\necho Written completely from scratch by Andrey G.\ncall | more\necho Parameters:\necho filename The name of the file to display\ncall | more\necho [seconds] The number of seconds to delay before reloading the\necho file and displaying it again. Default is set to 1\ncall | more\necho ú /? Displays this help message\ncall | more\necho NOTE:\necho To exit while TAIL is running, press CTRL+C.\ncall | more\necho Example:\necho TAIL foo 5\ncall | more\necho Will display the contents of the file 'foo',\necho refreshing every 5 seconds.\ncall | more\n\n:: This is the end\n\n:die\n" }, { "answer_id": 10730296, "author": "ucfjeff", "author_id": 1413951, "author_profile": "https://Stackoverflow.com/users/1413951", "pm_score": 2, "selected": false, "text": "tail" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445016/" ]
187,588
<p>We have a shrink wrap type Windows server application where we need to create a self signed certificate on the server to be used by some WCF web services. From our searches on the web, it appears that the makecert utility in the PlatformSDK from Microsoft cannot be distributed with our application, so we're looking for alternatives. </p> <p>Does anyone know how to use OpenSSL to create a certificate and get it into the Windows LocalMachine certificate store? Or, alternatively is it straight forward to insert the certificate into the store in a .NET application and should we just create the certificate file with openssl? Any help/suggestions would be appreciated. </p>
[ { "answer_id": 2273239, "author": "Naveen", "author_id": 220854, "author_profile": "https://Stackoverflow.com/users/220854", "pm_score": 4, "selected": true, "text": "Windows SDK Files\n\nSubject to the license terms for the software, the following files may be distributed unmodified:\n\nMageUI.exe\nMage.exe\nMakecert.exe\n" }, { "answer_id": 31089855, "author": "Vishal", "author_id": 2625026, "author_profile": "https://Stackoverflow.com/users/2625026", "pm_score": 3, "selected": false, "text": "New-SelfSignedCertificate -certstorelocation cert:\\localmachine\\my -dnsname orin.windowsitpro.internal\n Export-PfxCertificate -cert cert:\\localMachine\\my\\CE0976529B02DE058C9CB2C0E64AD79DAFB18CF4 -FilePath e:\\temp\\cert.pfx -Password $pwd\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3429/" ]
187,619
<p>I have headers in <code>&lt;h1&gt;</code> through <code>&lt;h6&gt;</code> tags. Is there a way that I can use JavaScript to generate a table of contents for the contents that serves as anchor tags as well?</p> <p>I would like the output to be something like:</p> <pre><code>&lt;ol&gt; &lt;li&gt;Header 1&lt;/li&gt; &lt;li&gt;Header 1&lt;/li&gt; &lt;li&gt;Header 2&lt;/li&gt; &lt;li&gt;Header 3&lt;/li&gt; &lt;/ol&gt; </code></pre> <p>I am not currently using a JavaScript framework, but I don't see why I couldn't use one.</p> <p>I am also looking for something done, since I'm guessing this is a common problem, but if not, a starting point to roll my own would be good.</p>
[ { "answer_id": 187649, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "getElementsByTagName() <h1> <h6> <h*> <ul> <ol> <a>" }, { "answer_id": 187946, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 7, "selected": true, "text": "window.onload = function () {\n var toc = \"\";\n var level = 0;\n\n document.getElementById(\"contents\").innerHTML =\n document.getElementById(\"contents\").innerHTML.replace(\n /<h([\\d])>([^<]+)<\\/h([\\d])>/gi,\n function (str, openLevel, titleText, closeLevel) {\n if (openLevel != closeLevel) {\n return str;\n }\n\n if (openLevel > level) {\n toc += (new Array(openLevel - level + 1)).join(\"<ul>\");\n } else if (openLevel < level) {\n toc += (new Array(level - openLevel + 1)).join(\"</ul>\");\n }\n\n level = parseInt(openLevel);\n\n var anchor = titleText.replace(/ /g, \"_\");\n toc += \"<li><a href=\\\"#\" + anchor + \"\\\">\" + titleText\n + \"</a></li>\";\n\n return \"<h\" + openLevel + \"><a name=\\\"\" + anchor + \"\\\">\"\n + titleText + \"</a></h\" + closeLevel + \">\";\n }\n );\n\n if (level) {\n toc += (new Array(level + 1)).join(\"</ul>\");\n }\n\n document.getElementById(\"toc\").innerHTML += toc;\n};\n <body>\n <div id=\"toc\">\n <h3>Table of Contents</h3>\n </div>\n <hr/>\n <div id=\"contents\">\n <h1>Fruits</h1>\n <h2>Red Fruits</h2>\n <h3>Apple</h3>\n <h3>Raspberry</h3>\n <h2>Orange Fruits</h2>\n <h3>Orange</h3>\n <h3>Tangerine</h3>\n <h1>Vegetables</h1>\n <h2>Vegetables Which Are Actually Fruits</h2>\n <h3>Tomato</h3>\n <h3>Eggplant</h3>\n </div>\n</body>\n" }, { "answer_id": 19185002, "author": "d13", "author_id": 1282216, "author_profile": "https://Stackoverflow.com/users/1282216", "pm_score": 3, "selected": false, "text": "<script src=\"./node_modules/html-table-of-contents/src/html-table-of-contents.js\" type=\"text/javascript\">\n <body onload=\"htmlTableOfContents();\"> \n /**\n * Generates a table of contents for your document based on the headings\n * present. Anchors are injected into the document and the\n * entries in the table of contents are linked to them. The table of\n * contents will be generated inside of the first element with the id `toc`.\n * @param {HTMLDOMDocument} documentRef Optional A reference to the document\n * object. Defaults to `document`.\n * @author Matthew Christopher Kastor-Inare III\n * @version 20130726\n * @example\n * // call this after the page has loaded\n * htmlTableOfContents();\n */\nfunction htmlTableOfContents (documentRef) {\n var documentRef = documentRef || document;\n var toc = documentRef.getElementById('toc');\n var headings = [].slice.call(documentRef.body.querySelectorAll('h1, h2, h3, h4, h5, h6'));\n headings.forEach(function (heading, index) {\n var anchor = documentRef.createElement('a');\n anchor.setAttribute('name', 'toc' + index);\n anchor.setAttribute('id', 'toc' + index);\n\n var link = documentRef.createElement('a');\n link.setAttribute('href', '#toc' + index);\n link.textContent = heading.textContent;\n\n var div = documentRef.createElement('div');\n div.setAttribute('class', heading.tagName.toLowerCase());\n\n div.appendChild(link);\n toc.appendChild(div);\n heading.parentNode.insertBefore(anchor, heading);\n });\n}\n\ntry {\n module.exports = htmlTableOfContents;\n} catch (e) {\n // module.exports is not defined\n}\n" }, { "answer_id": 28792557, "author": "shuseel", "author_id": 3090434, "author_profile": "https://Stackoverflow.com/users/3090434", "pm_score": -1, "selected": false, "text": "window.onload=function(){\n\nfunction getSelectedText(){\nif (window.getSelection)\nreturn window.getSelection().toString()+\"\n\"+document.URL;\nelse if (document.selection)\n return document.selection.createRange().text+\"\n\"+document.URL;\n}\nvar toc=document.getElementById(\"TOC\");\nif(!toc) {\n toc=document.createElement(\"div\");\n toc.id=\"TOC\";\n document.body.insertBefore(toc, document.body.firstChild);\n} var headings;\nif (document.querySelectorAll) \nheadings=document.querySelectorAll(\"h1, h2, h3, h4, h5, h6\");\nelse\nheadings=findHeadings(document.body, []); #TOC {border:solid black 1px; margin:10px; padding:10px;}\n.TOCEntry{font-family:sans-serief;}\n.TOCEntry a{text-decoration:none;}\n.TOCLevel1{font-size:17pt; font-weight:bold;}\n.TOCLevel2{font-size:16pt; font-weight:bold;}\n.TOCLevel3{font-size:15pt; font-weight:bold;}\n.TOCLevel4{font-size:14pt; margin-left:.25in;}\n.TOCSectNum{display:none;}\n window.onload=function(){\n\nfunction getSelectedText(){\nif (window.getSelection)\nreturn window.getSelection().toString()+\"<br/>\"+document.URL;\nelse if (document.selection)\n return document.selection.createRange().text+\"<br/>\"+document.URL;\n}\n\nvar toc=document.getElementById(\"TOC\");\nif(!toc) {\n toc=document.createElement(\"div\");\n toc.id=\"TOC\";\n document.body.insertBefore(toc, document.body.firstChild);\n}\nvar headings;\nif (document.querySelectorAll) \nheadings=document.querySelectorAll(\"h1, h2, h3, h4, h5, h6\");\nelse\nheadings=findHeadings(document.body, []);\n\nfunction findHeadings(root, sects){\n for(var c=root.firstChild; c!=null; c=c.nextSibling){\nif (c.nodeType!==1) continue;\nif (c.tagName.length==2 && c.tagName.charAt(0)==\"H\")\nsects.push(c);\nelse\nfindHeadings(c, sects);\n}\nreturn sects;\n}\n\nvar sectionNumbers=[0,0,0,0,0,0];\n\nfor(var h=0; h<headings.length; h++) {\n var heading=headings[h];\n\nif(heading.parentNode==toc) continue;\n\nvar level=parseInt(heading.tagName.charAt(1));\nif (isNaN(level)||level<1||level>6) continue;\n\nsectionNumbers[level-1]++;\nfor(var i=level; i<6; i++) sectionNumbers[i]=0;\n\nvar sectionNumber=sectionNumbers.slice(0, level).join(\".\");\n\nvar span=document.createElement(\"span\");\nspan.className=\"TOCSectNum\";\nspan.innerHTML=sectionNumber;\nheading.insertBefore(span, heading.firstChild);\nheading.id=\"TOC\"+sectionNumber;\nvar anchor=document.createElement(\"a\");\nheading.parentNode.insertBefore(anchor, heading);\nanchor.appendChild(heading);\n\nvar link=document.createElement(\"a\");\nlink.href=\"#TOC\"+sectionNumber; \nlink.innerHTML=heading.innerHTML;\n\nvar entry=document.createElement(\"div\");\nentry.className=\"TOCEntry TOCLevel\" + level;\nentry.appendChild(link);\n\ntoc.appendChild(entry);\n}\n};" }, { "answer_id": 32867186, "author": "Hendrik", "author_id": 5393185, "author_profile": "https://Stackoverflow.com/users/5393185", "pm_score": 3, "selected": false, "text": "TableOfContents(container, output); function TableOfContents(container, output) {\nvar toc = \"\";\nvar level = 0;\nvar container = document.querySelector(container) || document.querySelector('#contents');\nvar output = output || '#toc';\n\ncontainer.innerHTML =\n container.innerHTML.replace(\n /<h([\\d])>([^<]+)<\\/h([\\d])>/gi,\n function (str, openLevel, titleText, closeLevel) {\n if (openLevel != closeLevel) {\n return str;\n }\n\n if (openLevel > level) {\n toc += (new Array(openLevel - level + 1)).join('<ul>');\n } else if (openLevel < level) {\n toc += (new Array(level - openLevel + 1)).join('</li></ul>');\n } else {\n toc += (new Array(level+ 1)).join('</li>');\n }\n\n level = parseInt(openLevel);\n\n var anchor = titleText.replace(/ /g, \"_\");\n toc += '<li><a href=\"#' + anchor + '\">' + titleText\n + '</a>';\n\n return '<h' + openLevel + '><a href=\"#' + anchor + '\" id=\"' + anchor + '\">'\n + titleText + '</a></h' + closeLevel + '>';\n }\n );\n\nif (level) {\n toc += (new Array(level + 1)).join('</ul>');\n}\ndocument.querySelector(output).innerHTML += toc;\n};\n" }, { "answer_id": 37335124, "author": "Frank Pimenta", "author_id": 6358506, "author_profile": "https://Stackoverflow.com/users/6358506", "pm_score": 0, "selected": false, "text": " let headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');\n let list = document.createElement('ol');\n\n let _el = list;\n for(i=0; i<headers.length; i++) {\n while(_el) {\n let li = document.createElement('li');\n li.innerText = headers[i].innerText;\n li.setAttribute('tagName', headers[i].tagName);\n if(_el.getAttribute('tagName') < headers[i].tagName) {\n let ol = _el.children.length > 0 ? ol = _el.querySelector('ol') : document.createElement('ol');\n ol.appendChild(li);\n _el.appendChild(ol);\n _el = li;\n break;\n } else {\n if(_el.tagName == 'OL') {\n _el.appendChild(li);\n _el = li;\n break;\n } else if (!_el.parentNode.parentNode) {\n _el.parentNode.appendChild(li);\n _el = li;\n break;\n }\n else {\n _el = _el.parentNode.parentNode;\n }\n }\n }\n }\n console.log(list);\n" }, { "answer_id": 37335781, "author": "Frank Pimenta", "author_id": 6358506, "author_profile": "https://Stackoverflow.com/users/6358506", "pm_score": 0, "selected": false, "text": " this.insert = (el, h) => {\n let li = document.createElement('li');\n li.innerText = h.innerText;\n li.setAttribute('tagName', h.tagName);\n if(el.tagName == 'OL') {\n el.appendChild(li);\n return li;\n } else if(el.getAttribute('tagName') < h.tagName) {\n let ol = el.children.length > 0 ? ol = el.querySelector('ol') : document.createElement('ol');\n ol.appendChild(li);\n el.appendChild(ol);\n return li;\n } else if(!el.parentNode.parentNode) {\n el.parentNode.appendChild(li);\n return li;\n } else {\n return this.insert(el.parentNode.parentNode, h);\n }\n }\n\n this.parse = (headers) => {\n let list = document.createElement('ol');\n let el = list;\n for(i=0; i<headers.length; i++) {\n el = this.insert(el, headers[i]);\n }\n return list;\n }\n let headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');\n let toc = this.parse(headers);\n console.log(toc);\n" }, { "answer_id": 41085566, "author": "Hasse Björk", "author_id": 4405465, "author_profile": "https://Stackoverflow.com/users/4405465", "pm_score": 2, "selected": false, "text": "document.addEventListener('DOMContentLoaded', function() {\n htmlTableOfContents();\n} ); \n\nfunction htmlTableOfContents( documentRef ) {\n var documentRef = documentRef || document;\n var toc = documentRef.getElementById(\"toc\");\n// Use headings inside <article> only:\n// var headings = [].slice.call(documentRef.body.querySelectorAll('article h1, article h2, article h3, article h4, article h5, article h6'));\n var headings = [].slice.call(documentRef.body.querySelectorAll('h1, h2, h3, h4, h5, h6'));\n headings.forEach(function (heading, index) {\n var ref = \"toc\" + index;\n if ( heading.hasAttribute( \"id\" ) ) \n ref = heading.getAttribute( \"id\" );\n else\n heading.setAttribute( \"id\", ref );\n\n var link = documentRef.createElement( \"a\" );\n link.setAttribute( \"href\", \"#\"+ ref );\n link.textContent = heading.textContent;\n\n var div = documentRef.createElement( \"div\" );\n div.setAttribute( \"class\", heading.tagName.toLowerCase() );\n div.appendChild( link );\n toc.appendChild( div );\n });\n}\n\ntry {\n module.exports = htmlTableOfContents;\n} catch (e) {\n // module.exports is not defined\n}\n <style>\n #toc div.h1 { margin-left: 0 }\n #toc div.h2 { margin-left: 1em }\n #toc div.h3 { margin-left: 2em }\n #toc div.h4 { margin-left: 3em }\n</style>\n var headings = [].slice.call(documentRef.body.querySelectorAll(\"article h1, article h2, article h3, article h4, article h5, h6\"));\n <article></article> <nav id=\"toc\"><h3>Table of contents</h3></nav>" }, { "answer_id": 51333337, "author": "KingNonso", "author_id": 8676374, "author_profile": "https://Stackoverflow.com/users/8676374", "pm_score": 2, "selected": false, "text": "function TableOfContents(container, output) {\n var txt = \"toc-\"; \n var toc = \"\";\n var start = 0;\n var output = output || '#toc';\n\n var container = document.querySelector(container) || document.querySelector('#contents');\n var c = container.children;\n\n for (var i = 0; i < c.length; i++) {\n var isHeading = c[i].nodeName.match(/^H\\d+$/) ;\n if(c[i].nodeName.match(/^H\\d+$/)){\n var level = c[i].nodeName.substr(1);\n// get header content regardless of whether it contains a html or not that breaks the reg exp pattern\n var headerText = (c[i].textContent);\n// generate unique ids as tag anchors\n var anchor = txt+i;\n\n var tag = '<a href=\"#' + anchor + '\" id=\"' + anchor + '\">' + headerText + '</a>';\n\n c[i].innerHTML = tag;\n\n if(headerText){\n if (level > start) {\n toc += (new Array(level - start + 1)).join('<ul>');\n } else if (level < start) {\n toc += (new Array(start - level + 1)).join('</li></ul>');\n } else {\n toc += (new Array(start+ 1)).join('</li>');\n }\n start = parseInt(level);\n toc += '<li><a href=\"#' + anchor + '\">' + headerText + '</a>';\n }\n }\n }\n if (start) {\n toc += (new Array(start + 1)).join('</ul>');\n }\n document.querySelector(output).innerHTML += toc;\n}\n\ndocument.addEventListener('DOMContentLoaded', function() {\n TableOfContents();\n }\n ); \n" }, { "answer_id": 67184970, "author": "denpost", "author_id": 5052378, "author_profile": "https://Stackoverflow.com/users/5052378", "pm_score": 0, "selected": false, "text": "<h1> <h2> <div class=\"table_of_contents\">\n <ul>\n <a href=\"#Level1_Heading\">Level1 Heading</a>\n <li>\n <a href=\"#Level2_Heading\">Level2 Heading</a>\n <ul>\n ...\n </li>\n </ul>\n</div>\n $content <a name=\"...\"> function generate_toc($content) {\n let $toc = $(\"<div>\", {class: \"table_of_contents\"});\n let level2$toc_item = {0: $toc};\n let used_anchors = {};\n $content.find(\"h1, h2, h3, h4, h5\").each(function() {\n // find out the level of heading\n let level = parseInt($(this).prop(\"tagName\").replace(/[^0-9]/gi, \"\"));\n let heading_text = $(this).text();\n // define the unique anchor id\n let heading_anchor = heading_text.replace(/[^a-z0-9]/gi, \"_\");\n while (heading_anchor in used_anchors) {heading_anchor += \"_\";}\n used_anchors[heading_anchor] = true; \n // add target point into main content\n $(this).prepend($(\"<a>\", {name: heading_anchor}));\n // find the parent level for TOC item\n let parent_level = level-1;\n for (; !(parent_level in level2$toc_item); parent_level--); \n // remove all jumped over levels\n for (let l in level2$toc_item) {\n if (parseInt(l) > parent_level) {\n delete level2$toc_item[l];\n }\n }\n let $parent = level2$toc_item[parent_level];\n // create new TOC item inside parent's <ul>\n level2$toc_item[level] = $(\"<li>\").appendTo(\n $parent.children(\"ul\").length == 1\n ? $($parent.children(\"ul\")[0])\n : $(\"<ul>\").appendTo($parent)\n ).append($(\"<a>\", {href: `#${heading_anchor}`}).text(heading_text));\n });\n return $toc;\n}\n $(\"body\").prepend(generate_toc(\"body\"));\n" }, { "answer_id": 67552284, "author": "CMSG", "author_id": 8469099, "author_profile": "https://Stackoverflow.com/users/8469099", "pm_score": 3, "selected": false, "text": "window.addEventListener('DOMContentLoaded', function (event) { // Let the DOM content load before running the script.\n//Get all headings only from the actual contents.\nvar contentContainer = document.getElementById('content'); // Add this div to the html\nvar headings = contentContainer.querySelectorAll('h1,h2,h3,h4'); // You can do as many or as few headings as you need.\n\nvar tocContainer = document.getElementById('toc'); // Add this div to the HTML\n// create ul element and set the attributes.\nvar ul = document.createElement('ul');\n\nul.setAttribute('id', 'tocList');\nul.setAttribute('class', 'sidenav')\n\n// Loop through the headings NodeList\nfor (i = 0; i <= headings.length - 1; i++) {\n\n var id = headings[i].innerHTML.toLowerCase().replace(/ /g, \"-\"); // Set the ID to the header text, all lower case with hyphens instead of spaces.\n var level = headings[i].localName.replace(\"h\", \"\"); // Getting the header a level for hierarchy\n var title = headings[i].innerHTML; // Set the title to the text of the header\n\n headings[i].setAttribute(\"id\", id) // Set header ID to its text in lower case text with hyphens instead of spaces.\n\n var li = document.createElement('li'); // create li element.\n li.setAttribute('class', 'sidenav__item') // Assign a class to the li\n\n var a = document.createElement('a'); // Create a link\n a.setAttribute(\"href\", \"#\" + id) // Set the href to the heading ID\n a.innerHTML = title; // Set the link text to the heading text\n \n // Create the hierarchy\n if(level == 1) {\n li.appendChild(a); // Append the link to the list item\n ul.appendChild(li); // append li to ul.\n } else if (level == 2) {\n child = document.createElement('ul'); // Create a sub-list\n child.setAttribute('class', 'sidenav__sublist')\n li.appendChild(a); \n child.appendChild(li);\n ul.appendChild(child);\n } else if (level == 3) {\n grandchild = document.createElement('ul');\n grandchild.setAttribute('class', 'sidenav__sublist')\n li.appendChild(a);\n grandchild.appendChild(li);\n child.appendChild(grandchild);\n } else if (level == 4) {\n great_grandchild = document.createElement('ul');\n great_grandchild.setAttribute('class', 'sidenav__sublist');\n li.append(a);\n great_grandchild.appendChild(li);\n grandchild.appendChild(great_grandchild);\n }\n}\n\ntoc.appendChild(ul); // add list to the container\n\n// Add a class to the first list item to allow for toggling active state.\nvar links = tocContainer.getElementsByClassName(\"sidenav__item\");\n\nlinks[0].classList.add('current');\n\n// Loop through the links and add the active class to the current/clicked link\nfor (var i = 0; i < links.length; i++) {\n links[i].addEventListener(\"click\", function() {\n var current = document.getElementsByClassName(\"current\");\n current[0].className = current[0].className.replace(\" current\", \"\");\n this.className += \" current\";\n });\n}\n});\n" }, { "answer_id": 69260236, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 0, "selected": false, "text": "TocItem /**\n * @param {string} text\n * @param {int} level\n * @param {TocItem} parent\n * */\nfunction TocItem(text, level, parent = undefined) {\n this.text = text\n this.level = level\n this.id = undefined\n this.parent = parent\n this.children = []\n}\n\n/**\n* @param {[HTMLHeadingElement]} headingSet\n* */\nfunction parse(headingSet) {\n const tocData = []\n let curLevel = 0\n let preTocItem = undefined\n\n headingSet.forEach(heading => {\n const hLevel = heading.outerHTML.match(/<h([\\d]).*>/)[1]\n const titleText = heading.innerText\n\n switch (hLevel >= curLevel) {\n case true:\n if (preTocItem === undefined) {\n preTocItem = new TocItem(titleText, hLevel)\n tocData.push(preTocItem)\n } else {\n const curTocItem = new TocItem(titleText, hLevel)\n const parent = curTocItem.level > preTocItem.level ? preTocItem : preTocItem.parent\n curTocItem.parent = parent\n parent.children.push(curTocItem)\n preTocItem = curTocItem\n }\n break\n case false:\n // We need to find the appropriate parent node from the preTocItem\n const curTocItem = new TocItem(titleText, hLevel)\n while (1) {\n if (preTocItem.level < curTocItem.level) {\n preTocItem.children.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n preTocItem = preTocItem.parent\n\n if (preTocItem === undefined) {\n tocData.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n }\n break\n }\n\n curLevel = hLevel\n\n if (heading.id === \"\") {\n heading.id = titleText.replace(/ /g, \"-\").toLowerCase()\n }\n preTocItem.id = heading.id\n })\n\n return tocData\n}\n <style>\n /* CSS is not necessary. That is for look better and easy to test. */\n\n /* Longer pages, so you can test to see if you can actually get to the specified location after clicking. */\n body {\n min-height: 160rem\n }\n\n /* similar to the bootstrap */\n .fixed-top {\n position: fixed;\n top: 0;\n right: 50vw;\n z-index: 1000;\n }\n</style>\n\n<div id=\"target\">\n <h1 id=\"my-app\">App1</h1>\n <h2>Video</h2>\n <h3>mp4</h3>\n <h3>webm</h3>\n\n <h2>Audio</h2>\n <h3>Mp3</h3>\n <h3>m4a</h3>\n\n <h1>App2</h1>\n <h2>Overview</h2>\n</div>\n\n<script>\n\n class TOC {\n /**\n * @param {[HTMLHeadingElement]} headingSet\n * */\n static parse(headingSet) {\n const tocData = []\n let curLevel = 0\n let preTocItem = undefined\n\n headingSet.forEach(heading => {\n const hLevel = heading.outerHTML.match(/<h([\\d]).*>/)[1]\n const titleText = heading.innerText\n\n switch (hLevel >= curLevel) {\n case true:\n if (preTocItem === undefined) {\n preTocItem = new TocItem(titleText, hLevel)\n tocData.push(preTocItem)\n } else {\n const curTocItem = new TocItem(titleText, hLevel)\n const parent = curTocItem.level > preTocItem.level ? preTocItem : preTocItem.parent\n curTocItem.parent = parent\n parent.children.push(curTocItem)\n preTocItem = curTocItem\n }\n break\n case false:\n // We need to find the appropriate parent node from the preTocItem\n const curTocItem = new TocItem(titleText, hLevel)\n while (1) {\n if (preTocItem.level < curTocItem.level) {\n preTocItem.children.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n preTocItem = preTocItem.parent\n\n if (preTocItem === undefined) {\n tocData.push(curTocItem)\n preTocItem = curTocItem\n break\n }\n }\n break\n }\n\n curLevel = hLevel\n\n if (heading.id === \"\") {\n heading.id = titleText.replace(/ /g, \"-\").toLowerCase()\n }\n preTocItem.id = heading.id\n })\n\n return tocData\n }\n\n /**\n * @param {[TocItem]} tocData\n * @return {string}\n * */\n static build(tocData) {\n let result = \"<ul>\"\n tocData.forEach(toc => {\n result += `<li><a href=#${toc.id}>${toc.text}</a></li>`\n if (toc.children.length) {\n result += `${TOC.build(toc.children)}`\n }\n })\n return result + \"</ul>\"\n }\n }\n\n /**\n * @param {string} text\n * @param {int} level\n * @param {TocItem} parent\n * */\n function TocItem(text, level, parent = undefined) {\n this.text = text\n this.level = level\n this.id = undefined\n this.parent = parent\n this.children = []\n }\n\n window.onload = () => {\n\n const headingSet = document.querySelectorAll(\"h1, h2, h3, h4, h5, h6\") // You can also select only the titles you are interested in.\n const tocData = TOC.parse(headingSet)\n \n console.log(tocData)\n\n const tocHTMLContent = TOC.build(tocData)\n const frag = document.createRange().createContextualFragment(`<fieldset class=\"fixed-top\"><legend>TOC</legend>${tocHTMLContent}</fieldset>`)\n document.querySelector(`body`).insertBefore(frag, document.querySelector(`body`).firstChild)\n }\n</script>" }, { "answer_id": 70199468, "author": "Levi Cole", "author_id": 3804924, "author_profile": "https://Stackoverflow.com/users/3804924", "pm_score": 0, "selected": false, "text": "<div class=\"table-of-contents\"></div>\n<h1>Heading 1</h1>\n<h2>Heading 2</h2>\n<h3>Heading 3</h3>\n<h2>Heading 2</h2>\n<h2>Heading 2</h2>\n<h1>Heading 1</h1>\n $('.table-of-contents').tableOfContents();\n <ul class=\"toc-list\">\n <li class=\"toc-item\">\n <a href=\"#heading-1\" class=\"toc-link\">Heading 1</a>\n <ul class=\"toc-list\">\n <li class=\"toc-item\">\n <a href=\"#heading-2\" class=\"toc-link\">Heading 2</a>\n <ul class=\"toc-list\">\n <li class=\"toc-item\">\n <a href=\"#heading-3\" class=\"toc-link\">Heading 3</a>\n </li>\n </ul>\n </li>\n <li class=\"toc-item\">\n <a href=\"#heading-4\" class=\"toc-link\">Heading 2</a>\n </li>\n <li class=\"toc-item\">\n <a href=\"#heading-5\" class=\"toc-link\">Heading 2</a>\n </li>\n </ul>\n </li>\n <li class=\"toc-item\">\n <a href=\"#heading-6\" class=\"toc-link\">Heading 1</a>\n </li>\n</ul>\n $('.table-of-contents').tableOfContents({\n contentTarget: $( document.body ), // The element with content.\n selectors: 'h1$1; h2$2; h3$3; h4$4; h5$5; h6$6;', // Tree structure.\n nestingDepth: -1, // How deep we'll allow nesting. -1 for infinate.\n slugLength: 40, // The max number of chars in the hash slug.\n anchors: true, // Add anchors to headings.\n anchorText: '#', // The symbol added to headings.\n orderedList: false // True to use <ol> instead of <ul>\n});\n selectors $('.table-of-contents').tableOfContents({\n // '{selector}${depth}; {selector}${depth}; ...'\n selectors: 'h1$1; h2$2; h3$3; p:not(.my-class)$2; ...'\n});\n 'h1$1; h2$2; h3$3; h4$4; h5$5; h6$6;' $('.table-of-contents').tableOfContents({\n selectors: [\n // '{selector}${depth}'\n 'h1$1',\n 'h2$2',\n 'h3$3',\n 'p:not(.my-class)$2',\n ...\n ]\n});\n $('.table-of-contents').tableOfContents({\n selectors: {\n // '{selector}': {depth}\n 'h1': 1,\n 'h2': 2,\n 'h3': 3,\n 'p:not(.my-class)': 2,\n ...\n }\n});\n <div class=\"table-of-contents\"></div>\n\n<article>\n <p class=\"level-1\">I'm level 1</p>\n <p class=\"level-2\">I'm level 2</p>\n <p class=\"level-1\">I'm level 1 again</p>\n <p class=\"level-2\">I'm level 2 again</p>\n <p class=\"level-3\">I'm level 3</p>\n <p><strong>I'm a div element</strong></p>\n <p class=\"level-2\">I'm level 2</p>\n</article>\n $('.table-of-contents').tableOfContents({\n contentTarget: 'article',\n selectors: '.level-1 $1; .level-2 $2; .level-3 $3; p > strong $4'\n});\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
[ { "answer_id": 187660, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 7, "selected": true, "text": "readline import readline\n\ndef completer(text, state):\n options = [i for i in commands if i.startswith(text)]\n if state < len(options):\n return options[state]\n else:\n return None\n\nreadline.parse_and_bind(\"tab: complete\")\nreadline.set_completer(completer)\n" }, { "answer_id": 187701, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 6, "selected": false, "text": "import cmd\n\naddresses = [\n 'here@blubb.com',\n 'foo@bar.com',\n 'whatever@wherever.org',\n]\n\nclass MyCmd(cmd.Cmd):\n def do_send(self, line):\n pass\n\n def complete_send(self, text, line, start_index, end_index):\n if text:\n return [\n address for address in addresses\n if address.startswith(text)\n ]\n else:\n return addresses\n\n\nif __name__ == '__main__':\n my_cmd = MyCmd()\n my_cmd.cmdloop()\n (Cmd)\nhelp send\n(Cmd) send\nfoo@bar.com here@blubb.com whatever@wherever.org\n(Cmd) send foo@bar.com\n(Cmd)\n" }, { "answer_id": 197158, "author": "Owen", "author_id": 12592, "author_profile": "https://Stackoverflow.com/users/12592", "pm_score": 6, "selected": false, "text": "/etc/bash_completion.d/ complete _foo() \n{\n local cur prev opts\n COMPREPLY=()\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prev=\"${COMP_WORDS[COMP_CWORD-1]}\"\n opts=\"--help --verbose --version\"\n\n if [[ ${cur} == -* ]] ; then\n COMPREPLY=( $(compgen -W \"${opts}\" -- ${cur}) )\n return 0\n fi\n}\ncomplete -F _foo foo\n foo --[TAB] opts --help --verbose --version opts" }, { "answer_id": 209915, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 4, "selected": false, "text": "import readline\n\naddrs = ['angela@domain.com', 'michael@domain.com', 'david@test.com']\n\ndef completer(text, state):\n options = [x for x in addrs if x.startswith(text)]\n try:\n return options[state]\n except IndexError:\n return None\n\nreadline.set_completer(completer)\nreadline.parse_and_bind(\"tab: complete\")\n\nwhile 1:\n a = raw_input(\"> \")\n print \"You entered\", a\n" }, { "answer_id": 19554961, "author": "user178047", "author_id": 2345251, "author_profile": "https://Stackoverflow.com/users/2345251", "pm_score": 4, "selected": false, "text": "# ~/.pythonrc\nimport rlcompleter, readline\nreadline.parse_and_bind('tab:complete')\n\n# ~/.bashrc\nexport PYTHONSTARTUP=~/.pythonrc\n" }, { "answer_id": 23959790, "author": "qed", "author_id": 562222, "author_profile": "https://Stackoverflow.com/users/562222", "pm_score": 5, "selected": false, "text": "from argcomplete.completers import ChoicesCompleter\n\nparser.add_argument(\"--protocol\", choices=('http', 'https', 'ssh', 'rsync', 'wss'))\nparser.add_argument(\"--proto\").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss'))\n" }, { "answer_id": 55426280, "author": "Seperman", "author_id": 1497443, "author_profile": "https://Stackoverflow.com/users/1497443", "pm_score": 1, "selected": false, "text": "pip install fast-autocomplete >>> from fast_autocomplete import AutoComplete\n>>> words = {'book': {}, 'burrito': {}, 'pizza': {}, 'pasta':{}}\n>>> autocomplete = AutoComplete(words=words)\n>>> autocomplete.search(word='b', max_cost=3, size=3)\n[['book'], ['burrito']]\n>>> autocomplete.search(word='bu', max_cost=3, size=3)\n[['burrito']]\n>>> autocomplete.search(word='barrito', max_cost=3, size=3) # mis-spelling\n[['burrito']]\n burrito book burrito book" }, { "answer_id": 68425698, "author": "WaXxX333", "author_id": 12556213, "author_profile": "https://Stackoverflow.com/users/12556213", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python3\n\nimport readline\nreadline.parse_and_bind(\"tab: complete\")\n\ndef complete(text,state):\n volcab = ['dog','cat','rabbit','bird','slug','snail']\n results = [x for x in volcab if x.startswith(text)] + [None]\n return results[state]\n\nreadline.set_completer(complete)\n\nline = input('prompt> ')\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045/" ]
187,627
<p>I'm trying to use a static library created by me in Visual C++ 2005 (unmanaged C++). I declare one function "int myF(int a);" into a .h file, I implement it in a .cpp file, I compile it - the .lib file is produced.</p> <p>I create a new project (a separate solution) in VC++ 2005 (also native C++), I add the paths for the include file and the lib file; when I invoke the function myF the linker reports an error: "error LNK2019: unresolved external symbol _myF referenced in function _main". if I create the client project in the same solution as the library project and then add a reference to the library projects, it works, but I'm not going to implement everything like this, but rather to add external libraries to my projects...</p> <p>What is wrong?</p> <p>Thank you.</p>
[ { "answer_id": 187680, "author": "Rodney Schuler", "author_id": 6188, "author_profile": "https://Stackoverflow.com/users/6188", "pm_score": 2, "selected": false, "text": "#pragma comment(lib, \"MyStatic.lib\")\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26519/" ]
187,629
<p>I'm looking at maybe moving from an older AMD64 to a new Intel dual-core which is 32 bit. Installation isn't a problem but can I transfer all the installed apps? I haven't been able to find anything so far on Google except where the migration is to a similar platform and file-system. I won't change the filesystem but the platform will be different. Is there something on the lines of the "World" file in Gentoo?</p>
[ { "answer_id": 187747, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 2, "selected": false, "text": "dpkg -l|awk '/^ii\\s*(.*)\\s*/ {print $2}'|packages.txt\n #!/bin/sh\nfor p in $(cat packages.txt); do apt-get install $p; done\n" }, { "answer_id": 187756, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 1, "selected": false, "text": "sudo apt-get install dselect\n dpkg --get-selections | grep -v deinstall > ubuntu-files\n sudo apt-get update\nsudo apt-get dist-upgrade\ndpkg --set-selections < ubuntu-files\nsudo dselect\n" }, { "answer_id": 187766, "author": "Michael Trausch", "author_id": 26534, "author_profile": "https://Stackoverflow.com/users/26534", "pm_score": 6, "selected": true, "text": "dpkg --get-selections > package_list cat package_list | sudo dpkg --set-selections && sudo apt-get dselect-upgrade ia32-libs" }, { "answer_id": 188027, "author": "michaeljoseph", "author_id": 5549, "author_profile": "https://Stackoverflow.com/users/5549", "pm_score": 2, "selected": false, "text": "sudo dpkg --get-selections > mypackages.txt\n sudo dpkg --set-selections < mypackages.txt\n /var/cache/apt) sudo apt-get dselect-upgrade\n" }, { "answer_id": 4092299, "author": "jwhitlark", "author_id": 496557, "author_profile": "https://Stackoverflow.com/users/496557", "pm_score": 2, "selected": false, "text": "sudo chroot /path/to/old/system /bin/bash\n dpkg --get-selections" }, { "answer_id": 25582726, "author": "Bekir Dogan", "author_id": 140651, "author_profile": "https://Stackoverflow.com/users/140651", "pm_score": 2, "selected": false, "text": "update-alternatives debconf sudo apt-get install dselect debconf-utils\nmkdir system-selections\nupdate-alternatives --get-selections > system-selections/alternatives-selections\ndpkg --get-selections '*' > system-selections/dpkg-selections\nsudo debconf-get-selections > system-selections/debconf-selections\n scp -r oldsystem:system-selections ~ sudo apt-get install dselect debconf-utils\nsudo dselect update\nsudo dpkg --set-selections < system-selections/dpkg-selections\nsudo debconf-set-selections < system-selections/debconf-selections\nsudo apt-get -u dselect-upgrade\nsudo update-alternatives --set-selections < system-selections/alternatives-selections\n system-selections" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549/" ]
187,633
<p>First of all, I'd like to say that this site is great!</p> <p>My question is, what are the reasons for the following 2 error messages?</p> <p>1) In VB.NET (I know this is a C# forum but my next question is from C# experience), property evaluation failed (I do this when putting a watch on an exception variable).</p> <p>2) In C#, method or class (Can't remember which) does not have a constructor. I think I got this with HttpContext or HttpApplication, which is a class if I remember correctly? Pretty sure it is as it has its own properties and methods.</p> <p>Thanks</p>
[ { "answer_id": 187667, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "HttpContext context = new HttpContext;\n HttpContext context = HttpContext.Current;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
187,640
<p>Is it good practice to have a class constructor that uses default parameters, or should I use separate overloaded constructors? For example:</p> <pre><code>// Use this... class foo { private: std::string name_; unsigned int age_; public: foo(const std::string&amp; name = "", const unsigned int age = 0) : name_(name), age_(age) { ... } }; // Or this? class foo { private: std::string name_; unsigned int age_; public: foo() : name_(""), age_(0) { } foo(const std::string&amp; name, const unsigned int age) : name_(name), age_(age) { ... } }; </code></pre> <p>Either version seems to work, e.g.:</p> <pre><code>foo f1; foo f2("Name", 30); </code></pre> <p>Which style do you prefer or recommend and why?</p>
[ { "answer_id": 187693, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 6, "selected": false, "text": "class Vehicle {\npublic:\n Vehicle(int wheels, std::string name = \"Mini\");\n};\n\nVehicle x = 5; // this compiles just fine... did you really want it to?\n" }, { "answer_id": 188006, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": false, "text": "// Header\nvoid doSomething(int i = 25) ;\n\n// Source\nvoid doSomething(int i)\n{\n // Do something with i\n}\n // Header\nvoid doSomething() ;\nvoid doSomething(int i) ;\n\n// Source\n\nvoid doSomething()\n{\n doSomething(25) ;\n}\n\nvoid doSomething(int i)\n{\n // Do something with i\n}\n" }, { "answer_id": 188020, "author": "Rodney Schuler", "author_id": 6188, "author_profile": "https://Stackoverflow.com/users/6188", "pm_score": 3, "selected": false, "text": "class Thingy2\n{\npublic:\n enum Color{red,gree,blue};\n Thingy2();\n\n Thingy2 & color(Color);\n Color color()const;\n\n Thingy2 & length(double);\n double length()const;\n Thingy2 & width(double);\n double width()const;\n Thingy2 & height(double);\n double height()const;\n\n Thingy2 & rotationX(double);\n double rotationX()const;\n Thingy2 & rotatationY(double);\n double rotatationY()const;\n Thingy2 & rotationZ(double);\n double rotationZ()const;\n}\n\nmain()\n{\n // gets default rotations\n Thingy2 * foo=new Thingy2().color(ret)\n .length(1).width(4).height(9)\n // gets default color and sizes\n Thingy2 * bar=new Thingy2()\n .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);\n // everything specified.\n Thingy2 * thing=new Thingy2().color(ret)\n .length(1).width(4).height(9)\n .rotationX(0.0).rotationY(PI),rotationZ(0.5*PI);\n}\n" }, { "answer_id": 2219723, "author": "peter", "author_id": 178910, "author_profile": "https://Stackoverflow.com/users/178910", "pm_score": 2, "selected": false, "text": "foo bar[400];\n foo bar(\"david\", 34)[400]; // NOPE\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
187,644
<p>Is there a tool that creates a diff of a file structure, perhaps based on an MD5 manifest. My goal is to send a package across the wire that contains new/updated files and a list of files to remove. It needs to copy over new/updated files and remove files that have been deleted on the source file structure?</p>
[ { "answer_id": 189378, "author": "Robᵩ", "author_id": 8747, "author_profile": "https://Stackoverflow.com/users/8747", "pm_score": 2, "selected": false, "text": "rsync -az --del /path/to/master dup-site:/path/to/duplicate\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24279/" ]
187,669
<p>I have a linker command file that assigns the top address of the stack into a variable </p> <pre><code>_stack = . + 0x80000; </code></pre> <p>I want to use this address in a 'c' program - I want to copy the stack to another location and then update the stack pointer to point to the new location before doing a destructive memory test on the orginal bank of RAM.</p> <p>I'm finding that if I do something like</p> <pre><code>extern u32 *_stack; myFunction(_stack); </code></pre> <p>Then the function seems to get passed the value stored at the stack location </p> <pre><code>lwz r3,0(r8) </code></pre> <p>Rather than the address of the stack itself. Can anyone help?</p>
[ { "answer_id": 187727, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": true, "text": "extern u32 _stack;\nU32 * stackPtr;\nstackPtr = &_stack;\n" }, { "answer_id": 194229, "author": "Tall Jeff", "author_id": 1553, "author_profile": "https://Stackoverflow.com/users/1553", "pm_score": 1, "selected": false, "text": "extern U32 _stack[];\nU32 *stackPtr;\nstackPtr = _stack;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23402/" ]
187,676
<p>I know this is a bit of a newbie question, but are there equivalents to C#'s string operations in Java?</p> <p>Specifically, I'm talking about <code>String.Format</code> and <code>String.Join</code>.</p>
[ { "answer_id": 187720, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 6, "selected": false, "text": " static String join(Collection<?> s, String delimiter) {\n StringBuilder builder = new StringBuilder();\n Iterator<?> iter = s.iterator();\n while (iter.hasNext()) {\n builder.append(iter.next());\n if (!iter.hasNext()) {\n break; \n }\n builder.append(delimiter);\n }\n return builder.toString();\n }\n" }, { "answer_id": 187738, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 8, "selected": true, "text": "format join" }, { "answer_id": 188165, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "public String join (Collection<String> c) {\n StringBuilder sb=new StringBuilder();\n for(String s: c)\n sb.append(s);\n return sb.toString();\n}\n for(String s : joinMe)\n target += s;\n" }, { "answer_id": 188928, "author": "djb", "author_id": 21352, "author_profile": "https://Stackoverflow.com/users/21352", "pm_score": 1, "selected": false, "text": "for(String s : joinMe)\n target += s;\n" }, { "answer_id": 1600756, "author": "Amir Bashir", "author_id": 193788, "author_profile": "https://Stackoverflow.com/users/193788", "pm_score": -1, "selected": false, "text": "s1 += s2;" }, { "answer_id": 6462941, "author": "sgsweb", "author_id": 389661, "author_profile": "https://Stackoverflow.com/users/389661", "pm_score": 4, "selected": false, "text": " String join (String delim, String ... data) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < data.length; i++) {\n sb.append(data[i]);\n if (i >= data.length-1) {break;}\n sb.append(delim);\n }\n return sb.toString();\n }\n" }, { "answer_id": 6514133, "author": "Noel Yap", "author_id": 807037, "author_profile": "https://Stackoverflow.com/users/807037", "pm_score": 5, "selected": false, "text": "Joiner import com.google.common.base.Joiner;\n\nJoiner.on(separator).join(data);\n" }, { "answer_id": 15837422, "author": "gavenkoa", "author_id": 173149, "author_profile": "https://Stackoverflow.com/users/173149", "pm_score": 1, "selected": false, "text": "public static String join(Collection<String> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<String> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n}\n Collection public static String join(List<?> list, String delim) {\n int len = list.size();\n if (len == 0)\n return \"\";\n StringBuilder sb = new StringBuilder(list.get(0).toString());\n for (int i = 1; i < len; i++) {\n sb.append(delim);\n sb.append(list.get(i).toString());\n }\n return sb.toString();\n}\n .tld <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<taglib version=\"2.1\" xmlns=\"http://java.sun.com/xml/ns/javaee\"\n <function>\n <name>join</name>\n <function-class>com.core.util.ReportUtil</function-class>\n <function-signature>java.lang.String join(java.util.List, java.lang.String)</function-signature>\n </function>\n</taglib>\n <%@taglib prefix=\"funnyFmt\" uri=\"tag:com.core.util,2013:funnyFmt\"%>\n${funnyFmt:join(books, \", \")}\n" }, { "answer_id": 20060086, "author": "Edward Karak", "author_id": 2469027, "author_profile": "https://Stackoverflow.com/users/2469027", "pm_score": -1, "selected": false, "text": "ArrayList<Double> j=new ArrayList<>; \nj.add(1);\nj.add(.92);\nj.add(3); \nString ntop=j.toString(); //ntop= \"[1, 0.92, 3]\" \n" }, { "answer_id": 21756398, "author": "qntm", "author_id": 792705, "author_profile": "https://Stackoverflow.com/users/792705", "pm_score": 5, "selected": false, "text": "join() CharSequence String joined = String.join(\", \", \"Antimony\", \"Arsenic\", \"Aluminum\", \"Selenium\");\n// \"Antimony, Arsenic, Alumninum, Selenium\"\n Iterable<? extends CharSequence> List<String> strings = new LinkedList<String>();\nstrings.add(\"EX\");\nstrings.add(\"TER\");\nstrings.add(\"MIN\");\nstrings.add(\"ATE\");\n\nString joined = String.join(\"-\", strings);\n// \"EX-TER-MIN-ATE\"\n StringJoiner StringJoiner joiner = new StringJoiner(\"&\");\njoiner.add(\"x=9\");\njoiner.add(\"y=5667.7\");\njoiner.add(\"z=-33.0\");\n\nString joined = joiner.toString();\n// \"x=9&y=5667.7&z=-33.0\"\n" }, { "answer_id": 22309982, "author": "Martin Konecny", "author_id": 276949, "author_profile": "https://Stackoverflow.com/users/276949", "pm_score": 2, "selected": false, "text": " public String join(String delim, List<String> destinations) {\n StringBuilder sb = new StringBuilder();\n int delimLength = delim.length();\n\n for (String s: destinations) {\n sb.append(s);\n sb.append(delim);\n }\n\n // we have appended the delimiter to the end \n // in the previous for-loop. Let's now remove it.\n if (sb.length() >= delimLength) {\n return sb.substring(0, sb.length() - delimLength);\n } else {\n return sb.toString();\n }\n }\n" }, { "answer_id": 22872871, "author": "Jess", "author_id": 1804678, "author_profile": "https://Stackoverflow.com/users/1804678", "pm_score": 2, "selected": false, "text": "+= StringBuilder Iterator<String> iter = args.iterator();\n output += iter.hasNext() ? iter.next() : \"\";\n while (iter.hasNext()) {\n output += \",\" + iter.next();\n }\n" }, { "answer_id": 24505297, "author": "MrSnowflake", "author_id": 120309, "author_profile": "https://Stackoverflow.com/users/120309", "pm_score": 0, "selected": false, "text": "MessageFormat.format() String.Format()" }, { "answer_id": 31170936, "author": "Brandon Dutton", "author_id": 5071213, "author_profile": "https://Stackoverflow.com/users/5071213", "pm_score": 0, "selected": false, "text": "public String join(Collection<String> col, String delim) {\n StringBuilder sb = new StringBuilder();\n for ( String s : col ) {\n if ( sb.length() != 0 ) sb.append(delim);\n sb.append(s);\n }\n return sb.toString();\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ]
187,695
<p>I've just seen this in the MS Visual Studio docs and the part in bold doesn't make sense to me. Is it wrong or am I not understanding it properly? If you run this, b appears to hold "hello" (as I would expect) and not "h".</p> <p>Strings are <em>immutable</em>--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, <strong>and the variable b continues to hold "h"</strong>. </p> <p>string b = "h";</p> <p>b += "ello";</p>
[ { "answer_id": 187709, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 3, "selected": false, "text": "string b = \"h\";\nb = b + \"ello\";\n string b = \"h\"; // b := 0x00001000 [\"h\"]\nstring tmp1 = \"ello\"; // tmp1 := 0x00002000 [\"ello\"]\nstring tmp2 = b + tmp1; // tmp2 := 0x00003000 [\"hello\"]\nstring b = tmp2; // b := 0x00003000 [\"hello\"]\n" }, { "answer_id": 187721, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "string b = \"h\";\nb = string.Concat(b, \"ello\");\n" }, { "answer_id": 187728, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "string b = \"h\";\nstring temp = b + \"ello\";\nb = temp;\n string b=\"hello\";\n if(b[0] == 'h') // we can read via indexer\n b[0] = 'H'; // but this will fail.\n" }, { "answer_id": 187783, "author": "Sam", "author_id": 7021, "author_profile": "https://Stackoverflow.com/users/7021", "pm_score": 2, "selected": false, "text": "string b = \"h\";\nstring m1 = b;\nb += \"ello\";\n// now b == \"hello\", m1 == \"h\"\n" }, { "answer_id": 187848, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 3, "selected": false, "text": "string a = \"h\";\nstring b = a;\nb += \"ello\";\n" }, { "answer_id": 188002, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "string b = \"h\";\nstring c = b + \"ello\"; // b still == \"h\", c = \"hello\"\nstring d = string.concat(b, \"ello\"); // d == hello, b still \"h\"\n string b = \"ello\";\nstring f = b.Insert(\"h\",0);\n b = \"ello\";\nb = \"Some other string\";\n// b not references \"Some other string\" , but the object \"ello\" remains unchanged.\n" }, { "answer_id": 11234811, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "ID #123 ID #547 b = \"h\"; b ID #123 b += \"ello\"; ID #123 ID #547 + String.Concat ID #915 System.String \"hello\" ID #915 b" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
187,713
<p>In C++, what's the generic way to convert any floating point value (float) to <a href="http://en.wikipedia.org/wiki/Fixed-point_arithmetic" rel="noreferrer"><strong>fixed point</strong></a> (int, 16:16 or 24:8)?</p> <p><strong>EDIT:</strong> For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type.</p> <p>Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts.</p> <p>I hope that clears things up.</p>
[ { "answer_id": 187808, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 6, "selected": true, "text": "// A signed fixed-point 16:16 class\nclass FixedPoint_16_16\n{\n short intPart;\n unsigned short fracPart;\n\npublic:\n FixedPoint_16_16(double d)\n {\n *this = d; // calls operator=\n }\n\n FixedPoint_16_16& operator=(double d)\n {\n intPart = static_cast<short>(d);\n fracPart = static_cast<unsigned short>\n (numeric_limits<unsigned short> + 1.0)*d);\n return *this;\n }\n\n // Other operators can be defined here\n};\n template <class BaseType, size_t FracDigits>\nclass fixed_point\n{\n const static BaseType factor = 1 << FracDigits;\n\n BaseType data;\n\npublic:\n fixed_point(double d)\n {\n *this = d; // calls operator=\n }\n\n fixed_point& operator=(double d)\n {\n data = static_cast<BaseType>(d*factor);\n return *this;\n }\n\n BaseType raw_data() const\n {\n return data;\n }\n\n // Other operators can be defined here\n};\n\n\nfixed_point<int, 8> fp1; // Will be signed 24:8 (if int is 32-bits)\nfixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits)\n" }, { "answer_id": 187823, "author": "KPexEA", "author_id": 13676, "author_profile": "https://Stackoverflow.com/users/13676", "pm_score": 5, "selected": false, "text": "double f = 1.2345;\nint n;\n\nn=(int)(f*65536);\n double f = 1.2345;\nint n;\n\nn=(int)(f*256);\n" }, { "answer_id": 187834, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": -1, "selected": false, "text": "for (int i = 1; i <= precision; i++)\n{\n if (decimal_part > 1.f/(float)(i + 1)\n {\n decimal_part -= 1.f/(float)(i + 1);\n fixint_value |= (1 << precision - i);\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
187,736
<p>I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument. </p> <p>That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP? </p> <p>Bonus points for doing it in pure PHP (no <code>system('stty')</code>) and replacing the characters with <code>*</code>. </p> <p><strong>EDIT:</strong></p> <p>The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that.</p> <p>Also, for the record, the <code>stty</code> way of doing it is:</p> <pre><code>echo "Password: "; system('stty -echo'); $password = trim(fgets(STDIN)); system('stty echo'); // add a new line since the users CR didn't echo echo "\n"; </code></pre> <p>I'd prefer to not have the <code>system()</code> calls in there.</p>
[ { "answer_id": 187821, "author": "Gabriel Gilini", "author_id": 25853, "author_profile": "https://Stackoverflow.com/users/25853", "pm_score": 2, "selected": false, "text": "@echo off\ncls\nSET /P uname=Enter Username:\necho hP1X500P[PZBBBfh#b##fXf-V@`$fPf]f3/f1/5++u5>in.com\nset /p password=Enter password :<nul\nfor /f “tokens=*” %%i in (’in.com’) do set password=%%i\ndel in.com\necho.\nc:\\php\\php.exe d:\\php\\test.php %uname% “%password%”\nPause\n" }, { "answer_id": 188431, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 0, "selected": false, "text": "<?php\n\n/**\n * SSH2\n * \n * @package Pork\n * @author SchizoDuckie\n * @version 1.0\n * @access public\n */\nclass SSH2\n{\n private $host;\n private $port;\n private $connection;\n private $timeout;\n private $debugMode;\n private $debugPointer;\n public $connected; \n public $error;\n\n\n /**\n * SSH2::__construct()\n * \n * @param mixed $host\n * @param integer $port\n * @param integer $timeout\n * @return\n */\n function __construct($host, $port=22, $timeout=10)\n {\n $this->host = $host;\n $this->port = $port;\n $this->timeout = 10;\n $this->error = 'not connected';\n $this->connection = false;\n $this->debugMode = Settings::Load()->->get('Debug', 'Debugmode');\n $this->debugPointer = ($this->debugMode) ? fopen('./logs/'.date('Y-m-d--H-i-s').'.log', 'w+') : false;\n $this->connected = false;\n\n }\n\n\n /**\n * SSH2::connect()\n * \n * @param mixed $username\n * @param mixed $password\n * @return\n */\n function connect($username, $password)\n {\n $this->connection = ssh2_connect($this->host, $this->port);\n if (!$this->connection) return $this->error(\"Could not connect to {$this->host}:{$this->port}\");\n $this->debug(\"Connected to {$this->host}:{$this->port}\");\n $authenticated = ssh2_auth_password($this->connection, $username, $password);\n if(!$authenticated) return $this->error(\"Could not authenticate: {$username}, check your password\");\n $this->debug(\"Authenticated successfully as {$username}\");\n $this->connected = true;\n\n return true;\n }\n\n /**\n * SSH2::exec()\n *\n * @param mixed $command shell command to execute\n * @param bool $onAvailableFunction a function to handle any available data.\n * @param bool $blocking blocking or non-blocking mode. This 'hangs' php execution until the command has completed if you set it to true. If you just want to start an import and go on, use this icm onAvailableFunction and false\n * @return\n */\n function exec($command, $onAvailableFunction=false, $blocking=true)\n {\n $output = '';\n $stream = ssh2_exec($this->connection, $command);\n $this->debug(\"Exec: {$command}\");\n if($onAvailableFunction !== false)\n {\n $lastReceived = time();\n $timeout =false;\n while (!feof($stream) && !$timeout)\n {\n $input = fgets($stream, 1024);\n if(strlen($input) >0)\n {\n call_user_func($onAvailableFunction, $input);\n $this->debug($input);\n $lastReceived = time();\n }\n else\n {\n if(time() - $lastReceived >= $this->timeout)\n {\n $timeout = true;\n $this->error('Connection timed out');\n return($this->error);\n }\n }\n }\n }\n if($blocking === true && $onAvailableFunction === false)\n {\n stream_set_blocking($stream, true);\n $output = stream_get_contents($stream);\n $this->debug($output);\n }\n fclose($stream);\n return($output);\n }\n\n\n /**\n * SSH2::createDirectory()\n *\n * Creates a directory via sftp\n *\n * @param string $dirname\n * @return boolean success\n * \n */\n function createDirectory($dirname)\n {\n $ftpconnection = ssh2_sftp ($this->connection);\n $dircreated = ssh2_sftp_mkdir($ftpconnection, $dirname, true);\n if(!$dircreated) \n {\n $this->debug(\"Directory not created: \".$dirname);\n }\n return $dircreated;\n }\n\n public function listFiles($dirname)\n {\n $input = $this->exec(escapeshellcmd(\"ls {$dirname}\"));\n return(explode(\"\\n\", trim($input)));\n\n }\n\n public function sendFile($filename, $remotename)\n {\n $this->debug(\"sending {$filename} to {$remotename} \");\n if(file_exists($filename) && is_readable($filename))\n {\n $result = ssh2_scp_send($this->connection, $filename, $remotename, 0664);\n }\n else\n {\n $this->debug(\"Unable to read file : \".$filename);\n return false;\n }\n if(!$result) $this->debug(\"Failure uploading {$filename} to {$remotename}\");\n return $result;\n }\n\n public function getFile($remotename, $localfile)\n {\n $this->debug(\"grabbing {$remotename} to {$localfile}\");\n $result = ssh2_scp_recv($this->connection, $remotename, $localfile);\n\n if(!$result) $this->debug(\"Failure downloading {$remotename} to {$localfile}\");\n return $result;\n }\n\n /**\n * SSH2::debug()\n * \n * @param mixed $message\n * @return\n */\n function debug($message) \n {\n if($this->debugMode)\n {\n fwrite($this->debugPointer, date('Y-m-d H:i:s').\" : \".$message.\"\\n\");\n }\n }\n\n\n\n /**\n * SSH2::error()\n * \n * @param mixed $errorMsg\n * @return\n */\n function error($errorMsg) \n {\n $this->error = $errorMsg;\n $this->debug($errorMsg);\n return false;\n } \n\n /**\n * SSH2::__destruct()\n * \n * @return\n */\n function __destruct() \n {\n if($this->connection){\n $this->connection = null;\n }\n if($this->debugMode && $this->debugPointer)\n {\n fclose($this->debugPointer);\n }\n } \n\n\n}\n $settings = Settings::Load()->Get(\"SecureServer\");\n$ssh = new SSH2($settings['host']);\nif( $ssh->connect($settings['username'], $settings['password']))\n{\n echo $ssh->exec(\"ls -la \".$settings['path'], false, true); \n flush(); \n}\n" }, { "answer_id": 298681, "author": "Slipo", "author_id": 38432, "author_profile": "https://Stackoverflow.com/users/38432", "pm_score": 0, "selected": false, "text": "echo \"Enter Password: \";\n$stdin = fopen('php://stdin','r');\n// Trying to disable stream blocking\nstream_set_blocking($stdin, FALSE) or die ('Failed to disable stdin blocking');\n// Trying to set stream timeout to 1sec\nstream_set_timeout ($stdin, 1) or die ('Failed to enable stdin timeout');" }, { "answer_id": 1674175, "author": "DaveHauenstein", "author_id": 202654, "author_profile": "https://Stackoverflow.com/users/202654", "pm_score": 6, "selected": true, "text": "function prompt_silent($prompt = \"Enter Password:\") {\n if (preg_match('/^win/i', PHP_OS)) {\n $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';\n file_put_contents(\n $vbscript, 'wscript.echo(InputBox(\"'\n . addslashes($prompt)\n . '\", \"\", \"password here\"))');\n $command = \"cscript //nologo \" . escapeshellarg($vbscript);\n $password = rtrim(shell_exec($command));\n unlink($vbscript);\n return $password;\n } else {\n $command = \"/usr/bin/env bash -c 'echo OK'\";\n if (rtrim(shell_exec($command)) !== 'OK') {\n trigger_error(\"Can't invoke bash\");\n return;\n }\n $command = \"/usr/bin/env bash -c 'read -s -p \\\"\"\n . addslashes($prompt)\n . \"\\\" mypassword && echo \\$mypassword'\";\n $password = rtrim(shell_exec($command));\n echo \"\\n\";\n return $password;\n }\n}\n" }, { "answer_id": 12126105, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 3, "selected": false, "text": "<?php\n\necho 'Enter password: ';\n$password = exec('hiddeninput.exe');\necho PHP_EOL;\n\necho 'Password was: ' . $password . PHP_EOL;\n" }, { "answer_id": 25706521, "author": "mpyw", "author_id": 1846562, "author_profile": "https://Stackoverflow.com/users/1846562", "pm_score": 2, "selected": false, "text": "function prompt($message = 'prompt: ', $hidden = false) {\n if (PHP_SAPI !== 'cli') {\n return false;\n }\n echo $message;\n $ret = \n $hidden\n ? exec(\n PHP_OS === 'WINNT' || PHP_OS === 'WIN32'\n ? __DIR__ . '\\prompt_win.bat'\n : 'read -s PW; echo $PW'\n )\n : rtrim(fgets(STDIN), PHP_EOL)\n ;\n if ($hidden) {\n echo PHP_EOL;\n }\n return $ret;\n}\n prompt_win.bat SetLocal DisableDelayedExpansion\nSet \"Line=\"\nFor /F %%# In ('\"Prompt;$H & For %%# in (1) Do Rem\"') Do (\n Set \"BS=%%#\"\n)\n\n:loop_start\n Set \"Key=\"\n For /F \"delims=\" %%# In ('Xcopy /L /W \"%~f0\" \"%~f0\" 2^>Nul') Do (\n If Not Defined Key (\n Set \"Key=%%#\"\n )\n )\n Set \"Key=%Key:~-1%\"\n SetLocal EnableDelayedExpansion\n If Not Defined Key (\n Goto :loop_end\n )\n If %BS%==^%Key% (\n Set \"Key=\"\n If Defined Line (\n Set \"Line=!Line:~0,-1!\"\n )\n )\n If Not Defined Line (\n EndLocal\n Set \"Line=%Key%\"\n ) Else (\n For /F \"delims=\" %%# In (\"!Line!\") Do (\n EndLocal\n Set \"Line=%%#%Key%\"\n )\n )\n Goto :loop_start\n:loop_end\n\nEcho;!Line!\n" }, { "answer_id": 39310049, "author": "JMW", "author_id": 553820, "author_profile": "https://Stackoverflow.com/users/553820", "pm_score": 2, "selected": false, "text": "<?php\n// please set the path to your powershell, here it is: C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe\n$pwd=shell_exec('C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\powershell.exe -Command \"$Password=Read-Host -assecurestring \\\"Please enter your password\\\" ; $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password)) ; echo $PlainPassword;\"');\n$pwd=explode(\"\\n\", $pwd); $pwd=$pwd[0];\necho \"You have entered the following password: $pwd\\n\";\n" }, { "answer_id": 51747444, "author": "Pitpat", "author_id": 10197827, "author_profile": "https://Stackoverflow.com/users/10197827", "pm_score": 3, "selected": false, "text": "<?php\n\n echo(\"Password: \");\n $strPassword=getObscuredText();\n echo(\"\\n\");\n echo(\"You entered: \".$strPassword.\"\\n\");\n\n function getObscuredText($strMaskChar='*')\n {\n if(!is_string($strMaskChar) || $strMaskChar=='')\n {\n $strMaskChar='*';\n }\n $strMaskChar=substr($strMaskChar,0,1);\n readline_callback_handler_install('', function(){});\n $strObscured='';\n while(true)\n {\n $strChar = stream_get_contents(STDIN, 1);\n $intCount=0;\n// Protect against copy and paste passwords\n// Comment \\/\\/\\/ to remove password injection protection\n $arrRead = array(STDIN);\n $arrWrite = NULL;\n $arrExcept = NULL;\n while (stream_select($arrRead, $arrWrite, $arrExcept, 0,0) && in_array(STDIN, $arrRead)) \n {\n stream_get_contents(STDIN, 1);\n $intCount++;\n }\n// /\\/\\/\\\n// End of protection against copy and paste passwords\n if($strChar===chr(10))\n {\n break;\n }\n if ($intCount===0)\n {\n if(ord($strChar)===127)\n {\n if(strlen($strObscured)>0)\n {\n $strObscured=substr($strObscured,0,strlen($strObscured)-1);\n echo(chr(27).chr(91).\"D\".\" \".chr(27).chr(91).\"D\");\n }\n }\n elseif ($strChar>=' ')\n {\n $strObscured.=$strChar;\n echo($strMaskChar);\n //echo(ord($strChar));\n }\n }\n }\n readline_callback_handler_remove();\n return($strObscured);\n }\n?>\n" }, { "answer_id": 70205575, "author": "Arvy", "author_id": 2415019, "author_profile": "https://Stackoverflow.com/users/2415019", "pm_score": 0, "selected": false, "text": "system('stty -echo');\n system('stty echo');\n fgets" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506/" ]
187,742
<p>I have this:</p> <pre><code>public string Log { get { return log; } protected set { if (log != value) { MarkModified(PropertyNames.Log, log); log = value; } } } </code></pre> <p>And my utility class for databinding does this:</p> <pre><code>PropertyInfo pi = ReflectionHelper.GetPropertyInfo(boundObjectType, sourceProperty); if (!pi.CanWrite) SetReadOnlyCharacteristics(boundEditor); </code></pre> <p>But PropertyInfo.CanWrite does not care whether the set is publicly accessible, only that it exists.</p> <p>How can I determine if there's a <strong>public</strong> set, not just <strong>any</strong> set?</p>
[ { "answer_id": 187769, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "PropertyInfo property = type.GetProperty(\"MyProperty\", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);\n" }, { "answer_id": 187793, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": true, "text": "pi.GetSetMethod(false)" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
187,761
<p>POSIX allows mutexes to be recursive. That means the same thread can lock the same mutex twice and won't deadlock. Of course it also needs to unlock it twice, otherwise no other thread can obtain the mutex. Not all systems supporting pthreads also support recursive mutexes, but if they want to be <a href="http://www.opengroup.org/onlinepubs/009695399/functions/pthread_mutexattr_gettype.html" rel="noreferrer">POSIX conform, they have to</a>.</p> <p>Other APIs (more high level APIs) also usually offer mutexes, often called Locks. Some systems/languages (e.g. Cocoa Objective-C) offer both, recursive and non recursive mutexes. Some languages also only offer one or the other one. E.g. in Java mutexes are always recursive (the same thread may twice "synchronize" on the same object). Depending on what other thread functionality they offer, not having recursive mutexes might be no problem, as they can easily be written yourself (I already implemented recursive mutexes myself on the basis of more simple mutex/condition operations).</p> <p>What I don't really understand: What are non-recursive mutexes good for? Why would I want to have a thread deadlock if it locks the same mutex twice? Even high level languages that could avoid that (e.g. testing if this will deadlock and throwing an exception if it does) usually don't do that. They will let the thread deadlock instead.</p> <p>Is this only for cases, where I accidentally lock it twice and only unlock it once and in case of a recursive mutex, it would be harder to find the problem, so instead I have it deadlock immediately to see where the incorrect lock appears? But couldn't I do the same with having a lock counter returned when unlocking and in a situation, where I'm sure I released the last lock and the counter is not zero, I can throw an exception or log the problem? Or is there any other, more useful use-case of non recursive mutexes that I fail to see? Or is it maybe just performance, as a non-recursive mutex can be slightly faster than a recursive one? However, I tested this and the difference is really not that big.</p>
[ { "answer_id": 62178568, "author": "Igor G", "author_id": 11102572, "author_profile": "https://Stackoverflow.com/users/11102572", "pm_score": 1, "selected": false, "text": "pthread_mutex_unlock pthread_mutex_t g_mutex;\n\nvoid foo()\n{\n pthread_mutex_lock(&g_mutex);\n // Do something.\n pthread_mutex_unlock(&g_mutex);\n\n bar();\n}\n g_mutex bar() bar() g_mutex" }, { "answer_id": 64199419, "author": "BitTickler", "author_id": 2225104, "author_profile": "https://Stackoverflow.com/users/2225104", "pm_score": 1, "selected": false, "text": "class EvilFoo {\n std::vector<std::string> data;\n std::vector<std::function<void(EvilFoo&)> > changedEventHandlers;\npublic:\n size_t registerChangedHandler( std::function<void(EvilFoo&)> handler) { // ... \n }\n void unregisterChangedHandler(size_t handlerId) { // ...\n }\n void fireChangedEvent() { \n // bad bad, even evil idea!\n for( auto& handler : changedEventHandlers ) {\n handler(*this);\n }\n }\n void AddItem(const std::string& item) { \n data.push_back(item);\n fireChangedEvent();\n }\n};\n fireChangedEvent() EvilFoo EvilFoo fireChangedEvent() changedEventHandlers void EvilFoo::bar() {\n auto_lock lock(this); // this->lock_holder = this->lock_if_not_already_locked_by_same_thread())\n // do what we gotta do\n \n // ~auto_lock() { if (lock_holder) unlock() }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15809/" ]
187,768
<p>I've created a copy utility in c# (.NET 2.0 Framework) that copies files, directories and recursive sub directories etc. The program has a GUI that shows the current file being copied, the current file number (sequence), the total number of files to be copied and the percentage completed for the copy operations. There is also a progress bar, that is based on current file / total files.</p> <p>My problem is related to copying large files. I've been unable to find a way to indicate the total copy progress of a large file (using my current class structure that utilitzes FileInfo.CopyTo method). As a workaround I've separated the file copy operations and GUI display to their own threads and set up a visual cue to show that work is being done. At least the user is aware that the program isn't frozen and is still copying files.</p> <p>It would be nicer to be able to show the progress based on the total number of bytes or have some type of event that fires from the FileInfo.CopyTo method that indicates the total number of bytes copied from the current file.</p> <p>I'm aware of the FileInfo.Length property, so I'm sure there is a way MacGuyver my own event that is based on this and have a handler on the GUI side of things reading the updates (maybe based on checking the FileInfo.Length property of the destination object using some type of timer?).</p> <p>Does anyone know of a way to do this that I'm overlooking. If I can avoid it, I'd rather not rewrite my class to copy bytes through a stream and track it that way (though I'm thinking I might be stuck with going that route).</p> <p>PS - I'm stuck with the .NET 2.0 framework for now, so any solution that requires features available in &gt;= 3.0 only are not an option for me.</p> <p>PPS - I'm open to solutions in any .NET language variety, not only c#.</p>
[ { "answer_id": 190853, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": false, "text": "Microsoft.VisualBasic.FileIO.FileSystem.CopyFile(\n srcPath, \n dstPath, \n Microsoft.VisualBasic.FileIO.UIOption.AllDialogs, \n Microsoft.VisualBasic.FileIO.UICancelOption.ThrowException\n);\n" }, { "answer_id": 8341945, "author": "Dennis", "author_id": 73025, "author_profile": "https://Stackoverflow.com/users/73025", "pm_score": 5, "selected": false, "text": "XCopy.Copy(networkFile.FullPath, temporaryFilename, true, true, (o, pce) => \n{\n worker.ReportProgress(pce.ProgressPercentage, networkFile);\n});\n /// <summary>\n/// PInvoke wrapper for CopyEx\n/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363852.aspx\n/// </summary>\npublic class XCopy\n{\n public static void Copy(string source, string destination, bool overwrite, bool nobuffering)\n {\n new XCopy().CopyInternal(source, destination, overwrite, nobuffering, null); \n }\n\n public static void Copy(string source, string destination, bool overwrite, bool nobuffering, EventHandler<ProgressChangedEventArgs> handler)\n { \n new XCopy().CopyInternal(source, destination, overwrite, nobuffering, handler); \n }\n\n private event EventHandler Completed;\n private event EventHandler<ProgressChangedEventArgs> ProgressChanged;\n\n private int IsCancelled;\n private int FilePercentCompleted;\n private string Source;\n private string Destination; \n\n private XCopy()\n {\n IsCancelled = 0;\n }\n\n private void CopyInternal(string source, string destination, bool overwrite, bool nobuffering, EventHandler<ProgressChangedEventArgs> handler)\n {\n try\n {\n CopyFileFlags copyFileFlags = CopyFileFlags.COPY_FILE_RESTARTABLE;\n if (!overwrite)\n copyFileFlags |= CopyFileFlags.COPY_FILE_FAIL_IF_EXISTS;\n\n if (nobuffering)\n copyFileFlags |= CopyFileFlags.COPY_FILE_NO_BUFFERING;\n\n Source = source;\n Destination = destination;\n\n if (handler != null)\n ProgressChanged += handler;\n\n bool result = CopyFileEx(Source, Destination, new CopyProgressRoutine(CopyProgressHandler), IntPtr.Zero, ref IsCancelled, copyFileFlags);\n if (!result)\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n catch (Exception)\n {\n if (handler != null)\n ProgressChanged -= handler;\n\n throw;\n }\n }\n\n private void OnProgressChanged(double percent)\n {\n // only raise an event when progress has changed\n if ((int)percent > FilePercentCompleted)\n {\n FilePercentCompleted = (int)percent;\n\n var handler = ProgressChanged;\n if (handler != null)\n handler(this, new ProgressChangedEventArgs((int)FilePercentCompleted, null));\n }\n }\n\n private void OnCompleted()\n {\n var handler = Completed;\n if (handler != null)\n handler(this, EventArgs.Empty);\n }\n\n #region PInvoke\n\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName, CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel, CopyFileFlags dwCopyFlags);\n\n private delegate CopyProgressResult CopyProgressRoutine(long TotalFileSize, long TotalBytesTransferred, long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, CopyProgressCallbackReason dwCallbackReason,\n IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData);\n\n private enum CopyProgressResult : uint\n {\n PROGRESS_CONTINUE = 0,\n PROGRESS_CANCEL = 1,\n PROGRESS_STOP = 2,\n PROGRESS_QUIET = 3\n }\n\n private enum CopyProgressCallbackReason : uint\n {\n CALLBACK_CHUNK_FINISHED = 0x00000000,\n CALLBACK_STREAM_SWITCH = 0x00000001\n }\n\n [Flags]\n private enum CopyFileFlags : uint\n {\n COPY_FILE_FAIL_IF_EXISTS = 0x00000001,\n COPY_FILE_NO_BUFFERING = 0x00001000,\n COPY_FILE_RESTARTABLE = 0x00000002,\n COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004,\n COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 0x00000008\n }\n\n private CopyProgressResult CopyProgressHandler(long total, long transferred, long streamSize, long streamByteTrans, uint dwStreamNumber,\n CopyProgressCallbackReason reason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)\n {\n if (reason == CopyProgressCallbackReason.CALLBACK_CHUNK_FINISHED)\n OnProgressChanged((transferred / (double)total) * 100.0);\n\n if (transferred >= total)\n OnCompleted();\n\n return CopyProgressResult.PROGRESS_CONTINUE;\n }\n\n #endregion\n\n}\n" }, { "answer_id": 18544392, "author": "srsyogesh", "author_id": 2480969, "author_profile": "https://Stackoverflow.com/users/2480969", "pm_score": 2, "selected": false, "text": " /// <summary>\n /// Type indicates how the copy gets completed.\n /// </summary>\n internal enum CopyCompletedType\n {\n Succeeded,\n Aborted,\n Exception\n }\n\n/// <summary>\n/// Event arguments for file copy \n/// </summary>\ninternal class FileCopyEventArgs : EventArgs\n{\n /// <summary>\n /// Constructor\n /// </summary>\n /// <param name=\"type\">type of the copy completed type enum</param>\n /// <param name=\"exception\">exception if any</param>\n public FileCopyEventArgs(CopyCompletedType type, Exception exception)\n {\n Type = type;\n Exception = exception;\n }\n\n /// <summary>\n /// Type of the copy completed type\n /// </summary>\n public CopyCompletedType Type\n {\n get;\n private set;\n\n }\n\n /// <summary>\n /// Exception if any happend during copy.\n /// </summary>\n public Exception Exception\n {\n get;\n private set;\n }\n\n}\n\n/// <summary>\n/// PInvoke wrapper for CopyEx\n/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363852.aspx\n/// </summary>\ninternal class XCopy\n{\n\n private int IsCancelled;\n private int FilePercentCompleted;\n\n public XCopy()\n {\n IsCancelled = 0;\n }\n\n /// <summary>\n /// Copies the file asynchronously\n /// </summary>\n /// <param name=\"source\">the source path</param>\n /// <param name=\"destination\">the destination path</param>\n /// <param name=\"nobuffering\">Bufferig status</param>\n /// <param name=\"handler\">Event handler to do file copy.</param>\n public void CopyAsync(string source, string destination, bool nobuffering)\n {\n try\n {\n //since we needed an async copy ..\n Action action = new Action(\n () => CopyInternal(source, destination, nobuffering)\n );\n Task task = new Task(action);\n task.Start();\n }\n catch (AggregateException ex)\n {\n //handle the inner exception since exception thrown from task are wrapped in\n //aggreate exception.\n OnCompleted(CopyCompletedType.Exception, ex.InnerException);\n }\n catch (Exception ex)\n {\n OnCompleted(CopyCompletedType.Exception, ex);\n }\n }\n\n /// <summary>\n /// Event which will notify the subscribers if the copy gets completed\n /// There are three scenarios in which completed event will be thrown when\n /// 1.Copy succeeded\n /// 2.Copy aborted.\n /// 3.Any exception occured.\n /// These information can be obtained from the Event args.\n /// </summary>\n public event EventHandler<FileCopyEventArgs> Completed;\n /// <summary>\n /// Event which will notify the subscribers if there is any progress change while copying.\n /// This will indicate the progress percentage in its event args.\n /// </summary>\n public event EventHandler<ProgressChangedEventArgs> ProgressChanged;\n\n /// <summary>\n /// Aborts the copy asynchronously and throws Completed event when done.\n /// User may not want to wait for completed event in case of Abort since \n /// the event will tell that copy has been aborted.\n /// </summary>\n public void AbortCopyAsync()\n {\n Trace.WriteLine(\"Aborting the copy\");\n //setting this will cancel an operation since we pass the\n //reference to copyfileex and it will periodically check for this.\n //otherwise also We can check for iscancelled on onprogresschanged and return \n //Progress_cancelled .\n IsCancelled = 1;\n\n Action completedEvent = new Action(() =>\n {\n //wait for some time because we ll not know when IsCancelled is set , at what time windows stops copying.\n //so after sometime this may become valid .\n Thread.Sleep(500);\n //do we need to wait for some time and send completed event.\n OnCompleted(CopyCompletedType.Aborted);\n //reset the value , otherwise if we try to copy again since value is 1 , \n //it thinks that its aborted and wont allow to copy.\n IsCancelled = 0;\n });\n\n Task completedTask = new Task(completedEvent);\n completedTask.Start();\n }\n\n\n /// <summary>\n /// Copies the file using asynchronos task\n /// </summary>\n /// <param name=\"source\">the source path</param>\n /// <param name=\"destination\">the destination path</param>\n /// <param name=\"nobuffering\">Buffering status</param>\n /// <param name=\"handler\">Delegate to handle Progress changed</param>\n private void CopyInternal(string source, string destination, bool nobuffering)\n {\n CopyFileFlags copyFileFlags = CopyFileFlags.COPY_FILE_RESTARTABLE;\n\n if (nobuffering)\n {\n copyFileFlags |= CopyFileFlags.COPY_FILE_NO_BUFFERING;\n }\n\n try\n {\n Trace.WriteLine(\"File copy started with Source: \" + source + \" and destination: \" + destination);\n //call win32 api.\n bool result = CopyFileEx(source, destination, new CopyProgressRoutine(CopyProgressHandler), IntPtr.Zero, ref IsCancelled, copyFileFlags);\n if (!result)\n {\n //when ever we get the result as false it means some error occured so get the last win 32 error.\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n }\n catch (Exception ex)\n {\n //the mesage will contain the requested operation was aborted when the file copy\n //was cancelled. so we explicitly check for that and do a graceful exit\n if (ex.Message.Contains(\"aborted\"))\n {\n Trace.WriteLine(\"Copy aborted.\");\n }\n else\n {\n OnCompleted(CopyCompletedType.Exception, ex.InnerException);\n }\n }\n }\n\n private void OnProgressChanged(double percent)\n {\n // only raise an event when progress has changed\n if ((int)percent > FilePercentCompleted)\n {\n FilePercentCompleted = (int)percent;\n\n var handler = ProgressChanged;\n if (handler != null)\n {\n handler(this, new ProgressChangedEventArgs((int)FilePercentCompleted, null));\n }\n }\n }\n\n private void OnCompleted(CopyCompletedType type, Exception exception = null)\n {\n var handler = Completed;\n if (handler != null)\n {\n handler(this, new FileCopyEventArgs(type, exception));\n }\n }\n\n #region PInvoke\n\n /// <summary>\n /// Delegate which will be called by Win32 API for progress change\n /// </summary>\n /// <param name=\"total\">the total size</param>\n /// <param name=\"transferred\">the transferrred size</param>\n /// <param name=\"streamSize\">size of the stream</param>\n /// <param name=\"streamByteTrans\"></param>\n /// <param name=\"dwStreamNumber\">stream number</param>\n /// <param name=\"reason\">reason for callback</param>\n /// <param name=\"hSourceFile\">the source file handle</param>\n /// <param name=\"hDestinationFile\">the destination file handle</param>\n /// <param name=\"lpData\">data passed by users</param>\n /// <returns>indicating whether to continue or do somthing else.</returns>\n private CopyProgressResult CopyProgressHandler(long total, long transferred, long streamSize, long streamByteTrans, uint dwStreamNumber,\n CopyProgressCallbackReason reason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)\n {\n //when a chunk is finished call the progress changed.\n if (reason == CopyProgressCallbackReason.CALLBACK_CHUNK_FINISHED)\n {\n OnProgressChanged((transferred / (double)total) * 100.0);\n }\n\n //transfer completed\n if (transferred >= total)\n {\n if (CloseHandle(hDestinationFile))\n {\n OnCompleted(CopyCompletedType.Succeeded, null);\n }\n else\n {\n OnCompleted(CopyCompletedType.Exception,\n new System.IO.IOException(\"Unable to close the file handle\"));\n }\n }\n\n return CopyProgressResult.PROGRESS_CONTINUE;\n }\n [System.Runtime.InteropServices.DllImport(\"Kernel32\")]\n private extern static Boolean CloseHandle(IntPtr handle);\n\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName, CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel, CopyFileFlags dwCopyFlags);\n\n private delegate CopyProgressResult CopyProgressRoutine(long TotalFileSize, long TotalBytesTransferred, long StreamSize, long StreamBytesTransferred, uint dwStreamNumber, CopyProgressCallbackReason dwCallbackReason,\n IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData);\n\n private enum CopyProgressResult : uint\n {\n PROGRESS_CONTINUE = 0,\n PROGRESS_CANCEL = 1,\n PROGRESS_STOP = 2,\n PROGRESS_QUIET = 3\n }\n\n private enum CopyProgressCallbackReason : uint\n {\n CALLBACK_CHUNK_FINISHED = 0x00000000,\n CALLBACK_STREAM_SWITCH = 0x00000001\n }\n\n [Flags]\n private enum CopyFileFlags : uint\n {\n COPY_FILE_FAIL_IF_EXISTS = 0x00000001,\n COPY_FILE_NO_BUFFERING = 0x00001000,\n COPY_FILE_RESTARTABLE = 0x00000002,\n COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004,\n COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 0x00000008\n }\n\n #endregion\n\n}\n" }, { "answer_id": 27179497, "author": "AJ Richardson", "author_id": 1299394, "author_profile": "https://Stackoverflow.com/users/1299394", "pm_score": 4, "selected": false, "text": "CopyFileEx Task CancellationToken IProgress<double> await public static class FileEx\n{\n public static Task CopyAsync(string sourceFileName, string destFileName)\n {\n return CopyAsync(sourceFileName, destFileName, CancellationToken.None);\n }\n\n public static Task CopyAsync(string sourceFileName, string destFileName, CancellationToken token)\n {\n return CopyAsync(sourceFileName, destFileName, token, null);\n }\n\n public static Task CopyAsync(string sourceFileName, string destFileName, IProgress<double> progress)\n {\n return CopyAsync(sourceFileName, destFileName, CancellationToken.None, progress);\n }\n\n public static Task CopyAsync(string sourceFileName, string destFileName, CancellationToken token, IProgress<double> progress)\n {\n int pbCancel = 0;\n CopyProgressRoutine copyProgressHandler;\n if (progress != null)\n {\n copyProgressHandler = (total, transferred, streamSize, streamByteTrans, dwStreamNumber, reason, hSourceFile, hDestinationFile, lpData) =>\n {\n progress.Report((double)transferred / total * 100);\n return CopyProgressResult.PROGRESS_CONTINUE;\n };\n }\n else\n {\n copyProgressHandler = EmptyCopyProgressHandler;\n }\n token.ThrowIfCancellationRequested();\n var ctr = token.Register(() => pbCancel = 1);\n var copyTask = Task.Run(() =>\n {\n try\n {\n CopyFileEx(sourceFileName, destFileName, copyProgressHandler, IntPtr.Zero, ref pbCancel, CopyFileFlags.COPY_FILE_RESTARTABLE);\n token.ThrowIfCancellationRequested();\n }\n finally\n {\n ctr.Dispose();\n }\n }, token);\n return copyTask;\n }\n\n private static CopyProgressResult EmptyCopyProgressHandler(long total, long transferred, long streamSize, long streamByteTrans, uint dwStreamNumber, CopyProgressCallbackReason reason, IntPtr hSourceFile, IntPtr hDestinationFile, IntPtr lpData)\n {\n return CopyProgressResult.PROGRESS_CONTINUE;\n }\n\n #region DLL Import\n\n [DllImport(\"kernel32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CopyFileEx(string lpExistingFileName, string lpNewFileName,\n CopyProgressRoutine lpProgressRoutine, IntPtr lpData, ref Int32 pbCancel,\n CopyFileFlags dwCopyFlags);\n\n delegate CopyProgressResult CopyProgressRoutine(\n long totalFileSize,\n long totalBytesTransferred,\n long streamSize,\n long streamBytesTransferred,\n uint dwStreamNumber,\n CopyProgressCallbackReason dwCallbackReason,\n IntPtr hSourceFile,\n IntPtr hDestinationFile,\n IntPtr lpData);\n\n enum CopyProgressResult : uint\n {\n PROGRESS_CONTINUE = 0,\n PROGRESS_CANCEL = 1,\n PROGRESS_STOP = 2,\n PROGRESS_QUIET = 3\n }\n\n enum CopyProgressCallbackReason : uint\n {\n CALLBACK_CHUNK_FINISHED = 0x00000000,\n CALLBACK_STREAM_SWITCH = 0x00000001\n }\n\n [Flags]\n enum CopyFileFlags : uint\n {\n COPY_FILE_FAIL_IF_EXISTS = 0x00000001,\n COPY_FILE_RESTARTABLE = 0x00000002,\n COPY_FILE_OPEN_SOURCE_FOR_WRITE = 0x00000004,\n COPY_FILE_ALLOW_DECRYPTED_DESTINATION = 0x00000008\n }\n\n #endregion\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9732/" ]
187,770
<p>I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?</p>
[ { "answer_id": 187785, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 9, "selected": true, "text": "INSERT INTO bar..tblFoobar( *fieldlist* )\nSELECT *fieldlist* FROM foo..tblFoobar\n" }, { "answer_id": 187833, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 7, "selected": false, "text": "SELECT * \nINTO DestinationDB..MyDestinationTable \nFROM SourceDB..MySourceTable \n INSERT INTO DestinationDB..MyDestinationTable \nSELECT * FROM SourceDB..MySourceTable\n" }, { "answer_id": 187837, "author": "ScottStonehouse", "author_id": 2342, "author_profile": "https://Stackoverflow.com/users/2342", "pm_score": 5, "selected": false, "text": "create table INSERT bar.[schema].table SELECT * FROM foo.[schema].table" }, { "answer_id": 10466996, "author": "NeverHopeless", "author_id": 751527, "author_profile": "https://Stackoverflow.com/users/751527", "pm_score": 3, "selected": false, "text": "insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB)\nSelect columnA, columnB from DeveloperDB.dbo.Customers\n select (name + ',') as TableColumns from sys.columns \nwhere object_id = object_id('YourTableName')\n select (name + ',') as TableColumns from sys.columns \nwhere object_id = object_id('YourTableName') and is_identity = 0\n select * into <Destination_table> from <Servername>.<DatabaseName>.dbo.<sourceTable>\n" }, { "answer_id": 69825362, "author": "Francesco Mantovani", "author_id": 4652358, "author_profile": "https://Stackoverflow.com/users/4652358", "pm_score": 0, "selected": false, "text": "SELECT * INTO My_New_Table FROM [HumanResources].[Department];\n SELECT * INTO My_New_Table FROM [ServerName].[AdventureWorks2012].[HumanResources].[Department];\n SELECT * INTO My_New_Table\nFROM OPENROWSET('SQLNCLI', 'Server=My_Remote_Server;Trusted_Connection=yes;',\n 'SELECT * FROM AdventureWorks2012.HumanResources.Department');\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
187,774
<p>I have XML that looks like</p> <pre><code>&lt;answers&gt; &lt;answer&gt; &lt;question-number&gt;1&lt;/question-number&gt; &lt;value&gt;3&lt;/value&gt; &lt;mean xsi:nil="1" /&gt; &lt;/answer&gt; &lt;answer&gt; &lt;question-number&gt;2&lt;/question-number&gt; &lt;value&gt;2&lt;/value&gt; &lt;mean&gt;2.3&lt;/mean&gt; &lt;/answer&gt; &lt;answer&gt; &lt;question-number&gt;3&lt;/question-number&gt; &lt;value&gt;3&lt;/value&gt; &lt;mean xsi:nil="1" /&gt; &lt;/answer&gt; .... &lt;/answers&gt; </code></pre> <p>I'm formatting each answer using xsl:for-each. If there is a mean present I have a graphical representation of the mean. For some potential lists of answers the mean will always be null.</p> <p>At the bottom of the page I want to put a legend explaining the graphical representation of the mean. But I only want it to appear if I actually displayed a mean at all. So I want to be able to do a check, after closing the xsl:for-each, to say "do any of the answer elements have a non-null mean value?".</p> <p>Really not sure how to do that. </p>
[ { "answer_id": 187843, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 0, "selected": false, "text": "<xs:if test=\"/answers/answer/mean\">You have a mean</xs:if>\n <xs:if test=\"(count(/answers/answer/mean)==1)\">You have a mean<xs:if>\n <xs:if test=\"/answers/answer/mean != nil\">You have a mean</xs:if>\n" }, { "answer_id": 187933, "author": "Jasper", "author_id": 18702, "author_profile": "https://Stackoverflow.com/users/18702", "pm_score": 3, "selected": false, "text": "<xs:if test=\"(count(/answers/answer/mean[not(@xsi:nil)])>0\"><xs:if>\n <xs:if test=\"//answer/mean[not(text())]\"><xs:if>\n <xs:if test=\"//answer/mean[attribute::xsi:nil]\"><xs:if>\n" }, { "answer_id": 187938, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 0, "selected": false, "text": " <xsl:for-each select=\"/answers/answer\">\n <xsl:if test=\"mean &gt;= 0\">\n ... other code ...\n </xsl:if>\n </xsl:for-each>\n" }, { "answer_id": 187942, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "<xs:if test=\"count(/answers/answer/mean[@xsi:nil != '1']) > 0\">Mean stuff here</xs:if>\n" }, { "answer_id": 188426, "author": "Jacob Mattison", "author_id": 1237, "author_profile": "https://Stackoverflow.com/users/1237", "pm_score": 2, "selected": true, "text": "<xsl:if test=\"//answers/answer/mean>0\">\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1237/" ]
187,777
<p>How can I get the BSSID / MAC (Media Access Control) address of the wireless access point my system is connected to using C#?</p> <p>Note that I'm interested in the BSSID of the WAP. This is different from the MAC address of the networking portion of the WAP.</p>
[ { "answer_id": 187867, "author": "Iain", "author_id": 5993, "author_profile": "https://Stackoverflow.com/users/5993", "pm_score": 6, "selected": true, "text": "netsh wlan show networks mode=Bssid | findstr \"BSSID\"\n arp -a | findstr 192.168.1.254\n var wlanClient = new WlanClient();\nforeach (WlanClient.WlanInterface wlanInterface in wlanClient.Interfaces)\n{\n Wlan.WlanBssEntry[] wlanBssEntries = wlanInterface.GetNetworkBssList();\n foreach (Wlan.WlanBssEntry wlanBssEntry in wlanBssEntries)\n {\n byte[] macAddr = wlanBssEntry.dot11Bssid;\n var macAddrLen = (uint) macAddr.Length;\n var str = new string[(int) macAddrLen];\n for (int i = 0; i < macAddrLen; i++)\n {\n str[i] = macAddr[i].ToString(\"x2\");\n }\n string mac = string.Join(\"\", str);\n Console.WriteLine(mac);\n }\n}\n" }, { "answer_id": 7797261, "author": "Lennard", "author_id": 999671, "author_profile": "https://Stackoverflow.com/users/999671", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Diagnostics;\n\nclass Program\n{\n static void Main(string[] args)\n { \n Process proc = new Process();\n proc.StartInfo.CreateNoWindow = true;\n proc.StartInfo.FileName = \"cmd\";\n\n proc.StartInfo.Arguments = @\"/C \"\"netsh wlan show networks mode=bssid | findstr BSSID \"\"\";\n\n proc.StartInfo.RedirectStandardOutput = true; \n proc.StartInfo.UseShellExecute = false;\n proc.Start();\n string output = proc.StandardOutput.ReadToEnd();\n proc.WaitForExit(); \n\n Console.WriteLine(output); \n } \n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993/" ]
187,779
<p>Is it possible to update IIS on Windows XP from 5.1 to 6?</p> <p>If so how?</p> <p>Thanks.</p>
[ { "answer_id": 187802, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 6, "selected": true, "text": "XP = IIS 5.1\n2003 = IIS 6\n2008 = IIS 7\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12148/" ]
187,795
<p>For simplicity lets say I have two flex mxml pages. </p> <p>form.mxml<br> button.mxml</p> <p>If the form.mxml page had the following code, it should work fine:</p> <pre><code>&lt;custom:SelectView dSource="{_thedata}" id="form" visible="false"&gt; &lt;/custom:SelectView&gt; &lt;mx:LinkButton label="Show" id="lbShow" click="form.visible=true;&gt; &lt;mx:LinkButton label="Show" id="lbHide" click="form.visible=false;&gt; </code></pre> <p>But if the code was like:</p> <p>form.mxml</p> <pre><code> &lt;custom:SelectView dSource="{_thedata}" id="form" visible="false"&gt; &lt;/custom:SelectView&gt; </code></pre> <p>button.mxml</p> <pre><code>&lt;mx:LinkButton label="Show" id="lbShow" click="form.visible=true;&gt; &lt;mx:LinkButton label="Show" id="lbHide" click="form.visible=false;&gt; </code></pre> <p>how can I make a call from button.mxml to change form.mxml</p> <p>---- a bit more details ---</p> <p>My page actually looks like this: where query:AdvancedSearchFields is basically including a flex form into the page, and I want it to show/hide the custom view below after the search is complete. </p> <pre><code>&lt;query:AdvancedSearchFields searchType="projects" searchCategory="advanced" visible="true" id="AdvancedSearch" /&gt; &lt;custom:SelectView dSource="{_searchResults}" id="sv" visible="false"&gt; </code></pre>
[ { "answer_id": 187889, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 0, "selected": false, "text": "button.mxml <mx:Script>\n<![CDATA[\n [Bindable] public var myForm:MyFormClass;\n]]>\n</mx:Script>\n\n<mx:LinkButton label=\"Show\" id=\"lbShow\" click=\"myForm.form.visible=true;\">\n<mx:LinkButton label=\"Show\" id=\"lbHide\" click=\"myForm.form.visible=false;\">\n Button" }, { "answer_id": 187914, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": true, "text": "<custom:SelectView dSource=\"{_thedata}\" id=\"form\" visible=\"{buttons.showForm}\">\n</custom:SelectView>\n\n<!-- include your buttons.mxml component using an ID of \"buttons\" -->\n <mx:Script>\n<![CDATA[\n [Bindable] public var showForm:Boolean = true;\n]]>\n</mx:Script>\n\n<mx:LinkButton label=\"Show\" id=\"lbShow\" click=\"this.showForm=true;\">\n<mx:LinkButton label=\"Hide\" id=\"lbHide\" click=\"this.showForm=false;\">\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24563/" ]
187,797
<p>Say I've got a class like this:</p> <pre><code>class Test { int x; SomeClass s; } </code></pre> <p>And I instantiate it like this:</p> <pre><code>Test* t = new Test; </code></pre> <p>Is x on the stack, or the heap? What about s?</p>
[ { "answer_id": 187806, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 3, "selected": false, "text": "new t" }, { "answer_id": 187811, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 4, "selected": false, "text": "Test a;\nTest *t = new Test;\n" }, { "answer_id": 187951, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 4, "selected": true, "text": "struct A\n{\n A()\n {\n c = new C() ;\n }\n\n B b ;\n C * c ;\n}\n\nvoid doSomething()\n{\n A aa00 ;\n A * aa01 = new A() ;\n}\n" }, { "answer_id": 188174, "author": "DJClayworth", "author_id": 19276, "author_profile": "https://Stackoverflow.com/users/19276", "pm_score": 1, "selected": false, "text": "class MyClass {\n int i;\n MyInnerClass m;\n MyInnerClass *p = new MyInnerClass();\n}\n\nMyClass a;\nMyClass *b = new MyClass();\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12828/" ]
187,799
<p>Let me start by saying I'm a huge fan of the elegance of this pattern -- I have a group of basic entities that I have implemented builders for (specifically for testing). However I have found (and this may be the caveat) that as my program evolved I kept having to go back and re-work the builders. In the end, it really hasn't seemed worth it to keep them updated, and I've gone back to primarily keeping a Object Mother that has a lot of pre-configured entities. Should I continue to update the builders for future use, or is the TDBs something that should only be created once you're design has reached some stability and the Object Mother becomes too large?</p> <p>Also note, I've found I'm not using the builders anywhere else in the app, as I enjoy using .Net 3.0 's new syntax for property initialization.</p>
[ { "answer_id": 222686, "author": "craigb", "author_id": 18590, "author_profile": "https://Stackoverflow.com/users/18590", "pm_score": 4, "selected": true, "text": "User fred = CreateUser(\"fred\").WithReputation(900)\n .WithScholarBadge()\n .WithCriticBadge()\n User fred = UserObjectMother.Fred()\n Fred()" }, { "answer_id": 33691394, "author": "Andrew Chaa", "author_id": 437961, "author_profile": "https://Stackoverflow.com/users/437961", "pm_score": 1, "selected": false, "text": "User fred = new UserTestDataBuilder()\n .With(u => u.Name = \"fred\")\n .With(u => u.Reputation = 900)\n .With(u => u.ScholarBadge = true)\n .With(u => u.CriticBadge = true)\n public class UserSpec\n{\n public string Name {get; set;}\n public int Reputation {get; set;}\n ...\n}\n\npublic class UserTestDataBuilder() \n{\n private UserSpec _userSpec = new UserSpec();\n public UserTestDataBuilder With(Action<UserSpec> action) \n {\n action(_userSpec);\n return this;\n }\n\n public User Build() \n {\n return new User(_userSpec.Name, _userSpec.Reputation, _userSpec.ScholarBadge, _userSpec.CriticBadge);\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25807/" ]
187,804
<p>I would like a "system" that monitors a process and would kill said process if:</p> <ul> <li>the process exceeds some memory requirements</li> <li>the process does not respond to a message from the "system" in some period of time</li> </ul> <p>I assume this "system" could be something as simple as a monitoring process? A code example of how this could be done would be useful. I am of course not averse to a completely different solution to this problem.</p>
[ { "answer_id": 187824, "author": "Avdi", "author_id": 20487, "author_profile": "https://Stackoverflow.com/users/20487", "pm_score": 4, "selected": true, "text": "ulimit" }, { "answer_id": 12206999, "author": "Jon Jensen", "author_id": 1637217, "author_profile": "https://Stackoverflow.com/users/1637217", "pm_score": 3, "selected": false, "text": "#!/usr/local/bin/perl\n\nuse strict;\nuse warnings;\nuse Proc::ProcessTable;\n\nmy $table = Proc::ProcessTable->new;\n\nfor my $process (@{$table->table}) {\n # skip root processes\n next if $process->uid == 0 or $process->gid == 0;\n\n # skip anything other than Passenger application processes\n #next unless $process->fname eq 'ruby' and $process->cmndline =~ /\\bRails\\b/;\n\n # skip any using less than 1 GiB\n next if $process->rss < 1_073_741_824;\n\n # document the slaughter\n (my $cmd = $process->cmndline) =~ s/\\s+\\z//;\n print \"Killing process: pid=\", $process->pid, \" uid=\", $process->uid, \" rss=\", $process->rss, \" fname=\", $process->fname, \" cmndline=\", $cmd, \"\\n\";\n\n # try first to terminate process politely\n kill 15, $process->pid;\n\n # wait a little, then kill ruthlessly if it's still around\n sleep 5;\n kill 9, $process->pid;\n}\n" }, { "answer_id": 66970510, "author": "Marcel Kohls", "author_id": 4963247, "author_profile": "https://Stackoverflow.com/users/4963247", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n\nif [ -z \"$1\" ]\n then\n maxlimit=99\nelse\n maxlimit=$1\nfi\n\nps axo user,%cpu,pid,vsz,rss,uid,gid --sort %cpu,rss\\\n| awk -v max=$maxlimit '$6 != 0 && $7 != 0 && $2 > max'\\\n| awk '{print $3}'\\\n| while read line;\\\n do\\\n ps u --no-headers -p $line;\\\n echo \"$(date) - $(ps u --no-headers -p $line)\" >> pkill.log;\\\n notify-send 'Killing proccess!' $(ps -p $line -o command --no-headers | awk '{print $1}') -u normal -i dialog-warning -t 3000;\\\n kill $line;\\\n done;\n sh ./pkill.sh <limit-cpu> watch -n 10 sh ./pkill.sh 90" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21317/" ]
187,827
<p>So for this one project, we have a bunch of queries that are executed on a regular basis (every minute or so. I used the "Analyze Query in Database Engine " to check on them. </p> <p>They are pretty simple: select * from tablex where processed='0'</p> <p>There is an index on processed, and each query should return &lt;1000 rows on a table with 1MM records.</p> <p>The Analyzer recommended creating some STATISTICS on this.... So my question is: What are those statistics ? do they really help performance ? how costly are they for a table like above ? </p> <p>Please bear in mind that by no means I would call myself a SQL Server experienced user ... And this is the first time using this Analyzer.</p>
[ { "answer_id": 188179, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 6, "selected": true, "text": "SELECT * FROM tablename WHERE col1=value col1 col1 AUTO UPDATE STATISTICS" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23238/" ]
187,836
<p>Sometimes while debugging, I need to restart a service on a remote machine. Currently, I'm doing this via Remote Desktop. How can it be done from the command line on my local machine?</p>
[ { "answer_id": 187854, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 9, "selected": true, "text": "sc \\\\machine stop <service>\n" }, { "answer_id": 187918, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 3, "selected": false, "text": "AT \\\\computername time \"NET STOP servicename\"\nAT \\\\computername time \"NET START servicename\"\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/549/" ]
187,849
<p>I am experiencing some weird behavior with localized messages reported from my background worker process in my windows forms application.</p> <p>The application is a setup application with windows forms. The application launches a background worker to perform and IIS reset and then install MSIs.</p> <p>The first time I run the application on a Spanish Win Server 2003 VM the forms are in spanish but not the BWP messages. If i immediately run it again, the messages are in spanish.</p> <p>The .Resources files are embedded resources and are extracted to the temp directory upon application startup.</p> <p>My code retrieves the localized strings through a custom resource manager class. This class creates a file based resource to the .Resources files in the temp directory. This is working correctly because the windows forms labels and title are localized every time.</p> <p>Has anyone experienced this? I'm absolutely stuck, please help. Thanks, Andrew</p>
[ { "answer_id": 8898322, "author": "Maik Preuss", "author_id": 1154412, "author_profile": "https://Stackoverflow.com/users/1154412", "pm_score": 2, "selected": false, "text": " private delegate CultureInfo GetUICultureCallback();\n\n private CultureInfo GetUICulture()\n {\n if (this.InvokeRequired)\n {\n return (CultureInfo)this.Invoke(new GetUICultureCallback(GetUICulture));\n }\n\n return System.Threading.Thread.CurrentThread.CurrentUICulture;\n }\n\n void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n {\n System.Threading.Thread.CurrentThread.CurrentUICulture = GetUICulture();\n\n for (; ; )\n {\n if (backgroundWorker.CancellationPending)\n {\n e.Cancel = true;\n return;\n }\n.\n.\n.\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26540/" ]
187,851
<p>How can I open a synchronous dialog in Flex? I need to call a function from an External Interface (JavaScript) that will open a simple dialog in the Flex application and returns an value according to the button the user has clicked (OK/Cancel).</p> <p>So it should by a synchronous call to a dialog, i.e. the call waits until the user has closed the dialog like this.</p> <pre><code>//This function is called by JavaScript function onApplicationUnload():Boolean { var result:Boolean; result = showDialogAndWaitForResult(); return result } </code></pre> <p>Does anybody know how I can do this? I could write a loop that waits until the dialog has set a flag and then reads the result to return it, but there must be something that is way more elegant and reusable for waiting of the completion of other asynchronous calls.</p> <p><strong>EDIT:</strong> Unfortunately a callback does not work as the JavaScript function that calls onApplicationUnload() itself has to return a value (similar to the onApplicationUnload() function in Flex). This JavaScript function has a fixed signature as it is called by a framework and I cannot change it. Or in other words: The call from JavaScript to Flex must also be synchronous.</p>
[ { "answer_id": 187955, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": 2, "selected": false, "text": "function onApplicationUnload():void\n{\n showDialog(resultMethod);\n}\n\nfunction resultMethod(result:Boolean):void\n{\n ExternalInterface.call(\"javaScriptCallback\", [result]);\n}\n" }, { "answer_id": 211494, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": -1, "selected": false, "text": "Alert.show(\"Hello World\");" }, { "answer_id": 634637, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "private function deleteFileCheck():void\n{\n Alert.show(\"Are you sure you want to delete this file?\",\n \"Confirm Delete\",\n Alert.YES| Alert.NO,\n this, deleteFileHandler, null, Alert.NO);\n}\n\nprivate function deleteFileHandler(event:CloseEvent):void\n{\n if (event.detail == Alert.YES)\n {\n ...do your processing here\n }\n}\n" }, { "answer_id": 2648089, "author": "Grafton", "author_id": 317822, "author_profile": "https://Stackoverflow.com/users/317822", "pm_score": 1, "selected": false, "text": "CairngormEventDispatcher.getInstance().addEventListener(ClosingDialogCompleteEvent.DIALOG_COMPLETE, onClosingDialogComplete); CairngormEventDispatcher.dispatchEvent(new ClosingDialogCompleteEvent(<parameters>)); \npublic function onClosingDialogComplete (e: ClosingDialogCompleteEvent):void\n{\n param1 = e.param1;\n param2 = e.param2;\n // etc.\n // Continue processing or set the global variable that signals the main thread to continue.\n}\n \npackage com. ... .event // You define where the event lives.\n{\nimport com.adobe.cairngorm.control.CairngormEvent;\n\npublic class ClosingDialogCompleteEvent extends CairngormEvent\n{\n // Event type.\n public static const DIALOG_COMPLETE:String = \"dialogComplete\";\n\n public var param1:String;\n public var param2:String;\n\n public function ClosingDialogCompleteEvent(param1:String, param2:String)\n {\n super(DIALOG_COMPLETE);\n this.param1 = param1;\n this.param2 = param2;\n }\n}\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7524/" ]
187,855
<p>I keep hearing about the DRY Principle and how it is so important in ASP.NET MVC, but when I do research on Google I don't seem to quite understand exactly how it applies to MVC.</p> <p>From what I've read its not really the copy &amp; paste code smell, which I thought it was, but it is more than that.</p> <p>Can any of you give some insight into how I might use the DRY Principle in my ASP.NET MVC application?</p>
[ { "answer_id": 195769, "author": "Matt Hinze", "author_id": 2676, "author_profile": "https://Stackoverflow.com/users/2676", "pm_score": 3, "selected": true, "text": "FormsAuthentication.Logout()" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ]
187,857
<p>We have a TIBCO EMS solution that uses built-in server failover in a 2-4 server environment. If the TIBCO admins fail-over services from one EMS server to another, connections are supposed to be transfered to the new server automatically at the EMS service level. For our C# applications using the EMS service, this is not happening - our user connections are not being transfered to the new server after failover and we're not sure why.</p> <p>Our application connection to EMS at startup only so if the TIBCO admins failover after users have started our application, they users need to restart the app in order to reconnect to the new server (our EMS connection uses a server string including all 4 production EMS servers - if the first attempt fails, it moves to the next server in the string and tries again).</p> <p>I'm looking for an automated approach that will attempt to reconnect to EMS periodically if it detects that the connection is dead but I'm not sure how best to do that.</p> <p>Any ideas? We are using TIBCO.EMS.dll version 4.4.2 and .Net 2.x (SmartClient app)</p> <p>Any help would be appreciated.</p>
[ { "answer_id": 234966, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 3, "selected": false, "text": "private void initEMS()\n{\n Tibems.SetExceptionOnFTSwitch(true);\n _ConnectionFactory = new TIBCO.EMS.TopicConnectionFactory(<server>);\n _ConnectionFactory.SetReconnAttemptCount(30); // 30retries\n _ConnectionFactory.SetReconnAttemptDelay(120000); // 2minutes\n _ConnectionFactory.SetReconnAttemptTimeout(2000); // 2seconds\n_Connection = _ConnectionFactory.CreateTopicConnectionM(<username>, <password>);\n _Connection.ExceptionHandler += new EMSExceptionHandler(_Connection_ExceptionHandler);\n}\nprivate void _Connection_ExceptionHandler(object sender, EMSExceptionEventArgs args)\n{\n EMSException e = args.Exception;\n // args.Exception = \"Connection has been terminated\" -- single server failure\n // args.Exception = \"Connection has performed fault-tolerant switch to <server url>\" -- fault-tolerant multi-server\n MessageBox.Show(e.ToString());\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24179/" ]
187,886
<p>I need to grant select permission for all tables owned by a specific user to another user. Can I do this with a single command along the lines of:</p> <pre><code>Grant Select on OwningUser.* to ReceivingUser </code></pre> <p>Or do I have to generate the sql for each table with something along the lines of:</p> <pre><code> Select 'GRANT SELECT ON OwningUser.'||Table_Name||'TO ReceivingUser' From All_Tables Where Owner='OWNINGUSER' </code></pre>
[ { "answer_id": 189496, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 7, "selected": true, "text": "BEGIN\n FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP\n EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';\n END LOOP;\nEND; \n" }, { "answer_id": 18511808, "author": "user2729366", "author_id": 2729366, "author_profile": "https://Stackoverflow.com/users/2729366", "pm_score": 2, "selected": false, "text": "thoko grant select any table, insert any table, delete any table, update any table to thoko;\n" }, { "answer_id": 39404932, "author": "dcvetkov", "author_id": 6812202, "author_profile": "https://Stackoverflow.com/users/6812202", "pm_score": 2, "selected": false, "text": "SET SERVEROUT ON\nDECLARE\n o_type VARCHAR2(60) := '';\n o_name VARCHAR2(60) := '';\n o_owner VARCHAR2(60) := '';\n l_error_message VARCHAR2(500) := '';\nBEGIN\n FOR R IN (SELECT owner, object_type, object_name\n FROM all_objects \n WHERE owner='SCHEMANAME'\n AND object_type IN ('TABLE','VIEW')\n ORDER BY 1,2,3) LOOP\n BEGIN\n o_type := r.object_type;\n o_owner := r.owner;\n o_name := r.object_name;\n DBMS_OUTPUT.PUT_LINE(o_type||' '||o_owner||'.'||o_name);\n EXECUTE IMMEDIATE 'grant select on '||o_owner||'.'||o_name||' to USERNAME';\n EXCEPTION\n WHEN OTHERS THEN\n l_error_message := sqlerrm;\n DBMS_OUTPUT.PUT_LINE('Error with '||o_type||' '||o_owner||'.'||o_name||': '|| l_error_message);\n CONTINUE;\n END;\n END LOOP;\nEND;\n/\n" }, { "answer_id": 46579155, "author": "J. Chomel", "author_id": 6019417, "author_profile": "https://Stackoverflow.com/users/6019417", "pm_score": 0, "selected": false, "text": "CREATE OR REPLACE PROCEDURE GRANT_SELECT(to_user in varchar2) AS\n\n CURSOR ut_cur IS SELECT table_name FROM user_tables;\n\n RetVal NUMBER;\n sCursor INT;\n sqlstr VARCHAR2(250);\n\nBEGIN\n FOR ut_rec IN ut_cur\n LOOP\n sqlstr := 'GRANT SELECT ON '|| ut_rec.table_name || ' TO ' || to_user;\n sCursor := dbms_sql.open_cursor;\n dbms_sql.parse(sCursor,sqlstr, dbms_sql.native);\n RetVal := dbms_sql.execute(sCursor);\n dbms_sql.close_cursor(sCursor);\n\n END LOOP;\nEND grant_select;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
187,890
<p>I have an ASP.NET page which pulls a set of images from a database table, and using an enumerator, goes through all of them and displays then.</p> <p>This all happens in the codebehind (VB.NET), where the code adds the placeholder and some controls inside tables (tables inside the placeholder).</p> <p>I've added a button to this placeholder (inside a table cell), all programatically, but how can I add a click event to the button programatically? I want to fire a javascript (lightbox) which shows a large preview of the image (this works when the user clicks a small image, which invokes a string hyperlink on the code that points to the javascript).</p>
[ { "answer_id": 187898, "author": "alexmac", "author_id": 23066, "author_profile": "https://Stackoverflow.com/users/23066", "pm_score": 4, "selected": false, "text": "cmdMyButton.attributes.add(\"onclick\", \"alert('hello');\")" }, { "answer_id": 187905, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 3, "selected": false, "text": "btnMyButton.OnClientClick = \"window.open('http://www.myimage.com'); return false;\";\n btnMyButton.Attributes.Add(\"onclick\", \"window.open('http://www.myimage.com'); return false;\";\n" }, { "answer_id": 187910, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 1, "selected": false, "text": "button.Attributes.Add(\"onclick\", \"javascript:fireLightBox()\")" }, { "answer_id": 187968, "author": "Ed Altorfer", "author_id": 26552, "author_profile": "https://Stackoverflow.com/users/26552", "pm_score": 2, "selected": false, "text": "control.Attributes.Add(\"onclick\", \"javascript:DoSomething('\" + control.Value + \"')\")\n Private Sub ctlControlName_ActionName(ByVal sender As Object, ByVal e As System.EventArgs)\n Handles ctlControlName.ActionName\nDim control As ControlType = DirectCast(sender, ControlType)\ncontrol.Attributes.Add(\"onclick\", \"javascript:DoSomething('\" + control.Value + \"')\")\nEnd Sub\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
187,893
<p>This is what I'd like to do, but it doesn't seem possible: (edit: changed single to double quotes)</p> <pre><code>function get_archives($limit, $offset) { $query = $this-&gt;db-&gt;query(" SELECT archivalie.id, archivalie.signature, type_of_source.description AS type_of_source_description, media_type.description AS media_type_description, origin.description AS origin_description FROM archivalie, type_of_source, media_type, origin WHERE archivalie.type_of_source_id = type_of_source.id AND type_of_source.media_type_id = media_type.id AND archivalie.origin_id = origin.id ORDER BY archivalie.id ASC LIMIT $limit, $offset "); // etc... } </code></pre> <p>It gives this error: (edit: new error message using double quotes, and with an offset number passed in the URL)</p> <pre><code>ERROR: LIMIT #,# syntax is not supported HINT: Use separate LIMIT and OFFSET clauses. </code></pre> <p>It only works if you pass the variables using the ActiveRecord format:</p> <pre><code>$this-&gt;db-&gt;select('archivalie.id, archivalie.signature, etc, etc'); // from, where, etc. $this-&gt;db-&gt;limit($limit, $offset); $query = $this-&gt;db-&gt;get(); </code></pre>
[ { "answer_id": 190539, "author": "meleyal", "author_id": 4196, "author_profile": "https://Stackoverflow.com/users/4196", "pm_score": 1, "selected": false, "text": "$query = $this->db->query(\"\n SELECT archivalie.id, \n archivalie.signature, \n type_of_source.description AS type_of_source_description, \n media_type.description AS media_type_description,\n origin.description AS origin_description\n\n FROM archivalie, \n type_of_source, \n media_type,\n origin\n\n WHERE archivalie.type_of_source_id = type_of_source.id \n AND type_of_source.media_type_id = media_type.id \n AND archivalie.origin_id = origin.id \n\n ORDER BY archivalie.id ASC\n LIMIT $limit\n OFFSET $offset\n\");\n # Check/assign an offset\n$offset = (!$this->uri->segment(3)) ? 0 : $this->uri->segment(3);\n\n# Get the data\n$archives = $this->archive->get_archives($config['per_page'], $offset);\n" }, { "answer_id": 12884069, "author": "Angel Talavera", "author_id": 405164, "author_profile": "https://Stackoverflow.com/users/405164", "pm_score": 2, "selected": false, "text": "$query = $this->db->query('\nSELECT archivalie.id, \n archivalie.signature, \n type_of_source.description AS type_of_source_description, \n media_type.description AS media_type_description,\n origin.description AS origin_description\nFROM archivalie, \n type_of_source, \n media_type,\n origin\nWHERE archivalie.type_of_source_id = type_of_source.id \nAND type_of_source.media_type_id = media_type.id \nAND archivalie.origin_id = origin.id \nORDER BY archivalie.id ASC\nLIMIT ?\nOFFSET ?',array($limit,$offset));\n" }, { "answer_id": 41008420, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 0, "selected": false, "text": "$page = '10'; // for some reason this arrives as a string\n$sql = \"select * from customers limit 10 offset ?\";\n$result = $this->db->query($sql, array(intval($page));\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
187,894
<p>From C#, I want to do the equivalent of the following:</p> <pre><code>arp -a |findstr 192.168.1.254 </code></pre> <p>Alternatively, the answer could call the <a href="http://msdn.microsoft.com/en-us/library/aa366358.aspx" rel="noreferrer">SendARP</a> function and get the results.</p> <p>This will allow my application to do some other processing that requires the MAC address.</p>
[ { "answer_id": 187929, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 6, "selected": true, "text": "[DllImport(\"iphlpapi.dll\", ExactSpelling=true)]\npublic static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen );\n IPAddress dst = IPAddress.Parse(\"192.168.2.1\"); // the destination IP address\n\nbyte[] macAddr = new byte[6];\nuint macAddrLen = (uint)macAddr.Length;\n\nif (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0)\n throw new InvalidOperationException(\"SendARP failed.\");\n\nstring[] str = new string[(int)macAddrLen];\nfor (int i=0; i<macAddrLen; i++)\n str[i] = macAddr[i].ToString(\"x2\");\n\nConsole.WriteLine(string.Join(\":\", str));\n" }, { "answer_id": 187972, "author": "Douglas Anderson", "author_id": 5678, "author_profile": "https://Stackoverflow.com/users/5678", "pm_score": 1, "selected": false, "text": "ManagementClass mc = new ManagementClass(\"Win32_NetworkAdapterConfiguration\");\n\nManagementObjectCollection mcCol = mc.GetInstances();\n\nforeach (ManagementObject mcObj in mcCol)\n{\n Console.WriteLine(mcObj[\"Caption\"].ToString());\n Console.WriteLine(mcObj[\"MacAddress\"].ToString());\n}\n" }, { "answer_id": 37155004, "author": "Dominic Jonas", "author_id": 6229375, "author_profile": "https://Stackoverflow.com/users/6229375", "pm_score": 2, "selected": false, "text": "public static class MacResolver\n{\n /// <summary>\n /// Convert a string into Int32 \n /// </summary>\n [DllImport(\"Ws2_32.dll\")]\n private static extern Int32 inet_addr(string ip);\n\n /// <summary>\n /// The main funtion \n /// </summary> \n [DllImport(\"Iphlpapi.dll\")]\n private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 len);\n\n /// <summary>\n /// Returns the MACAddress by a string.\n /// </summary>\n public static Int64 GetRemoteMAC(string remoteIP)\n { \n Int32 ldest = inet_addr(remoteIP);\n\n try\n {\n Int64 macinfo = 0; \n Int32 len = 6; \n\n int res = SendARP(ldest, 0, ref macinfo, ref len);\n\n return macinfo; \n }\n catch (Exception e)\n {\n return 0;\n }\n }\n\n /// <summary>\n /// Format a long/Int64 into string. \n /// </summary>\n public static string FormatMac(this Int64 mac, char separator)\n {\n if (mac <= 0)\n return \"00-00-00-00-00-00\";\n\n char[] oldmac = Convert.ToString(mac, 16).PadLeft(12, '0').ToCharArray();\n\n System.Text.StringBuilder newMac = new System.Text.StringBuilder(17);\n\n if (oldmac.Length < 12)\n return \"00-00-00-00-00-00\";\n\n newMac.Append(oldmac[10]);\n newMac.Append(oldmac[11]);\n newMac.Append(separator);\n newMac.Append(oldmac[8]);\n newMac.Append(oldmac[9]);\n newMac.Append(separator);\n newMac.Append(oldmac[6]);\n newMac.Append(oldmac[7]);\n newMac.Append(separator);\n newMac.Append(oldmac[4]);\n newMac.Append(oldmac[5]);\n newMac.Append(separator);\n newMac.Append(oldmac[2]);\n newMac.Append(oldmac[3]);\n newMac.Append(separator);\n newMac.Append(oldmac[0]);\n newMac.Append(oldmac[1]);\n\n return newMac.ToString();\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5993/" ]
187,913
<p>What I'd like to avoid: </p> <pre><code>ManagementClass m = new ManagementClass("Win32_LogicalDisk"); ManagementObjectCollection managementObjects = m.GetInstances(); List&lt;ManagementObject&gt; managementList = new List&lt;ManagementObject&gt;(); foreach(ManagementObject m in managementObjects){ managementList.Add(m); } </code></pre> <p>Isn't there a way to get that collection into a List that looks something like: </p> <pre><code>List&lt;ManagementObject&gt; managementList = new List&lt;ManagementObjec&gt;(collection_array); </code></pre>
[ { "answer_id": 187922, "author": "steffenj", "author_id": 15328, "author_profile": "https://Stackoverflow.com/users/15328", "pm_score": 1, "selected": false, "text": "List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());\n List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count); // or .Length\n" }, { "answer_id": 187923, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();\n ManagementObjectCollection IEnumerable" }, { "answer_id": 187957, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "List<ManagementObject> managementList = new List<ManagementObjec>(managementObjects);\n" }, { "answer_id": 187967, "author": "mancaus", "author_id": 13797, "author_profile": "https://Stackoverflow.com/users/13797", "pm_score": 2, "selected": false, "text": "managementObjects.Cast<ManagementBaseObject>().ToList(); \n public static class Helpers\n {\n public static List<T> CollectionToList<T>(this System.Collections.ICollection other)\n {\n var output = new List<T>(other.Count);\n\n output.AddRange(other.Cast<T>());\n\n return output;\n }\n }\n" }, { "answer_id": 649425, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "Collection<A> obj=new Collection<return ListRetunAPI()>\n" }, { "answer_id": 12517929, "author": "stoto", "author_id": 81641, "author_profile": "https://Stackoverflow.com/users/81641", "pm_score": 2, "selected": false, "text": "List<ManagementObject> managementList = ManagementObjectCollection.OfType<ManagementObject>().ToList();\n" }, { "answer_id": 31767807, "author": "jacobsgriffith", "author_id": 941632, "author_profile": "https://Stackoverflow.com/users/941632", "pm_score": 5, "selected": false, "text": "using System.Linq;\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64/" ]
187,915
<p>How do I detect if a process is already running under the Windows Task Manager? I'd like to get the memory and cpu usage as well. </p>
[ { "answer_id": 187930, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "\"SELECT * FROM Win32_Process WHERE Name = '<your process name here>'\"\n" }, { "answer_id": 187977, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 5, "selected": false, "text": "bool processIsRunning(string process)\n{\n return (System.Diagnostics.Process.GetProcessesByName(process).Length != 0);\n}\n bool processIsRunning(string process)\n{\nSystem.Diagnostics.Process[] processes = \n System.Diagnostics.Process.GetProcessesByName(process);\nforeach (System.Diagnostics.Process proc in processes)\n{\n Console.WriteLine(\"Current physical memory : \" + proc.WorkingSet64.ToString());\n Console.WriteLine(\"Total processor time : \" + proc.TotalProcessorTime.ToString());\n Console.WriteLine(\"Virtual memory size : \" + proc.VirtualMemorySize64.ToString());\n}\nreturn (processes.Length != 0);\n}\n" }, { "answer_id": 187978, "author": "StubbornMule", "author_id": 13341, "author_profile": "https://Stackoverflow.com/users/13341", "pm_score": 2, "selected": false, "text": "Process" }, { "answer_id": 188008, "author": "Millhouse", "author_id": 26500, "author_profile": "https://Stackoverflow.com/users/26500", "pm_score": 2, "selected": false, "text": "System.Diagnostics.Process[] ieProcs = Process.GetProcessesByName(\"IEXPLORE\");\n\nif (ieProcs.Length > 0)\n{\n foreach (System.Diagnostics.Process p in ieProcs)\n { \n String virtualMem = p.VirtualMemorySize64.ToString();\n String physicalMem = p.WorkingSet64.ToString();\n String cpu = p.TotalProcessorTime.ToString(); \n }\n}\n" }, { "answer_id": 188010, "author": "Mike L", "author_id": 12085, "author_profile": "https://Stackoverflow.com/users/12085", "pm_score": 0, "selected": false, "text": "foreach ( WindowsProcess in Process.GetProcesses) \n{ \n if (WindowsProcess.ProcessName == nameOfProcess) { \n Console.WriteLine(WindowsProcess.WorkingSet64.ToString); \n Console.WriteLine(WindowsProcess.UserProcessorTime.ToString); \n Console.WriteLine(WindowsProcess.TotalProcessorTime.ToString); \n } \n} \n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1316/" ]
187,920
<p>I'm logged into a SQL Server 2005 database as a non-sa user, 'bhk', that is a member of the 'public' server role only. The following code tries to execute within a stored procedure called by user 'bhk'. This line of code...</p> <pre><code>TRUNCATE TABLE #Table1 DBCC CHECKIDENT('#Table1', RESEED, @SequenceNumber) WITH NO_INFOMSGS </code></pre> <p>causes this error...</p> <blockquote> <p>User 'guest' does not have permission to run DBCC CHECKIDENT for object<br> '#Table1__00000000007F'.</p> </blockquote> <p>I'm aware of the permissions required to run DBCC CHECKIDENT...<br> <strong><em>Caller must own the table</strong>, or be a member of the sysadmin fixed server role, the db_owner fixed database role, or the db_ddladmin fixed database role.</em></p> <p>So I have two questions:</p> <ol> <li>Since 'bhk' is calling a stored procedure that creates a temporary table, shouldn't 'bhk' be the owner and be allowed to run DBCC CHECKIDENT?</li> <li>Why does the error message return that user 'guest' doesn't have permission? To my knowledge, I'm not logged in as 'guest'.</li> </ol> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 194185, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 2, "selected": false, "text": "CREATE TABLE #NotMyTable (TestID int identity) SELECT user_name(uid) FROM sysobjects WHERE name LIKE '#NotMyTable%'" }, { "answer_id": 197069, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 1, "selected": false, "text": "DROP TABLE #Table1\n\nCREATE TABLE #Table1\n(\n ....\n)\n" }, { "answer_id": 198027, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 4, "selected": true, "text": "TRUNCATE #Table1\n\nSET IDENTITY_INSERT #Table1 ON\n\nINSERT INTO #Table1 (TableID) -- This is your primary key field\nVALUES (@SequenceNumber - 1)\n\nSET IDENTITY_INSERT #Table1 OFF\n\nDELETE FROM #Table1\n" }, { "answer_id": 4935938, "author": "Bob", "author_id": 608486, "author_profile": "https://Stackoverflow.com/users/608486", "pm_score": 2, "selected": false, "text": "DBCC CHECKIDENT([tempdb..#Table1], RESEED, @SequenceNumber) WITH NO_INFOMSGS\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14360/" ]
187,974
<p>I have a simple Word to Pdf converter as an MSBuild Task. The task takes Word files (ITaskItems) as input and Pdf files (ITaskItems) as output. The script uses a Target transform for conversion:</p> <pre><code>&lt;Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="3.5"&gt; &lt;UsingTask AssemblyFile="$(MSBuildExtensionsPath)\MyTasks.dll" TaskName="MyTasks.DocToPdf" /&gt; &lt;Target Name="Build" DependsOnTargets="Convert" /&gt; &lt;Target Name="Convert" Inputs="@(WordDocuments)" Outputs="@(WordDocuments-&gt;'%(FileName).pdf')"&gt; &lt;DocToPdf Inputs="@(WordDocuments)" Outputs="%(FileName).pdf"&gt; &lt;Output TaskParameter="ConvertedFiles" ItemName="PdfDocuments" /&gt; &lt;/DocToPdf&gt; &lt;/Target&gt; &lt;ItemGroup&gt; &lt;WordDocuments Include="One.doc" /&gt; &lt;WordDocuments Include="SubDir\Two.doc" /&gt; &lt;WordDocuments Include="**\*.doc" /&gt; &lt;/ItemGroup&gt; &lt;/Project&gt; </code></pre> <p>What's happening is that SubDir\Two.doc gets converted on every incremental build, One.doc does not (ie MSBuild correctly skips that file because it was already converted). If I use the recursive items spec (the third one above), I get the same behaviour (ie. One.doc only gets converted if the PDF is out of date or missing, but all documents in subdirectories always get converted regardless).</p> <p>What am I doing wrong here?</p>
[ { "answer_id": 188060, "author": "lesscode", "author_id": 18482, "author_profile": "https://Stackoverflow.com/users/18482", "pm_score": 3, "selected": true, "text": " <Target Name=\"Convert\"\n Inputs=\"@(WordDocuments)\"\n Outputs=\"@(WordDocuments->'%(RelativeDir)%(FileName).pdf')\">\n <DocToPdf Inputs=\"%(WordDocuments.Identity)\"\n Outputs=\"%(RelativeDir)%(FileName).pdf\">\n <Output TaskParameter=\"ConvertedFiles\" ItemName=\"PdfDocuments\" />\n </DocToPdf>\n </Target>\n" }, { "answer_id": 193205, "author": "Adam", "author_id": 1341, "author_profile": "https://Stackoverflow.com/users/1341", "pm_score": 0, "selected": false, "text": " <Target Name=\"Build\" Inputs=\"@(RequestTextFiles)\" Outputs=\"@(RequestTextFiles -> '%(Rootdir)%(Directory)%(Filename).out')\">\n\n <DoSomething SourceFiles=\"@(RequestTextFiles)\" />\n\n </Target>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18482/" ]
187,981
<p>I have the following regular expression : I figured out most of the part which is as follows :</p> <pre> ValidationExpression="^[\u0020\u0027\u002C\u002D\u0030-\u0039\u0041-\u005A\u005F\u0061-\u007A\u00C0-\u00FF°&#46;/]{1,256}$" u0020 : SPACE u0027 : APOSTROPHE u002C : COMMA u002D : HYPHEN / MINUS u0030-\u0039\ : 0-9 u0041-\u005A : A - Z u005F : UNDERSCORE u0061-\u007A\ : a - z u00C0-\u00FF°&#46;/ : ?? </pre> <p>Need help in understanding the final part of the validation expression : </p> <pre>u00C0-\u00FF°&#46;/</pre> <p>Anyone has any idea what does this mean?</p>
[ { "answer_id": 49766641, "author": "Roland Illig", "author_id": 225757, "author_profile": "https://Stackoverflow.com/users/225757", "pm_score": 0, "selected": false, "text": "\\u0020\n\\u0027\n\\u002C\n\\u002D\n\\u0030-\\u0039\n\\u0041-\\u005A\n\\u005F\n\\u0061-\\u007A\n\\u00C0-\\u00FF\n°\n.\n/\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24958/" ]
187,983
<p>I have a requirement to hide a process in Task Manager. It is for Intranet scenario. So, everything is legitimate. :) </p> <p>Please feel free to share any code you have (preferably in C#) or any other techniques or any issues in going with this route.</p> <p><strong>Update1</strong>: Most of the users have admin privileges in order to run some legacy apps. So, one of the suggestion was to hide it in task manager. If there are other approaches to prevent users from killing the process, that would be great.</p> <p><strong>Update2</strong>: Removing the reference to rootkit. Somehow made this post look negative.</p>
[ { "answer_id": 188092, "author": "Chris Smith", "author_id": 9073, "author_profile": "https://Stackoverflow.com/users/9073", "pm_score": 4, "selected": false, "text": "DACL_SECURITY_INFORMATION SECURITY_DESCRIPTOR sd;\nACL dacl;\nSID_IDENTIFIER_AUTHORITY ntauth = SECURITY_NT_AUTHORITY;\nPSID owner;\n\nassert(InitializeAcl(&dacl, sizeof dacl, ACL_REVISION));\n\nassert(AllocateAndInitializeSid(&ntauth, 1, SECURITY_LOCAL_SYSTEM_RID, 0,0,0,0,0,0,0, &owner));\n\nassert(InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION));\n\nassert(SetSecurityDescriptorDacl(&sd, TRUE, &dacl, FALSE));\n\nassert(SetSecurityDescriptorOwner(&sd, owner, FALSE));\n\nassert(SetKernelObjectSecurity(GetCurrentProcess(), DACL_SECURITY_INFORMATION | OWNER_SECURITY_INFORMATION, &sd));\n\nassert(FreeSid(owner) == NULL);\n" }, { "answer_id": 14278714, "author": "Cacoon", "author_id": 1948659, "author_profile": "https://Stackoverflow.com/users/1948659", "pm_score": 2, "selected": false, "text": "public static void ToggleTaskManager(bool toggle)\n{\n Microsoft.Win32.RegistryKey HKCU = Microsoft.Win32.Registry.LocalMachine;\n Microsoft.Win32.RegistryKey key = HKCU.CreateSubKey(@\"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System\");\n key.SetValue(\"DisableTaskMgr\", toggle ? 0 : 1, Microsoft.Win32.RegistryValueKind.DWord);\n}\n" }, { "answer_id": 47375461, "author": "E235", "author_id": 2153777, "author_profile": "https://Stackoverflow.com/users/2153777", "pm_score": 2, "selected": false, "text": " using System;\n using System.Collections.Generic;\n using System.ComponentModel;\n using System.Data;\n using System.Drawing;\n using System.Linq;\n using System.Runtime.InteropServices;\n using System.Security.AccessControl;\n using System.Security.Principal;\n using System.Text;\n using System.Threading.Tasks;\n using System.Windows.Forms;\n\nnamespace Hide2\n{\n public partial class Form1 : Form\n {\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool GetKernelObjectSecurity(IntPtr Handle, int securityInformation, [Out] byte[] pSecurityDescriptor,\n uint nLength, out uint lpnLengthNeeded);\n\n public static RawSecurityDescriptor GetProcessSecurityDescriptor(IntPtr processHandle)\n {\n const int DACL_SECURITY_INFORMATION = 0x00000004;\n byte[] psd = new byte[0];\n uint bufSizeNeeded;\n // Call with 0 size to obtain the actual size needed in bufSizeNeeded\n GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, psd, 0, out bufSizeNeeded);\n if (bufSizeNeeded < 0 || bufSizeNeeded > short.MaxValue)\n throw new Win32Exception();\n // Allocate the required bytes and obtain the DACL\n if (!GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION,\n psd = new byte[bufSizeNeeded], bufSizeNeeded, out bufSizeNeeded))\n throw new Win32Exception();\n // Use the RawSecurityDescriptor class from System.Security.AccessControl to parse the bytes:\n return new RawSecurityDescriptor(psd, 0);\n }\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool SetKernelObjectSecurity(IntPtr Handle, int securityInformation, [In] byte[] pSecurityDescriptor);\n\n [DllImport(\"kernel32.dll\")]\n public static extern IntPtr GetCurrentProcess();\n\n [Flags]\n public enum ProcessAccessRights\n {\n PROCESS_CREATE_PROCESS = 0x0080, // Required to create a process.\n PROCESS_CREATE_THREAD = 0x0002, // Required to create a thread.\n PROCESS_DUP_HANDLE = 0x0040, // Required to duplicate a handle using DuplicateHandle.\n PROCESS_QUERY_INFORMATION = 0x0400, // Required to retrieve certain information about a process, such as its token, exit code, and priority class (see OpenProcessToken, GetExitCodeProcess, GetPriorityClass, and IsProcessInJob).\n PROCESS_QUERY_LIMITED_INFORMATION = 0x1000, // Required to retrieve certain information about a process (see QueryFullProcessImageName). A handle that has the PROCESS_QUERY_INFORMATION access right is automatically granted PROCESS_QUERY_LIMITED_INFORMATION. Windows Server 2003 and Windows XP/2000: This access right is not supported.\n PROCESS_SET_INFORMATION = 0x0200, // Required to set certain information about a process, such as its priority class (see SetPriorityClass).\n PROCESS_SET_QUOTA = 0x0100, // Required to set memory limits using SetProcessWorkingSetSize.\n PROCESS_SUSPEND_RESUME = 0x0800, // Required to suspend or resume a process.\n PROCESS_TERMINATE = 0x0001, // Required to terminate a process using TerminateProcess.\n PROCESS_VM_OPERATION = 0x0008, // Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).\n PROCESS_VM_READ = 0x0010, // Required to read memory in a process using ReadProcessMemory.\n PROCESS_VM_WRITE = 0x0020, // Required to write to memory in a process using WriteProcessMemory.\n DELETE = 0x00010000, // Required to delete the object.\n READ_CONTROL = 0x00020000, // Required to read information in the security descriptor for the object, not including the information in the SACL. To read or write the SACL, you must request the ACCESS_SYSTEM_SECURITY access right. For more information, see SACL Access Right.\n SYNCHRONIZE = 0x00100000, // The right to use the object for synchronization. This enables a thread to wait until the object is in the signaled state.\n WRITE_DAC = 0x00040000, // Required to modify the DACL in the security descriptor for the object.\n WRITE_OWNER = 0x00080000, // Required to change the owner in the security descriptor for the object.\n STANDARD_RIGHTS_REQUIRED = 0x000f0000,\n PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF),// All possible access rights for a process object.\n }\n public static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)\n {\n const int DACL_SECURITY_INFORMATION = 0x00000004;\n byte[] rawsd = new byte[dacl.BinaryLength];\n dacl.GetBinaryForm(rawsd, 0);\n if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))\n throw new Win32Exception();\n }\n\n public Form1()\n {\n InitializeComponent();\n\n // Get the current process handle\n IntPtr hProcess = GetCurrentProcess();\n // Read the DACL\n var dacl = GetProcessSecurityDescriptor(hProcess);\n // Insert the new ACE\n dacl.DiscretionaryAcl.InsertAce(\n 0,\n new CommonAce(\n AceFlags.None,\n AceQualifier.AccessDenied,\n (int)ProcessAccessRights.PROCESS_ALL_ACCESS,\n new SecurityIdentifier(WellKnownSidType.WorldSid, null),\n false,\n null)\n );\n // Save the DACL\n SetProcessSecurityDescriptor(hProcess, dacl);\n }\n }\n}\n X $source = @\"\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Runtime.InteropServices;\nusing System.Security.AccessControl;\nusing System.Security.Principal;\n\nnamespace Hide2\n{\n public class myForm\n {\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool GetKernelObjectSecurity(IntPtr Handle, int securityInformation, [Out] byte[] pSecurityDescriptor,\n uint nLength, out uint lpnLengthNeeded);\n\n public static RawSecurityDescriptor GetProcessSecurityDescriptor(IntPtr processHandle)\n {\n const int DACL_SECURITY_INFORMATION = 0x00000004;\n byte[] psd = new byte[0];\n uint bufSizeNeeded;\n // Call with 0 size to obtain the actual size needed in bufSizeNeeded\n GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, psd, 0, out bufSizeNeeded);\n if (bufSizeNeeded < 0 || bufSizeNeeded > short.MaxValue)\n throw new Win32Exception();\n // Allocate the required bytes and obtain the DACL\n if (!GetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION,\n psd = new byte[bufSizeNeeded], bufSizeNeeded, out bufSizeNeeded))\n throw new Win32Exception();\n // Use the RawSecurityDescriptor class from System.Security.AccessControl to parse the bytes:\n return new RawSecurityDescriptor(psd, 0);\n }\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool SetKernelObjectSecurity(IntPtr Handle, int securityInformation, [In] byte[] pSecurityDescriptor);\n\n [DllImport(\"kernel32.dll\")]\n public static extern IntPtr GetCurrentProcess();\n\n [Flags]\n public enum ProcessAccessRights\n {\n PROCESS_CREATE_PROCESS = 0x0080, // Required to create a process.\n PROCESS_CREATE_THREAD = 0x0002, // Required to create a thread.\n PROCESS_DUP_HANDLE = 0x0040, // Required to duplicate a handle using DuplicateHandle.\n PROCESS_QUERY_INFORMATION = 0x0400, // Required to retrieve certain information about a process, such as its token, exit code, and priority class (see OpenProcessToken, GetExitCodeProcess, GetPriorityClass, and IsProcessInJob).\n PROCESS_QUERY_LIMITED_INFORMATION = 0x1000, // Required to retrieve certain information about a process (see QueryFullProcessImageName). A handle that has the PROCESS_QUERY_INFORMATION access right is automatically granted PROCESS_QUERY_LIMITED_INFORMATION. Windows Server 2003 and Windows XP/2000: This access right is not supported.\n PROCESS_SET_INFORMATION = 0x0200, // Required to set certain information about a process, such as its priority class (see SetPriorityClass).\n PROCESS_SET_QUOTA = 0x0100, // Required to set memory limits using SetProcessWorkingSetSize.\n PROCESS_SUSPEND_RESUME = 0x0800, // Required to suspend or resume a process.\n PROCESS_TERMINATE = 0x0001, // Required to terminate a process using TerminateProcess.\n PROCESS_VM_OPERATION = 0x0008, // Required to perform an operation on the address space of a process (see VirtualProtectEx and WriteProcessMemory).\n PROCESS_VM_READ = 0x0010, // Required to read memory in a process using ReadProcessMemory.\n PROCESS_VM_WRITE = 0x0020, // Required to write to memory in a process using WriteProcessMemory.\n DELETE = 0x00010000, // Required to delete the object.\n READ_CONTROL = 0x00020000, // Required to read information in the security descriptor for the object, not including the information in the SACL. To read or write the SACL, you must request the ACCESS_SYSTEM_SECURITY access right. For more information, see SACL Access Right.\n SYNCHRONIZE = 0x00100000, // The right to use the object for synchronization. This enables a thread to wait until the object is in the signaled state.\n WRITE_DAC = 0x00040000, // Required to modify the DACL in the security descriptor for the object.\n WRITE_OWNER = 0x00080000, // Required to change the owner in the security descriptor for the object.\n STANDARD_RIGHTS_REQUIRED = 0x000f0000,\n PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF),// All possible access rights for a process object.\n }\n public static void SetProcessSecurityDescriptor(IntPtr processHandle, RawSecurityDescriptor dacl)\n {\n const int DACL_SECURITY_INFORMATION = 0x00000004;\n byte[] rawsd = new byte[dacl.BinaryLength];\n dacl.GetBinaryForm(rawsd, 0);\n if (!SetKernelObjectSecurity(processHandle, DACL_SECURITY_INFORMATION, rawsd))\n throw new Win32Exception();\n }\n\n public static void ProtectMyProcess()\n {\n // Get the current process handle\n IntPtr hProcess = GetCurrentProcess();\n // Read the DACL\n var dacl = GetProcessSecurityDescriptor(hProcess);\n // Insert the new ACE\n dacl.DiscretionaryAcl.InsertAce(\n 0,\n new CommonAce(\n AceFlags.None,\n AceQualifier.AccessDenied,\n (int)ProcessAccessRights.PROCESS_ALL_ACCESS,\n new SecurityIdentifier(WellKnownSidType.WorldSid, null),\n false,\n null)\n );\n // Save the DACL\n SetProcessSecurityDescriptor(hProcess, dacl);\n\n }\n }\n}\n\"@\n\nAdd-Type -TypeDefinition $Source -Language CSharp \n\n[ScriptBlock]$scriptNewForm = {\n Add-Type -AssemblyName System.Windows.Forms\n\n $Form = New-Object system.Windows.Forms.Form\n $Form.Text = \"PowerShell form\"\n $Form.TopMost = $true\n $Form.Width = 303\n $Form.Height = 274\n\n [void]$Form.ShowDialog()\n $Form.Dispose()\n}\n\n\n\n$SleepTimer = 200\n$MaxResultTime = 120\n$MaxThreads = 3\n\n$ISS = [system.management.automation.runspaces.initialsessionstate]::CreateDefault()\n$RunspacePool = [runspacefactory]::CreateRunspacePool(1, $MaxThreads, $ISS, $Host)\n$RunspacePool.Open()\n\n$Jobs = @()\n\n$PowershellThread = [powershell]::Create().AddScript($scriptNewForm)\n$PowershellThread.RunspacePool = $RunspacePool\n$Handle = $PowershellThread.BeginInvoke()\n$Job = \"\" | Select-Object Handle, Thread, object\n$Job.Handle = $Handle\n$Job.Thread = $PowershellThread\n$Job.Object = $computer\n$Jobs += $Job\n\n[Hide2.myForm]::ProtectMyProcess()\n\n<#\nForEach ($Job in $Jobs){\n $Job.Thread.EndInvoke($Job.Handle)\n $Job.Thread.Dispose()\n $Job.Thread = $Null\n $Job.Handle = $Null\n}\n#>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337/" ]
187,990
<p>I'm not a C++ developer, but I've always been interested in compilers, and I'm interested in tinkering with some of the GCC stuff (particularly LLVM).</p> <p>On Windows, GCC requires a POSIX-emulation layer (cygwin or MinGW) to run correctly.</p> <p>Why is that?</p> <p>I use lots of other software, written in C++ and cross-compiled for different platforms (Subversion, Firefox, Apache, MySQL), and none of them require cygwin or MinGW.</p> <p>My understanding about C++ best-practice programming is that you can write reasonably platform-neutral code and deal with all the differences during the compilation process.</p> <p>So what's the deal with GCC? Why can't it run natively on Windows?</p> <hr> <p>EDIT:</p> <p>Okay, the two replies so far say, basically, "GCC uses the posix layer because it uses the posix headers".</p> <p>But that doesn't really answer the question.</p> <p>Let's say I already have a set of headers for my favorite standard library. Why would I still need the posix headers?</p> <p>Does GCC require cygwin/mingw to actually <em>RUN</em>?</p> <p>Or does it only need the emulation layer for headers and libraries? If so, why can't I just give it a "lib" directory with the required resources?</p> <hr> <p>EDIT AGAIN:</p> <p>Okay, I'll try again to clarify the question...</p> <p>I also write code in <a href="http://digitalmars.com/d" rel="noreferrer">the D Programming Language</a>. The official compiler is named "dmd" and there are official compiler binaries for both Windows and linux.</p> <p>The Windows version doesn't require any kind of POSIX emulation. And the Linux version doesn't require any kind of Win32 emulation. If the compiler has assumptions about its environment, it hides those assumptions pretty well.</p> <p>Of course, I have to tell the compiler where to find the standard library and where to find libraries to statically or dynamically link against.</p> <p>GCC, by contrast, insists on pretending it's operating within a posix environment, and it asks ME to humor those assumptions by setting up an emulation layer.</p> <p>But what, exactly, within GCC relies on that layer? Is it just looking for stdlib headers, and it assumes it'll find those headers within "/usr/lib"?</p> <p>If that's the case, shouldn't I just be able to tell it to look in "C:/gcc/lib" to find those header files?</p> <p>Or does GCC itself rely on the POSIX libraries to access the file system (and to do other low-level stuff)? If that's the case, then I wonder why they don't just statically link with their favorite windows POSIX libraries. Why require the user to set up the dependencies, when they could build those dependencies right into the application?</p>
[ { "answer_id": 354767, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 5, "selected": false, "text": "cygwin1.dll fork() mmap() ioctl()" }, { "answer_id": 764852, "author": "Artyom", "author_id": 66522, "author_profile": "https://Stackoverflow.com/users/66522", "pm_score": 2, "selected": false, "text": "readdir stat" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22979/" ]
187,998
<p>Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it's possible to do:</p> <pre><code>SELECT * FROM MyTable OFFSET 50 LIMIT 25 </code></pre> <p>to get results 51-75. This construct does not appear to exist in SQL Server. </p> <p>How can I accomplish this without loading all the rows I don't care about? Thanks! </p>
[ { "answer_id": 188031, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 2, "selected": false, "text": "select top 25 *\nfrom ( \n select top 75 *\n from table \n order by field asc\n) a \norder by field desc \n" }, { "answer_id": 188040, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 5, "selected": false, "text": "SELECT * FROM\n(\n SELECT TOP (@pageSize) * FROM\n (\n SELECT TOP (@pageNumber * @pageSize) *\n FROM tableName \n ORDER BY columnName ASC\n ) AS t1 \n ORDER BY columnName DESC\n) AS t2 \nORDER BY columnName ASC\n ;WITH results AS (\n SELECT \n rowNo = ROW_NUMBER() OVER( ORDER BY columnName ASC )\n , *\n FROM tableName \n) \nSELECT * \nFROM results\nWHERE rowNo between (@pageNumber-1)*@pageSize+1 and @pageNumber*@pageSize\n" }, { "answer_id": 188044, "author": "Brian Kim", "author_id": 5704, "author_profile": "https://Stackoverflow.com/users/5704", "pm_score": 8, "selected": true, "text": "SELECT * SELECT col1, col2 \nFROM (\n SELECT col1, col2, ROW_NUMBER() OVER (ORDER BY ID) AS RowNum\n FROM MyTable\n) AS MyDerivedTable\nWHERE MyDerivedTable.RowNum BETWEEN @startRow AND @endRow\n" }, { "answer_id": 188053, "author": "Matthias Meid", "author_id": 17713, "author_profile": "https://Stackoverflow.com/users/17713", "pm_score": 4, "selected": false, "text": "ROW_NUMBER() SELECT *\nFROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t\nWHERE RowNr BETWEEN 10 AND 20\n" }, { "answer_id": 188061, "author": "Aheho", "author_id": 21155, "author_profile": "https://Stackoverflow.com/users/21155", "pm_score": 1, "selected": false, "text": "DECLARE @Limit INT\nDECLARE @Offset INT\nSET @Offset = 120000\nSET @Limit = 10\n\nSELECT \n * \nFROM\n(\n SELECT \n row_number() \n OVER \n (ORDER BY column) AS rownum, column2, column3, .... columnX\n FROM \n table\n) AS A\nWHERE \n A.rownum BETWEEN (@Offset) AND (@Offset + @Limit-1) \n" }, { "answer_id": 1809287, "author": "Patrik Melander", "author_id": 220100, "author_profile": "https://Stackoverflow.com/users/220100", "pm_score": 2, "selected": false, "text": "ROW_NUMBER() OVER (ORDER BY) ROW_NUMBER() DECLARE @Offset INT = 120000\nDECLARE @Limit INT = 10\n\nDECLARE @ROWCOUNT INT = @Offset+@Limit\nSET ROWCOUNT @ROWCOUNT\n\nSELECT * FROM MyTable INTO #ResultSet\nWHERE MyTable.Type = 1\n\nSELECT * FROM\n(\n SELECT *, ROW_NUMBER() OVER(ORDER BY SortConst ASC) As RowNumber FROM\n (\n SELECT *, 1 As SortConst FROM #ResultSet\n ) AS ResultSet\n) AS Page\nWHERE RowNumber BETWEEN @Offset AND @ROWCOUNT\n\nDROP TABLE #ResultSet\n" }, { "answer_id": 5525978, "author": "Martin Smith", "author_id": 73226, "author_profile": "https://Stackoverflow.com/users/73226", "pm_score": 7, "selected": false, "text": "TOP (25) ... WHERE Key > @last_key ORDER BY Key ROW_NUMBER BETWEEN SELECT *\nFROM MyTable \nORDER BY OrderingColumn ASC \nOFFSET 50 ROWS \nFETCH NEXT 25 ROWS ONLY \n" }, { "answer_id": 10145878, "author": "Capilé", "author_id": 819311, "author_profile": "https://Stackoverflow.com/users/819311", "pm_score": 0, "selected": false, "text": "SET ROWCOUNT [OFFSET+LIMIT] SET ROWCOUNT 75 -- (50 + 25)\nDECLARE MyCursor SCROLL CURSOR FOR SELECT * FROM pessoas\nOPEN MyCursor\nFETCH ABSOLUTE 50 FROM MyCursor -- OFFSET\nWHILE @@FETCH_STATUS = 0 BEGIN\n FETCH next FROM MyCursor\nEND\nCLOSE MyCursor\nDEALLOCATE MyCursor\nSET ROWCOUNT 0\n" }, { "answer_id": 13072194, "author": "Arthur van Dijk", "author_id": 1774650, "author_profile": "https://Stackoverflow.com/users/1774650", "pm_score": 3, "selected": false, "text": "SELECT \n tablename.col1,\n tablename.col2,\n tablename.col3,\n ...\nFROM\n(\n (\n SELECT\n col1\n FROM \n (\n SELECT col1, ROW_NUMBER() OVER (ORDER BY col1 ASC) AS RowNum\n FROM tablename\n WHERE ([CONDITION])\n )\n AS T1 WHERE T1.RowNum BETWEEN [OFFSET] AND [OFFSET + LIMIT]\n )\n AS T2 INNER JOIN tablename ON T2.col1=tablename.col1\n);\n [CONDITION] can contain any WHERE clause for searching.\n[OFFSET] specifies the start,\n[LIMIT] the maximum results.\n" }, { "answer_id": 15487131, "author": "Ravi Ramaswamy", "author_id": 2184090, "author_profile": "https://Stackoverflow.com/users/2184090", "pm_score": 1, "selected": false, "text": "ID, KeyId, Rank\n select top 2 * from Table1 where Rank >= @Rank and ID > @Id 11 21 1\n14 22 1\n7 11 1\n6 19 2\n12 31 2\n13 18 2\n" }, { "answer_id": 20749237, "author": "PerfectLion", "author_id": 3130456, "author_profile": "https://Stackoverflow.com/users/3130456", "pm_score": 3, "selected": false, "text": "SELECT TOP @limit * FROM (\n SELECT ROW_NUMBER() OVER (ORDER BY colunx ASC) offset, * FROM (\n\n -- YOU SELECT HERE\n SELECT * FROM mytable\n\n\n ) myquery\n) paginator\nWHERE offset > @offset\n" }, { "answer_id": 23613493, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 3, "selected": false, "text": "OFFSET .. FETCH ORDER BY ORDER BY SELECT * FROM MyTable \nORDER BY @@VERSION \nOFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY\n SELECT * FROM MyTable \nORDER BY (SELECT 0)\nOFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY\n" }, { "answer_id": 23777477, "author": "Jithin Shaji", "author_id": 3265371, "author_profile": "https://Stackoverflow.com/users/3265371", "pm_score": 2, "selected": false, "text": "SELECT TOP 75 * FROM MyTable\nEXCEPT \nSELECT TOP 50 * FROM MyTable\n" }, { "answer_id": 30094393, "author": "Shb", "author_id": 4281154, "author_profile": "https://Stackoverflow.com/users/4281154", "pm_score": 2, "selected": false, "text": "SELECT * FROM MyTable ORDER BY ID OFFSET 50 ROWS FETCH NEXT 25 ROWS ONLY;\n" }, { "answer_id": 41661284, "author": "8Unlimited8", "author_id": 3526863, "author_profile": "https://Stackoverflow.com/users/3526863", "pm_score": 1, "selected": false, "text": "select 0 as tmp,Column1 from Table1 Order by tmp OFFSET 5000000 ROWS FETCH NEXT 50 ROWS ONLY\n" }, { "answer_id": 61351735, "author": "Tejasvi Hegde", "author_id": 1726296, "author_profile": "https://Stackoverflow.com/users/1726296", "pm_score": 1, "selected": false, "text": "USE AdventureWorks2012; \nGO \n-- Specifying variables for OFFSET and FETCH values \nDECLARE @skip int = 0 , @take int = 8; \nSELECT DepartmentID, Name, GroupName \nFROM HumanResources.Department \nORDER BY DepartmentID ASC \n OFFSET @skip ROWS \n FETCH NEXT @take ROWS ONLY; \n" }, { "answer_id": 68969012, "author": "mrsagar105", "author_id": 15160381, "author_profile": "https://Stackoverflow.com/users/15160381", "pm_score": 0, "selected": false, "text": "SELECT *\nFROM MyTable\nLIMIT 25\nOFFSET 50\n SELECT *\nFROM MyTable\nLIMIT 50, 25\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420/" ]
187,999
<p>One small function of a large program examines assemblies in a folder and replaces out-of-date assemblies with the latest versions. To accomplish this, it needs to read the version numbers of the existing assembly files without actually loading those assemblies into the executing process.</p>
[ { "answer_id": 188036, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 3, "selected": false, "text": "AssemblyName.GetAssemblyName(\"assembly.dll\");" }, { "answer_id": 188038, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 6, "selected": true, "text": "using System.Reflection;\nusing System.IO;\n\n...\n\n// Get current and updated assemblies\nAssemblyName currentAssemblyName = AssemblyName.GetAssemblyName(currentAssemblyPath);\nAssemblyName updatedAssemblyName = AssemblyName.GetAssemblyName(updatedAssemblyPath);\n\n// Compare both versions\nif (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) <= 0)\n{\n // There's nothing to update\n return;\n}\n\n// Update older version\nFile.Copy(updatedAssemblyPath, currentAssemblyPath, true);\n" }, { "answer_id": 188045, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "FileVersionInfo FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(path)\nstring ver = fvi.FileVersion;\n [AssemblyFileVersion] [AssemblyVersion]" }, { "answer_id": 21755415, "author": "Bjørn", "author_id": 3306167, "author_profile": "https://Stackoverflow.com/users/3306167", "pm_score": 2, "selected": false, "text": "public static Version GetFileVersionCe(string fileName)\n{\n int handle = 0;\n int length = GetFileVersionInfoSize(fileName, ref handle);\n Version v = null;\n if (length > 0)\n {\n IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal(length);\n if (GetFileVersionInfo(fileName, handle, length, buffer))\n {\n IntPtr fixedbuffer = IntPtr.Zero;\n int fixedlen = 0;\n if (VerQueryValue(buffer, \"\\\\\", ref fixedbuffer, ref fixedlen))\n {\n byte[] fixedversioninfo = new byte[fixedlen];\n System.Runtime.InteropServices.Marshal.Copy(fixedbuffer, fixedversioninfo, 0, fixedlen);\n v = new Version(\n BitConverter.ToInt16(fixedversioninfo, 10), \n BitConverter.ToInt16(fixedversioninfo, 8), \n BitConverter.ToInt16(fixedversioninfo, 14),\n BitConverter.ToInt16(fixedversioninfo, 12));\n }\n }\n Marshal.FreeHGlobal(buffer);\n }\n return v;\n}\n\n[DllImport(\"coredll\", EntryPoint = \"GetFileVersionInfo\", SetLastError = true)]\nprivate static extern bool GetFileVersionInfo(string filename, int handle, int len, IntPtr buffer);\n[DllImport(\"coredll\", EntryPoint = \"GetFileVersionInfoSize\", SetLastError = true)]\nprivate static extern int GetFileVersionInfoSize(string filename, ref int handle);\n[DllImport(\"coredll\", EntryPoint = \"VerQueryValue\", SetLastError = true)]\nprivate static extern bool VerQueryValue(IntPtr buffer, string subblock, ref IntPtr blockbuffer, ref int len);\n" }, { "answer_id": 66390504, "author": "Eric Patrick", "author_id": 1088293, "author_profile": "https://Stackoverflow.com/users/1088293", "pm_score": 0, "selected": false, "text": ".netcore using System.IO;\nusing System.Reflection;\nusing System.Runtime.Loader;\n\n...\n\n// Get current and updated assemblies\nAssemblyName currentAssemblyName = AssemblyLoadContext.GetAssemblyName(currentAssemblyPath);\nAssemblyName updatedAssemblyName = AssemblyLoadContext.GetAssemblyName(updatedAssemblyPath);\n\n// Compare both versions\nif (updatedAssemblyName.Version.CompareTo(currentAssemblyName.Version) <= 0)\n{\n // There's nothing to update\n return;\n}\n\n// Update older version\nFile.Copy(updatedAssemblyPath, currentAssemblyPath, true);\n AppDomain" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/187999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26553/" ]
188,001
<p>I am attempting to rewrite my <a href="http://ForestPad.com" rel="nofollow noreferrer">ForestPad</a> application utilizing WPF for the presentation layer. In WinForms, I am populating each node programmatically but I would like to take advantage of the databinding capabilities of WPF, if possible.</p> <p>In general, what is the best way to two-way databind the WPF TreeView to an Xml document?</p> <p>A generic solution is fine but for reference, the structure of the Xml document that I am trying to bind to looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;forestPad guid="6c9325de-dfbe-4878-9d91-1a9f1a7696b0" created="5/14/2004 1:05:10 AM" updated="5/14/2004 1:07:41 AM"&gt; &lt;forest name="A forest node" guid="b441a196-7468-47c8-a010-7ff83429a37b" created="01/01/2003 1:00:00 AM" updated="5/14/2004 1:06:15 AM"&gt; &lt;data&gt; &lt;![CDATA[A forest node This is the text of the forest node.]]&gt; &lt;/data&gt; &lt;tree name="A tree node" guid="768eae66-e9df-4999-b950-01fa9be1a5cf" created="5/14/2004 1:05:38 AM" updated="5/14/2004 1:06:11 AM"&gt; &lt;data&gt; &lt;![CDATA[A tree node This is the text of the tree node.]]&gt; &lt;/data&gt; &lt;branch name="A branch node" guid="be4b0993-d4e4-4249-8aa5-fa9c940ae2be" created="5/14/2004 1:06:00 AM" updated="5/14/2004 1:06:24 AM"&gt; &lt;data&gt; &lt;![CDATA[A branch node This is the text of the branch node.]]&gt;&lt;/data&gt; &lt;leaf name="A leaf node" guid="9c76ff4e-3ae2-450e-b1d2-232b687214aa" created="5/14/2004 1:06:26 AM" updated="5/14/2004 1:06:38 AM"&gt; &lt;data&gt; &lt;![CDATA[A leaf node This is the text of the leaf node.]]&gt; &lt;/data&gt; &lt;/leaf&gt; &lt;/branch&gt; &lt;/tree&gt; &lt;/forest&gt; &lt;/forestPad&gt; </code></pre>
[ { "answer_id": 188084, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 4, "selected": true, "text": "<node type=\"forest\">\n <node type=\"tree\">\n ...\n HierarchicalDataTemplate DataTemplate leaf <Window.Resources>\n <HierarchicalDataTemplate\n DataType=\"forestPad\"\n ItemsSource=\"{Binding XPath=forest}\">\n <TextBlock\n Text=\"a forestpad\" />\n </HierarchicalDataTemplate>\n <HierarchicalDataTemplate\n DataType=\"forest\"\n ItemsSource=\"{Binding XPath=tree}\">\n <TextBox\n Text=\"{Binding XPath=data}\" />\n </HierarchicalDataTemplate>\n <HierarchicalDataTemplate\n DataType=\"tree\"\n ItemsSource=\"{Binding XPath=branch}\">\n <TextBox\n Text=\"{Binding XPath=data}\" />\n </HierarchicalDataTemplate>\n <HierarchicalDataTemplate\n DataType=\"branch\"\n ItemsSource=\"{Binding XPath=leaf}\">\n <TextBox\n Text=\"{Binding XPath=data}\" />\n </HierarchicalDataTemplate>\n <DataTemplate\n DataType=\"leaf\">\n <TextBox\n Text=\"{Binding XPath=data}\" />\n </DataTemplate>\n\n <XmlDataProvider\n x:Key=\"dataxml\"\n XPath=\"forestPad\" Source=\"D:\\fp.xml\">\n </XmlDataProvider>\n</Window.Resources>\n Source XmlDataProvider dp = this.FindResource( \"dataxml\" ) as XmlDataProvider;\ndp.Source = new Uri( @\"D:\\fp.xml\" );\n dp.Document.Save( dp.Source.LocalPath );\n TreeView Name ItemsSource XmlDataProvider <TreeView\n Name=\"treeview\"\n ItemsSource=\"{Binding Source={StaticResource dataxml}, XPath=.}\">\n TwoWay TextBox TextBox TreeView TextBox TextBlock TextBox TreeViewItem <TextBox\n DataContext=\"{Binding ElementName=treeview, Path=SelectedItem}\"\n Text=\"{Binding XPath=data, UpdateSourceTrigger=PropertyChanged}\"/>\n Binding Path XPath InnerXml InnerText XmlDataProvider XmlDocument XmlNodes InnerXml XmlNode InnerXml InnerText InnerText XmlDocument doc = dp.Document;\n\nXmlNodeList nodes = doc.SelectNodes( \"//data\" );\n\nforeach ( XmlNode node in nodes ) {\n string data = node.InnerText;\n node.InnerText = \"\";\n XmlCDataSection cdata = doc.CreateCDataSection( data );\n node.AppendChild( cdata );\n}\n\ndoc.Save( dp.Source.LocalPath );\n" }, { "answer_id": 71343808, "author": "B. Fuller", "author_id": 5552085, "author_profile": "https://Stackoverflow.com/users/5552085", "pm_score": 1, "selected": false, "text": "HierarchicalDataTemplate XPath=tree|branch|leaf <HierarchicalDataTemplate x:Key=\"forestTemplate\"\n ItemsSource=\"{Binding XPath=tree|branch|leaf}\">\n <TextBlock Text=\"{Binding XPath=data}\" />\n</HierarchicalDataTemplate>\n Page XmlDataProvider1 <Page \n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <Page.Resources>\n <XmlDataProvider x:Key=\"sampleForestPad\" XPath=\"forestPad/forest\">\n <x:XData>\n <forestPad xmlns=\"\"\n guid=\"6c9325de-dfbe-4878-9d91-1a9f1a7696b0\"\n created=\"5/14/2004 1:05:10 AM\"\n updated=\"5/14/2004 1:07:41 AM\">\n <forest \n name=\"A forest node\"\n guid=\"b441a196-7468-47c8-a010-7ff83429a37b\"\n created=\"01/01/2003 1:00:00 AM\"\n updated=\"5/14/2004 1:06:15 AM\">\n <data>\n <![CDATA[A forest node\n This is the text of the forest node.]]>\n </data>\n <tree\n name=\"A tree node\"\n guid=\"768eae66-e9df-4999-b950-01fa9be1a5cf\"\n created=\"5/14/2004 1:05:38 AM\"\n updated=\"5/14/2004 1:06:11 AM\">\n <data>\n <![CDATA[A tree node\n This is the text of the tree node.]]>\n </data>\n <branch\n name=\"A branch node\"\n guid=\"be4b0993-d4e4-4249-8aa5-fa9c940ae2be\"\n created=\"5/14/2004 1:06:00 AM\"\n updated=\"5/14/2004 1:06:24 AM\">\n <data>\n <![CDATA[A branch node\n This is the text of the branch node.]]></data>\n <leaf\n name=\"A leaf node\"\n guid=\"9c76ff4e-3ae2-450e-b1d2-232b687214aa\"\n created=\"5/14/2004 1:06:26 AM\"\n updated=\"5/14/2004 1:06:38 AM\">\n <data>\n <![CDATA[A leaf node\n This is the text of the leaf node.]]>\n </data>\n </leaf>\n </branch>\n </tree>\n </forest>\n </forestPad>\n </x:XData>\n </XmlDataProvider>\n\n <HierarchicalDataTemplate x:Key=\"forestTemplate\"\n ItemsSource=\"{Binding XPath=tree|branch|leaf}\">\n <TextBlock Text=\"{Binding XPath=data}\" />\n </HierarchicalDataTemplate>\n\n <Style TargetType=\"TreeViewItem\">\n <Setter Property=\"IsExpanded\" Value=\"True\"/>\n </Style>\n </Page.Resources>\n\n <TreeView ItemsSource=\"{Binding Source={StaticResource sampleForestPad}}\"\n ItemTemplate=\"{StaticResource forestTemplate}\"/>\n</Page>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12919/" ]
188,007
<p>I'm using my code-behind page to create a save button programmatically:</p> <pre><code> Button btnSave = new Button(); btnSave.ID = "btnSave"; btnSave.Text = "Save"; </code></pre> <p>However I think this must create an html button or perhaps needs something else as I cannot seem to set the OnClick attribute in the following line, I can specify OnClientClick but this isn't the one I want to set.</p>
[ { "answer_id": 188021, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": false, "text": "//Add the handler to your button, passing the name of the handling method \nbtnSave.Click += new System.EventHandler(btnSave_Click);\n\nprotected void btnSave_Click(object sender, EventArgs e)\n{\n //Your custom code goes here\n}\n" }, { "answer_id": 188056, "author": "Erikk Ross", "author_id": 18772, "author_profile": "https://Stackoverflow.com/users/18772", "pm_score": 5, "selected": true, "text": "Button btnSave = new Button(); \nbtnSave.ID = \"btnSave\"; \nbtnSave.Text = \"Save\"; \nbtnSave.Click += new System.EventHandler(btnSave_Click);\n\nprotected void btnSave_Click(object sender, EventArgs e)\n{\n //do something when button clicked. \n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26126/" ]
188,030
<p>I want to program graphical 2D games more complex than the basic 2D stuff I already know. I don't want to do 3D programming. Just more complex 2D stuff. I dropped high school before I could learn a lot of stuff so I walked away with enough algebra knowledge to balance my checkbook and do some light 2D Cartesian programming.</p> <p>Are there any good resources out there for a guy with a limited attention span (say 20 minutes apiece for a subject I'm keenly interested in) to learn, gradually, how to do something more useful with math in programming?</p>
[ { "answer_id": 15651914, "author": "superlogical", "author_id": 52360, "author_profile": "https://Stackoverflow.com/users/52360", "pm_score": 1, "selected": false, "text": "1. VECTORS\n2. FORCES\n3. OSCILLATION\n4. PARTICLE SYSTEMS\n5. PHYSICS LIBRARIES\n6. AUTONOMOUS AGENTS\n7. CELLULAR AUTOMATA\n8. FRACTALS\n9. THE EVOLUTION OF CODE\n10. NEURAL NETWORKS\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26557/" ]
188,057
<p>Quick question. What do you think, I have a few sites that use a 3 level drop-down menu that will be broken if IE8 released with its current CSS standards in IE8 beta2. So do I take the time to redo those drop downs now? I realize that the way they rendered CSS changed completely between beta 1 and 2, but 2 was/is supposed the be a general use beta and seeing as it is the final beta you would think something as crucial as CSS rendering would have been touched up to work properly.</p> <p>So what do you think, do you wait until 80% (random statistic) of ie7 users automatically update to IE8 and then worry about a broken navigation menu if it still exists. Or do you waste the time now. </p> <p>... if I had it my way all web developers would just make sure that their page did not work in IE8 and then Microsoft would be forced to properly handle CSS.... But I don't usually get things my way.</p>
[ { "answer_id": 188066, "author": "Gabriel Isenberg", "author_id": 1473493, "author_profile": "https://Stackoverflow.com/users/1473493", "pm_score": 4, "selected": true, "text": "<head>\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=EmulateIE7\"/>\n ...\n</head>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19226/" ]
188,098
<p>I have a problem when an unhandeld exception occurs while debugging a WinForm VB.NET project.</p> <p>The problem is that my application terminates and I have to start the application again, instead of retrying the action as was the case in VS2003</p> <p>The unhandeld exception is implemented in the new My.MyApplication class found in ApplicationEvents.vb</p> <pre><code>Private Sub MyApplication_UnhandledException(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException Dim handler As New GlobalErrorHandler() handler.HandleError(e.Exception) e.ExitApplication = False End Sub </code></pre> <p>Note: handler.HandleError just shows a dialog box and logs the error to a log file.</p> <p>I also tried the following code that used to work in VS2003 but it results in the same behaviour when run in VS2008:</p> <pre><code> AddHandler System.Windows.Forms.Application.ThreadException, AddressOf OnApplicationErrorHandler AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf OnUnhandledExceptionHandler </code></pre> <p>OnApplicationErrorHandler and OnUnhandledExceptionHandler does the same as handle.HandleError</p> <p>Running the application outside VS2008 results in the expected behaviour (the application doesn't terminate) but it is increasing our test cycle during debugging.</p> <p><strong>Update:</strong> I have added sample code in my answer to demonstrate this problem in C#</p>
[ { "answer_id": 190244, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Windows.Forms;\nnamespace TestCSharpUnhandledException\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n\n Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n }\n\n void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n MessageBox.Show(\"Oops an unhandled exception, terminating:\" + e.IsTerminating); \n }\n\n void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)\n {\n MessageBox.Show(\"Oops an unhandled thread exception\");\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n throw new Exception(\"Dummy unhandled exception\");\n }\n }\n}\n" }, { "answer_id": 190269, "author": "Philip Fourie", "author_id": 11123, "author_profile": "https://Stackoverflow.com/users/11123", "pm_score": 2, "selected": true, "text": "Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11123/" ]
188,114
<p>I'm trying to write a log file from an ASP.NET application under IIS7, but keep getting the following exception:</p> <blockquote> <p>UnauthorizedAccessException "Access to the path 'C:\Users\Brady\Exports' is denied."</p> </blockquote> <p>I have given write access to the iis_iusrs, iis_wpg, and aspnet users, based on various advices found by Google, but still get the error. Can someone please explain how I can create a log file in that directory, or, will creating a log directory under the web application itself automatically allow writing the file, and is this not perhaps a better solution?</p>
[ { "answer_id": 188125, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": true, "text": "ASPNET - Win XP and Win 2000\nNETWORK SERVICE - Win Vista and 2003\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
188,118
<p>I've tried this, but it doesn't work:</p> <pre><code>col * format a20000 </code></pre> <p>Do I really have to list every column specifically? That is a huge pain in the arse.</p>
[ { "answer_id": 188135, "author": "someguy", "author_id": 8913, "author_profile": "https://Stackoverflow.com/users/8913", "pm_score": 5, "selected": false, "text": "set wrap off\nset linesize 3000 -- (or to a sufficiently large value to hold your results page)\n show all\n" }, { "answer_id": 188144, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 5, "selected": false, "text": "SET NEWPAGE NONE\nSET PAGESIZE 0\nSET SPACE 0\nSET LINESIZE 16000\nSET ECHO OFF\nSET FEEDBACK OFF\nSET VERIFY OFF\nSET HEADING OFF\nSET TERMOUT OFF\nSET TRIMOUT ON\nSET TRIMSPOOL ON\nSET COLSEP |\n\nspool &1..txt\n\n@@&1\n\nspool off\nexit\n sqlplus -S user/password@database @dump.sql my_real_query.sql\n my_real_query.sql.txt" }, { "answer_id": 44264587, "author": "Camilo Peña", "author_id": 6851347, "author_profile": "https://Stackoverflow.com/users/6851347", "pm_score": 0, "selected": false, "text": "set WRAP OFF\nset PAGESIZE 0\n" }, { "answer_id": 48007491, "author": "Aziz Zoaib", "author_id": 9138097, "author_profile": "https://Stackoverflow.com/users/9138097", "pm_score": 1, "selected": false, "text": "set linesize 3000\n\nset wrap off\n\nset termout off\n\nset pagesize 0 embedded on\n\nset trimspool on\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8913/" ]
188,120
<p>So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ. Sometimes, I need to compare user-defined types that don't have a built-in comparison operator. In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key. Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions? Something like:</p> <pre><code>var f1 = ..., f2 = ...; var f3 = f1.Except( f2, new IEqualityComparer( (Foo a, Foo b) => a.key.CompareTo(b.key) ) ); </code></pre> <p>I'm pretty sure the above doesn't actually work. I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.</p>
[ { "answer_id": 188130, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "using System;\nusing System.Collections.Generic;\n\n/// <summary>\n/// Non-generic class to produce instances of the generic class,\n/// optionally using type inference.\n/// </summary>\npublic static class ProjectionEqualityComparer\n{\n /// <summary>\n /// Creates an instance of ProjectionEqualityComparer using the specified projection.\n /// </summary>\n /// <typeparam name=\"TSource\">Type parameter for the elements to be compared</typeparam>\n /// <typeparam name=\"TKey\">Type parameter for the keys to be compared,\n /// after being projected from the elements</typeparam>\n /// <param name=\"projection\">Projection to use when determining the key of an element</param>\n /// <returns>A comparer which will compare elements by projecting \n /// each element to its key, and comparing keys</returns>\n public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>(Func<TSource, TKey> projection)\n {\n return new ProjectionEqualityComparer<TSource, TKey>(projection);\n }\n\n /// <summary>\n /// Creates an instance of ProjectionEqualityComparer using the specified projection.\n /// The ignored parameter is solely present to aid type inference.\n /// </summary>\n /// <typeparam name=\"TSource\">Type parameter for the elements to be compared</typeparam>\n /// <typeparam name=\"TKey\">Type parameter for the keys to be compared,\n /// after being projected from the elements</typeparam>\n /// <param name=\"ignored\">Value is ignored - type may be used by type inference</param>\n /// <param name=\"projection\">Projection to use when determining the key of an element</param>\n /// <returns>A comparer which will compare elements by projecting\n /// each element to its key, and comparing keys</returns>\n public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>\n (TSource ignored,\n Func<TSource, TKey> projection)\n {\n return new ProjectionEqualityComparer<TSource, TKey>(projection);\n }\n\n}\n\n/// <summary>\n/// Class generic in the source only to produce instances of the \n/// doubly generic class, optionally using type inference.\n/// </summary>\npublic static class ProjectionEqualityComparer<TSource>\n{\n /// <summary>\n /// Creates an instance of ProjectionEqualityComparer using the specified projection.\n /// </summary>\n /// <typeparam name=\"TKey\">Type parameter for the keys to be compared,\n /// after being projected from the elements</typeparam>\n /// <param name=\"projection\">Projection to use when determining the key of an element</param>\n /// <returns>A comparer which will compare elements by projecting each element to its key,\n /// and comparing keys</returns> \n public static ProjectionEqualityComparer<TSource, TKey> Create<TKey>(Func<TSource, TKey> projection)\n {\n return new ProjectionEqualityComparer<TSource, TKey>(projection);\n }\n}\n\n/// <summary>\n/// Comparer which projects each element of the comparison to a key, and then compares\n/// those keys using the specified (or default) comparer for the key type.\n/// </summary>\n/// <typeparam name=\"TSource\">Type of elements which this comparer \n/// will be asked to compare</typeparam>\n/// <typeparam name=\"TKey\">Type of the key projected\n/// from the element</typeparam>\npublic class ProjectionEqualityComparer<TSource, TKey> : IEqualityComparer<TSource>\n{\n readonly Func<TSource, TKey> projection;\n readonly IEqualityComparer<TKey> comparer;\n\n /// <summary>\n /// Creates a new instance using the specified projection, which must not be null.\n /// The default comparer for the projected type is used.\n /// </summary>\n /// <param name=\"projection\">Projection to use during comparisons</param>\n public ProjectionEqualityComparer(Func<TSource, TKey> projection)\n : this(projection, null)\n {\n }\n\n /// <summary>\n /// Creates a new instance using the specified projection, which must not be null.\n /// </summary>\n /// <param name=\"projection\">Projection to use during comparisons</param>\n /// <param name=\"comparer\">The comparer to use on the keys. May be null, in\n /// which case the default comparer will be used.</param>\n public ProjectionEqualityComparer(Func<TSource, TKey> projection, IEqualityComparer<TKey> comparer)\n {\n if (projection == null)\n {\n throw new ArgumentNullException(\"projection\");\n }\n this.comparer = comparer ?? EqualityComparer<TKey>.Default;\n this.projection = projection;\n }\n\n /// <summary>\n /// Compares the two specified values for equality by applying the projection\n /// to each value and then using the equality comparer on the resulting keys. Null\n /// references are never passed to the projection.\n /// </summary>\n public bool Equals(TSource x, TSource y)\n {\n if (x == null && y == null)\n {\n return true;\n }\n if (x == null || y == null)\n {\n return false;\n }\n return comparer.Equals(projection(x), projection(y));\n }\n\n /// <summary>\n /// Produces a hash code for the given value by projecting it and\n /// then asking the equality comparer to find the hash code of\n /// the resulting key.\n /// </summary>\n public int GetHashCode(TSource obj)\n {\n if (obj == null)\n {\n throw new ArgumentNullException(\"obj\");\n }\n return comparer.GetHashCode(projection(obj));\n }\n}\n var f3 = f1.Except(f2, ProjectionEqualityComparer<Foo>.Create(a => a.key));\n" }, { "answer_id": 743228, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "var f3 = f1.Except(\n f2, \n (a, b) => a.key.CompareTo(b.key)\n );\n" }, { "answer_id": 10720211, "author": "mike", "author_id": 495956, "author_profile": "https://Stackoverflow.com/users/495956", "pm_score": 5, "selected": false, "text": "public class EqualityComparer<T> : IEqualityComparer<T>\n{\n public EqualityComparer(Func<T, T, bool> cmp)\n {\n this.cmp = cmp;\n }\n public bool Equals(T x, T y)\n {\n return cmp(x, y);\n }\n\n public int GetHashCode(T obj)\n {\n return obj.GetHashCode();\n }\n\n public Func<T, T, bool> cmp { get; set; }\n}\n processed.Union(suburbs, new EqualityComparer<Suburb>((s1, s2)\n => s1.SuburbId == s2.SuburbId));\n" }, { "answer_id": 29393382, "author": "Tamas Ionut", "author_id": 920202, "author_profile": "https://Stackoverflow.com/users/920202", "pm_score": 3, "selected": false, "text": " public class Comparer<T> : IEqualityComparer<T>\n {\n private readonly Func<T, T, bool> _equalityComparer;\n\n public Comparer(Func<T, T, bool> equalityComparer)\n {\n _equalityComparer = equalityComparer;\n }\n\n public bool Equals(T first, T second)\n {\n return _equalityComparer(first, second);\n }\n\n public int GetHashCode(T value)\n {\n return value.GetHashCode();\n }\n }\n Intersect IEnumerable<T> list.Intersect(otherList, new Comparer<T>( (x, y) => x.Property == y.Property));\n Comparer" }, { "answer_id": 33303472, "author": "mheyman", "author_id": 240845, "author_profile": "https://Stackoverflow.com/users/240845", "pm_score": 1, "selected": false, "text": "f3 = f1.Where(x1 => f2.All(x2 => x2.key != x1.key));\n var tmp = new HashSet<string>(f2.Select(f => f.key));\nf3 = f1.Where(f => tmp.Add(f.key));\n Type IEqualityComparer string f3 = f1.Where(x1 => (new HashSet<string>(f2.Select(x2 => x2.key))).Add(x1.key));\n" }, { "answer_id": 51548721, "author": "kofifus", "author_id": 460084, "author_profile": "https://Stackoverflow.com/users/460084", "pm_score": -1, "selected": false, "text": "public class LambdaComparer<T> : IEqualityComparer<T> {\n private readonly Func<T, T, bool> lambdaComparer;\n private readonly Func<T, int> lambdaHash;\n public LambdaComparer(Func<T, T, bool> lambdaComparer) : this(lambdaComparer, o => o.GetHashCode()) {}\n public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash) { this.lambdaComparer = lambdaComparer; this.lambdaHash = lambdaHash; }\n public bool Equals(T x, T y) => lambdaComparer is null ? false : lambdaComparer(x, y);\n public int GetHashCode(T obj) => lambdaHash is null ? 0 : lambdaHash(obj);\n}\n var a=List<string> { \"a\", \"b\" };\nvar b=List<string> { \"a\", \"*\" };\nreturn a.SequenceEquals(b, new LambdaComparer<string>((s1, s2) => s1 is null ? s2 is null : s1 == s2 || s2 == \"*\"); \n" }, { "answer_id": 56561286, "author": "OriolBG", "author_id": 2587320, "author_profile": "https://Stackoverflow.com/users/2587320", "pm_score": 1, "selected": false, "text": "Enumerable.Union public class Comparer<T> : IEqualityComparer<T>\n{\n private readonly Func<T, int> _hashFunction;\n\n public Comparer(Func<T, int> hashFunction)\n {\n _hashFunction = hashFunction;\n }\n\n public bool Equals(T first, T second)\n {\n return _hashFunction(first) == _hashFunction(second);\n }\n\n public int GetHashCode(T value)\n {\n return _hashFunction(value);\n }\n}\n list.Union(otherList, new Comparer<T>( x => x.StringValue.GetHashCode()));\n int" }, { "answer_id": 60283638, "author": "WhiteleyJ", "author_id": 961738, "author_profile": "https://Stackoverflow.com/users/961738", "pm_score": 3, "selected": false, "text": "var f1 = ...,\n f2 = ...;\nvar f3 = f1.Except(\n f2, new IEqualityComparer(\n (Foo a, Foo b) => a.key.CompareTo(b.key)\n ) );\n var f1 = ...,\n f2 = ...;\nvar distinctF = f1\n .Concat(f2) // Combine the lists\n .GroupBy(x => x.key) // Group them up by our equity comparison key\n .Select(x => x.FirstOrDefault()); // Just grab one of them.\n .GroupBy(f => new Uri(f.Url).PathAndQuery) \n .Select(x => x.FirstOrDefault(y => f1.Contains(y))\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26286/" ]
188,124
<p>I am writing a website with Visual Studio 2008 and ASP.NET 3.5. I have a masterpage set up to simplify the layout and to keep the content pages for content rather than content and layout.</p> <p>The navigation is list, css'd so it looks like a bar. In order to highlight the page on the bar, the list item needs to look like this <code>&lt;li id="current"&gt;</code>. I do not want to use <code>&lt;asp:ContentPlaceHolder&gt;</code> if I can avoid it. Is there some code I can add to each of my pages (or just to the masterpage?) to accomplish this or am I stuck using <code>&lt;asp:ContentPlaceHolder&gt;</code>'s?</p>
[ { "answer_id": 188173, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": true, "text": "public string PageSection { get; set; }\n <%@ MasterType VirtualPath=\"~/foo.master\" %>\n Master.PageSection = \"home\"; \n <body ID=\"bodyTag\" runat=\"server\">\n bodyTag.Attributes.Add(\"class\", this.PageSection);\n .home #homeNavItem,\n.contact #contactNavItem\n{ \n color: #f00; \n} \n" }, { "answer_id": 189069, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 2, "selected": false, "text": "<li id=\"homeNav\">home</li>\n<li id=\"blogNav\">blog</li>\n <body id=\"home\">\n<body id=\"blog\">\n #home #homeNav {background-image:url(homeNav-on.jpg);}\n#blog #blogNav {background-image:url(blogNav-on.jpg);}\n" }, { "answer_id": 458017, "author": "Joshua Carmody", "author_id": 8409, "author_profile": "https://Stackoverflow.com/users/8409", "pm_score": 4, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<siteMap xmlns=\"http://schemas.microsoft.com/AspNet/SiteMap-File-1.0\" >\n <siteMapNode>\n <siteMapNode url=\"~/Default.aspx\" title=\"Home\" description=\"\" />\n <siteMapNode url=\"~/Blog.aspx\" title=\"Blog\" description=\"\" />\n <siteMapNode url=\"~/AboutUs.aspx\" title=\"AboutUs\" description=\"\" />\n </siteMapNode>\n</siteMap>\n <asp:SiteMapDataSource ID=\"sitemapdata\" runat=\"server\" ShowStartingNode=\"false\" />\n<ul id=\"navigation\">\n <asp:Repeater runat=\"server\" ID=\"navrepeater\" DataSourceID=\"sitemapdata\">\n <ItemTemplate>\n <li class=\"<%# SiteMap.CurrentNode.Equals(Container.DataItem) ? \"activenav\" : \"inactivenav\" %>\"><a href=\"<%# DataBinder.Eval(Container.DataItem, \"url\") %>\"><%# DataBinder.Eval(Container.DataItem, \"title\") %></a></li>\n </ItemTemplate>\n </asp:Repeater>\n</ul>\n" }, { "answer_id": 2307652, "author": "Fras", "author_id": 278315, "author_profile": "https://Stackoverflow.com/users/278315", "pm_score": 0, "selected": false, "text": "protected string _bodyId;\n\nprotected override void OnLoad(EventArgs e)\n{\n _bodyId = \"your css id name\";\n}\n <body id=\"<%= _bodyId %>\">\n" }, { "answer_id": 18634060, "author": "Minesh Shah", "author_id": 2711201, "author_profile": "https://Stackoverflow.com/users/2711201", "pm_score": 0, "selected": false, "text": "$(\"ul.nav > li > a:contains('<%= SiteMap.CurrentNode.ParentNode.Title %>')\").addClass(\"navselected\");\n .nav ul.nav :contains" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
188,138
<p>I've seen a number of references to gzipping a javascript to save download time. <em>But</em> I also see a number of warnings that certain browsers do not support this.</p> <p>I have two different methods at my disposal:</p> <ol> <li>use <code>mod_deflate</code> to make Apache compress JS/CSS files in a given directory through htaccess</li> <li>use <code>ob_start('gzhandler')</code> to compress a file and return it to the browser with the correct headers.</li> </ol> <p>The problems with method 1 are that not all browsers support mod_deflate, and I have no clue how to write the <code>.htaccess</code> file to be smart enough to adjust for this.</p> <p>The problem with method 2 is that there is no definitive answer about how to tell if a browser supports a gzipped script, or stylesheet, and that if it does what mime-type must be given as the content type in the header.</p> <p>I need some advice. First, which method is more universally accepted by browsers? Second, how do I decay using either method to provide the uncompressed backup script? Third, would <code>&lt;script src="js/lib.js.gz" type="text/javascript"&gt;&lt;/script&gt;</code> work by itself? (It obviously wouldn't decay.)</p> <p>For the record, I'm using PHP5 with mod_deflate and full gzip creation capabilities, and my doctype is xhtml strict. Also, the javascript itself is compressed with YUI. <strong>Edit:</strong> I just went back and looked, but I have only Apache 1.3; I thought I had 2, so sorry for mentioning mod_deflate when I probably don't have it.</p>
[ { "answer_id": 188216, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 5, "selected": true, "text": "<IfModule mod_deflate.c>\n # stuff\n</IfModule>\n if (strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') ) {\n ob_start('ob_gzhandler');\n header(\"Content-Encoding: gzip\");\n// etc...\n}\n <FilesMatch \"\\\\.js.gz$\">\n ForceType text/javascript\n Header set Content-Encoding: gzip\n</FilesMatch>\n<FilesMatch \"\\\\.js$\">\n RewriteEngine On\n RewriteCond %{HTTP_USER_AGENT} !\".*Safari.*\"\n RewriteCond %{HTTP:Accept-Encoding} gzip\n RewriteCond %{REQUEST_FILENAME}.gz -f\n RewriteRule (.*)\\.js$ $1\\.js.gz [L]\n ForceType text/javascript\n</FilesMatch> \n" }, { "answer_id": 188271, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "Accept-Encoding Accept-Encoding: gzip,deflate\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24950/" ]
188,141
<p>I'm using C# on Framework 3.5. I'm looking to quickly sort a Generic <code>List&lt;T&gt;</code>. For the sake of this example, let's say I have a List of a <code>Person</code> type with a property of lastname. How would I sort this List using a lambda expression?</p> <pre><code>List&lt;Person&gt; people = PopulateList(); people.OrderBy(???? =&gt; ?????) </code></pre>
[ { "answer_id": 188149, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 5, "selected": false, "text": "people.OrderBy(person => person.lastname).ToList();\n" }, { "answer_id": 188154, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "var peopleInOrder = people.OrderBy(person => person.LastName);\n IComparer<Person> Comparison<Person> ProjectionComparer" }, { "answer_id": 188155, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 11, "selected": true, "text": "people.Sort((x, y) => string.Compare(x.LastName, y.LastName));\n var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional\n" }, { "answer_id": 4387813, "author": "Bruno", "author_id": 535015, "author_profile": "https://Stackoverflow.com/users/535015", "pm_score": 4, "selected": false, "text": "private void SortGridGenerico< T >(\n ref List< T > lista \n , SortDirection sort\n , string propriedadeAOrdenar)\n{\n\n if (!string.IsNullOrEmpty(propriedadeAOrdenar)\n && lista != null\n && lista.Count > 0)\n {\n\n Type t = lista[0].GetType();\n\n if (sort == SortDirection.Ascending)\n {\n\n lista = lista.OrderBy(\n a => t.InvokeMember(\n propriedadeAOrdenar\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 propriedadeAOrdenar\n , System.Reflection.BindingFlags.GetProperty\n , null\n , a\n , null\n )\n ).ToList();\n }\n }\n}\n" }, { "answer_id": 6865722, "author": "vampire203", "author_id": 868320, "author_profile": "https://Stackoverflow.com/users/868320", "pm_score": 5, "selected": false, "text": "System.linq;\nvar newList = people.OrderBy(x=>x.Name).ToList();\n" }, { "answer_id": 15744398, "author": "AnshuMan SrivAstav", "author_id": 2232244, "author_profile": "https://Stackoverflow.com/users/2232244", "pm_score": 3, "selected": false, "text": "var New1 = EmpList.OrderBy(z => z.Age).ToList();\n New1 List<Employee> EmpList List<Employee> z Employee" }, { "answer_id": 21503079, "author": "howserss", "author_id": 787622, "author_profile": "https://Stackoverflow.com/users/787622", "pm_score": 2, "selected": false, "text": "switch (sortColumn)\n{\n case \"user_name\":\n dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);\n dvm.UserNameSortDir = sortDir;\n break;\n case \"role_name\":\n dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);\n dvm.RoleNameSortDir = sortDir;\n break;\n case \"page_name\":\n dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);\n dvm.PageNameSortDir = sortDir;\n break;\n} \n\n\npublic List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)\n {\n if (direction == \"asc\")\n {\n list = list.OrderBy(sorter).ToList();\n direction = \"desc\";\n }\n else\n {\n list = list.OrderByDescending(sorter).ToList();\n direction = \"asc\";\n }\n return list;\n }\n" }, { "answer_id": 28274075, "author": "rosselder83", "author_id": 3556685, "author_profile": "https://Stackoverflow.com/users/3556685", "pm_score": 3, "selected": false, "text": "model.People = model.People.OrderBy(x => x.Name).ToList();\n" }, { "answer_id": 73709627, "author": "Misha Zaslavsky", "author_id": 2667173, "author_profile": "https://Stackoverflow.com/users/2667173", "pm_score": 0, "selected": false, "text": "System.Linq var sorted = people.Order();\n Sort" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ]
188,147
<p>Trying to setup the exception_logger plugin on a production server. Everything worked fine on the dev machine. Trying to rake db:migrate on the prod server and i get this error:</p> <pre><code>rake aborted! no such file to load -- pagination </code></pre> <p>What am i missing?</p>
[ { "answer_id": 188228, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 1, "selected": false, "text": "rake db:migrate --trace" }, { "answer_id": 188268, "author": "Jason Miesionczek", "author_id": 18811, "author_profile": "https://Stackoverflow.com/users/18811", "pm_score": 0, "selected": false, "text": "** Invoke db:migrate (first_time)\n** Invoke environment (first_time)\n** Execute environment\nrake aborted!\nno such file to load -- pagination\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `gem_original_require'\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in `new_constants_in'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/nfs/c01/h06/mnt/12348/containers/rails/mpg_prod/vendor/plugins/classic_pagination/init.rb:24:in `evaluate_init_rb'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin.rb:95:in `evaluate_init_rb'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin.rb:91:in `evaluate_init_rb'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin.rb:44:in `load'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin/loader.rb:33:in `load_plugins'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin/loader.rb:32:in `each'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/rails/plugin/loader.rb:32:in `load_plugins'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:283:in `load_plugins'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:138:in `process'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:93:in `send'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/initializer.rb:93:in `run'\n/nfs/c01/h06/mnt/12348/containers/rails/mpg_prod/config/environment.rb:13\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `gem_original_require'\n/home/12348/data/rubygems/lib/rubygems/custom_require.rb:27:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in `new_constants_in'\n/home/12348/data/rubygems/gems/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'\n/home/12348/data/rubygems/gems/gems/rails-2.1.0/lib/tasks/misc.rake:3\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:546:in `call'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:546:in `execute'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:541:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:541:in `execute'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:508:in `invoke_with_call_chain'\n/usr/lib/ruby/1.8/thread.rb:135:in `synchronize'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:501:in `invoke_with_call_chain'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:518:in `invoke_prerequisites'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1183:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1183:in `send'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1183:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:515:in `invoke_prerequisites'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:507:in `invoke_with_call_chain'\n/usr/lib/ruby/1.8/thread.rb:135:in `synchronize'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:501:in `invoke_with_call_chain'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:494:in `invoke'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1931:in `invoke_task'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1909:in `top_level'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1909:in `each'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1909:in `top_level'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1948:in `standard_exception_handling'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1903:in `top_level'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1881:in `run'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1948:in `standard_exception_handling'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/lib/rake.rb:1878:in `run'\n/home/12348/data/rubygems/gems/gems/rake-0.8.1/bin/rake:31\n/home/12348/data/rubygems/gems/bin/rake:19:in `load'\n/home/12348/data/rubygems/gems/bin/rake:19\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18811/" ]
188,160
<p>How have you decided to handle data/control validation in your silverlight applications? </p>
[ { "answer_id": 198728, "author": "Yuval Peled", "author_id": 20257, "author_profile": "https://Stackoverflow.com/users/20257", "pm_score": 2, "selected": false, "text": "// page.xaml.cs\n\nprivate bool clean = true;\n\n\nprivate void LayoutRoot_BindingValidationError( \n object sender, ValidationErrorEventArgs e )\n{\n if ( e.Action == ValidationErrorEventAction.Added )\n {\n QuantityOnHand.Background = new SolidColorBrush( Colors.Red );\n clean = false;\n }\n else if ( e.Action == ValidationErrorEventAction.Removed )\n {\n QuantityOnHand.Background = new SolidColorBrush( Colors.White );\n clean = true;\n }\n}\n\n\n\n// page.xaml\n\n<Grid x:Name=\"LayoutRoot\" Background=\"White\" BindingValidationError=\"LayoutRoot_BindingValidationError\" >\n\n<TextBox x:Name=\"QuantityOnHand\" \n Text=\"{Binding Mode=TwoWay, Path=QuantityOnHand, \n NotifyOnValidationError=true, ValidatesOnExceptions=true }\"\n VerticalAlignment=\"Bottom\"\n HorizontalAlignment=\"Left\"\n Height=\"30\" Width=\"90\"red\n Grid.Row=\"4\" Grid.Column=\"1\" />\n\n\n// book.cs\n\npublic int QuantityOnHand\n{\n get { return quantityOnHand; }\n set\n {\n if ( value < 0 )\n {\n throw new Exception( \"Quantity on hand cannot be negative!\" );\n }\n quantityOnHand = value;\n NotifyPropertyChanged( \"QuantityOnHand\" );\n } // end set\n}\n" }, { "answer_id": 6301921, "author": "Pankaj Awasthi", "author_id": 522781, "author_profile": "https://Stackoverflow.com/users/522781", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Net;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing System.Windows.Ink;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing System.Windows.Shapes;\nusing Silverlight.Validators.Controls;\n\nnamespace Silverlight.Validators\n{\n public enum ValidationType\n {\n Validator,\n OnDemand\n }\n\n\n public abstract class ValidatorBase : DependencyObject\n {\n protected ValidatorManager Manager { get; set; }\n\n\n public string ManagerName { get; set; }\n public ValidationType ValidationType { get; set; }\n public IIndicator Indicator { get; set; }\n public FrameworkElement ElementToValidate { get; set; }\n public bool IsRequired { get; set; }\n public bool IsValid { get; set; }\n public Brush InvalidBackground { get; set; }\n public Brush InvalidBorder { get; set; }\n public Thickness InvalidBorderThickness { get; set; }\n public string ErrorMessage { get; set; }\n\n private Brush OrigBackground = null;\n private Brush OrigBorder = null;\n private Thickness OrigBorderThickness = new Thickness(1);\n private object OrigTooltip = null;\n\n public ValidatorBase()\n {\n IsRequired = false;\n IsValid = true;\n ManagerName = \"\";\n this.ValidationType = ValidationType.Validator;\n }\n\n public void Initialize(FrameworkElement element)\n {\n ElementToValidate = element;\n element.Loaded += new RoutedEventHandler(element_Loaded);\n }\n\n private bool loaded = false;\n public UserControl UserControl { get; set; }\n public ChildWindow ChildUserControl { get; set; }\n private void element_Loaded(object sender, RoutedEventArgs e)\n {\n if (!loaded)\n {\n\n this.UserControl = FindUserControl(ElementToValidate);\n //UserControl o = FindUserControl(ElementToValidate);\n this.ChildUserControl = FindChildUserControl(ElementToValidate);\n //MessageBox.Show(o.GetType().BaseType.ToString());\n //no usercontrol. throw error?\n if ((this.UserControl == null) && (this.ChildUserControl==null)) return;\n\n if (this.UserControl != null)\n this.Manager = FindManager(this.UserControl, ManagerName);\n else if (this.ChildUserControl != null)\n this.Manager = FindManager(this.ChildUserControl, ManagerName);\n\n\n if (this.Manager == null)\n {\n System.Diagnostics.Debug.WriteLine(String.Format(\"No ValidatorManager found named '{0}'\", ManagerName));\n throw new Exception(String.Format(\"No ValidatorManager found named '{0}'\", ManagerName));\n }\n\n this.Manager.Register(ElementToValidate, this);\n\n if (ValidationType == ValidationType.Validator)\n {\n ActivateValidationRoutine();\n }\n\n //Use the properties from the manager if they are not set at the control level\n if (this.InvalidBackground == null)\n {\n this.InvalidBackground = this.Manager.InvalidBackground;\n }\n\n if (this.InvalidBorder == null)\n {\n this.InvalidBorder = this.Manager.InvalidBorder;\n\n if (InvalidBorderThickness.Bottom == 0)\n {\n this.InvalidBorderThickness = this.Manager.InvalidBorderThickness;\n }\n }\n\n if (this.Indicator ==null)\n {\n Type x = this.Manager.Indicator.GetType();\n this.Indicator = x.GetConstructor(System.Type.EmptyTypes).Invoke(null) as IIndicator;\n foreach (var param in x.GetProperties())\n {\n var val = param.GetValue(this.Manager.Indicator, null);\n if (param.CanWrite && val!= null && val.GetType().IsPrimitive)\n {\n param.SetValue(this.Indicator, val, null);\n }\n }\n }\n loaded = true;\n }\n ElementToValidate.Loaded -= new RoutedEventHandler(element_Loaded);\n }\n\n public void SetManagerAndControl(ValidatorManager manager, FrameworkElement element)\n {\n this.Manager = manager;\n this.ElementToValidate = element;\n }\n\n public bool Validate(bool checkControl)\n {\n bool newIsValid;\n if (checkControl)\n {\n newIsValid= ValidateControl() && ValidateRequired();\n }\n else\n {\n newIsValid = ValidateRequired();\n }\n\n if (newIsValid && !IsValid)\n {\n ControlValid();\n }\n if (!newIsValid && IsValid)\n {\n ControlNotValid();\n }\n IsValid=newIsValid;\n return IsValid;\n }\n\n public virtual void ActivateValidationRoutine()\n {\n ElementToValidate.LostFocus += new RoutedEventHandler(ElementToValidate_LostFocus);\n ElementToValidate.KeyUp += new KeyEventHandler(ElementToValidate_KeyUp);\n }\n\n /// <summary>\n /// Find the nearest UserControl up the control tree for the FrameworkElement passed in\n /// </summary>\n /// <param name=\"element\">Control to validate</param>\n protected static UserControl FindUserControl(FrameworkElement element)\n {\n if (element == null)\n {\n return null;\n }\n if (element.Parent != null)\n {\n //MessageBox.Show(element.Parent.GetType().BaseType.ToString());\n if (element.Parent is UserControl)\n {\n return element.Parent as UserControl;\n }\n return FindUserControl(element.Parent as FrameworkElement);\n }\n return null;\n }\n protected static ChildWindow FindChildUserControl(FrameworkElement element)\n {\n if (element == null)\n {\n return null;\n }\n if (element.Parent != null)\n {\n //MessageBox.Show(element.Parent.GetType().BaseType.ToString());\n if (element.Parent is ChildWindow)\n {\n return element.Parent as ChildWindow;\n }\n return FindChildUserControl(element.Parent as FrameworkElement);\n }\n return null;\n }\n\n protected virtual void ElementToValidate_KeyUp(object sender, RoutedEventArgs e)\n {\n Dispatcher.BeginInvoke(delegate() { Validate(false); });\n }\n\n protected virtual void ElementToValidate_LostFocus(object sender, RoutedEventArgs e)\n {\n Dispatcher.BeginInvoke(delegate() { Validate(true); });\n }\n\n protected abstract bool ValidateControl();\n\n protected bool ValidateRequired()\n {\n if (IsRequired && ElementToValidate is TextBox)\n {\n TextBox box = ElementToValidate as TextBox;\n return !String.IsNullOrEmpty(box.Text);\n }\n return true;\n }\n\n protected void ControlNotValid()\n {\n GoToInvalidStyle();\n }\n\n protected void ControlValid()\n {\n GoToValidStyle();\n }\n\n protected virtual void GoToInvalidStyle()\n {\n if (!string.IsNullOrEmpty(this.ErrorMessage))\n {\n object tooltip = ToolTipService.GetToolTip(ElementToValidate);\n\n if (tooltip != null)\n {\n OrigTooltip = tooltip;\n }\n\n //causing a onownermouseleave error currently...\n this.ElementToValidate.ClearValue(ToolTipService.ToolTipProperty);\n\n SetToolTip(this.ElementToValidate, this.ErrorMessage);\n }\n\n if (Indicator != null)\n {\n Indicator.ShowIndicator(this);\n }\n\n if (ElementToValidate is TextBox)\n {\n TextBox box = ElementToValidate as TextBox;\n\n if (InvalidBackground != null)\n {\n if (OrigBackground == null)\n {\n OrigBackground = box.Background;\n }\n box.Background = InvalidBackground;\n }\n\n if (InvalidBorder != null)\n {\n if (OrigBorder == null)\n {\n OrigBorder = box.BorderBrush;\n OrigBorderThickness = box.BorderThickness;\n }\n box.BorderBrush = InvalidBorder;\n\n if (InvalidBorderThickness != null)\n {\n box.BorderThickness = InvalidBorderThickness;\n }\n }\n } \n }\n\n protected virtual void GoToValidStyle()\n {\n if (!string.IsNullOrEmpty(this.ErrorMessage))\n {\n this.ElementToValidate.ClearValue(ToolTipService.ToolTipProperty);\n\n if (this.OrigTooltip != null)\n {\n SetToolTip(this.ElementToValidate, this.OrigTooltip);\n }\n }\n\n if (Indicator != null)\n {\n Indicator.HideIndicator();\n }\n\n if (ElementToValidate is TextBox)\n {\n TextBox box = ElementToValidate as TextBox;\n if (OrigBackground != null)\n {\n box.Background = OrigBackground;\n }\n\n if (OrigBorder != null)\n {\n box.BorderBrush = OrigBorder;\n\n if (OrigBorderThickness != null)\n {\n box.BorderThickness = OrigBorderThickness;\n }\n }\n }\n }\n\n protected void SetToolTip(FrameworkElement element, object tooltip)\n {\n Dispatcher.BeginInvoke(() =>\n ToolTipService.SetToolTip(element, tooltip));\n }\n\n private ValidatorManager FindManager(UserControl c, string groupName)\n {\n string defaultName = \"_DefaultValidatorManager\";\n var mgr = this.UserControl.FindName(ManagerName);\n if (mgr == null)\n {\n mgr = this.UserControl.FindName(defaultName);\n }\n if (mgr == null)\n {\n mgr = new ValidatorManager()\n {\n Name = defaultName\n };\n Panel g = c.FindName(\"LayoutRoot\") as Panel;\n g.Children.Add(mgr as ValidatorManager);\n }\n return mgr as ValidatorManager;\n }\n\n private ValidatorManager FindManager(ChildWindow c, string groupName)\n {\n string defaultName = \"_DefaultValidatorManager\";\n var mgr = this.ChildUserControl.FindName(ManagerName);\n if (mgr == null)\n {\n mgr = this.ChildUserControl.FindName(defaultName);\n }\n if (mgr == null)\n {\n mgr = new ValidatorManager()\n {\n Name = defaultName\n };\n Panel g = c.FindName(\"LayoutRoot\") as Panel;\n g.Children.Add(mgr as ValidatorManager);\n }\n return mgr as ValidatorManager;\n }\n\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
188,162
<p>Just wondering what little scripts/programs people here have written that helps one with his or her everyday life (aka not work related).</p> <p>Anything goes, groundbreaking or not. For me right now, it's a small python script to calculate running pace given distance and time elapsed.</p>
[ { "answer_id": 188183, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "o 0 o 0 0" }, { "answer_id": 188185, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": false, "text": "#! /bin/bash\n# check to see if site is up\n# if it is, don't worry\n# if it's down, restart apache after get a process listing\n#\n# v.1 Warren M Myers - initial stab\n# 31 Aug 06\n#\n\nERRCOD='7'\nWHEN=`date +%d%b%y`\nREPT=\"~/psaux.$WHEN.txt\"\nSTARS='********************'\n\ncurl -I http://www.shodor.org > /var/tmp/curlret.txt\n\nif [ \"$?\" = \"$ERRCOD\" ]; then\n # return was unable to connect to host: save ps -aux; mail report\n ps -aux > $REPT\n echo $STARS\n echo 'curl return results'\n echo\n cat curlret.txt\n echo\n echo $STARS\n echo 'ps -aux results'\n cat $REPT\n echo\n echo $STARS\n echo 'restarting apache'\n /etc/init.d/apache2 restart\n echo 'apache restarted'\n echo\n echo \"ps -aux results saved in $REPT\"\nfi\n\nrm -f /var/tmp/curlret.txt\n" }, { "answer_id": 188210, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 1, "selected": false, "text": "SetAppPool(\"W3SVC/1059997624/Root\", \"MyAppPool\");\n\n\n\nfunction SetAppPool(webId, appPoolName)\n{\nvar providerObj=GetObject(\"winmgmts:/root/MicrosoftIISv2\");\nvar vdirObj=providerObj.get(\"IIsWebVirtualDirSetting='\" + webId + \"'\");\nvdirObj.AppPoolId=appPoolName;\nvdirObj.Put_();\n}\n" }, { "answer_id": 188243, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 2, "selected": false, "text": "#!/bin/sh\nFNDIR=\"train-as-spam\"\nFPDIR=\"train-as-ham\"\n\nfor dir in /home/*/.maildir\ndo\n cd \"${dir}\"\n USER=`stat -c %U .`\n\n SRCDIR=\"${dir}/.${FNDIR}\"\n if [ ! -d ${SRCDIR} ]; then\n echo no \"${SRCDIR}\" directory\n else\n cd \"${SRCDIR}/cur\"\n ls -tr | while read file\n do\n if grep -q \"^X-DSPAM\" \"${file}\"; then\n SOURCE=\"error\"\n else\n SOURCE=\"corpus\"\n fi\n\n dspam --user \"${USER}\" --class=spam --source=\"${SOURCE}\" --deliver=innocent,spam --stdout < \"${file}\" > \"../tmp/${file}\"\n mv \"../tmp/${file}\" \"${dir}/new/${file%%:*}\" && rm \"${file}\"\n done\n fi\n\n SRCDIR=\"${dir}/.${FPDIR}\"\n if [ ! -d ${SRCDIR} ]; then\n echo no \"${SRCDIR}\" directory\n else\n cd \"${SRCDIR}/cur\"\n ls -tr | while read file\n do\n if grep -q \"^X-DSPAM\" \"${file}\"; then\n SOURCE=\"error\"\n else\n SOURCE=\"corpus\"\n fi\n\n dspam --user \"${USER}\" --class=innocent --source=\"${SOURCE}\" --deliver=innocent,spam --stdout < \"${file}\" > \"../tmp/${file}\"\n mv \"../tmp/${file}\" \"${dir}/new/${file%%:*}\" && rm \"${file}\"\n done\n fi\n\ndone\n" }, { "answer_id": 188283, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 1, "selected": false, "text": "#!/usr/bin/perl\nuse strict;\nuse utf8;\nuse Encode;\nuse File::Find;\nbinmode STDOUT, ':utf8';\nsub orderly {\n my ($x, $y) = @_{$a, $b};\n if (my $z = $x <=> $y) {return $z}\n $x = length $a;\n $y = length $b;\n my $z = $x < $y ? $x : $y;\n if (substr($a, 0, $z) eq substr($b, 0, $z)) {\n return $y <=> $x;\n }\n else {\n return $a cmp $b;\n }\n}\nmy %conf = map +($_ => 0), split //, 'acsxL';\nsub Stat {$conf{L} ? lstat : stat}\nmy @dirs = ();\nwhile (defined ($_ = shift)) {\n if ($_ eq \"--\") {push @dirs, @ARGV; last}\n elsif (/^-(.*)$/s) {\n for (split //, $1) {\n if (!exists $conf{$_} or $conf{$_} = 1 and $conf{a} and $conf{s}) {\n print STDERR \"$0 [-a] [-c] [-s] [-x] [-L] [--] ...\\n\";\n exit 1;\n }\n }\n }\n else {push @dirs, $_}\n}\ns/\\/*$//s for @dirs; # */ SO has crappy syntax highlighting\n@dirs = qw(.) unless @dirs;\nmy %spec = (follow => $conf{L}, no_chdir => 1);\nif ($conf{a}) {\n $spec{wanted} = sub {\n Stat;\n my $s = -f _ ? -s _ : 0;\n decode(utf8 => $File::Find::name) =~ /^\\Q$dirs[0]\\E\\/?(.*)$/s;\n my @a = split /\\//, $1;\n for (unshift @a, $dirs[0]; @a; pop @a) {\n $_{join \"/\", @a} += $s;\n }\n };\n}\nelsif ($conf{s}) {\n $spec{wanted} = sub {\n Stat;\n $_{$dirs[0]} += -f _ ? -s _ : 0;\n };\n}\nelse {\n $spec{wanted} = sub {\n Stat;\n my $s = -f _ ? -s _ : 0;\n decode(utf8 => $File::Find::name) =~ /^\\Q$dirs[0]\\E\\/?(.*)$/s;\n my @a = split /\\//, $1;\n ! -d _ and pop @a;\n for (unshift @a, $dirs[0]; @a; pop @a) {\n $_{join \"/\", @a} += $s;\n }\n };\n}\nif ($conf{x}) {\n $spec{preprocess} = sub {\n my $dev = (Stat $File::Find::dir)[0];\n grep {$dev == (Stat \"$File::Find::dir/$_\")[0]} @_;\n };\n}\nwhile (@dirs) {\n find(\\%spec, $dirs[0] eq \"\" ? \"/\" : $dirs[0]);\n $_{\"\"} += $_{$dirs[0]} if $conf{c};\n shift @dirs;\n}\n$_{$_} < 1024 ** 1 ? printf \"%s «%-6.6sB» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 0), $_ :\n$_{$_} < 1024 ** 2 ? printf \"%s «%-6.6sK» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 1), $_ :\n$_{$_} < 1024 ** 3 ? printf \"%s «%-6.6sM» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 2), $_ :\n$_{$_} < 1024 ** 4 ? printf \"%s «%-6.6sG» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 3), $_ :\n$_{$_} < 1024 ** 5 ? printf \"%s «%-6.6sT» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 4), $_ :\n$_{$_} < 1024 ** 6 ? printf \"%s «%-6.6sP» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 5), $_ :\n$_{$_} < 1024 ** 7 ? printf \"%s «%-6.6sE» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 6), $_ :\n$_{$_} < 1024 ** 8 ? printf \"%s «%-6.6sZ» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 7), $_ :\n printf \"%s «%-6.6sY» %s\\n\", $_{$_}, sprintf(\"%6.6f\", \"$_{$_}\" / 1024 ** 8), $_\n for grep {$_{$_} > 0} sort orderly keys %_;\n ~/bin/dush du -h du | sort -n #!/usr/bin/perl\n$t = 1;\n%p = map {$_ => ($t *= 1024)} qw(K M G T P E Z Y);\n$t = 4707319808;\nif (@ARGV) {\n if (($_ = shift) =~ /^-*dvd/i) {$t = 4707319808}\n elsif (/^-*cd[^w]*$/i) {$t = 737280000}\n elsif (/^-*cd/i) {$t = 681984000}\n elsif (/^-*([\\d.]+)([kmgtpezy])/i) {$t = $1 * ($p{\"\\U$2\"} || 1)}\n elsif (/^-*([\\d.]+)/) {$t = $1}\n else {unshift @ARGV, $_}\n}\n($q, $r, $s) = (0, ($ENV{COLUMNS} || 80) - 13, $t);\nwhile (<>) {\n chomp, stat;\n unless (-e _) {\n print STDERR \"$_ does not exist\\n\";\n next;\n }\n if (($s += -s _) > $t) {\n $s && $s < $t && printf \"-%7s %s\\n\",\n sprintf(\"%2.3f%%\", 100 * ($t - $s) / $t), $t - $s;\n printf \"-----------%d%*s\\n\", ++$q, $r, \"-\" x $r;\n $s = -s _;\n }\n printf \"%8s %s\\n\",\n sprintf(\"%3.3f%%\", $s * 100 / $t),\n /.{4}(.{$r})$/s ? \"...$1\" : $_;\n}\n$s && $s < $t && printf \"-%7s %s\\n\",\n sprintf(\"%2.3f%%\", 100 * ($t - $s) / $t), $t - $s;\n ~/bin/fit ls | fit ls | fit -cdrw" }, { "answer_id": 188362, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 2, "selected": false, "text": "divert(-1)\nchangequote(<<, >>)\ndefine(mailinglistrule, \n<<:0:\n* $2\nLists/$1\n>>)\ndefine(listdt, <<mailinglistrule($1,^Delivered-To:.*$2)>>)\ndefine(listid, <<mailinglistrule($1,^List-Id:.*<$2>)>>)\ndivert# Generated from .procmailrc.m4 -- DO NOT EDIT\n :0:\n* ^Delivered-To:.*foo@example.com\nLists/foo\n #! /bin/sh\n\nPROCMAILRC=.procmailrc\nTMPNAM=.procmailrc.tmp.$$\ncd $HOME\numask 077\ntrap \"rm -f $TMPNAM\" 0\n\nm4 < .procmailrc.m4 > $TMPNAM\ndiff -u $PROCMAILRC $TMPNAM\n\necho -n 'Is this acceptable? (y/N) '\nread accept\n\nif [ -z \"$accept\" ]; then\n accept=n\nfi\n\nif [ $accept = 'y' -o $accept = 'Y' ]; then\n mv -f $TMPNAM $PROCMAILRC && \\\n chmod 400 $PROCMAILRC && \\\n echo \"Created new $PROCMAILRC\"\n if [ \"$?\" -ne 0 ]; then\n echo \"*** FAILED creating $PROCMAILRC\"\n fi\nelse\n echo \"Didn't update $PROCMAILRC\"\nfi\n" }, { "answer_id": 188371, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 5, "selected": false, "text": "#!/usr/bin/python\n\nimport os\nimport string\nimport time\nimport shutil\n\n###################################################\n__SRCDIR__ = \"/mnt/camera\"\n__DESTDIR__ = \"/home/pictures/recent\"\n###################################################\ndef cbwalk(arg, dirname, names):\n sdatetime = time.strftime(\"%y%m%d%H%M\")\n for name in names:\n if string.lower(name[-3:]) in (\"jpg\", \"mov\"):\n srcfile = \"%s/%s\" % (dirname, name)\n destfile = \"%s/%s_%s\" % (__DESTDIR__, sdatetime, name)\n print destfile\n shutil.copyfile( srcfile, destfile)\n###################################################\nif __name__ == \"__main__\":\n os.path.walk(__SRCDIR__, cbwalk, None)\n" }, { "answer_id": 188718, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<br>function CD\n<br>{\n<br> unalias cd\n<br> command cd \"$@\" && PS1=\"\\${ORACLE_SID}:$(hostname):$PWD> \"\n<br> alias cd=CD\n<br>}\n<br>\nalias cd=CD\n" }, { "answer_id": 189349, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 6, "selected": false, "text": "dir /s /b * > dirlist.txt\n findstr findstr \".jpg\" dirlist.txt\nfindstr /i /r \"windows.*system32.*png$\" dirlist.txt\n findstr \"\\.java \\.py\" dirlist.txt > narrowlist.txt\nfindstr /i /r /f:narrowlist.txt \"flip.*image\"\n" }, { "answer_id": 189584, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 1, "selected": false, "text": " #!/usr/bin/python\n##############################################\n# Gentoo emerge status # \n# This script requires genlop, # \n# you can install it using `emerge genlop`. #\n# Milot Shala <milot@mymyah.com> #\n##############################################\n\nimport sys\nimport os\nimport time\n\n#colors\ncolor={}\ncolor[\"r\"]=\"\\x1b[31;01m\"\ncolor[\"g\"]=\"\\x1b[32;01m\"\ncolor[\"b\"]=\"\\x1b[34;01m\"\ncolor[\"0\"]=\"\\x1b[0m\"\n\n\ndef r(txt):\n return color[\"r\"]+txt+color[\"0\"]\ndef g(txt):\n return color[\"g\"]+txt+color[\"0\"]\ndef b(txt):\n return color[\"b\"]+txt+color[\"0\"]\n\n# View Options\ndef view_opt(): \n\n print\n print\n print g(\"full-info - View full information for emerged package\")\n print g(\"cur - View current emerge\")\n print g(\"hist - View history of emerged packages by day\")\n print g(\"hist-all - View full list of history of emerged packages\")\n print g(\"rsync - View rsync history\")\n print g(\"time - View time for compiling a package\")\n print g(\"time-unmerged - View time of unmerged packages\")\n print\n command = raw_input(r(\"Press Enter to return to main \"))\n if command == '':\n c()\n program()\n else:\n c()\n program()\n\n# system command 'clear'\ndef c():\n os.system('clear')\n\n\n# Base program\ndef program():\n c()\n print g(\"Gentoo emerge status script\")\n print (\"---------------------------\")\n print\n\n print (\"1]\") + g(\" Enter options\")\n print (\"2]\") + g(\" View options\")\n print (\"3]\") + g(\" Exit\")\n print\n command = input(\"[]> \")\n\n\n if command == 1: \n print\n print r(\"\"\"First of all you must view options to know what to use, you can enter option name ( if you know any ) or type `view-opt` to view options.\"\"\")\n print\n time.sleep(2)\n command = raw_input(b(\"Option name: \"))\n if (command == 'view-opt' or command == 'VIEW-OPT'):\n view_opt()\n\n\n elif command == 'full-info':\n c()\n print g(\"Full information for a single package\")\n print (\"-------------------------------------\")\n print\n print b(\"Enter package name\")\n command=raw_input(\"> \")\n c()\n print g(\"Full information for package\"), b(command)\n print (\"-----------------------------------\")\n print\n pack=['genlop -i '+command]\n pack_=\" \".join(pack)\n os.system(pack_)\n print\n print r(\"Press Enter to return to main.\")\n command=raw_input()\n if command == '':\n c()\n program()\n\n else:\n c()\n program()\n\n\n elif command == 'cur':\n if command == 'cur':\n c()\n print g(\"Current emerge session(s)\")\n print (\"-------------------------\")\n print\n print b(\"Listing current emerge session(s)\")\n print\n time.sleep(1)\n os.system('genlop -c')\n print\n print r(\"Press Enter to return to main.\")\n command = raw_input()\n if (command == ''):\n c()\n program()\n\n else:\n c()\n program()\n\n\n elif command == 'hist':\n if command == 'hist':\n c()\n print g(\"History of merged packages\")\n print (\"---------------------------\")\n print\n time.sleep(1)\n print b(\"Enter number of how many days ago you want to see the packages\")\n command = raw_input(\"> \")\n c()\n print g(\"Packages merged \"+b(command)+ g(\" day(s) before\"))\n print (\"------------------------------------\")\n pkg=['genlop --list --date '+command+' days ago']\n pkg_=\" \".join(pkg)\n os.system(pkg_)\n print\n print r(\"Press Enter to return to main.\")\n command = raw_input()\n if command == '':\n c()\n program()\n\n else:\n c()\n program()\n\n\n elif command == 'hist-all':\n c()\n print g(\"Full history of merged individual packages\")\n print (\"--------------------------------------\")\n print\n print b(\"Do you want to view individual package?\")\n print r(\"YES/NO?\")\n command = raw_input(\"> \")\n print\n if (command == 'yes' or command == 'YES'):\n print g(\"Enter package name\")\n command = raw_input(\"> \")\n print\n pkg=['genlop -l | grep '+command+ ' | less']\n pkg_=\" \".join(pkg)\n os.system(pkg_)\n print\n print r(\"Press Enter to return to main\")\n command = raw_input()\n if command == '':\n c()\n program()\n else:\n c()\n program()\n\n elif (command == 'no' or command == 'NO'):\n pkg=['genlop -l | less']\n pkg_=\" \".join(pkg)\n os.system(pkg_)\n print\n print r(\"Press Enter to return to main\")\n command = raw_input()\n if command == '':\n c()\n program()\n\n else:\n c()\n program()\n\n else:\n c()\n program()\n\n\n elif command == 'rsync':\n print g(\"RSYNC updates\")\n print\n print\n print\n print b(\"You can view rsynced time by year!\")\n print r(\"Do you want this script to do it for you? (yes/no)\")\n command = raw_input(\"> \")\n if (command == 'yes' or command == 'YES'):\n print\n print g(\"Enter year i.e\"), b(\"2005\")\n print\n command = raw_input(\"> \")\n rsync=['genlop -r | grep '+command+' | less']\n rsync_=\" \".join(rsync)\n os.system(rsync_)\n print\n print r(\"Press Enter to return to main.\")\n c()\n program()\n elif (command == 'no' or command == 'NO'):\n os.system('genlop -r | less')\n print\n print r(\"Press Enter to return to main.\")\n command = raw_input()\n if command == '':\n c()\n program()\n\n else:\n c()\n program()\n\n elif command == 'time':\n c()\n print g(\"Time of package compilation\")\n print (\"---------------------------\")\n print\n print\n\n print b(\"Enter package name\")\n pkg_name = raw_input(\"> \")\n pkg=['emerge '+pkg_name+' -p | genlop -p | less']\n pkg_=\" \".join(pkg)\n os.system(pkg_)\n print\n print r(\"Press Enter to return to main\")\n time.sleep(2)\n command = raw_input()\n if command == '':\n c()\n program()\n\n else:\n c()\n program()\n\n\n elif command == 'time-unmerged':\n c()\n print g(\"Show when package(s) is/when is unmerged\")\n print (\"----------------------------------------\")\n print\n\n print b(\"Enter package name: \")\n name = raw_input(\"> \")\n pkg=['genlop -u '+name]\n pkg_=\" \".join(pkg)\n os.system(pkg_)\n print\n print r(\"Press Enter to return to main\")\n time.sleep(2)\n command = raw_input()\n if command == '':\n c()\n program()\n\n else:\n c()\n program()\n\n else:\n print\n print r(\"Wrong Selection!\")\n time.sleep(2)\n c()\n program()\n\n\n elif command == 2:\n view_opt()\n command = raw_input(r(\"Press Enter to return to main \"))\n if command == '':\n c()\n program()\n else:\n c()\n program()\n\n\n elif command == 3:\n print\n print b(\"Thank you for using this script\")\n print\n time.sleep(1)\n sys.exit()\n\n else:\n print\n print r(\"Wrong Selection!\")\n time.sleep(2)\n c()\n program()\n command = (\"\")\n\n\nprogram()\n" }, { "answer_id": 190312, "author": "Mark Allen", "author_id": 5948, "author_profile": "https://Stackoverflow.com/users/5948", "pm_score": 2, "selected": false, "text": "@echo off\nif not exist *.sln goto csproj\nfor %%f in (*.sln) do start /max %%f\ngoto end\n\n:csproj\nfor %%f in (*.csproj) do start /max %%f\ngoto end\n\n:end\n" }, { "answer_id": 197339, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "#!/usr/bin/python \n\nimport sys, re, zlib\n\nc_null=\"^[[00;00m\"\nc_red=\"^[[31;01m\"\nc_green=\"^[[32;01m\"\n\ndef crc_checksum(filename):\n filedata = open(filename, \"rb\").read()\n sum = zlib.crc32(filedata)\n if sum < 0:\n sum &= 16**8-1\n return \"%.8X\" %(sum)\n\nfor file in sys.argv[1:]:\n sum = crc_checksum(file)\n try:\n dest_sum = re.split('[\\[\\]]', file)[-2]\n if sum == dest_sum:\n c_in = c_green\n else:\n c_in = c_red\n sfile = file.split(dest_sum)\n print \"%s%s%s %s%s%s%s%s\" % (c_in, sum, c_null, sfile[0], c_in, dest_sum, c_null, sfile[1])\n except IndexError:\n print \"%s %s\" %(sum, file)\n" }, { "answer_id": 197371, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 1, "selected": false, "text": "alias snoot='find . ! -path \"*/.svn*\" -print0 | xargs -0 egrep '\n" }, { "answer_id": 231931, "author": "Sniggerfardimungus", "author_id": 30997, "author_profile": "https://Stackoverflow.com/users/30997", "pm_score": 3, "selected": false, "text": " export PROMPT_COMMAND='export TRIM=`~/bin/trim.pl`'\n export PS1=\"\\[\\e]0;\\$TRIM\\a\\]\\$TRIM> \"\n trap 'CMD=`history|~/bin/hist.pl`;echo -en \"\\e]0;$TRIM> $CMD\\007\"' DEBUG\n ... ============trim.pl===========\n #!/usr/bin/perl\n\n #It seems that my cygwin box doesn't have HOSTNAME available in the \n #environment - at least not to scripts - so I'm getting it elsewhere.\n open (IN, \"/usr/bin/hostname|\");\n $hostname = <IN>;\n close (IN);\n $hostname =~ /^([A-Za-z0-9-]*)/;\n $host_short = $1;\n\n $preamble = \"...\" if (length($ENV{\"PWD\"})>37);\n\n $ENV{\"PWD\"} =~ /(.{1,37}$)/;\n $path_short = $1;\n\n print \"$host_short: $preamble$path_short\";\n\n ==============================\n trap 'CMD=`history|~/bin/hist.pl`;echo -en \"\\e]0;$TRIM> $CMD\\007\"' DEBUG\n ===========hist.pl============\n#!/usr/bin/perl\n\nwhile (<STDIN>)\n{\n $line = $_\n}\n\nchomp $line;\n$line =~ /^.{27}(.*)/;\nprint $1;\n ==============================\n castro: /home/ronb blog\n Ron-D630: /C/ronb/rails/depot script/server\n Ron-D630: /C/ronb/rails/depot mysql -u ron -p\n Ron-D630: /C/ronb/rails/depot find . > /C/ronb/system.map\n Ron-D630: /C/ronb/rails/depot vi app/views/cart.html.erb\n Ron-D630: /C/perforce/depot/ p4 protect\n Ron-D630: /C/perforce/depot/ p4 sync -f\n Ron-D630: /C/perforce/depot/\n" }, { "answer_id": 245724, "author": "foxdonut", "author_id": 26353, "author_profile": "https://Stackoverflow.com/users/26353", "pm_score": 7, "selected": false, "text": "/a/very/deeply/nested/path/somewhere up N #!/bin/bash\nLIMIT=$1\nP=$PWD\nfor ((i=1; i <= LIMIT; i++))\ndo\n P=$P/..\ndone\ncd $P\n /a/very/deeply/nested/path/somewhere> up 4\n/a/very> \n function up( )\n{\nLIMIT=$1\nP=$PWD\nfor ((i=1; i <= LIMIT; i++))\ndo\n P=$P/..\ndone\ncd $P\nexport MPWD=$P\n}\n\nfunction back( )\n{\nLIMIT=$1\nP=$MPWD\nfor ((i=1; i <= LIMIT; i++))\ndo\n P=${P%/..}\ndone\ncd $P\nexport MPWD=$P\n}\n" }, { "answer_id": 245784, "author": "Ethan Post", "author_id": 4527, "author_profile": "https://Stackoverflow.com/users/4527", "pm_score": 3, "selected": false, "text": "function mycd {\n\nMYCD=/tmp/mycd.txt\ntouch ${MYCD}\n\ntypeset -i x\ntypeset -i ITEM_NO\ntypeset -i i\nx=0\n\nif [[ -n \"${1}\" ]]; then\n if [[ -d \"${1}\" ]]; then\n print \"${1}\" >> ${MYCD}\n sort -u ${MYCD} > ${MYCD}.tmp\n mv ${MYCD}.tmp ${MYCD}\n FOLDER=${1}\n else\n i=${1}\n FOLDER=$(sed -n \"${i}p\" ${MYCD})\n fi\nfi\n\nif [[ -z \"${1}\" ]]; then\n print \"\"\n cat ${MYCD} | while read f; do\n x=$(expr ${x} + 1)\n print \"${x}. ${f}\"\n done\n print \"\\nSelect #\"\n read ITEM_NO\n FOLDER=$(sed -n \"${ITEM_NO}p\" ${MYCD})\nfi\n\nif [[ -d \"${FOLDER}\" ]]; then\n cd ${FOLDER}\nfi\n\n}\n" }, { "answer_id": 255374, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "lpr lpr" }, { "answer_id": 398647, "author": "Alex", "author_id": 30181, "author_profile": "https://Stackoverflow.com/users/30181", "pm_score": 1, "selected": false, "text": " ls -l -t | awk 'NR<15{print $0}'\n" }, { "answer_id": 563796, "author": "robmandu", "author_id": 67082, "author_profile": "https://Stackoverflow.com/users/67082", "pm_score": 1, "selected": false, "text": "@echo off\n\nGOTO :MAIN\n###########################################################\n#\n# Reason: \n# This script runs the defrag utility.\n#\n# Suggestion:\n# Schedule this script to run daily (via schtasks)\n#\n# Example:\n# SCHTASKS /Create /SC DAILY /ST 03:00:00 \n# /TR \\\"C:\\path\\to\\DAILY_DEFRAG.BAT\" /TN \"Daily Defrag of C Drive\\\"\n#\n# Example:\n# AT 03:00 /every:Su,M,T,W,Th,F,Sa C:\\path\\to\\DAILY_DEFRAG.BAT\n#\n# Required OS: \n# Windows XP or Windows Server 2003\n#\n# Required files:\n# DEFRAG.EXE\n#\n#\n###########################################################\n\n:MAIN\n\n :: Output a listing of scheduled tasks\n SCHTASKS /QUERY /V > C:\\temp\\schtasks.out\n\n\n\n :: *****************************************************\n :: * SITE SPECIFIC Program Parameters *\n :: *****************************************************\n :: * Drive to defrag\n SET TARGET=C:\n\n :: * Log file\n SET LOGFILE=C:\\temp\\defrag.log\n\n\n :: *****************************************************\n :: * No editable parameters below this line *\n :: *****************************************************\n\n\n SETLOCAL\n\n\n :: Announce intentions\n echo.\n echo Beginning defragmentation of disk %TARGET%\n echo ----------------------------------------------\n\n echo.\n for /f \"tokens=1 delims=_\" %%a in ('date /t') do set NOW=%%a\n for /f \"tokens=1 delims=_\" %%a in ('time /t') do set NOW=%NOW% %%a\n echo Start time: %NOW%\n\n :: Run the defrag utility\n C:\\WINNT\\SYSTEM32\\defrag.exe %TARGET% -f -v > %LOGFILE%\n\n echo.\n for /f \"tokens=1 delims=_\" %%a in ('date /t') do set NOW=%%a\n for /f \"tokens=1 delims=_\" %%a in ('time /t') do set NOW=%NOW% %%a\n echo End time: %NOW%\n\n echo.\n echo ----------------------------------------------\n echo Defrag complete. \n echo.\n\n\n:END\n" }, { "answer_id": 592936, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 1, "selected": false, "text": "rsync" }, { "answer_id": 655854, "author": "Telemachus", "author_id": 26702, "author_profile": "https://Stackoverflow.com/users/26702", "pm_score": 2, "selected": false, "text": "fortune telemachus ~ $ haiku \n\n January--\nin other provinces,\n plums blooming.\n Issa\n" }, { "answer_id": 684083, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "#!/usr/bin/php -f\n<?php\n$process = $argv[1];\necho shell_exec(\"ps -ef | grep $process | grep -v grep\");\nexit(0);" }, { "answer_id": 684147, "author": "Eddy", "author_id": 67900, "author_profile": "https://Stackoverflow.com/users/67900", "pm_score": 1, "selected": false, "text": "\n#!/bin/bash \n\n\nBACKUPDIR=/media/proxy/store/backups/ \n\n[ ! -d $BACKUPDIR ] && { echo \"BACKUP DIRECTORY NOT AVAILABLE!\"; exit; } \n\ndobackup() { \n SDIR=$2 \n PARENTDIR=$1 \n echo \"BACKING UP $PARENTDIR/$SDIR to $BACKUPDIR\" \n bnum=20\n count=$bnum\n [ -d ${BACKUPDIR}${SDIR}.$bnum ] && { mv ${BACKUPDIR}${SDIR}.$bnum ${BACKUPDIR}${SDIR}.tmp; }\n until [ $count -eq 1 ]; do\n let lastdir=$count-1\n [ -d ${BACKUPDIR}${SDIR}.$lastdir ] && { mv ${BACKUPDIR}${SDIR}.$lastdir ${BACKUPDIR}${SDIR}.$count; }\n let count-=1\n done\n cp -al ${BACKUPDIR}${SDIR}.0 ${BACKUPDIR}${SDIR}.1\n rsync -a --delete --bwlimit=2000 $PARENTDIR/$SDIR ${BACKUPDIR}${SDIR}.0\n}\n\nfor backup in $(cat /sbin/backup.directories); do\n PDIR=$(echo $backup | awk -F '::' {'print$1'})\n DIR=$(echo $backup | awk -F '::' {'print$2'})\n dobackup $PDIR $DIR\ndone\n\nexit;\n\n\ncat /sbin/backup.directories\n/media/warehouse::Archive\n/media/warehouse::concept\n\n" }, { "answer_id": 1040037, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "grep -R sourcecodetext sourcedir | nosvn\n alias nosvn=\"grep -v \\\"\\.svn\\|tags\\|cscope\\|Binary\\\"\"\nalias less=\"less -R\"\nalias diff=\"colordiff -u\"\nalias cgrep=\"grep --color=always\"\n\nexport GREP_OPTIONS='--color=auto'\n #!/bin/bash\n\nold_file=$1\ntmp_file=$2\nold_hex=$3\nold_mode=$4\nnew_file=$5\nnew_mode=$6\n\ncolordiff -u $old_file $tmp_file\n [diff]\n external = $HOME/bin/gitdiffwrapper\n diff-cmd = /usr/bin/colordiff\n" }, { "answer_id": 1768775, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "copy con c.bat\nc:\ncd\\\ncls\n^Z\n" }, { "answer_id": 5629703, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "en() {\nif [[ -z $1 ]] ; then\nls '.'\n\nelif [[ -d $1 ]] ; then\ncd $1\n\nelif [[ -f $1 ]] ; then\nless <$1\nfi\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25664/" ]
188,166
<p>I am using Team Foundation Server (TFS) for Visual Studio 2005.</p> <p>Whenever i wish to compare two file's versions TFS displays a window with the differences.</p> <p><strong>The problem is that it is always split vertically.</strong></p> <p>In fact, almost every time, <strong>i would prefer to have it split horizontally.</strong> I've already looked at TFS options and googled but i found nothing. I'm appalled to think that such option is not available!</p> <p>Is there any way to configure TFS to split it horizontally?</p>
[ { "answer_id": 36343799, "author": "palswim", "author_id": 393280, "author_profile": "https://Stackoverflow.com/users/393280", "pm_score": 0, "selected": false, "text": ".* Compare Merge WinMergeU.exe /x /e /u /wl /wr /dl %6 /dr %7 %1 %2" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335/" ]
188,184
<p>Here I have:</p> <pre><code>Public Structure MyStruct Public Name as String Public Content as String End Structure Dim oStruct as MyStruct = New MyStruct() oStruct.Name = ... oStruct.Content = ... Dim alList as ArrayList = new ArrayList() alList.Add(oStruct) </code></pre> <p>I'd like to convert the ArrayList to a static strongly-typed Array of type MyStruct. How can I do that? I had no luck with ToArray.</p> <p>I am using .NET Framework 2.0.</p>
[ { "answer_id": 188196, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "ToArray MyStruct[] structs = (MyStruct[]) alList.ToArray(typeof(MyStruct));\n" }, { "answer_id": 188197, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "ArrayList list = new ArrayList();\nMyStruct[] array = new MyStruct[list.Count];\nlist.CopyTo(array); \n public class SomeType\n{\n public string Name {get;set;}\n public string Content {get;set;}\n}\n" }, { "answer_id": 188203, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "MyStruct[] array = (MyStruct[]) alList.ToArray(typeof(MyStruct));\n" }, { "answer_id": 188215, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "Dim array As MyStruct() = alList.ToArray(GetType(MyStruct))\n" }, { "answer_id": 188223, "author": "John Chuckran", "author_id": 25511, "author_profile": "https://Stackoverflow.com/users/25511", "pm_score": 0, "selected": false, "text": " Dim alList As New List(Of MyStruct)\n alList.Add(oStruct)\n" }, { "answer_id": 188227, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "Dim alList as New List(Of MyStruct)()\nalList.Add(oStruct)\n IEnumerable<T>, IList<T>, or ICollection<T> New List<MyStruct>" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
188,188
<p>We recently upgraded an application that that contained web services using the WSE 2.0 to .NET 3.5. When we converted the project in Visual Studio 2008, It did not mention anything about the removing and/or modifying the WSE 2.0 namespaces. Here is the basic architecture of the web services in the .NET 1.1 project.</p> <p>Web Service Source Code:</p> <pre><code>[WebService(Namespace="http://tempuri.org")] public class MyWebService : BaseWebService { //Do some stuff } </code></pre> <p>BaseWebService Source Code:</p> <pre><code>using Microsoft.Web.Services2; using Microsoft.Web.Services2.Security; using Microsoft.Web.Services2.Security.Tokens; namespace MyNameSpace { public class BaseWebService : System.Web.Services.WebService { public BaseWebService() { if(RequestSoapContext.Current == null) throw new ApplicationExcpetion("Only SOAP requests are permitted."); } } } </code></pre> <p>During the conversion, the BaseWebService.cs class was excluded from the project and the WSE2.0 namespaces were removed from the class.</p> <p>Have anyone else experiences any issues with trying to upgrade a web service from .NET 1.1 using the WSE to .NET 3.5?</p> <p>This is related to the previous question I had regarding a client consuming the upgraded web service:</p> <p><a href="https://stackoverflow.com/questions/185420/issues-with-client-consuming-a-net-web-service-upgraded-from-net-11-to-35">Stack Overflow Question</a></p>
[ { "answer_id": 202052, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 0, "selected": false, "text": "<system.web>\n <webServices>\n <soapExtensionTypes>\n <add type=\"Microsoft.Web.Services2.WebServicesExtension, Microsoft.Web.Services2, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" priority=\"1\" group=\"0\" />\n <!--<add type=\"Microsoft.Web.Services2.Configuration.WebServicesConfiguration, Microsoft.Web.Services2, Version=2.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>-->\n </soapExtensionTypes>\n </webServices> \n</system.web> \n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
188,208
<p>There seem to be two bash idioms for redirecting STDOUT and STDERR to a file:</p> <pre><code>fooscript &amp;&gt; foo </code></pre> <p>... and ...</p> <pre><code>fooscript &gt; foo 2&gt;&amp;1 </code></pre> <p>What's the difference? It seems to me that the first one is just a shortcut for the second one, but my coworker contends that the second one will produce no output even if there's an error with the initial redirect, whereas the first one will spit redirect errors to STDOUT.</p> <p><strong>EDIT</strong>: Okay... it seems like people are not understanding what I am asking, so I will try to clarify:</p> <p>Can anyone give me an example where the two <em>specific lines</em> lines written above will yield different behavior?</p>
[ { "answer_id": 188217, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "&> foo # Will take all and redirect all output to foo.\n\n2>&1 # will redirect stderr to stdout.\n" }, { "answer_id": 188230, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "2>&1" }, { "answer_id": 188307, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "&>foo >foo 2>&1 2>&1 1> |" }, { "answer_id": 188320, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 2, "selected": false, "text": "2>&1 &> 2>&1 program >> alloutput.log 2>&1" }, { "answer_id": 188326, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 4, "selected": true, "text": "&>word\n >&word\n >word 2>&1\n" }, { "answer_id": 188415, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 3, "selected": false, "text": "fooscript &> foo\n fooscript > foo 2>&1\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034/" ]
188,209
<p>I have a page something.aspx, with associated codebehind something.aspx.cs. In that codebehind, I want to know the filesystem location of something.aspx. Is there any convenient way to get it?</p> <p>Update: I got several excellent answers, which unfortunately didn't work because of something else crazy I'm doing. I'm encoding some additional information on the URL I pass in, so it looks like this:</p> <p><a href="http://server/path/something.aspx/info1/info2/info3.xml" rel="nofollow noreferrer">http://server/path/something.aspx/info1/info2/info3.xml</a></p> <p>The server deals with this OK (and I'm not using querystring parameters to work around some other code that I didn't write). But when I call Server.MapPath(Request.Url.ToString()) I get an error that the full URL with the 'info' segments isn't a valid virtual path.</p>
[ { "answer_id": 188219, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 3, "selected": false, "text": "// File path\nstring absoluteSystemPath = Server.MapPath(\"~/relative/path.aspx\");\n// Directory path\nstring dir = System.IO.Path.GetDirectoryName(absoluteSystemPath);\n// Or simply\nstring dir2 = Server.MapPath(\"~/relative\");\n" }, { "answer_id": 188222, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 3, "selected": false, "text": "string physicalPath = Server.MapPath(Request.Url);\n" }, { "answer_id": 188347, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "Server.MapPath( Request.AppRelativeCurrentExecutionFilePath )" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6310/" ]
188,225
<p>I use Visual C++ 2008 in Visual Studio 2008. I frequently use the following command to diff an open file against its most recent checked-in version:</p> <pre><code>File | Source Control | Compare... </code></pre> <p>I can also do the same thing by clicking on an icon in the Source Control toolbar.</p> <p>I'm not certain, but I believe this command is the same for any source control plugin (I happen to use the Perforce plugin.)</p> <p>I'd like to assign a keyboard shortcut to execute this command but I can't seem to find it listed anywhere in dialog where such assignments are normally made:</p> <pre><code>Tools | Customize... | Commands </code></pre> <p>Did I just not see the command in the customize dialog? Is there another method to assign such a keyboard shortcut?</p>
[ { "answer_id": 188528, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 1, "selected": false, "text": "Tools | Options | Environment | Keyboard File.Compare" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ]
188,242
<p>I just downloaded and installed the latest Adventure Works database from <a href="http://www.codeplex.com/MSFTDBProdSamples/Release/ProjectReleases.aspx?ReleaseId=16040" rel="nofollow noreferrer">http://www.codeplex.com/MSFTDBProdSamples/Release/ProjectReleases.aspx?ReleaseId=16040</a> to do some more playing around with LINQ and found that there are some data types that are not natively supported within Visual Studio 2008. I get the "One or more selected items contain a data type that is not supported by the designer." error message. </p> <p>I found that the spatial data type is the issue in this case. </p> <p>My questions are:</p> <ul> <li>What other data types are not inherently supported by Visual Studio that is in SQL Serve 2008?</li> <li>Why are these types not supported?</li> </ul> <p>The second question is I guess the most puzzling to me. I can understand why not all data types would be supported from MySQL, Oracle, Postgre SQL and so forth. I would think that the SQLServer development group, might give a heads up to the Visual Studio development group, you know yell down the hall or something. </p>
[ { "answer_id": 8906546, "author": "Pavan Bhardwaj", "author_id": 1155634, "author_profile": "https://Stackoverflow.com/users/1155634", "pm_score": 2, "selected": false, "text": "Geometry Geography CAST(geography_column AS VARBINARY(MAX)) Server Explorer Database Explorer" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5578/" ]
188,248
<p>Does anyone have any info on creating/drawing a customised ListView object?</p> <p>Currently Im working on a project that requires a customised look and feel within the application. I am using a standard (Windows.Forms) ListView which is not in the same style as the rest of the GUI. We are NOT using a toolbox for custom controls, all controlls are 'skinned' inhouse as it were by overriding hte OnPaint() method for each control.</p> <p>What Im looking for is: - Information about how to handle drawing of the Scroll Bar. - How to use customised drawing routines to handle the column headers. - How to still handle the data shown and draw that correctly.</p> <p>Any and all help would be greatly received.</p>
[ { "answer_id": 188824, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": true, "text": "NM_CUSTOMDRAW" }, { "answer_id": 189131, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "ListBox OwnerDrawVariable OnDrawItem OnMeasureItem object" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
188,250
<p>I believe there is a discussion on this very topic somewhere on the net but I lost the url and I am unable to find it via googling.</p> <p>What I might try right now would be:</p> <pre><code>ISessionFactoryHolder factoryHolder = ActiveRecordMediator&lt;EntityClass&gt;.GetSessionFactoryHolder(); ISession session = factoryHolder.CreateSession(typeof(EntityClass)); try { IDbCommand cmd = session.Connection.CreateCommand(); cmd.CommandText = "spName"; cmd.ExecuteNonQuery(); } catch(Exception ex) { } finally { factoryHolder.ReleaseSession(session); } </code></pre> <p>However, I am not quite sure if this is the correct way to do this or if perhaps a better way exists.</p>
[ { "answer_id": 325642, "author": "Mauricio Scheffer", "author_id": 21239, "author_profile": "https://Stackoverflow.com/users/21239", "pm_score": 1, "selected": false, "text": "ActiveRecordMediator.GetSessionFactoryHolder()\n .GetSessionFactory(typeof(ActiveRecordBase))\n .ConnectionProvider.GetConnection();\n" }, { "answer_id": 4246582, "author": "peter miller", "author_id": 516240, "author_profile": "https://Stackoverflow.com/users/516240", "pm_score": 2, "selected": false, "text": "// get Connection\nSystem.Data.IDbConnection con = ActiveRecordMediator.GetSessionFactoryHolder()\n .GetSessionFactory(typeof(Autocomplete))\n .ConnectionProvider.GetConnection();\n\n// set Command\nSystem.Data.IDbCommand cmd = con.CreateCommand();\ncmd.CommandText = \"name_of_stored_procedure\";\ncmd.CommandType = System.Data.CommandType.StoredProcedure;\n\n// set Parameter of Stored Procedure\nSystem.Data.SqlClient.SqlParameter param = new System.Data.SqlClient.SqlParameter(\"@parameter_name\", System.Data.SqlDbType.NVarChar);\nparam.Value = \"value_of_parameter\";\n((System.Data.SqlClient.SqlParameterCollection)cmd.Parameters).Add(param);\n\n// call Stored Procedure (without getting result)\ncmd.ExecuteNonQuery();\n\n// ... or read results\nSystem.Data.SqlClient.SqlDataReader r = (System.Data.SqlClientSqlDataReader)cmd.ExecuteReader();\nwhile(r.Read()) {\n System.Console.WriteLine(\"result first col: \" + r.GetString(0));\n}\n" }, { "answer_id": 5749406, "author": "yorch", "author_id": 443600, "author_profile": "https://Stackoverflow.com/users/443600", "pm_score": 0, "selected": false, "text": "IDbConnection connection = ActiveRecordMediator.GetSessionFactoryHolder()\n .GetSessionFactory(typeof(ActiveRecordBase))\n .OpenSession().Connection;\n" }, { "answer_id": 23934416, "author": "Christian", "author_id": 3687724, "author_profile": "https://Stackoverflow.com/users/3687724", "pm_score": -1, "selected": false, "text": "public ArrayList DevolverCamposDeObjetoSTP(T Objeto, List<Consulta> Consultas, string StoredProcedureName)\n {\n ArrayList results;\n try\n {\n var queryString = @\"EXEC \" + StoredProcedureName;\n foreach (var consulta in Consultas)\n {\n switch (consulta.tipoCampo)\n {\n case Consulta.TipoCampo.dato:\n queryString = queryString + \" \" + consulta.Campo + \" = \" + \"'\" + consulta.Valor + \"'\";\n break;\n case Consulta.TipoCampo.numero:\n queryString = queryString + \" \" + consulta.Campo + \" = \" + consulta.Valor;\n break;\n } \n queryString = queryString + \",\";\n }\n queryString = queryString.Remove(queryString.Count() - 1, 1);\n var query = new HqlBasedQuery(typeof(T),QueryLanguage.Sql, queryString);\n results = (ArrayList)ActiveRecordMediator.ExecuteQuery(query);\n }\n catch (Exception exception)\n {\n throw new Exception(exception.Message);\n }\n return results;\n }\npublic class Consulta\n{\n public enum TipoCampo\n {\n dato,\n numero\n }\n public string Campo { get; set; }\n public TipoCampo tipoCampo { get; set; }\n public string Valor { get; set; }\n public string Indicador { get; set; }\n}\npublic void _Pruebastp()\n {\n var p = new Recurso().DevolverCamposDeObjetoSTP(\n new Recurso(),\n new List<Consulta> { new Consulta { Campo = \"@nombre\", tipoCampo = Consulta.TipoCampo.dato, Valor = \"chr\" }, new Consulta { Campo = \"@perfil\", tipoCampo = Consulta.TipoCampo.numero, Valor = \"1\" } },\n \"Ejemplo\");\n }\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15396/" ]
188,281
<p>In Delphi 2009 I'm finding that any time I use TThread.CurrentThread in an application, I'll get an error message like the following when the application closes:</p> <pre><code>Exception EAccessViolation in module ntdll.dll at 0003DBBA. Access violation at address 7799DBBA in module 'ntdll.dll'. Write of address 00000014. </code></pre> <p>Unless it's just my machine, you can replicate this in a few seconds: create a new Delphi Forms Application, add a button to the form, and use something like the following for the button's event handler:</p> <pre><code>procedure TForm1.Button1Click(Sender: TObject); begin TThread.CurrentThread; end; </code></pre> <p>On both my Vista machine and my XP machine I'm finding that, if I <em>don't</em> click the button everything's fine, but if I <em>do</em> click the button I get the above error message when I close the application.</p> <p>So... I'm wondering if this is a bug, but at the same time I think it's rather likely that I'm simply not understanding something very basic about how you're supposed to work with TThreads in Delphi. I am a bit of a Delphi newbie I'm afraid.</p> <p>Is there something obviously wrong with using TThread.CurrentThread like that?</p> <p>If not, and you have Delphi 2009, do you get the same problem if you implement my simple sample project?</p> <hr> <h2><strong>Update: As François noted below, this actually is a bug in Delphi 2009 at the moment - you can <a href="http://qc.codegear.com/wc/qcmain.aspx?d=67726" rel="noreferrer">vote for it here</a>.</strong></h2> <hr> <h2><strong>Update: This bug was fixed in Delphi 2010.</strong></h2>
[ { "answer_id": 188448, "author": "Francesca", "author_id": 9842, "author_profile": "https://Stackoverflow.com/users/9842", "pm_score": 5, "selected": true, "text": "DoneThreadSynchronization ThreadLock FreeExternalThreads CurrentThread EnterCriticalSection(ThreadLock) TThread.RemoveQueuedEvents" }, { "answer_id": 192027, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 4, "selected": false, "text": "{ Fix Delphi 2009's invalid finalization order in Classes.pas.\n Written by Primoz Gabrijelcic, http://gp.17slon.com.\n No rights reserved - released to public domain.\n}\nunit FixD2009Classes;\n\ninterface\n\nimplementation\n\nuses\n Windows,\n SysUtils,\n Classes;\n\ntype\n TCode = array [0..109] of byte;\n\n{$WARN SYMBOL_PLATFORM OFF}\n\nprocedure PatchClasses;\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\nvar\n i : integer;\n oldProtect: cardinal;\n pCode : ^TCode;\n tmp : DWORD;\nconst\n COffsets_Call: array [1..12] of integer = (0, 15, 24, 34, 49, 59, 69, 79, 89, 94, 99, 109);\n COffset_UnRegisterModuleClasses = 106;\n COffset_DoneThreadSynchronization = 94;\n COffset_FreeExternalThreads = 99;\n CCallDelta = COffset_FreeExternalThreads - COffset_DoneThreadSynchronization;\n{$IFEND}\n{$ENDIF}\nbegin\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\n pCode := pointer(cardinal(@TStreamReader.ReadToEnd) + COffset_UnRegisterModuleClasses);\n Win32Check(VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], PAGE_READWRITE, oldProtect));\n try\n for i := Low(COffsets_Call) to High(COffsets_Call) do\n if pCode^[COffsets_Call[i]] <> $E8 then\n raise Exception.Create('Unexpected version of Classes - cannot patch');\n tmp := PDword(@pCode^[COffset_DoneThreadSynchronization+1])^;\n PDword(@pCode^[COffset_DoneThreadSynchronization+1])^ :=\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ + CCallDelta;\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ := tmp - CCallDelta;\n finally VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], oldProtect, oldProtect); end;\n{$IFEND}\n{$ENDIF}\nend;\n\ninitialization\n PatchClasses;\nend.\n" }, { "answer_id": 982021, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": false, "text": "{ Fix Delphi 2009's invalid finalization order in Classes.pas.\n Written by Primoz Gabrijelcic, http://gp.17slon.com.\n No rights reserved - released to public domain.\n\n D2009 update 3 only.\n}\nunit FixD2009Classes;\n\ninterface\n\nimplementation\n\nuses\n Windows,\n SysUtils,\n Classes;\n\ntype\n TCode = array [0..144] of byte;\n\n{$WARN SYMBOL_PLATFORM OFF}\n\nprocedure PatchClasses;\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\nvar\n i : integer;\n oldProtect: cardinal;\n pCode : ^TCode;\n tmp : DWORD;\nconst\n COffsets_Call: array [1..12] of integer = (0, 15, 24, 42, 47, 58, 73, 91, 101, 111, 134, 139);\n COffset_UnRegisterModuleClasses = 107;\n COffset_DoneThreadSynchronization = 134;\n COffset_FreeExternalThreads = 139;\n CCallDelta = COffset_FreeExternalThreads - COffset_DoneThreadSynchronization;\n{$IFEND}\n{$ENDIF}\nbegin\n{$IFDEF ConditionalExpressions}\n{$IF RTLVersion = 20}\n pCode := pointer(cardinal(@TStreamReader.ReadToEnd) + COffset_UnRegisterModuleClasses);\n Win32Check(VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], PAGE_READWRITE, oldProtect));\n try\n for i := Low(COffsets_Call) to High(COffsets_Call) do\n if pCode^[COffsets_Call[i]] <> $E8 then\n raise Exception.Create('Unexpected version of Classes - cannot patch');\n tmp := PDword(@pCode^[COffset_DoneThreadSynchronization+1])^;\n PDword(@pCode^[COffset_DoneThreadSynchronization+1])^ :=\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ + CCallDelta;\n PDword(@pCode^[COffset_FreeExternalThreads+1])^ := tmp - CCallDelta;\n finally VirtualProtect(pCode, COffsets_Call[High(COffsets_Call)], oldProtect, oldProtect); end;\n{$IFEND}\n{$ENDIF}\nend;\n\ninitialization\n PatchClasses;\nend.\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11961/" ]
188,299
<p>I have the following struct in C++:</p> <pre><code>#define MAXCHARS 15 typedef struct { char data[MAXCHARS]; int prob[MAXCHARS]; } LPRData; </code></pre> <p>And a function that I'm p/invoking into to get an array of 3 of these structures:</p> <pre><code>void GetData(LPRData *data); </code></pre> <p>In C++ I would just do something like this:</p> <pre><code>LPRData *Results; Results = (LPRData *)malloc(MAXRESULTS*sizeof(LPRData)); GetData( Results ); </code></pre> <p>And it would work just fine, but in C# I can't seem to get it to work. I've created a C# struct like this:</p> <pre><code>public struct LPRData { /// char[15] [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)] public string data; /// int[15] [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)] public int[] prob; } </code></pre> <p>And if I initialize an array of 3 of those (and all their sub-arrays) and pass it into this:</p> <pre><code>GetData(LPRData[] data); </code></pre> <p>It returns with success, but the data in the LPRData array has not changed.</p> <p>I've even tried to create a raw byte array the size of 3 LPRData's and pass that into a function prototype like this:</p> <p>GetData(byte[] data);</p> <p>But in that case I will get the "data" string from the very first LPRData structure, but nothing after it, including the "prob" array from the same LPRData.</p> <p>Any ideas of how to properly handle this?</p>
[ { "answer_id": 188396, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 4, "selected": false, "text": "static extern void GetData([Out] out IntPtr ptr);\n\nLPRData[] GetData()\n{\n IntPtr value;\n LPRData[] array = new LPRData[3];\n GetData(out value);\n for (int i = 0; i < array.Length; i++)\n {\n array[i] = Marshal.PtrToStructure(value, typeof(LPRData));\n value += Marshal.SizeOf(typeof(LPRData));\n }\n return array;\n}\n" }, { "answer_id": 188407, "author": "denny", "author_id": 27, "author_profile": "https://Stackoverflow.com/users/27", "pm_score": 6, "selected": true, "text": "[StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]\npublic struct LPRData\n{\n/// char[15]\n[MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]\npublic string data;\n\n/// int[15]\n[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]\npublic int[] prob;\n}\n" }, { "answer_id": 9189225, "author": "Zenexer", "author_id": 1188377, "author_profile": "https://Stackoverflow.com/users/1188377", "pm_score": 2, "selected": false, "text": "CharSet CharSet.Ansi wchar_t char [Serializable]\n[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\npublic struct LPRData\n{\n [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 15)]\n public string data;\n\n [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 15)]\n public int[] prob;\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
188,306
<p>Right now, my SVN repository is on my laptop's HDD (although I use a code hosting service for more "critical" personal projects) and I just copy the directory over on a weekly basis (which will eventually be scripted or perhaps I'll make an app for the hell of it). Am I at risk for corrupting my SVN repository? So far, I haven't had any problems with the original or the copy, but that doesn't mean that I'm not at risk in the future.</p>
[ { "answer_id": 188319, "author": "Benjamin W. Smith", "author_id": 1068060, "author_profile": "https://Stackoverflow.com/users/1068060", "pm_score": 5, "selected": true, "text": "--clean-logs svnadmin" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
188,311
<p>In a nutshell, the hashCode contract, according to Java's object.hashCode():</p> <ol> <li>The hash code shouldn't change unless something affecting equals() changes</li> <li>equals() implies hash codes are ==</li> </ol> <p>Let's assume interest primarily in immutable data objects - their information never changes after they're constructed, so #1 is assumed to hold. That leaves #2: the problem is simply one of confirming that equals implies hash code ==.</p> <p>Obviously, we can't test every conceivable data object unless that set is trivially small. So, what is the best way to write a unit test that is likely to catch the common cases?</p> <p>Since the instances of this class are immutable, there are limited ways to construct such an object; this unit test should cover all of them if possible. Off the top of my head, the entry points are the constructors, deserialization, and constructors of subclasses (which should be reducible to the constructor call problem).</p> <p>[I'm going to try to answer my own question via research. Input from other StackOverflowers is a welcome safety mechanism to this process.]</p> <p>[This could be applicable to other OO languages, so I'm adding that tag.]</p>
[ { "answer_id": 188345, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "Set MySet s1 = new MySet( new String[]{\"Hello\", \"World\"} );\nMySet s2 = new MySet( new String[]{\"World\", \"Hello\"} );\nassertEquals(s1, s2);\nassertTrue( s1.hashCode()==s2.hashCode() );\n" }, { "answer_id": 188665, "author": "Rob Spieldenner", "author_id": 5118, "author_profile": "https://Stackoverflow.com/users/5118", "pm_score": 1, "selected": false, "text": "A one = new A(...);\nA two = new A(...);\nassertEquals(\"These should be equal\", one, two);\nint oneCode = one.hashCode();\nassertEquals(\"HashCodes should be equal\", oneCode, two.hashCode());\nassertEquals(\"HashCode should not change\", oneCode, one.hashCode());\n" }, { "answer_id": 193278, "author": "Paul Brinkley", "author_id": 18160, "author_profile": "https://Stackoverflow.com/users/18160", "pm_score": 2, "selected": false, "text": "hashCode equals equals() hashCode() hashCode() equals() equals() equals() equals() equals() new Data(\"foo\") new Data(\"foo\") new Data(new String(\"foo\")) Data.equals() equals Collection" }, { "answer_id": 17777837, "author": "Raedwald", "author_id": 545127, "author_profile": "https://Stackoverflow.com/users/545127", "pm_score": 0, "selected": false, "text": "Thing ThingTest ThingTest public static void checkInvariants(final Thing thing) {\n ...\n }\n Thing public static void checkInvariants(final Thing thing1, Thing thing2) {\n ObjectTest.checkInvariants(thing1, thing2);\n ... invariants that are specific to Thing\n }\n Thing ObjectTest equals hashCode hashCode equals Thing checkInvariants checkInvariants" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18160/" ]
188,327
<p>My question is on the ASP.NET GridView control. I am using a CommandField in the Columns tag as seen below.</p> <pre><code>&lt;asp:CommandField ShowEditButton="True" HeaderStyle-Width="40px" UpdateText="Save" ButtonType="Link" HeaderStyle-Wrap="true" ItemStyle-Wrap="true" ItemStyle-Width="40px"/&gt; </code></pre> <p>What renders is the shown in the following image (after I click on the Edit button). </p> <p><a href="https://i.stack.imgur.com/BUGrY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BUGrY.jpg" alt="alt text"></a></p> <p>As you can see <strong>I am trying to have the Cancel link show up a new line and my question is how do you do what?</strong> If I change the <code>ButtonType="Link"</code> to <code>ButtonType="Button"</code>, I get it rendering correctly as shown below.</p> <p><a href="http://i38.tinypic.com/2pqopxi.jpg" rel="nofollow noreferrer">alt text http://i38.tinypic.com/2pqopxi.jpg</a></p> <p>I've tried Google already and maybe I'm not searching on the right tags but I couldn't see this one addressed before.</p>
[ { "answer_id": 188662, "author": "denny", "author_id": 27, "author_profile": "https://Stackoverflow.com/users/27", "pm_score": 3, "selected": true, "text": "<asp:GridView id=\"gvGrid\" runat=\"server\" OnRowCommand=\"gvGrid_Command\">\n <Columns>\n <asp:TemplateField>\n <ItemTemplate>\n Some Stuff random content\n <br />\n <asp:LinkButton id=\"lbDoIt\" runat=\"server\" CommandName=\"Cancel\" CommandArgument=\"SomeIdentifierIfNecessary\" />\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n</asp:GridView>\n protected void gvGrid_Command(object sender, GridViewCommandEventArgs e)\n{\n if(e.CommandName==\"Cancel\")\n {\n // Do your cancel stuff here.\n }\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26573/" ]
188,349
<p>I need to knock out a quick animation in C#/Windows Forms for a Halloween display. Just some 2D shapes moving about on a solid background. Since this is just a quick one-off project I <strong><em>really</em></strong> don't want to install and learn an entire new set of tools for this. (DirectX dev kits, Silverlight, Flash, etc..) I also have to install this on multiple computers so anything beyond the basic .Net framework (2.0) would be a pain in the arse.</p> <p>For tools I've got VS2k8, 25 years of development experience, a wheelbarrow, holocaust cloak, and about 2 days to knock this out. I haven't done animation since using assembler on my Atari 130XE (hooray for page flipping and player/missile graphics!)</p> <p>Advice? Here's some of the things I'd like to know:</p> <ul> <li>I can draw on any empty widget (like a panel) by fiddling with it's OnPaint handler, right? That's how I'd draw a custom widget. Is there a better technique than this?</li> <li>Is there a page-flipping technique for this kind of thing in Windows Forms? I'm not looking for a high frame rate, just as little flicker/drawing as necessary.</li> </ul> <p>Thanks.</p> <p><strong>Post Mortem Edit ... "a couple of coding days later"</strong></p> <p>Well, the project is done. The links below came in handy although a couple of them were 404. (I wish SO would allow more than one reply to be marked "correct"). The biggest problem I had to overcome was flickering, and a persistent bug when I tried to draw on the form directly.</p> <ul> <li>Using the OnPaint event for the Form: bad idea. I never got that to work; lots of mysterious errors (stack overflows, or ArgumentNullExceptions). I wound up using a panel sized to fill the form and that worked fine.</li> <li>Using the OnPaint method is slow anyway. Somewhere online I read that building the PaintEventArgs was slow, and they weren't kidding. Lots of flickering went away when I abandoned this. Skip the OnPaint/Invalidate() and just paint it yourself. </li> <li><p>Setting all of the "double buffering" options on the form still left some flicker that had to be fixed. (And I found conflicting docs that said "set them on the control" and "set them on the form". Well controls don't have a .SetStyle() method.) I haven't tested without them, so they might be doing something (<code>this</code> is the form):</p> <pre><code> this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); </code></pre></li> </ul> <p>So the workhorse of the code wound up looking like (<code>pf</code> is the panel control):</p> <pre><code> void PaintPlayField() { Bitmap bufl = new Bitmap(pf.Width, pf.Height); using (Graphics g = Graphics.FromImage(bufl)) { g.FillRectangle(Brushes.Black, new Rectangle(0, 0, pf.Width, pf.Height)); DrawItems(g); DrawMoreItems(g); pf.CreateGraphics().DrawImageUnscaled(bufl, 0, 0); } } </code></pre> <p>And I just called PaintPlayField from the inside of my Timer loop. No flicker at all.</p>
[ { "answer_id": 188377, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 5, "selected": true, "text": "Invalidate(true)" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8173/" ]
188,351
<p>I am using a DataGridView control in a Windows Forms application. When a user holds down control to select multiple items, it works fine. Now when the user releases control and clicks (and holds down the left mouse button) to start a drag operation, the selection changes. How can I stop the selection from clearing when the user holds down the left mouse button?</p>
[ { "answer_id": 11800199, "author": "charles young", "author_id": 604608, "author_profile": "https://Stackoverflow.com/users/604608", "pm_score": 0, "selected": false, "text": " private SC.ArrayList selectedCells()\n {\n SC.ArrayList cellsList = new SC.ArrayList();\n Int32 selectedCellCount = dataViewImages.GetCellCount(DataGridViewElementStates.Selected);\n if (selectedCellCount > 0)\n {\n for (int i = 0;i < selectedCellCount; i++) {\n int cell = dataViewImages.SelectedCells[i].RowIndex*ShowImages.NumColumnsForWidth() + dataViewImages.SelectedCells[i].ColumnIndex;\n cellsList.Add(cell);\n }\n cellsList.Sort();\n return cellsList;\n }\n else\n return null;\n }\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
188,364
<p>I've created a language pack for a site before, but I'm not sure if what I'm doing is the best method.</p> <p>Basically, all I have is a file with variables defining string constants. Usually a set of arrays where an array usually refers to a particular elements of the site.</p> <p>Then the site code just includes the appropriate file based on a flag and then echo's out the appropriate array element. </p> <p>What are some ways of doing this to reduce maintenance headaches and performance?</p>
[ { "answer_id": 188401, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "define('SOME_STRING', 'Some string'); translate('My String') translate('I can count to [number]', 10);" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26577/" ]
188,366
<p>I am trying to run a query that will give time averages but when I do... some duplicate records are in the calculation. how can I remove duplicates?</p> <p>ex.</p> <p>Column 1 / 07-5794 / 07-5794 / 07-5766 / 07-8423 / 07-4259</p> <p>Column 2 / 00:59:59 / 00:48:22 / 00:42:48/ 00:51:47 / 00:52:12</p> <p>I can get the average of the column 2 but I don't want identical values in column 1 to be calculated twice (07-5794) ???</p>
[ { "answer_id": 188380, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 1, "selected": false, "text": "select avg(min_time) as avg_time from\n (select incnum, min(col2) as min_time from inc group by incnum)\n" }, { "answer_id": 188394, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 0, "selected": false, "text": "SELECT AVG(col2)\n FROM (\n SELECT col1, MAX(col2) AS col2\n FROM table\n GROUP BY col1\n HAVING COUNT(*) = 1\n )\n" }, { "answer_id": 188436, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 0, "selected": false, "text": "select Column1, Avg(Convert(decimal,Column2)) \nfrom Table1\nwhere TableId in\n(\nselect Max(TableId)\nfrom Table1\ngroup by Column1\n)\ngroup by column1\n CREATE TABLE [dbo].[Table1] (\n[TableId] [int] IDENTITY (1, 1) NOT NULL ,\n[Column1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\n[Column2] [int] NULL ) ON [PRIMARY]\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
188,373
<p>I'd like to re-brand (and send error emails) for all of the SSRS default error pages (picture below) when you access reports via /ReportServer/. I'm already handling the ASP OnError event and <em>some</em> of the default SSRS errors appear to catch their own exceptions and then render this page cancel the response all before the OnError event is ever fired.</p> <p>Any idea on how I can get a handle into SSRS to brand all error pages?</p> <p><img src="https://www.jazz2online.com/junk/reporting_error.gif" alt="Reporting Services Error"></p>
[ { "answer_id": 188380, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 1, "selected": false, "text": "select avg(min_time) as avg_time from\n (select incnum, min(col2) as min_time from inc group by incnum)\n" }, { "answer_id": 188394, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 0, "selected": false, "text": "SELECT AVG(col2)\n FROM (\n SELECT col1, MAX(col2) AS col2\n FROM table\n GROUP BY col1\n HAVING COUNT(*) = 1\n )\n" }, { "answer_id": 188436, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 0, "selected": false, "text": "select Column1, Avg(Convert(decimal,Column2)) \nfrom Table1\nwhere TableId in\n(\nselect Max(TableId)\nfrom Table1\ngroup by Column1\n)\ngroup by column1\n CREATE TABLE [dbo].[Table1] (\n[TableId] [int] IDENTITY (1, 1) NOT NULL ,\n[Column1] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\n[Column2] [int] NULL ) ON [PRIMARY]\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15050/" ]
188,388
<p>I would like to have both Eclipse and Netbeans (with JUnit) installed on one system, so I can be somewhat familiar with both.</p> <p>Besides GUI development (see "<a href="https://stackoverflow.com/questions/174308/using-both-eclipse-and-netbeans">Using both Eclipse and Netbeans</a>"), are there any other issues with using both IDEs on the same system, or even the same project?</p>
[ { "answer_id": 188818, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "project.xml" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16312/" ]
188,389
<p>I try to define a schema for XML documents I receive.</p> <p>The documents look like:</p> <pre><code>&lt;root&gt; &lt;items&gt; &lt;group name="G-1"&gt; &lt;item name="I-1"/&gt; &lt;item name="I-2"/&gt; &lt;item name="I-3"/&gt; &lt;item name="I-4"/&gt; &lt;/group&gt; &lt;/items&gt; &lt;data&gt; &lt;group name="G-1" place="here"&gt; &lt;customer name="C-1"&gt; &lt;item name="I-1" count="3"/&gt; &lt;item name="I-2" count="4"/&gt; &lt;/customer&gt; &lt;customer name="C-2"&gt; &lt;item name="I-3" count="7"/&gt; &lt;/customer&gt; &lt;/group&gt; &lt;/data&gt; &lt;/root&gt; </code></pre> <p>I tried XmlSpy and xsd.exe from .NET 2.0. Both created schema definitions which allow below <code>&lt;group&gt;</code> any number of <code>&lt;item&gt;</code> and <code>&lt;customer&gt;</code> elements. But what I'm looking for should restrict <code>&lt;group&gt;</code> below <code>&lt;items&gt;</code> to <code>&lt;item&gt;</code> elements, and <code>&lt;group&gt;</code> below <code>&lt;data&gt;</code> to <code>&lt;customer&gt;</code> elements.</p> <p>Is this something xml schema is not capable at all?</p>
[ { "answer_id": 188430, "author": "Peter Meyer", "author_id": 1875, "author_profile": "https://Stackoverflow.com/users/1875", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:element name=\"root\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"items\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"group\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"item\">\n <xs:complexType>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"data\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"group\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"customer\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"item\">\n <xs:complexType>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"count\" type=\"xs:unsignedByte\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"optional\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\" />\n <xs:attribute name=\"place\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n" }, { "answer_id": 233093, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 3, "selected": false, "text": "<xs:complexType name=\"CustomerType\" abstract=\"true\" > \n <xs:sequence> \n <xs:element ref=\"cust:FirstName\" /> \n <xs:element ref=\"cust:LastName\" /> \n <xs:element ref=\"cust:PhoneNumber\" minOccurs=\"0\"/> \n </xs:sequence> \n <xs:attribute name=\"customerID\" type=\"xs:integer\" /> \n</xs:complexType>\n <xs:complexType name=\"MandatoryPhoneCustomerType\" > \n <xs:complexContent> \n <xs:restriction base=\"cust:CustomerType\"> \n <xs:sequence> \n <xs:element ref=\"cust:FirstName\" /> \n <xs:element ref=\"cust:LastName\" /> \n <xs:element ref=\"cust:PhoneNumber\" minOccurs=\"1\" /> \n </xs:sequence> \n </xs:restriction> \n </xs:complexContent> \n</xs:complexType>\n <xs:complexType name=\"AddressableCustomerType\" > \n <xs:complexContent> \n <xs:extension base=\"cust:CustomerType\"> \n <xs:sequence> \n <xs:element ref=\"cust:Address\" /> \n <xs:element ref=\"cust:City\" /> \n <xs:element ref=\"cust:State\" /> \n <xs:element ref=\"cust:Zip\" /> \n </xs:sequence> \n </xs:extension> \n </xs:complexContent> \n</xs:complexType>\n <xs:element name=\"Customer\" type=\"cust:CustomerType\" />\n <cust:Customer customerID=\"12345\" xsi:type=\"cust:MandatoryPhoneCustomerType\" > \n <cust:FirstName>Dare</cust:FirstName> \n <cust:LastName>Obasanjo</cust:LastName> \n <cust:PhoneNumber>425-555-1234</cust:PhoneNumber> \n</cust:Customer>\n <cust:Customer customerID=\"67890\" xsi:type=\"cust:AddressableCustomerType\" > \n <cust:FirstName>John</cust:FirstName> \n <cust:LastName>Smith</cust:LastName> \n <cust:Address>2001</cust:Address> \n <cust:City>Redmond</cust:City> \n <cust:State>WA</cust:State> \n <cust:Zip>98052</cust:Zip> \n</cust:Customer>\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23772/" ]
188,414
<p>I have used the XML Parser before, and even though it worked OK, I wasn't happy with it in general, it felt like I was using workarounds for things that should be basic functionality.</p> <p>I recently saw SimpleXML but I haven't tried it yet. Is it any simpler? What advantages and disadvantages do both have? Any other parsers you've used?</p>
[ { "answer_id": 188445, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 8, "selected": true, "text": "$root->myElement" }, { "answer_id": 4942773, "author": "NexusRex", "author_id": 445500, "author_profile": "https://Stackoverflow.com/users/445500", "pm_score": 5, "selected": false, "text": "<?php\n/**\n * Convert XML to an Array\n *\n * @param string $XML\n * @return array\n */\nfunction XMLtoArray($XML)\n{\n $xml_parser = xml_parser_create();\n xml_parse_into_struct($xml_parser, $XML, $vals);\n xml_parser_free($xml_parser);\n // wyznaczamy tablice z powtarzajacymi sie tagami na tym samym poziomie\n $_tmp='';\n foreach ($vals as $xml_elem) {\n $x_tag=$xml_elem['tag'];\n $x_level=$xml_elem['level'];\n $x_type=$xml_elem['type'];\n if ($x_level!=1 && $x_type == 'close') {\n if (isset($multi_key[$x_tag][$x_level]))\n $multi_key[$x_tag][$x_level]=1;\n else\n $multi_key[$x_tag][$x_level]=0;\n }\n if ($x_level!=1 && $x_type == 'complete') {\n if ($_tmp==$x_tag)\n $multi_key[$x_tag][$x_level]=1;\n $_tmp=$x_tag;\n }\n }\n // jedziemy po tablicy\n foreach ($vals as $xml_elem) {\n $x_tag=$xml_elem['tag'];\n $x_level=$xml_elem['level'];\n $x_type=$xml_elem['type'];\n if ($x_type == 'open')\n $level[$x_level] = $x_tag;\n $start_level = 1;\n $php_stmt = '$xml_array';\n if ($x_type=='close' && $x_level!=1)\n $multi_key[$x_tag][$x_level]++;\n while ($start_level < $x_level) {\n $php_stmt .= '[$level['.$start_level.']]';\n if (isset($multi_key[$level[$start_level]][$start_level]) && $multi_key[$level[$start_level]][$start_level])\n $php_stmt .= '['.($multi_key[$level[$start_level]][$start_level]-1).']';\n $start_level++;\n }\n $add='';\n if (isset($multi_key[$x_tag][$x_level]) && $multi_key[$x_tag][$x_level] && ($x_type=='open' || $x_type=='complete')) {\n if (!isset($multi_key2[$x_tag][$x_level]))\n $multi_key2[$x_tag][$x_level]=0;\n else\n $multi_key2[$x_tag][$x_level]++;\n $add='['.$multi_key2[$x_tag][$x_level].']';\n }\n if (isset($xml_elem['value']) && trim($xml_elem['value'])!='' && !array_key_exists('attributes', $xml_elem)) {\n if ($x_type == 'open')\n $php_stmt_main=$php_stmt.'[$x_type]'.$add.'[\\'content\\'] = $xml_elem[\\'value\\'];';\n else\n $php_stmt_main=$php_stmt.'[$x_tag]'.$add.' = $xml_elem[\\'value\\'];';\n eval($php_stmt_main);\n }\n if (array_key_exists('attributes', $xml_elem)) {\n if (isset($xml_elem['value'])) {\n $php_stmt_main=$php_stmt.'[$x_tag]'.$add.'[\\'content\\'] = $xml_elem[\\'value\\'];';\n eval($php_stmt_main);\n }\n foreach ($xml_elem['attributes'] as $key=>$value) {\n $php_stmt_att=$php_stmt.'[$x_tag]'.$add.'[$key] = $value;';\n eval($php_stmt_att);\n }\n }\n }\n return $xml_array;\n}\n?>\n" }, { "answer_id": 9829852, "author": "Vahan", "author_id": 976170, "author_profile": "https://Stackoverflow.com/users/976170", "pm_score": 4, "selected": false, "text": "$xml = simplexml_load_file(\"som_xml.xml\");\n\n$blocks = $xml->xpath('//block'); //gets all <block/> tags\n$blocks2 = $xml->xpath('//layout/block'); //gets all <block/> which parent are <layout/> tags\n SimpleXml C" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25910/" ]
188,422
<p>How can I transform a website to be able to handle multi language (example : english, french, spanish)?</p> <p>I do not like the resource file because I feel limited and it's pretty long to build the list. Do you have any suggestion?</p> <h2>Update</h2> <p>For the moment the best way we found is to use an XML file and with some Xpath et get values.</p>
[ { "answer_id": 188475, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 3, "selected": false, "text": " <asp:linkbutton runat='server' text='<%$ LanguageStrings:ClickMe%>' />\n <r:languagelabel runat=\"server\" name=\"AboutUs\">About Us</r:languagelabel>\n ''' <summary>\n''' Retrieves a language-specific string.\n''' </summary>\nPublic Class LanguageLabel\n Inherits Label\n\n Private _Name As String\n Public Property Name() As String\n Get\n Return _Name\n End Get\n Set(ByVal value As String)\n _Name = value\n End Set\n End Property\n\n Private Sub Populate()\n If Len(Me.Name) > 0 Then\n Dim LanguageString As String = GetLanguageString(Me.Name, Me.Text)\n If Len(LanguageString) > 0 Then Me.Text = LanguageString\n End If\n End Sub\n\n Private Sub LanguageLabel_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender\n Populate()\n End Sub\n\n Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)\n ' By default a label wraps the text in a <span>, which we don't want in some situations\n writer.Write(Me.Text)\n End Sub\n\nEnd Class\n Public Function GetLanguageString(ByVal Name As String, Optional ByVal DefaultText As String = \"\") As String\n Dim DefaultLanguage As Language = Languages.GetById(1)\n Name = StripPunctuation(Name).Trim.Replace(\" \", \"\") ' Remove punctuation, spaces from name\n Dim SelectSql As String = String.Format(\"Select {0},{1} from LanguageStrings where Name=@Name\", Languages.CurrentLanguage.Code, DefaultLanguage.Code)\n Dim LanguageStringTable As DataTable = ExecuteDataset(cs, CommandType.Text, SelectSql, New SqlParameter(\"@Name\", Name)).Tables(0)\n If LanguageStringTable IsNot Nothing AndAlso LanguageStringTable.Rows.Count > 0 Then\n Dim LanguageText As String = LanguageStringTable.Rows(0)(Languages.CurrentLanguage.Code).ToString\n Dim DefaultLanguageText As String = LanguageStringTable.Rows(0)(DefaultLanguage.Code).ToString\n If Len(LanguageText) > 0 Then\n ' We have a string in this language\n Return LanguageText\n Else\n ' Nothing in this language - return default language value\n Return DefaultLanguageText\n End If\n Else\n ' No record with this name - create a dummy one\n If DefaultText = \"\" Then DefaultText = Name\n Dim InsertSql As String = String.Format(\"Insert into LanguageStrings (Name, {0}) values (@Name, @Text)\", DefaultLanguage.Code)\n ExecuteNonQuery(cs, CommandType.Text, InsertSql, New SqlParameter(\"@Name\", Name), New SqlParameter(\"@Text\", DefaultText))\n Return Name\n End If\n End Function\n" }, { "answer_id": 11031726, "author": "Satinder singh", "author_id": 1192188, "author_profile": "https://Stackoverflow.com/users/1192188", "pm_score": 0, "selected": false, "text": " void Application_BeginRequest(Object sender, EventArgs e)\n {\n // Code that runs on application startup\n HttpCookie cookie = HttpContext.Current.Request.Cookies[\"CultureInfo\"];\n if (cookie != null &amp;&amp; cookie.Value != null)\n {\n System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);\n System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);\n }\n else\n {\n System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(\"en\");\n System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(\"en\");\n }\n }\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ]
188,425
<p>I have been trying to work my way through Project Euler, and have noticed a handful of problems ask for you to determine a prime number as part of it.</p> <ol> <li><p>I know I can just divide x by 2, 3, 4, 5, ..., square root of X and if I get to the square root, I can (safely) assume that the number is prime. Unfortunately this solution seems quite klunky.</p></li> <li><p>I've looked into better algorithms on how to determine if a number is prime, but get confused fast.</p></li> </ol> <p>Is there a simple algorithm that can determine if X is prime, and not confuse a mere mortal programmer?</p> <p>Thanks much!</p>
[ { "answer_id": 188470, "author": "Lance Roberts", "author_id": 13295, "author_profile": "https://Stackoverflow.com/users/13295", "pm_score": -1, "selected": false, "text": "Input: Integer n > 1 \n\n\nif (n is has the form ab with b > 1) then output COMPOSITE \n\nr := 2 \nwhile (r < n) { \n if (gcd(n,r) is not 1) then output COMPOSITE \n if (r is prime greater than 2) then { \n let q be the largest factor of r-1 \n if (q > 4sqrt(r)log n) and (n(r-1)/q is not 1 (mod r)) then break \n } \n r := r+1 \n} \n\nfor a = 1 to 2sqrt(r)log n { \n if ( (x-a)n is not (xn-a) (mod xr-1,n) ) then output COMPOSITE \n} \n\noutput PRIME; \n" }, { "answer_id": 188562, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "// Author: James J. Carman\n// Project: Sieve of Eratosthenes\n// Description: I take an array of 2 ... max values. Instead of removeing the non prime numbers,\n// I mark them as 0, and ignoring them.\n// More info: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n#include <iostream>\n\nint main(void) {\n // using unsigned short.\n // maximum value is around 65000\n const unsigned short max = 50000;\n unsigned short x[max];\n for(unsigned short i = 0; i < max; i++)\n x[i] = i + 2;\n\n for(unsigned short outer = 0; outer < max; outer++) {\n if( x[outer] == 0)\n continue;\n unsigned short item = x[outer];\n for(unsigned short multiplier = 2; (multiplier * item) < x[max - 1]; multiplier++) {\n unsigned int searchvalue = item * multiplier;\n unsigned int maxValue = max + 1;\n for( unsigned short maxIndex = max - 1; maxIndex > 0; maxIndex--) {\n if(x[maxIndex] != 0) {\n maxValue = x[maxIndex];\n break;\n }\n }\n for(unsigned short searchindex = multiplier; searchindex < max; searchindex++) {\n if( searchvalue > maxValue )\n break;\n if( x[searchindex] == searchvalue ) {\n x[searchindex] = 0;\n break;\n }\n }\n }\n }\n for(unsigned short printindex = 0; printindex < max; printindex++) {\n if(x[printindex] != 0)\n std::cout << x[printindex] << \"\\t\";\n }\n return 0;\n}\n" }, { "answer_id": 193589, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "/** \n * to compile:\n * $ dmd -run prime_trial.d\n * to optimize:\n * $ dmd -O -inline -release prime_trial.d \n */\nmodule prime_trial;\n\nimport std.conv : to; \nimport std.stdio : w = writeln;\n\n/// Adapted from: http://www.devx.com/vb2themax/Tip/19051 \nbool \nisprime(Integer)(in Integer number) \n{\n /* manually test 1, 2, 3 and multiples of 2 and 3 */\n if (number == 2 || number == 3)\n return true;\n else if (number < 2 || number % 2 == 0 || number % 3 == 0)\n return false;\n\n /* we can now avoid to consider multiples \n * of 2 and 3. This can be done really simply \n * by starting at 5 and incrementing by 2 and 4 \n * alternatively, that is: \n * 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, ... \n * we don't need to go higher than the square root of the number */\n for (Integer divisor = 5, increment = 2; divisor*divisor <= number; \n divisor += increment, increment = 6 - increment) \n if (number % divisor == 0)\n return false;\n\n return true; // if we get here, the number is prime\n}\n\n/// print all prime numbers less then a given limit\nvoid main(char[][] args) \n{\n const limit = (args.length == 2) ? to!(uint)(args[1]) : 100;\n for (uint i = 0; i < limit; ++i) \n if (isprime(i))\n w(i);\n}\n" }, { "answer_id": 193605, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "def iprimes_upto(limit):\n is_prime = [True] * limit\n for n in range(2, limit):\n if is_prime[n]:\n yield n\n for i in range(n*n, limit, n): # start at ``n`` squared\n is_prime[i] = False\n >>> list(iprimes_upto(15))\n[2, 3, 5, 7, 11, 13]\n" }, { "answer_id": 473100, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "require \"mathn.rb\"\nputs 600851475143.prime_division.last.first\n" }, { "answer_id": 478464, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "bool isPrime(unsigned long n)\n{\n if (n == 1) return false; // 1 is not prime\n if (n < 4) return true; // 2 and 3 are both prime\n if ((n % 2) == 0) return false; // exclude even numbers\n if (n < 9) return true; //we have already excluded 4, 6, and 8.\n if ((n % 3) == 0) return false; // exclude remaining multiples of 3\n\n unsigned long r = floor( sqrt(n) );\n unsigned long f = 5;\n while (f <= r)\n {\n if ((n % f) == 0) return false;\n if ((n % (f + 2)) == 0) return false;\n f = f + 6;\n }\n return true; // (in all other cases)\n}\n" }, { "answer_id": 562109, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 0, "selected": false, "text": "def primes(limit) :\n limit += 1\n x = range(limit)\n for i in xrange(2,limit) :\n if x[i] == i:\n x[i] = 1\n for j in xrange(i*i, limit, i) :\n x[j] = i\n return [j for j in xrange(2, limit) if x[j] == 1]\n def factors(limit) :\n limit += 1\n x = range(limit)\n for i in xrange(2,limit) :\n if x[i] == i:\n x[i] = 1\n for j in xrange(i*i, limit, i) :\n x[j] = i\n result = []\n y = limit-1\n while x[y] != 1 :\n divisor = x[y]\n result.append(divisor)\n y /= divisor\n result.append(y)\n return result\n" }, { "answer_id": 588086, "author": "marc lincoln", "author_id": 47204, "author_profile": "https://Stackoverflow.com/users/47204", "pm_score": -1, "selected": false, "text": "import math\n\ndef main():\n count = 1\n while True:\n isprime = True\n\n for x in range(2, int(math.sqrt(count) + 1)):\n if count % x == 0: \n isprime = False\n break\n\n if isprime:\n print count\n\n\n count += 2\n\n\nif __name__ == '__main__':\n main() \n" }, { "answer_id": 15831796, "author": "ferret96", "author_id": 1959207, "author_profile": "https://Stackoverflow.com/users/1959207", "pm_score": 0, "selected": false, "text": " function isprime(number){\n\n if (number == 1)\n return false;\n\n var times = 0;\n\n for (var i = 1; i <= number; i++){\n if(number % i == 0){\n times ++;\n }\n }\n if (times > 2){\n return false;\n }\n\n return true;\n }\n" }, { "answer_id": 51813798, "author": "Koray Tugay", "author_id": 1173112, "author_profile": "https://Stackoverflow.com/users/1173112", "pm_score": 0, "selected": false, "text": "public class SieveOfEratosthenes {\n\n /**\n * Calling this method with argument 7 will return: true true false false true false true false\n * which must be interpreted as : 0 is NOT prime, 1 is NOT prime, 2 IS prime, 3 IS prime, 4 is NOT prime\n * 5 is prime, 6 is NOT prime, 7 is prime.\n * Caller may either revert the array for easier reading, count the number of primes or extract the prime values\n * by looping.\n * @param upTo Find prime numbers up to this value. Must be a positive integer.\n * @return a boolean array where index represents the integer value and value at index returns\n * if the number is NOT prime or not.\n */\n public static boolean[] isIndexNotPrime(int upTo) {\n if (upTo < 2) {\n return new boolean[0];\n }\n\n // 0-index array, upper limit must be upTo + 1\n final boolean[] isIndexNotPrime = new boolean[upTo + 1];\n\n isIndexNotPrime[0] = true; // 0 is not a prime number.\n isIndexNotPrime[1] = true; // 1 is not a prime number.\n\n // Find all non primes starting from 2 by finding 2 * 2, 2 * 3, 2 * 4 until 2 * multiplier > isIndexNotPrime.len\n // Find next by 3 * 3 (since 2 * 3 was found before), 3 * 4, 3 * 5 until 3 * multiplier > isIndexNotPrime.len\n // Move to 4, since isIndexNotPrime[4] is already True (not prime) no need to loop..\n // Move to 5, 5 * 5, (2 * 5 and 3 * 5 was already set to True..) until 5 * multiplier > isIndexNotPrime.len\n // Repeat process until i * i > isIndexNotPrime.len.\n // Assume we are looking up to 100. Break once you reach 11 since 11 * 11 == 121 and we are not interested in\n // primes above 121..\n for (int i = 2; i < isIndexNotPrime.length; i++) {\n if (i * i >= isIndexNotPrime.length) {\n break;\n }\n if (isIndexNotPrime[i]) {\n continue;\n }\n int multiplier = i;\n while (i * multiplier < isIndexNotPrime.length) {\n isIndexNotPrime[i * multiplier] = true;\n multiplier++;\n }\n }\n\n return isIndexNotPrime;\n }\n\n public static void main(String[] args) {\n final boolean[] indexNotPrime = SieveOfEratosthenes.isIndexNotPrime(7);\n assert !indexNotPrime[2]; // Not (not prime)\n assert !indexNotPrime[3]; // Not (not prime)\n assert indexNotPrime[4]; // (not prime)\n assert !indexNotPrime[5]; // Not (not prime)\n assert indexNotPrime[6]; // (not prime)\n assert !indexNotPrime[7]; // Not (not prime)\n }\n}\n" } ]
2008/10/09
[ "https://Stackoverflow.com/questions/188425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156/" ]