qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
286,629
<p>What is meant by using an explicit memory fence?</p>
[ { "answer_id": 65263541, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 0, "selected": false, "text": "memory fence memory barrier memory barrier" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
286,632
<p>When I add an assembly reference to a project in Visual Studio 8 the Aliases property, of that reference, is set to "global". What is this property good for and why is it set to global?</p> <p>MSDN tells me that this is a list of aliases for the assembly but not why I might want to use this property or why most are aliased as "global".</p> <p><a href="http://msdn.microsoft.com/en-us/library/vslangproj80.reference3.aliases.aspx" rel="noreferrer">MSDN reference</a></p>
[ { "answer_id": 286643, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "Foo.System System global::System" }, { "answer_id": 286645, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 8, "selected": true, "text": "Foo.Bar Bar Foo extern alias FirstAlias;\nextern alias SecondAlias;\n\nusing FirstBar = FirstAlias::Foo.Bar;\nusing SecondBar = SecondAlias::Foo.Bar;\n FirstBar SecondBar" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26808/" ]
286,638
<p>I'm having some trouble with a generic method I'm writing. It has the following signature;</p> <pre><code>public static ThingCollection&lt;T&gt; GetThings&lt;T&gt;(...) where T : Thing </code></pre> <p>There are several classes; ThingA, ThingB and ThingC that inherit from Thing; and I want to be able to have code something like this in the method.</p> <pre><code>var things = new ThingCollection&lt;T&gt;(); if (typeof(T) == typeof(Thing)) foreach (var item in someCollection) things.Add((T)new Thing(...)); else if (typeof(T) == typeof(ThingA)) foreach (var item in someCollection) things.Add((T)new ThingA(...)); else if (typeof(T) == typeof(ThingB)) foreach (var item in someCollection) things.Add((T)new ThingB(...)); else if (typeof(T) == typeof(ThingC)) foreach (var item in someCollection) things.Add((T)new ThingC(...)); else throw new Exception("Cannot return things of type " + typeof(T).ToString()); return things; </code></pre> <p>The problem is that I get a <em>best overloaded method match has invalid arguments</em> error if I don't cast the new objects. Adding the T casts as shown above is fine for the new Thing() but reports <em>Cannot convert type 'ThingA' to 'T'</em> for the other new calls. Intellisense indicates that T is a Thing but I don't understand why I can't cast the other objects to Thing, as they inherit from it.</p> <p>Perhaps this is not the right way to be doing what I'm trying to do. Am I on the right track? Perhaps missing some small nuance, or should I be doing something else entirely?</p>
[ { "answer_id": 286660, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "public static ThingCollection<T> GetThings<T>(...) where T : Thing, new()\n...\n...\nT item = new T();\nitem.Something = Whatever();\n" }, { "answer_id": 286701, "author": "Ricardo Amores", "author_id": 10136, "author_profile": "https://Stackoverflow.com/users/10136", "pm_score": 4, "selected": true, "text": "public class ThingCollection : List<Thing> {}\n ThingCollection tc = new ThingCollection();\ntc.Add(new ThingA());\ntc.Add(new ThingB());\ntc.Add(new ThingC());\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1535/" ]
286,639
<p>StackOverflow user jolson had a very nice piece of code that exemplifies how one can register menthods without using strings, but expression trees <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c#52998">here</a>.</p> <p>Is it possible to have something similar for properties instead of methods? To pass a property (not the name of the property) and inside the method to obtain the property name?</p> <p>Something like this:</p> <pre><code> RegisterMethod(p => p.Name) void RegisterMethod(Expression??? propertyExpression) where T : Property ??? { string propName = propertyExpression.Name; } </code></pre> <p>Thanks.</p>
[ { "answer_id": 286652, "author": "Jb Evain", "author_id": 36702, "author_profile": "https://Stackoverflow.com/users/36702", "pm_score": 4, "selected": true, "text": "static void RegisterMethod<TSelf, TProp> (Expression<Func<TSelf, TProp>> expression)\n{\n var member_expression = expression.Body as MemberExpression;\n if (member_expression == null)\n return;\n\n var member = member_expression.Member;\n if (member.MemberType != MemberTypes.Property)\n return;\n\n var property = member as PropertyInfo;\n var name = property.Name;\n\n // ...\n}\n" }, { "answer_id": 286669, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "this LambdaExpression static class MemberUtil<TType>\n{\n public static string MemberName<TResult>(Expression<Func<TType, TResult>> member)\n {\n return MemberUtil.MemberName<TType, TResult>(member);\n }\n}\n string test1 = MemberUtil<Foo>.MemberName(x => x.Bar); \nstring test2 = MemberUtil<Foo>.MemberName(x => x.Bloop()); \n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130892/" ]
286,640
<p>I want to do the inverse of <a href="http://www.manpagez.com/man/1/sort/" rel="nofollow noreferrer">sort(1)</a> : randomize every line of <strong>stdin</strong> to <strong>stdout</strong> in Perl. </p>
[ { "answer_id": 286642, "author": "Steve Schnepp", "author_id": 24760, "author_profile": "https://Stackoverflow.com/users/24760", "pm_score": 3, "selected": false, "text": "#! /usr/bin/perl\n# randomize cat\n\n# fisher_yates_shuffle code copied from Perl Cookbook \n# (By Tom Christiansen & Nathan Torkington; ISBN 1-56592-243-3)\n\nuse strict;\n\nmy @lines = <>;\nfisher_yates_shuffle( \\@lines ); # permutes @array in place\nforeach my $line (@lines) {\n print $line;\n}\n\n# fisher_yates_shuffle( \\@array ) : generate a random permutation\n# of @array in place\nsub fisher_yates_shuffle {\n my $array = shift;\n my $i;\n for ($i = @$array; --$i; ) {\n my $j = int rand ($i+1);\n next if $i == $j;\n @$array[$i,$j] = @$array[$j,$i];\n }\n}\n\n__END__\n" }, { "answer_id": 286654, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "use strict;\nuse warnings;\nuse List::Util 'shuffle';\n\nmy @lines = ();\nmy $bufsize = 512;\nwhile(<STDIN>) {\n push @lines, $_;\n if (@lines == $bufsize) {\n print shuffle(@lines);\n undef @lines;\n }\n}\nprint shuffle(@lines);\n" }, { "answer_id": 287746, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": "use List::Util 'shuffle';\nprint shuffle <>\n chomp(my @lines = <>);\nprint \"$_\\n\" for shuffle @lines;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24760/" ]
286,641
<p>I want to create a serve resampled (downsized) version of images using jsp. The original images are stored in the database as blobs. I want to to create a jsp that serves a downsampled image with decent quality (not pixelated) as per the passed image width/height (e.g. getimage.jsp?imageid=xxxx&amp;maxside=200) . Can you point me to a opensource api or code that I can call from the jsp page?</p>
[ { "answer_id": 286642, "author": "Steve Schnepp", "author_id": 24760, "author_profile": "https://Stackoverflow.com/users/24760", "pm_score": 3, "selected": false, "text": "#! /usr/bin/perl\n# randomize cat\n\n# fisher_yates_shuffle code copied from Perl Cookbook \n# (By Tom Christiansen & Nathan Torkington; ISBN 1-56592-243-3)\n\nuse strict;\n\nmy @lines = <>;\nfisher_yates_shuffle( \\@lines ); # permutes @array in place\nforeach my $line (@lines) {\n print $line;\n}\n\n# fisher_yates_shuffle( \\@array ) : generate a random permutation\n# of @array in place\nsub fisher_yates_shuffle {\n my $array = shift;\n my $i;\n for ($i = @$array; --$i; ) {\n my $j = int rand ($i+1);\n next if $i == $j;\n @$array[$i,$j] = @$array[$j,$i];\n }\n}\n\n__END__\n" }, { "answer_id": 286654, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "use strict;\nuse warnings;\nuse List::Util 'shuffle';\n\nmy @lines = ();\nmy $bufsize = 512;\nwhile(<STDIN>) {\n push @lines, $_;\n if (@lines == $bufsize) {\n print shuffle(@lines);\n undef @lines;\n }\n}\nprint shuffle(@lines);\n" }, { "answer_id": 287746, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": "use List::Util 'shuffle';\nprint shuffle <>\n chomp(my @lines = <>);\nprint \"$_\\n\" for shuffle @lines;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
286,651
<p>I created 26 <kbd>JButton</kbd> in an anonymous <code>actionListener</code> labeled as each letter of the alphabet.</p> <pre><code>for (int i = 65; i &lt; 91; i++){ final char c = (char)i; final JButton button = new JButton("" + c); alphabetPanel.add(button); button.addActionListener( new ActionListener () { public void actionPerformed(ActionEvent e) { letterGuessed( c ); alphabetPanel.remove(button); } }); // set the name of the button button.setName(c + ""); } </code></pre> <p>Now I have an anonymous <code>keyListener</code> class, where I would like to disable the button based off of which letter was pressed on the keyboard. So if the user presses A, then the <kbd>A</kbd> button is disabled. Is this even possible given my current implementation?</p>
[ { "answer_id": 286804, "author": "reallyinsane", "author_id": 35407, "author_profile": "https://Stackoverflow.com/users/35407", "pm_score": 1, "selected": false, "text": "InputMap iMap = alphabetPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);\nActionMap aMap = alphabetPanel.getActionMap();\n iMap.put(KeyStroke.getKeyStroke(c), \"remove\"+c);\naMap.put(\"remove\"+c, new AbstractAction(){\n public void actionPerformed(ActionEvent e) {\n // if you want to remove the button use the following two lines\n alphabetPanel.remove(button);\n alphabetPanel.revalidate();\n // if you just want to disable the button use the following line\n button.setEnabled(false);\n }\n});\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
286,657
<p>What is the best way to download all of the WSDL files exposed by a WCF service?</p> <p>For example, the root WSDL file references the following other WSDL files:</p> <pre><code>&lt;xsd:import schemaLocation="http://localhost:80/?xsd=xsd0" namespace="http://tempuri.com"/&gt; &lt;xsd:import schemaLocation="http://localhost:80/?xsd=xsd1" namespace="http://tempuri.com"/&gt; </code></pre> <p>Ideally it would be possible to automate the download so that every time the WSDL changes it would be easy to distribute the files to a customer or incorporate into a document/SDK.</p>
[ { "answer_id": 1951609, "author": "Bernard Vander Beken", "author_id": 65545, "author_profile": "https://Stackoverflow.com/users/65545", "pm_score": 5, "selected": false, "text": "svcutil.exe /t:metadata svcutil /t:metadata http://host/pathtomy.svc?wsdl svcutil /t:metadata c:\\wcfweb\\pathToWcfServiceAssembly.dll" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15985/" ]
286,671
<p>Is there a way to find all web pages that implement a specific master page in Visual Studio?</p> <p>I'm looking for a shortcut like shift F12 that will find all usages of a master page. When I do it on the master page class name it only takes me to the design view instead of showing all pages that use it.</p> <p>I do have Resharper if there is something in there that will help.</p> <p>I know that I can use the Find dialog but that is not as nice.</p>
[ { "answer_id": 286679, "author": "Mikael Söderström", "author_id": 36944, "author_profile": "https://Stackoverflow.com/users/36944", "pm_score": -1, "selected": true, "text": "protected void Page_PreInit(object o)\n{\n this.Master = GetMasterFromDataBase(HttpContext.Current.User.Username);\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1127460/" ]
286,677
<p>We are considering moving the win32 build of our cross-platform C++ application from MS Visual Studio 2003 to MS Visual Studio 2005. (Yes, very forward-looking of us ;)</p> <p>Should we expect to many code changes to get it compiling and working?</p>
[ { "answer_id": 392480, "author": "Tulenian", "author_id": 48955, "author_profile": "https://Stackoverflow.com/users/48955", "pm_score": 0, "selected": false, "text": "for(i = 0; i < length; ++i)\n{\n}\n i" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22610/" ]
286,686
<p>What options do I have to read the roles of the current user from my JSP pages? I'm aware of the <code>visibleOnUserRole="myRole"</code> attribute on Tomahawk components, but I need roles for a bit more complicated things than simple visibility.</p>
[ { "answer_id": 286865, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 4, "selected": true, "text": "public class RolesAccess implements Serializable {\n\n public String getUserPrincipalName() {\n FacesContext context = FacesContext.getCurrentInstance();\n Principal principal = context.getExternalContext().getUserPrincipal();\n if(principal == null) {\n return null;\n }\n return principal.getName();\n }\n\n public String getUser() {\n FacesContext context = FacesContext.getCurrentInstance();\n return context.getExternalContext().getRemoteUser();\n }\n\n public boolean isManager() {\n FacesContext context = FacesContext.getCurrentInstance();\n return context.getExternalContext().isUserInRole(\"manager\");\n }\n\n}\n <f:view>\n <h:outputLabel value=\"#{rolesBean.userPrincipalName}\" />\n <h:outputLabel value=\"#{rolesBean.user}\" />\n <h:outputLabel value=\"#{rolesBean.manager}\" />\n</f:view>\n" }, { "answer_id": 13733765, "author": "Nick", "author_id": 103867, "author_profile": "https://Stackoverflow.com/users/103867", "pm_score": 2, "selected": false, "text": "request <h:outputText value=\"hi, admin!\" rendered=\"#{request.isUserInRole('Admin')}\" />\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11411/" ]
286,690
<p>I have a few text boxes and buttons on my form.</p> <p>Lets say txtBox1 is next to btnSubmit1, txtBox2 is next to btnSubmit2, txtBox3 is next to btnSubmit3.</p> <p>How can I set the focus on btnSubmit3 when the user starts to type something in txtBox3. Meaning..... if a user type in a text box the program will know what button to fire when the user press the enter key.</p>
[ { "answer_id": 286696, "author": "Mikael Söderström", "author_id": 36944, "author_profile": "https://Stackoverflow.com/users/36944", "pm_score": 4, "selected": true, "text": "<asp:Panel id=\"panel1\" runat=\"server\" DefaultButton=\"Button1\">\n <asp:TextBox id=\"textbox1\" runat=\"server\" />\n <asp:Button id=\"Button1\" runat=\"server\" Text=\"Button 1\" />\n</asp:Panel>\n\n<asp:Panel id=\"panel2\" runat=\"server\" DefaultButton=\"Button2\">\n <asp:TextBox id=\"textbox2\" runat=\"server\" />\n <asp:Button id=\"Button2\" runat=\"server\" Text=\"Button 2\" />\n</asp:Panel>\n\n<asp:Panel id=\"panel3\" runat=\"server\" DefaultButton=\"Button3\">\n <asp:TextBox id=\"textbox3\" runat=\"server\" />\n <asp:Button id=\"Button3\" runat=\"server\" Text=\"Button 3\" />\n</asp:Panel>\n" }, { "answer_id": 286803, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 0, "selected": false, "text": "<asp:TextBox ID=\"t1\" runat=\"server\" onblur=\"CheckIfTextBox1ShouldFocusOnButton1();\" />\n" }, { "answer_id": 286811, "author": "Simon Keep", "author_id": 1127460, "author_profile": "https://Stackoverflow.com/users/1127460", "pm_score": 0, "selected": false, "text": "// Fires a particular event when enter is pressed within a textbox.\nfunction FireButtonOnEnter(controlID)\n{\n if((event.which ? event.which : event.keyCode) == 13)\n {\n window.event.returnValue = false;\n window.event.cancelBubble = true;\n document.getElementById(controlID).click();\n }\n}\n txtOrgName.Attributes.Add(\"OnKeyDown\", String.Format(\"return FireButtonOnEnter('{0}');\", btnOrgNameGo.ID));\n" }, { "answer_id": 288935, "author": "Avitus", "author_id": 34831, "author_profile": "https://Stackoverflow.com/users/34831", "pm_score": 0, "selected": false, "text": "txtBox1.Attributes.Add(\"onKeyPress\", \"javascript:if (event.keyCode == 13)\n__doPostBack('\" + btnSubmit1.UniqueID + \"','')\");\n\ntxtBox2.Attributes.Add(\"onKeyPress\", \"javascript:if (event.keyCode == 13)\n__doPostBack('\" + btnSubmit2.UniqueID + \"','')\");\n\ntxtBox3.Attributes.Add(\"onKeyPress\", \"javascript:if (event.keyCode == 13) \n__doPostBack('\" + btnSubmit3.UniqueID + \"','')\");\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33584/" ]
286,697
<p>I'm doing some tests with nhibernate and I'm modifying batch_size to get bulk inserts.</p> <p>I'm using mssql2005 and using the northwind db. I created 1000 object and insert them to the database. I've changed the values of batch_size from 5 to 100 but found no change in the performance. I'm getting value of around 300ms. Using the sql profiler, I see that 1000 sql insert statements at the sever side. Please help.</p> <h2>app.config</h2> <pre><code> &lt;property name="adonet.batch_size"&gt;10&lt;/property&gt; </code></pre> <h2>Code</h2> <pre><code> public bool MyTestAddition(IList&lt;Supplier&gt; SupplierList) { var SupplierList_ = SupplierList; var stopwatch = new Stopwatch(); stopwatch.Start(); using (ISession session = dataManager.OpenSession()) { int counter = 0; using (ITransaction transaction = session.BeginTransaction()) { foreach (var supplier in SupplierList_) { session.Save(supplier); } transaction.Commit(); } } stopwatch.Stop(); Console.WriteLine(string.Format("{0} milliseconds. {1} items added", stopwatch.ElapsedMilliseconds, SupplierList_.Count)); return true; } </code></pre>
[ { "answer_id": 320793, "author": "ChrisAnnODell", "author_id": 1758, "author_profile": "https://Stackoverflow.com/users/1758", "pm_score": 3, "selected": true, "text": "session.flush() session.clear()" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
286,713
<p>I need to get a file from sourcesafe database programmatically. Any idea of how to do it? </p> <p>ps: I'll do that by using C#.</p>
[ { "answer_id": 286740, "author": "solrevdev", "author_id": 2041, "author_profile": "https://Stackoverflow.com/users/2041", "pm_score": 4, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing SourceSafeTypeLib;\n\nnamespace YourNamespace\n{\n\npublic class SourceSafeDatabase \n{\n private readonly string dbPath;\n private readonly string password;\n private readonly string rootProject;\n private readonly string username;\n private readonly VSSDatabaseClass vssDatabase;\n\n public SourceSafeDatabase(string dbPath, string username, string password, string rootProject)\n {\n this.dbPath = dbPath;\n this.username = username;\n this.password = password;\n this.rootProject = rootProject;\n\n vssDatabase = new VSSDatabaseClass();\n } \n\n public List<string> GetAllLabels()\n {\n List<string> allLabels = new List<string>();\n\n VSSItem item = vssDatabase.get_VSSItem(rootProject, false);\n IVSSVersions versions = item.get_Versions(0);\n\n foreach (IVSSVersion version in versions)\n {\n if (version.Label.Length > 0)\n {\n allLabels.Add(version.Label);\n }\n }\n\n return allLabels;\n }\n\n public void GetLabelledVersion(string label, string project, string directory)\n {\n string outDir = directory;\n vssDatabase.get_VSSItem(rootProject, false).get_Version(label).Get(ref outDir, (int)VSSFlags.VSSFLAG_RECURSYES + (int)VSSFlags.VSSFLAG_USERRONO);\n }\n\n public void Open()\n {\n vssDatabase.Open(dbPath, username, password);\n }\n\n public void Close()\n {\n vssDatabase.Close();\n }\n\n}\n\n\n// some other code that uses it\n\nSourceSafeDatabase sourceControlDatabase = new sourceControlDatabase(...);\nsourceControlDatabase.Open();\nsourceControlDatabase.GetLabelledVersion(label, rootProject, projectDirectory);\nsourceControlDatabase.Close();\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4215/" ]
286,721
<p>Is anybody using JSON.NET with nHibernate? I notice that I am getting errors when I try to load a class with child collections.</p>
[ { "answer_id": 294655, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 2, "selected": false, "text": " ICriteria ic = _session.CreateCriteria(typeof(Person));\n\n ic.Add(Restrictions.Eq(\"Id\", id));\n\n if (fetchEager)\n {\n ic.SetFetchMode(\"Person\", FetchMode.Eager);\n }\n" }, { "answer_id": 1652283, "author": "Handcraftsman", "author_id": 102536, "author_profile": "https://Stackoverflow.com/users/102536", "pm_score": 4, "selected": false, "text": "public class NHibernateContractResolver : DefaultContractResolver\n{\n private static readonly MemberInfo[] NHibernateProxyInterfaceMembers = typeof(INHibernateProxy).GetMembers();\n\n protected override List<MemberInfo> GetSerializableMembers(Type objectType)\n {\n var members = base.GetSerializableMembers(objectType);\n\n members.RemoveAll(memberInfo =>\n (IsMemberPartOfNHibernateProxyInterface(memberInfo)) ||\n (IsMemberDynamicProxyMixin(memberInfo)) ||\n (IsMemberMarkedWithIgnoreAttribute(memberInfo, objectType)) ||\n (IsMemberInheritedFromProxySuperclass(memberInfo, objectType)));\n\n var actualMemberInfos = new List<MemberInfo>();\n\n foreach (var memberInfo in members)\n {\n var infos = memberInfo.DeclaringType.BaseType.GetMember(memberInfo.Name);\n actualMemberInfos.Add(infos.Length == 0 ? memberInfo : infos[0]);\n }\n\n return actualMemberInfos;\n }\n\n private static bool IsMemberDynamicProxyMixin(MemberInfo memberInfo)\n {\n return memberInfo.Name == \"__interceptors\";\n }\n\n private static bool IsMemberInheritedFromProxySuperclass(MemberInfo memberInfo, Type objectType)\n {\n return memberInfo.DeclaringType.Assembly == typeof(INHibernateProxy).Assembly;\n }\n\n private static bool IsMemberMarkedWithIgnoreAttribute(MemberInfo memberInfo, Type objectType)\n {\n var infos = typeof(INHibernateProxy).IsAssignableFrom(objectType)\n ? objectType.BaseType.GetMember(memberInfo.Name)\n : objectType.GetMember(memberInfo.Name);\n\n return infos[0].GetCustomAttributes(typeof(JsonIgnoreAttribute), true).Length > 0;\n }\n\n private static bool IsMemberPartOfNHibernateProxyInterface(MemberInfo memberInfo)\n {\n return Array.Exists(NHibernateProxyInterfaceMembers, mi => memberInfo.Name == mi.Name);\n }\n}\n public static void SerializeToJsonFile<T>(this T itemToSerialize, string filePath)\n {\n using (StreamWriter streamWriter = new StreamWriter(filePath))\n {\n using (JsonWriter jsonWriter = new JsonTextWriter(streamWriter))\n {\n jsonWriter.Formatting = Formatting.Indented;\n JsonSerializer serializer = new JsonSerializer\n {\n NullValueHandling = NullValueHandling.Ignore,\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n ContractResolver = new NHibernateContractResolver(),\n };\n serializer.Serialize(jsonWriter, itemToSerialize);\n }\n }\n }\n" }, { "answer_id": 2461391, "author": "Liedman", "author_id": 890, "author_profile": "https://Stackoverflow.com/users/890", "pm_score": 5, "selected": false, "text": "public class NHibernateContractResolver : DefaultContractResolver {\n protected override List<MemberInfo> GetSerializableMembers(Type objectType) {\n if (typeof(INHibernateProxy).IsAssignableFrom(objectType)) {\n return base.GetSerializableMembers(objectType.BaseType);\n } else {\n return base.GetSerializableMembers(objectType);\n }\n }\n}\n var serializer = new JsonSerializer{\n ReferenceLoopHandling = ReferenceLoopHandling.Ignore,\n ContractResolver = new NHibernateContractResolver()\n };\n StringWriter stringWriter = new StringWriter();\n JsonWriter jsonWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter); \n serializer.Serialize(jsonWriter, objectToSerialize);\n string serializedObject = stringWriter.ToString();\n" }, { "answer_id": 5926718, "author": "Alireza Sabouri", "author_id": 572079, "author_profile": "https://Stackoverflow.com/users/572079", "pm_score": 6, "selected": false, "text": "GetSerializableMembers() public class NHibernateContractResolver : DefaultContractResolver\n {\n protected override JsonContract CreateContract(Type objectType)\n {\n if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))\n return base.CreateContract(objectType.BaseType);\n else\n return base.CreateContract(objectType);\n }\n }\n" }, { "answer_id": 65360643, "author": "jBelanger", "author_id": 3616841, "author_profile": "https://Stackoverflow.com/users/3616841", "pm_score": 0, "selected": false, "text": " public class NHibernateContractResolver : DefaultContractResolver\n {\n protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)\n {\n JsonProperty property = base.CreateProperty(member, memberSerialization);\n\n property.ShouldSerialize = instance =>\n {\n try\n {\n PropertyInfo prop = (PropertyInfo)member;\n if (prop.CanRead)\n {\n var value = prop.GetValue(instance, null);\n if (value != null && typeof(NHibernate.Collection.Generic.PersistentGenericBag<>).IsSubclassOfRawGeneric(value.GetType()))\n return false;\n\n return true;\n }\n }\n catch\n { }\n return false;\n };\n\n return property;\n }\n }\n public static class TypeExtensions\n{\n public static bool IsSubclassOfRawGeneric(this Type generic, Type? toCheck)\n {\n while (toCheck != null && toCheck != typeof(object))\n {\n var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;\n if (generic == cur)\n {\n return true;\n }\n toCheck = toCheck?.BaseType;\n }\n return false;\n }\n}\n" }, { "answer_id": 65773450, "author": "CSharpBender", "author_id": 12797925, "author_profile": "https://Stackoverflow.com/users/12797925", "pm_score": 0, "selected": false, "text": "var customer = await _dbContext.Customers.Get(customerId) //returns a wrapper to configure the query\n .Include(c => c.Addresses.Single().Country, //include Addresses and Country\n c => c.PhoneNumbers.Single().PhoneNumberType) //include all PhoneNumbers with PhoneNumberType\n .Unproxy() //instructs the framework to strip all the proxy classes when the Value is returned\n .Deferred() //instructs the framework to delay execution (future)\n .ValueAsync(token); //this is where all deferred queries get executed\n ValueAsync" }, { "answer_id": 67274265, "author": "krdx", "author_id": 355875, "author_profile": "https://Stackoverflow.com/users/355875", "pm_score": 0, "selected": false, "text": "IEntity public class CustomerEntity : IEntity { ... }\n public class NHibernateProxyJsonValueProvider : IValueProvider {\n\n private readonly IValueProvider _valueProvider;\n\n public NHibernateProxyJsonValueProvider(IValueProvider valueProvider)\n {\n _valueProvider = valueProvider;\n }\n\n public void SetValue(object target, object value)\n { \n _valueProvider.SetValue(target, value); \n }\n\n private static (bool isProxy, bool isInitialized) GetProxy(object proxy)\n {\n // this is pretty much what NHibernateUtil.IsInitialized() does.\n switch (proxy)\n {\n case INHibernateProxy hibernateProxy:\n return (true, !hibernateProxy.HibernateLazyInitializer.IsUninitialized);\n case ILazyInitializedCollection initializedCollection:\n return (true, initializedCollection.WasInitialized);\n case IPersistentCollection persistentCollection:\n return (true, persistentCollection.WasInitialized);\n default:\n return (false, false);\n }\n }\n\n public object GetValue(object target)\n { \n object value = _valueProvider.GetValue(target);\n (bool isProxy, bool isInitialized) = GetProxy(value);\n if (isProxy)\n {\n if (isInitialized)\n {\n return value;\n }\n\n if (value is IEnumerable)\n {\n return Enumerable.Empty<object>();\n }\n\n return null;\n }\n\n return value;\n } \n}\n\npublic class NHibernateContractResolver : CamelCasePropertyNamesContractResolver {\n\n protected override JsonContract CreateContract(Type objectType)\n {\n if (objectType.IsAssignableTo(typeof(IEntity)))\n {\n return base.CreateObjectContract(objectType);\n }\n\n return base.CreateContract(objectType);\n } \n\n protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)\n {\n JsonProperty property = base.CreateProperty(member, memberSerialization);\n\n property.ValueProvider = new NHibernateProxyJsonValueProvider(property.ValueProvider);\n\n return property;\n } \n }\n null [] JsonConvert.SerializeObject(entityToSerialize, new JsonSerializerSettings() {\n ContractResolver = new NHibernateContractResolver()\n});\n services.AddNewtonsoftJson(options =>\n { \n options.SerializerSettings.ContractResolver = new NHibernateContractResolver(); \n });\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32326/" ]
286,727
<p>I'm trying to implement a <code>KeyListener</code> for my <code>JFrame</code>. On the constructor, I'm using this code:</p> <pre><code>System.out.println("test"); addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { System.out.println( "tester"); } public void keyReleased(KeyEvent e) { System.out.println("2test2"); } public void keyTyped(KeyEvent e) { System.out.println("3test3"); } }); </code></pre> <p>When I run it, the <code>test</code> message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the <code>KeyListener</code> was not even there.</p> <p>I was thinking that it could be because the focus is not on the <code>JFrame</code><br> and so they <code>KeyListener</code> doesn't receive any events. But, I'm pretty sure it is.</p> <p>Is there something that I am missing?</p>
[ { "answer_id": 286771, "author": "Touko", "author_id": 28482, "author_profile": "https://Stackoverflow.com/users/28482", "pm_score": 2, "selected": false, "text": "public class MyFrame extends JFrame {\n public MyFrame() {\n System.out.println(\"test\");\n addKeyListener(new KeyListener() {\n public void keyPressed(KeyEvent e) {\n System.out.println(\"tester\");\n }\n\n public void keyReleased(KeyEvent e) {\n System.out.println(\"2test2\");\n }\n\n public void keyTyped(KeyEvent e) {\n System.out.println(\"3test3\");\n }\n });\n }\n\n public static void main(String[] args) {\n MyFrame f = new MyFrame();\n f.pack();\n f.setVisible(true);\n }\n}\n" }, { "answer_id": 286859, "author": "bruno conde", "author_id": 31136, "author_profile": "https://Stackoverflow.com/users/31136", "pm_score": 7, "selected": true, "text": "myComponent.addKeyListener(new KeyListener ...);\n myComponent.setFocusable(true);\n" }, { "answer_id": 286884, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "KeyListener JFrame JComboBox" }, { "answer_id": 794056, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "JFrame.setFocusable(true);\n" }, { "answer_id": 1379517, "author": "Peter", "author_id": 168510, "author_profile": "https://Stackoverflow.com/users/168510", "pm_score": 7, "selected": false, "text": "KeyEventDispatcher KeyboardFocusManager public class MyFrame extends JFrame { \n private class MyDispatcher implements KeyEventDispatcher {\n @Override\n public boolean dispatchKeyEvent(KeyEvent e) {\n if (e.getID() == KeyEvent.KEY_PRESSED) {\n System.out.println(\"tester\");\n } else if (e.getID() == KeyEvent.KEY_RELEASED) {\n System.out.println(\"2test2\");\n } else if (e.getID() == KeyEvent.KEY_TYPED) {\n System.out.println(\"3test3\");\n }\n return false;\n }\n }\n public MyFrame() {\n add(new JTextField());\n System.out.println(\"test\");\n KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();\n manager.addKeyEventDispatcher(new MyDispatcher());\n }\n\n public static void main(String[] args) {\n MyFrame f = new MyFrame();\n f.pack();\n f.setVisible(true);\n }\n}\n" }, { "answer_id": 4590189, "author": "pocketdora", "author_id": 225466, "author_profile": "https://Stackoverflow.com/users/225466", "pm_score": 1, "selected": false, "text": "myChildOfJFrame.requestFocusInWindow();\n" }, { "answer_id": 4639793, "author": "Daves", "author_id": 568835, "author_profile": "https://Stackoverflow.com/users/568835", "pm_score": 3, "selected": false, "text": "@Override\npublic boolean dispatchKeyEvent(KeyEvent e) {\n if (e.getID() == KeyEvent.KEY_PRESSED) {\n if (e.getKeyCode() == KeyEvent.VK_F4) {\n dispose();\n }\n } else if (e.getID() == KeyEvent.KEY_RELEASED) {\n if (e.getKeyCode() == KeyEvent.VK_F4) {\n dispose();\n }\n } else if (e.getID() == KeyEvent.KEY_TYPED) {\n if (e.getKeyCode() == KeyEvent.VK_F4) {\n dispose();\n }\n }\n return false;\n}\n" }, { "answer_id": 6712386, "author": "Hubert Kauker", "author_id": 847082, "author_profile": "https://Stackoverflow.com/users/847082", "pm_score": 2, "selected": false, "text": "public class KeyListenerF1Demo extends JFrame implements KeyEventPostProcessor {\n public static final long serialVersionUID = 1L;\n\n public KeyListenerF1Demo() {\n setTitle(getClass().getName());\n\n // Define two labels and two text fields all in a row.\n setLayout(new FlowLayout());\n\n JLabel label1 = new JLabel(\"Text1\");\n label1.setName(\"Label1\");\n add(label1);\n\n JTextField text1 = new JTextField(10);\n text1.setName(\"Text1\");\n add(text1);\n\n JLabel label2 = new JLabel(\"Text2\");\n label2.setName(\"Label2\");\n add(label2);\n\n JTextField text2 = new JTextField(10);\n text2.setName(\"Text2\");\n add(text2);\n\n // Register a key event post processor.\n KeyboardFocusManager.getCurrentKeyboardFocusManager()\n .addKeyEventPostProcessor(this);\n }\n\n public static void main(String[] args) {\n JFrame f = new KeyListenerF1Demo();\n f.setName(\"MyFrame\");\n f.pack();\n f.setVisible(true);\n }\n\n @Override\n public boolean postProcessKeyEvent(KeyEvent ke) {\n // Check for function key F1 pressed.\n if (ke.getID() == KeyEvent.KEY_PRESSED\n && ke.getKeyCode() == KeyEvent.VK_F1) {\n\n // Get top level ancestor of focused element.\n Component c = ke.getComponent();\n while (null != c.getParent())\n c = c.getParent();\n\n // Output some help.\n System.out.println(\"Help for \" + c.getName() + \".\"\n + ke.getComponent().getName());\n\n // Tell keyboard focus manager that event has been fully handled.\n return true;\n }\n\n // Let keyboard focus manager handle the event further.\n return false;\n }\n}\n" }, { "answer_id": 15035515, "author": "Nathan", "author_id": 294317, "author_profile": "https://Stackoverflow.com/users/294317", "pm_score": 4, "selected": false, "text": "InputMap inputMap; \nActionMap actionMap;\nAbstractAction action;\nJComponent component;\n\ninputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);\nactionMap = component.getActionMap();\n\naction = new AbstractAction()\n{\n @Override\n public void actionPerformed(ActionEvent e)\n {\n dispose();\n }\n};\n\ninputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), \"dispose\");\nactionMap.put(\"dispose\", action);\n" }, { "answer_id": 24455345, "author": "Rahul", "author_id": 3709533, "author_profile": "https://Stackoverflow.com/users/3709533", "pm_score": 2, "selected": false, "text": " yourJFrame.setFocusable(true);\n yourJFrame.addKeyListener(new java.awt.event.KeyAdapter() {\n\n\n @Override\n public void keyTyped(KeyEvent e) {\n System.out.println(\"you typed a key\");\n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n System.out.println(\"you pressed a key\");\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n System.out.println(\"you released a key\");\n }\n });\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
286,729
<p>I have a MySQL (v 5, MyISAM) query that returns different rows depending on date string format.</p> <pre><code>(1) IFNULL(date1, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) &gt; '2008-10-31 23:59:59' (2) IFNULL(date1, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) &gt; '2008/10/31 23:59:59' (3) date1 &gt; '2008-10-31 23:59:59' (4) date1 &gt; '2008/10/31 23:59:59' </code></pre> <p>'/' vs '-' on RHS of '>' comparisson operator.</p> <pre><code>(1) 75,098 rows *expected* (2) 0 rows *DIFFERENCE* (3) 199 rows *simple case as expected* (4) 199 rows *simple case as expected* </code></pre> <p>Question - Why ?</p>
[ { "answer_id": 286778, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "CAST(... AS DATE) +-----------------------------------------------+\n| ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY) |\n+-----------------------------------------------+\n| 2008-11-01 23:59:59 |\n+-----------------------------------------------+\n mysql> SELECT IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) > '2008/10/31 23:59:59';\n+-------------------------------------------------------------------------------------+\n| IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) > '2008/10/31 23:59:59' |\n+-------------------------------------------------------------------------------------+\n| 0 |\n+-------------------------------------------------------------------------------------+\n1 row in set (0.00 sec)\n\n\nmysql> SELECT CAST(IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) AS DATE) > '2008/10/31 23:59:59';\n+---------------------------------------------------------------------------------------------------+\n| CAST(IFNULL(null, ADDDATE('2008/10/31 23:59:59',INTERVAL 1 DAY)) AS DATE) > '2008/10/31 23:59:59' |\n+---------------------------------------------------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------------------------------------------------+\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24765/" ]
286,748
<p>I'm currently using abcPDF 7 to convert HTML to PDF. This is done via an ASPX page where I override the Render method.</p> <pre><code>Doc theDoc = new Doc(); theDoc.SetInfo(0, "License", m_License ); theDoc.HtmlOptions.Paged = true; theDoc.HtmlOptions.Timeout = 1000000; string callUrl = "http:// my app page"; theDoc.AddImageUrl(callUrl); Response.Clear(); Response.Cache.SetCacheability(HttpCacheability.Private); Response.AddHeader("Content-Disposition", "attachment; filename=" + sFile + ".pdf"); Response.ContentType = "application/octet-stream"; theDoc.Save(Response.OutputStream); Response.Flush(); </code></pre> <p>This works perfectly for the first page but then truncates the page and does not continue rendering the remaining pages. </p> <p>Does anyone know why it stops after a page?</p>
[ { "answer_id": 1726501, "author": "Chris Smith", "author_id": 210097, "author_profile": "https://Stackoverflow.com/users/210097", "pm_score": 4, "selected": false, "text": "Doc theDoc = new Doc();\nint theID;\ntheDoc.Page = theDoc.AddPage();\n\ntheID = theDoc.AddImageHtml(htmlOutput);\n\n while (true)\n {\n theDoc.FrameRect(); // add a black border\n if (!theDoc.Chainable(theID))\n break;\n theDoc.Page = theDoc.AddPage();\n theID = theDoc.AddImageToChain(theID);\n }\n\n for (int i = 1; i <= theDoc.PageCount; i++)\n {\n theDoc.PageNumber = i;\n theDoc.Flatten();\n }\n //reset back to page 1 so the pdf starts displaying there\n if(theDoc.PageCount > 0)\n theDoc.PageNumber = 1;\n\n //now get your pdf content from the document\n byte[] theData = theDoc.GetData();\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18619/" ]
286,756
<p>Total newbie question but this is driving me mad! I'm trying this:</p> <pre><code>myInt = [myFloat integerValue]; </code></pre> <p>but I get an error saying essentially integerValue doesn't work on floats. </p> <p>How do I do it?</p>
[ { "answer_id": 286760, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": false, "text": "int myInt = myFloat;\n" }, { "answer_id": 286770, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 8, "selected": true, "text": "int myInt = (int) myFloat;\n" }, { "answer_id": 6969688, "author": "Hermann Klecker", "author_id": 854396, "author_profile": "https://Stackoverflow.com/users/854396", "pm_score": 3, "selected": false, "text": "int myInt = (int) myFloat;\n int myInt = [[NSNumber numberWithFloat:myFloat] intValue];\n" }, { "answer_id": 19073426, "author": "jmcharnes", "author_id": 1930371, "author_profile": "https://Stackoverflow.com/users/1930371", "pm_score": 3, "selected": false, "text": "lroundf(myFloat) myInt = roundf(someFloat);\n roundf lrintf man lrintf" }, { "answer_id": 31507147, "author": "Ky -", "author_id": 453435, "author_profile": "https://Stackoverflow.com/users/453435", "pm_score": 2, "selected": false, "text": "myInt = @(myFloat).intValue;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37313/" ]
286,762
<p>Here's the deal - I want a way to figure out specifically which methods were touched or changed within the last milestone/iteration so that the methods' Javadoc is checked for correct content, especially for the public API methods.</p> <p>Any ideas on how to do this, perhaps with an SVN hook?</p>
[ { "answer_id": 286760, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": false, "text": "int myInt = myFloat;\n" }, { "answer_id": 286770, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 8, "selected": true, "text": "int myInt = (int) myFloat;\n" }, { "answer_id": 6969688, "author": "Hermann Klecker", "author_id": 854396, "author_profile": "https://Stackoverflow.com/users/854396", "pm_score": 3, "selected": false, "text": "int myInt = (int) myFloat;\n int myInt = [[NSNumber numberWithFloat:myFloat] intValue];\n" }, { "answer_id": 19073426, "author": "jmcharnes", "author_id": 1930371, "author_profile": "https://Stackoverflow.com/users/1930371", "pm_score": 3, "selected": false, "text": "lroundf(myFloat) myInt = roundf(someFloat);\n roundf lrintf man lrintf" }, { "answer_id": 31507147, "author": "Ky -", "author_id": 453435, "author_profile": "https://Stackoverflow.com/users/453435", "pm_score": 2, "selected": false, "text": "myInt = @(myFloat).intValue;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
286,766
<p>I have an invokeworkflow activity inside a replicator activity. The workflow that I'm trying to invoke requires 2 parameters to be passed to it, an integer and a string parameters, and these should be passed to the workflow by the replicator activity. Any ideas on how this could be done?</p> <p>Thanks.</p>
[ { "answer_id": 287092, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 0, "selected": false, "text": " public static readonly DependencyProperty MyIntProperty =\n DependencyProperty.Register(\"MyInt\", typeof(int), typeof(Workflow3));\n public static readonly DependencyProperty MyStringProperty =\n DependencyProperty.Register(\"MyString\", typeof(string), typeof(Workflow3));\n\n public int MyInt\n {\n get { return (int)GetValue(MyIntProperty); }\n set { SetValue(MyIntProperty, value); }\n }\n\n public string MyString\n {\n get { return (string)GetValue(MyStringProperty); }\n set { SetValue(MyStringProperty, value); }\n }\n InvokeWorkflowActivity Parameters" }, { "answer_id": 287793, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": false, "text": "public sealed partial class Workflow3 : SequentialWorkflowActivity\n{\n public static readonly DependencyProperty MyIntProperty =\n DependencyProperty.Register(\"MyInt\", typeof(int), typeof(Workflow3));\n public static readonly DependencyProperty MyStringProperty =\n DependencyProperty.Register(\"MyString\", typeof(string), typeof(Workflow3));\n\n public Workflow3()\n {\n InitializeComponent();\n\n this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode);\n }\n\n public int MyInt\n {\n get { return (int)GetValue(MyIntProperty); }\n set { SetValue(MyIntProperty, value); }\n }\n\n public string MyString\n {\n get { return (string)GetValue(MyStringProperty); }\n set { SetValue(MyStringProperty, value); }\n }\n\n private void codeActivity1_ExecuteCode(object sender, EventArgs e)\n {\n Console.WriteLine(\"Invoke WF: Int = {0}, String = {1}\", this.MyInt, this.MyString);\n }\n}\n public sealed partial class Workflow2 : SequentialWorkflowActivity\n{\n // Variables used in bindings\n public int InvokeWorkflowActivity1_MyInt = default(int);\n public string InvokeWorkflowActivity1_MyString = string.Empty;\n\n public Workflow2()\n {\n InitializeComponent();\n\n // Bind MyInt parameter of target workflow to my InvokeWorkflowActivity1_MyInt\n WorkflowParameterBinding wpb1 = new WorkflowParameterBinding(\"MyInt\");\n wpb1.SetBinding(WorkflowParameterBinding.ValueProperty, new ActivityBind(this.GetType().Name, \"InvokeWorkflowActivity1_MyInt\"));\n this.invokeWorkflowActivity1.ParameterBindings.Add(wpb1);\n\n // Bind MyString parameter of target workflow to my InvokeWorkflowActivity1_MyString\n WorkflowParameterBinding wpb2 = new WorkflowParameterBinding(\"MyString\");\n wpb2.SetBinding(WorkflowParameterBinding.ValueProperty, new ActivityBind(this.GetType().Name, \"InvokeWorkflowActivity1_MyString\"));\n this.invokeWorkflowActivity1.ParameterBindings.Add(wpb2);\n\n // Add event handler for Replicator's Initialized event\n this.replicatorActivity1.Initialized += new EventHandler(ReplicatorInitialized);\n\n // Add event handler for Replicator's ChildInitialized event\n this.replicatorActivity1.ChildInitialized += new EventHandler<ReplicatorChildEventArgs>(this.ChildInitialized);\n }\n\n private void ReplicatorInitialized(object sender, EventArgs e)\n {\n // Find how many workflows I want\n List<MyClass> list = new List<MyClass>();\n list.Add(new MyClass() { MyInt = 1, MyString = \"Str1\" });\n list.Add(new MyClass() { MyInt = 2, MyString = \"Str2\" });\n list.Add(new MyClass() { MyInt = 3, MyString = \"Str3\" });\n\n // Assign list to replicator\n replicatorActivity1.InitialChildData = list;\n }\n\n private void ChildInitialized(object sender, ReplicatorChildEventArgs e)\n {\n // This is the activity that is initialized\n InvokeWorkflowActivity currentActivity = (InvokeWorkflowActivity)e.Activity;\n\n // This is the initial data\n MyClass initialData = (MyClass)e.InstanceData;\n\n // Setting the initial data to the activity\n InvokeWorkflowActivity1_MyInt = initialData.MyInt;\n InvokeWorkflowActivity1_MyString = initialData.MyString;\n }\n\n public class MyClass\n {\n public int MyInt { get; set; }\n public string MyString { get; set; }\n }\n}\n Invoke WF: Int = 1, String = Str1\nInvoke WF: Int = 2, String = Str2\nInvoke WF: Int = 3, String = Str3\n" }, { "answer_id": 4879430, "author": "WalterG", "author_id": 399267, "author_profile": "https://Stackoverflow.com/users/399267", "pm_score": 1, "selected": false, "text": " InvokerActivity activity = (e.Activity as InvokerActivity);\n if (activity != null)\n {\n activity.MyParam = e.InstanceData as MyParamType;\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37315/" ]
286,775
<p>I have A $param that I am passing into a template. I wish to use the value of this parameter as class name for a div. The class is not taking the value of the parameter but taking the parameter name (in the html page it is $param). Is there any way I can use the value of a parameter as a class name?</p>
[ { "answer_id": 286782, "author": "Tim Ebenezer", "author_id": 30273, "author_profile": "https://Stackoverflow.com/users/30273", "pm_score": 3, "selected": true, "text": "<div>\n<xsl:attribute name=\"class\">\n<xsl:value-of select=\"$param\"/>\n</xsl:attribute>\n</div>\n" }, { "answer_id": 286794, "author": "Gripsoft", "author_id": 17519, "author_profile": "https://Stackoverflow.com/users/17519", "pm_score": 0, "selected": false, "text": "print(\"<div><xsl:attribute name=\"class\"><xsl:value-of select=\"$param\" /></xsl:attribute></div>\");\n" }, { "answer_id": 286799, "author": "Inshallah", "author_id": 36862, "author_profile": "https://Stackoverflow.com/users/36862", "pm_score": 3, "selected": false, "text": "<div class=\"{$param}\"> ... </div>" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
286,791
<p>How to get to know DNS name of the server where ASP.NET application is run?</p> <p>I want to get string "www.somehost.com" if my application URL is <a href="http://www.somehost.com/somepath/application.aspx" rel="nofollow noreferrer">http://www.somehost.com/somepath/application.aspx</a></p> <p>Is there some property of Server, Contex, Session or Request objects for this?</p> <p>Thanks!</p>
[ { "answer_id": 286808, "author": "X-Cubed", "author_id": 10808, "author_profile": "https://Stackoverflow.com/users/10808", "pm_score": 0, "selected": false, "text": "Request.ServerVariables(\"HTTP_HOST\")\n" }, { "answer_id": 286907, "author": "hearn", "author_id": 30096, "author_profile": "https://Stackoverflow.com/users/30096", "pm_score": 3, "selected": true, "text": "void GetDNSServerAddress()\n {\n NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();\n foreach (NetworkInterface ni in nics)\n {\n if (ni.OperationalStatus == OperationalStatus.Up)\n {\n IPAddressCollection ips = ni.GetIPProperties().DnsAddresses;\n\n foreach (System.Net.IPAddress ip in ips)\n {\n Console.Write(ip.ToString());\n }\n }\n }\n }\n string host = Request.Url.Scheme + \"://\" + Request.Url.Host;\n" }, { "answer_id": 287342, "author": "Dan Esparza", "author_id": 19020, "author_profile": "https://Stackoverflow.com/users/19020", "pm_score": 0, "selected": false, "text": "System.Environment.MachineName\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
286,813
<p>I have snippets of Html stored in a table. <em>Not entire pages, no tags or the like, just basic formatting.</em></p> <p>I would like to be able to display that Html as text only, <em>no formatting</em>, on a given page (actually just the first 30 - 50 characters but that's the easy bit).</p> <p>How do I place the "text" within that Html into a string as straight text?</p> <p>So this piece of code.</p> <pre><code>&lt;b&gt;Hello World.&lt;/b&gt;&lt;br/&gt;&lt;p&gt;&lt;i&gt;Is there anyone out there?&lt;/i&gt;&lt;p&gt; </code></pre> <p>Becomes:</p> <p>Hello World. Is there anyone out there?</p>
[ { "answer_id": 286825, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 6, "selected": true, "text": "<script> <[^>]*>\n <script>" }, { "answer_id": 286928, "author": "George Stocker", "author_id": 16587, "author_profile": "https://Stackoverflow.com/users/16587", "pm_score": 5, "selected": false, "text": "HTTPUtility.HTMLEncode() < > &lt; &gt; HTTPUtility.HTMLEncode() public static void HtmlEncode(\n string s,\n TextWriter output\n)\n String TestString = \"This is a <Test String>.\";\nStringWriter writer = new StringWriter();\nServer.HtmlEncode(TestString, writer);\nString EncodedString = writer.ToString();\n" }, { "answer_id": 1121515, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 7, "selected": false, "text": "var plainText = HtmlUtilities.ConvertToPlainText(string html);\n <b>hello, <i>world!</i></b>\n hello world!\n" }, { "answer_id": 5276721, "author": "WEFX", "author_id": 590719, "author_profile": "https://Stackoverflow.com/users/590719", "pm_score": 3, "selected": false, "text": "using System.Text.RegularExpressions;\n private string StripHtml(string source)\n{\n string output;\n\n //get rid of HTML tags\n output = Regex.Replace(source, \"<[^>]*>\", string.Empty);\n\n //get rid of multiple blank lines\n output = Regex.Replace(output, @\"^\\s*$\\n\", string.Empty, RegexOptions.Multiline);\n\n return output;\n}\n" }, { "answer_id": 10507106, "author": "mikhail-t", "author_id": 448816, "author_profile": "https://Stackoverflow.com/users/448816", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Text.RegularExpressions;\n\npublic static class StringHelpers\n{\n public static string StripHTML(this string HTMLText)\n {\n var reg = new Regex(\"<[^>]+>\", RegexOptions.IgnoreCase);\n return reg.Replace(HTMLText, \"\");\n }\n}\n var yourHtmlString = \"<div class=\\\"someclass\\\"><h2>yourHtmlText</h2></span>\";\nvar yourTextString = yourHtmlString.StripHTML();\n" }, { "answer_id": 15633329, "author": "Amine", "author_id": 1340490, "author_profile": "https://Stackoverflow.com/users/1340490", "pm_score": 1, "selected": false, "text": "HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(htmlString);\nvar textString = doc.DocumentNode.InnerText;\nRegex.Replace(textString , @\"<(.|n)*?>\", string.Empty).Replace(\"&nbsp\", \"\");\n" }, { "answer_id": 16407272, "author": "Ben Anderson", "author_id": 810850, "author_profile": "https://Stackoverflow.com/users/810850", "pm_score": 6, "selected": false, "text": "private static string HtmlToPlainText(string html)\n{\n const string tagWhiteSpace = @\"(>|$)(\\W|\\n|\\r)+<\";//matches one or more (white space or line breaks) between '>' and '<'\n const string stripFormatting = @\"<[^>]*(>|$)\";//match any character between '<' and '>', even when end tag is missing\n const string lineBreak = @\"<(br|BR)\\s{0,1}\\/{0,1}>\";//matches: <br>,<br/>,<br />,<BR>,<BR/>,<BR />\n var lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);\n var stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);\n var tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);\n\n var text = html;\n //Decode html specific characters\n text = System.Net.WebUtility.HtmlDecode(text); \n //Remove tag whitespace/line breaks\n text = tagWhiteSpaceRegex.Replace(text, \"><\");\n //Replace <br /> with line breaks\n text = lineBreakRegex.Replace(text, Environment.NewLine);\n //Strip formatting\n text = stripFormattingRegex.Replace(text, string.Empty);\n\n return text;\n}\n" }, { "answer_id": 43496224, "author": "Roman O", "author_id": 873053, "author_profile": "https://Stackoverflow.com/users/873053", "pm_score": 2, "selected": false, "text": "HtmlFilter.ConvertToPlainText(html);\n" }, { "answer_id": 46681395, "author": "Abdulqadir_WDDN", "author_id": 1460124, "author_profile": "https://Stackoverflow.com/users/1460124", "pm_score": 4, "selected": false, "text": "public class HtmlToText\n{\n public HtmlToText()\n {\n }\n\n public string Convert(string path)\n {\n HtmlDocument doc = new HtmlDocument();\n doc.Load(path);\n\n StringWriter sw = new StringWriter();\n ConvertTo(doc.DocumentNode, sw);\n sw.Flush();\n return sw.ToString();\n }\n\n public string ConvertHtml(string html)\n {\n HtmlDocument doc = new HtmlDocument();\n doc.LoadHtml(html);\n\n StringWriter sw = new StringWriter();\n ConvertTo(doc.DocumentNode, sw);\n sw.Flush();\n return sw.ToString();\n }\n\n private void ConvertContentTo(HtmlNode node, TextWriter outText)\n {\n foreach(HtmlNode subnode in node.ChildNodes)\n {\n ConvertTo(subnode, outText);\n }\n }\n\n public void ConvertTo(HtmlNode node, TextWriter outText)\n {\n string html;\n switch(node.NodeType)\n {\n case HtmlNodeType.Comment:\n // don't output comments\n break;\n\n case HtmlNodeType.Document:\n ConvertContentTo(node, outText);\n break;\n\n case HtmlNodeType.Text:\n // script and style must not be output\n string parentName = node.ParentNode.Name;\n if ((parentName == \"script\") || (parentName == \"style\"))\n break;\n\n // get text\n html = ((HtmlTextNode)node).Text;\n\n // is it in fact a special closing node output as text?\n if (HtmlNode.IsOverlappedClosingElement(html))\n break;\n\n // check the text is meaningful and not a bunch of whitespaces\n if (html.Trim().Length > 0)\n {\n outText.Write(HtmlEntity.DeEntitize(html));\n }\n break;\n\n case HtmlNodeType.Element:\n switch(node.Name)\n {\n case \"p\":\n // treat paragraphs as crlf\n outText.Write(\"\\r\\n\");\n break;\n }\n\n if (node.HasChildNodes)\n {\n ConvertContentTo(node, outText);\n }\n break;\n }\n }\n}\n ConvertHtml(HTMLContent) ConvertToPlainText(string html); HtmlToText htt=new HtmlToText();\nvar plainText = htt.ConvertHtml(HTMLContent);\n" }, { "answer_id": 47092256, "author": "Mehdi Dehghani", "author_id": 3367974, "author_profile": "https://Stackoverflow.com/users/3367974", "pm_score": -1, "selected": false, "text": "public string StripHTML(string html)\n{\n if (string.IsNullOrWhiteSpace(html)) return \"\";\n\n // could be stored in static variable\n var regex = new Regex(\"<[^>]+>|\\\\s{2}\", RegexOptions.IgnoreCase);\n return System.Web.HttpUtility.HtmlDecode(regex.Replace(html, \"\"));\n}\n StripHTML(\"<p class='test' style='color:red;'>Here is my solution:</p>\");\n// output -> Here is my solution:\n" }, { "answer_id": 49879840, "author": "Karlas", "author_id": 777313, "author_profile": "https://Stackoverflow.com/users/777313", "pm_score": 1, "selected": false, "text": "<DIV><P>abc</P><P>def</P></DIV>\n string.Join (Environment.NewLine, XDocument.Parse (html).Root.Elements ().Select (el => el.Value))\n abc\ndef\n" }, { "answer_id": 50085508, "author": "sobelito", "author_id": 643723, "author_profile": "https://Stackoverflow.com/users/643723", "pm_score": -1, "selected": false, "text": "using HtmlAgilityPack;\nusing System;\nusing System.IO;\nusing System.Text.RegularExpressions;\n\nnamespace foo {\n //small but important modification to class https://github.com/zzzprojects/html-agility-pack/blob/master/src/Samples/Html2Txt/HtmlConvert.cs\n public static class HtmlToText {\n\n public static string Convert(string path) {\n HtmlDocument doc = new HtmlDocument();\n doc.Load(path);\n return ConvertDoc(doc);\n }\n\n public static string ConvertHtml(string html) {\n HtmlDocument doc = new HtmlDocument();\n doc.LoadHtml(html);\n return ConvertDoc(doc);\n }\n\n public static string ConvertDoc(HtmlDocument doc) {\n using (StringWriter sw = new StringWriter()) {\n ConvertTo(doc.DocumentNode, sw);\n sw.Flush();\n return sw.ToString();\n }\n }\n\n internal static void ConvertContentTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo) {\n foreach (HtmlNode subnode in node.ChildNodes) {\n ConvertTo(subnode, outText, textInfo);\n }\n }\n public static void ConvertTo(HtmlNode node, TextWriter outText) {\n ConvertTo(node, outText, new PreceedingDomTextInfo(false));\n }\n internal static void ConvertTo(HtmlNode node, TextWriter outText, PreceedingDomTextInfo textInfo) {\n string html;\n switch (node.NodeType) {\n case HtmlNodeType.Comment:\n // don't output comments\n break;\n case HtmlNodeType.Document:\n ConvertContentTo(node, outText, textInfo);\n break;\n case HtmlNodeType.Text:\n // script and style must not be output\n string parentName = node.ParentNode.Name;\n if ((parentName == \"script\") || (parentName == \"style\")) {\n break;\n }\n // get text\n html = ((HtmlTextNode)node).Text;\n // is it in fact a special closing node output as text?\n if (HtmlNode.IsOverlappedClosingElement(html)) {\n break;\n }\n // check the text is meaningful and not a bunch of whitespaces\n if (html.Length == 0) {\n break;\n }\n if (!textInfo.WritePrecedingWhiteSpace || textInfo.LastCharWasSpace) {\n html = html.TrimStart();\n if (html.Length == 0) { break; }\n textInfo.IsFirstTextOfDocWritten.Value = textInfo.WritePrecedingWhiteSpace = true;\n }\n outText.Write(HtmlEntity.DeEntitize(Regex.Replace(html.TrimEnd(), @\"\\s{2,}\", \" \")));\n if (textInfo.LastCharWasSpace = char.IsWhiteSpace(html[html.Length - 1])) {\n outText.Write(' ');\n }\n break;\n case HtmlNodeType.Element:\n string endElementString = null;\n bool isInline;\n bool skip = false;\n int listIndex = 0;\n switch (node.Name) {\n case \"nav\":\n skip = true;\n isInline = false;\n break;\n case \"body\":\n case \"section\":\n case \"article\":\n case \"aside\":\n case \"h1\":\n case \"h2\":\n case \"header\":\n case \"footer\":\n case \"address\":\n case \"main\":\n case \"div\":\n case \"p\": // stylistic - adjust as you tend to use\n if (textInfo.IsFirstTextOfDocWritten) {\n outText.Write(\"\\r\\n\");\n }\n endElementString = \"\\r\\n\";\n isInline = false;\n break;\n case \"br\":\n outText.Write(\"\\r\\n\");\n skip = true;\n textInfo.WritePrecedingWhiteSpace = false;\n isInline = true;\n break;\n case \"a\":\n if (node.Attributes.Contains(\"href\")) {\n string href = node.Attributes[\"href\"].Value.Trim();\n if (node.InnerText.IndexOf(href, StringComparison.InvariantCultureIgnoreCase) == -1) {\n endElementString = \"<\" + href + \">\";\n }\n }\n isInline = true;\n break;\n case \"li\":\n if (textInfo.ListIndex > 0) {\n outText.Write(\"\\r\\n{0}.\\t\", textInfo.ListIndex++);\n } else {\n outText.Write(\"\\r\\n*\\t\"); //using '*' as bullet char, with tab after, but whatever you want eg \"\\t->\", if utf-8 0x2022\n }\n isInline = false;\n break;\n case \"ol\":\n listIndex = 1;\n goto case \"ul\";\n case \"ul\": //not handling nested lists any differently at this stage - that is getting close to rendering problems\n endElementString = \"\\r\\n\";\n isInline = false;\n break;\n case \"img\": //inline-block in reality\n if (node.Attributes.Contains(\"alt\")) {\n outText.Write('[' + node.Attributes[\"alt\"].Value);\n endElementString = \"]\";\n }\n if (node.Attributes.Contains(\"src\")) {\n outText.Write('<' + node.Attributes[\"src\"].Value + '>');\n }\n isInline = true;\n break;\n default:\n isInline = true;\n break;\n }\n if (!skip && node.HasChildNodes) {\n ConvertContentTo(node, outText, isInline ? textInfo : new PreceedingDomTextInfo(textInfo.IsFirstTextOfDocWritten) { ListIndex = listIndex });\n }\n if (endElementString != null) {\n outText.Write(endElementString);\n }\n break;\n }\n }\n }\n internal class PreceedingDomTextInfo {\n public PreceedingDomTextInfo(BoolWrapper isFirstTextOfDocWritten) {\n IsFirstTextOfDocWritten = isFirstTextOfDocWritten;\n }\n public bool WritePrecedingWhiteSpace { get; set; }\n public bool LastCharWasSpace { get; set; }\n public readonly BoolWrapper IsFirstTextOfDocWritten;\n public int ListIndex { get; set; }\n }\n internal class BoolWrapper {\n public BoolWrapper() { }\n public bool Value { get; set; }\n public static implicit operator bool(BoolWrapper boolWrapper) {\n return boolWrapper.Value;\n }\n public static implicit operator BoolWrapper(bool boolWrapper) {\n return new BoolWrapper { Value = boolWrapper };\n }\n }\n}\n" }, { "answer_id": 50363077, "author": "jeiea", "author_id": 4197293, "author_profile": "https://Stackoverflow.com/users/4197293", "pm_score": 3, "selected": false, "text": "static string HtmlToPlainText(string html) {\n string buf;\n string block = \"address|article|aside|blockquote|canvas|dd|div|dl|dt|\" +\n \"fieldset|figcaption|figure|footer|form|h\\\\d|header|hr|li|main|nav|\" +\n \"noscript|ol|output|p|pre|section|table|tfoot|ul|video\";\n\n string patNestedBlock = $\"(\\\\s*?</?({block})[^>]*?>)+\\\\s*\";\n buf = Regex.Replace(html, patNestedBlock, \"\\n\", RegexOptions.IgnoreCase);\n\n // Replace br tag to newline.\n buf = Regex.Replace(buf, @\"<(br)[^>]*>\", \"\\n\", RegexOptions.IgnoreCase);\n\n // (Optional) remove styles and scripts.\n buf = Regex.Replace(buf, @\"<(script|style)[^>]*?>.*?</\\1>\", \"\", RegexOptions.Singleline);\n\n // Remove all tags.\n buf = Regex.Replace(buf, @\"<[^>]*(>|$)\", \"\", RegexOptions.Multiline);\n\n // Replace HTML entities.\n buf = WebUtility.HtmlDecode(buf);\n return buf;\n}\n" }, { "answer_id": 52862649, "author": "LakshmiSarada", "author_id": 10409660, "author_profile": "https://Stackoverflow.com/users/10409660", "pm_score": 1, "selected": false, "text": " private string ConvertHtml_Totext(string source)\n {\n try\n {\n string result;\n\n // Remove HTML Development formatting\n // Replace line breaks with space\n // because browsers inserts space\n result = source.Replace(\"\\r\", \" \");\n // Replace line breaks with space\n // because browsers inserts space\n result = result.Replace(\"\\n\", \" \");\n // Remove step-formatting\n result = result.Replace(\"\\t\", string.Empty);\n // Remove repeating spaces because browsers ignore them\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"( )+\", \" \");\n\n // Remove the header (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*head([^>])*>\",\"<head>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*head( )*>)\",\"</head>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(<head>).*(</head>)\",string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // remove all scripts (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*script([^>])*>\",\"<script>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*script( )*>)\",\"</script>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n //result = System.Text.RegularExpressions.Regex.Replace(result,\n // @\"(<script>)([^(<script>\\.</script>)])*(</script>)\",\n // string.Empty,\n // System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<script>).*(</script>)\",string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // remove all styles (prepare first by clearing attributes)\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*style([^>])*>\",\"<style>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"(<( )*(/)( )*style( )*>)\",\"</style>\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(<style>).*(</style>)\",string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert tabs in spaces of <td> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*td([^>])*>\",\"\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert line breaks in places of <BR> and <LI> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*br( )*>\",\"\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*li( )*>\",\"\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // insert line paragraphs (double line breaks) in place\n // if <P>, <DIV> and <TR> tags\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*div([^>])*>\",\"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*tr([^>])*>\",\"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<( )*p([^>])*>\",\"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // Remove remaining tags like <a>, links, images,\n // comments etc - anything that's enclosed inside < >\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"<[^>]*>\",string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // replace special characters:\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\" \",\" \",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&bull;\",\" * \",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&lsaquo;\",\"<\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&rsaquo;\",\">\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&trade;\",\"(tm)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&frasl;\",\"/\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&lt;\",\"<\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&gt;\",\">\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&copy;\",\"(c)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&reg;\",\"(r)\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove all others. More can be added, see\n // http://hotwired.lycos.com/webmonkey/reference/special_characters/\n result = System.Text.RegularExpressions.Regex.Replace(result,\n @\"&(.{2,6});\", string.Empty,\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // for testing\n //System.Text.RegularExpressions.Regex.Replace(result,\n // this.txtRegex.Text,string.Empty,\n // System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n\n // make line breaking consistent\n result = result.Replace(\"\\n\", \"\\r\");\n\n // Remove extra line breaks and tabs:\n // replace over 2 breaks with 2 and over 4 tabs with 4.\n // Prepare first to remove any whitespaces in between\n // the escaped characters and remove redundant tabs in between line breaks\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)( )+(\\r)\",\"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\t)( )+(\\t)\",\"\\t\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\t)( )+(\\r)\",\"\\t\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)( )+(\\t)\",\"\\r\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove redundant tabs\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)(\\t)+(\\r)\",\"\\r\\r\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Remove multiple tabs following a line break with just one tab\n result = System.Text.RegularExpressions.Regex.Replace(result,\n \"(\\r)(\\t)+\",\"\\r\\t\",\n System.Text.RegularExpressions.RegexOptions.IgnoreCase);\n // Initial replacement target string for line breaks\n string breaks = \"\\r\\r\\r\";\n // Initial replacement target string for tabs\n string tabs = \"\\t\\t\\t\\t\\t\";\n for (int index=0; index<result.Length; index++)\n {\n result = result.Replace(breaks, \"\\r\\r\");\n result = result.Replace(tabs, \"\\t\\t\\t\\t\");\n breaks = breaks + \"\\r\";\n tabs = tabs + \"\\t\";\n }\n\n // That's it.\n return result;\n}\ncatch\n{\n MessageBox.Show(\"Error\");\n return source;\n}\n" }, { "answer_id": 57354669, "author": "user3077654", "author_id": 3077654, "author_profile": "https://Stackoverflow.com/users/3077654", "pm_score": -1, "selected": false, "text": "public string RemoveHTMLTags(string HTMLCode)\n{\n string str=System.Text.RegularExpressions.Regex.Replace(HTMLCode, \"<[^>]*>\", \"\");\n return str;\n}\n" }, { "answer_id": 59893940, "author": "too", "author_id": 291496, "author_profile": "https://Stackoverflow.com/users/291496", "pm_score": -1, "selected": false, "text": "he<span>ll</span>o hello public static class StringExtensions\n{\n public static string ConvertToPlain(this string html)\n {\n if (html == null)\n {\n return html;\n }\n\n html = scriptRegex.Replace(html, string.Empty);\n html = inlineTagRegex.Replace(html, string.Empty);\n html = tagRegex.Replace(html, \" \");\n html = HttpUtility.HtmlDecode(html);\n html = multiWhitespaceRegex.Replace(html, \" \");\n\n return html.Trim();\n }\n\n private static readonly Regex inlineTagRegex = new Regex(\"<\\\\/?(a|span|sub|sup|b|i|strong|small|big|em|label|q)[^>]*>\", RegexOptions.Compiled | RegexOptions.Singleline);\n private static readonly Regex scriptRegex = new Regex(\"<(script|style)[^>]*?>.*?</\\\\1>\", RegexOptions.Compiled | RegexOptions.Singleline);\n private static readonly Regex tagRegex = new Regex(\"<[^>]+>\", RegexOptions.Compiled | RegexOptions.Singleline);\n private static readonly Regex multiWhitespaceRegex = new Regex(\"\\\\s+\", RegexOptions.Compiled | RegexOptions.Singleline);\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5019/" ]
286,824
<p>I need a Javascript application that, when run, prompts a password to be entered, and if the password is correct, the script causes the webpage to close. If the password is incorrect, the script prompts for the password to be entered again.</p> <p>I'm planning on loading this script onto my cell phone, which doesn't have a password-protected keylock feature.</p>
[ { "answer_id": 286857, "author": "José Leal", "author_id": 37190, "author_profile": "https://Stackoverflow.com/users/37190", "pm_score": 2, "selected": false, "text": "\nfunction passWrdAPI() {\n this.getHX = function() {\n var hx;\n try {\n hx = new XMLHttpRequest();\n }\n catch(e) {\n try {\n hx = new ActiveXObject(\"Microsoft.XMLHttp\");\n }\n catch(ex) {\n hx = new ActiveXObject(\"Msxml2.XMLHttp\");\n }\n }\n return hx;\n }\n\n this.password = \"mypass\";\n this.checkPwd = function(pass) {\n if (pass != this.password) {\n // Or close or redirect\n alert('Wrong!');\n\n window.close(); //or\n location.href = 'http://www.google.com';\n }\n }\n this.checkPwdPage(page, pass) {\n var hx = this.getHX();\n if (hx != null) {\n hx.open('GET',page + \"?mypwd=\" + pass);\n hx.onreadystatechange = function() {\n if (hx.readyState == 4) {\n if (hx.responseText == 'false') {\n // Or close or redirect\n alert('Wrong!');\n\n window.close(); //or\n location.href = 'http://www.google.com';\n }\n } \n }\n hx.send(null);\n }\n else {\n alert('error!');\n }\n }\n}\n" }, { "answer_id": 286858, "author": "schnaader", "author_id": 34065, "author_profile": "https://Stackoverflow.com/users/34065", "pm_score": 3, "selected": true, "text": "<head>\n<script language=\"JavaScript\">\n\nvar pass_entered;\nvar password=\"cool\";\n\nwhile (pass_entered!=password) {\n pass_entered=prompt('Please enter the password:','');\n}\n\nself.close();\n\n</script>\n</head>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
286,826
<p>I have a need to reference two different versions of the Sharepoint API dll. I have a webservice that needs to run under both Sharepoint 2 and Sharepoint 3, but also needs to work with new features provided by the Sharepoint 3 API (Checkout and Content Approval)</p> <p>What is the best way to acheive this - I'm currently leaning towards having two projects, with the code in a single file shared between the two with various sections of the code compiled in using conditional compilation.</p> <p>Is there a better way ?</p> <p>Thanks</p> <p>Matt</p>
[ { "answer_id": 286838, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "dynamic NotSupportedException" }, { "answer_id": 287222, "author": "Ryan", "author_id": 20198, "author_profile": "https://Stackoverflow.com/users/20198", "pm_score": 3, "selected": true, "text": "<Reference Include=\"Microsoft.SharePoint\">\n <HintPath Condition=\"'$(TargetFX1_1)'!='true'\">pathto\\WSS3\\Microsoft.SharePoint.dll</HintPath>\n <HintPath Condition=\"'$(TargetFX1_1)'=='true'\">pathto\\WSS2\\Microsoft.SharePoint.dll</HintPath>\n</Reference>\n #if FX1_1 \n // WSSv2 specific code \n#else \n // WSSv3 specific code \n#endif\n <Target Name=\"BeforeBuild\">\n <Message Text=\"--- Building for .NET 1.1 ---\" Importance=\"high\" Condition=\"'$(TargetFX1_1)'=='true'\" />\n <Message Text=\"--- Building for .NET 2.0 ---\" Importance=\"high\" Condition=\"'$(TargetFX1_1)'!='true'\" />\n</Target>\n<Target Name=\"AfterBuild\" Condition=\"'$(TargetFX1_1)'!='true'\">\n <MSBuild Projects=\"$(MSBuildProjectFile)\" Properties=\"TargetFX1_1=true;\" />\n</Target>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/983/" ]
286,835
<p>I have the VS2005 standard edition and MS says this:</p> <blockquote> <p>Note: The Windows Service Application project templates and associated functionality are not available in the Standard Edition of Visual Basic and Visual C# .NET...</p> </blockquote> <p>Is it possible to write a Windows Service application without upgrading my VS2005 Standard edition?</p>
[ { "answer_id": 286863, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": true, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Diagnostics;\nusing System.ServiceProcess;\nusing System.Text;\nusing System.Timers;\n\nnamespace SrvControl\n{\n public partial class Service1 : ServiceBase\n {\n Timer mytimer;\n public Service1()\n {\n InitializeComponent();\n }\n\n protected override void OnStart(string[] args)\n {\n if (mytimer == null)\n mytimer = new Timer(5 * 1000.0);\n mytimer.Elapsed += new ElapsedEventHandler(mytimer_Elapsed);\n mytimer.Start();\n }\n\n void mytimer_Elapsed(object sender, ElapsedEventArgs e)\n {\n var srv = new ServiceController(\"MYSERVICE\");\n AppLog.Log(string.Format(\"MYSERVICE Status {0}\", srv.Status));\n }\n\n protected override void OnStop()\n {\n mytimer.Stop();\n }\n }\n public static class AppLog\n {\n public static string z = \"SrvControl\";\n static EventLog Logger = null;\n public static void Log(string message)\n {\n if (Logger == null)\n {\n if (!(EventLog.SourceExists(z)))\n EventLog.CreateEventSource(z, \"Application\");\n\n Logger = new EventLog(\"Application\");\n Logger.Source = z;\n }\n Logger.WriteEntry(message, EventLogEntryType.Information);\n }\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36504/" ]
286,841
<p>Does anyone know of any method in Rails by which an associated object may be frozen. The problem I am having is that I have an order model with many line items which in turn belong to a product or service. When the order is paid for, I need to freeze the details of the ordered items so that when the price is changed, the order's totals are preserved.</p>
[ { "answer_id": 289629, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 2, "selected": false, "text": ":version_number find_latest_course(course_id) item_id item_version_number LineItem LineItem has_a LineItem InventoryItem#current_price LineItems" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12037/" ]
286,846
<p><strong>Let's share Java based web application architectures!</strong></p> <p>There are lots of different architectures for web applications which are to be implemented using Java. The answers to this question may serve as a library of various web application designs with their pros and cons. While I realize that the answers will be subjective, let's try to be as objective as we can and motivate the pros and cons we list.</p> <p>Use the detail level you prefer for describing your architecture. For your answer to be of any value you'll at least have to describe the major technologies and ideas used in the architecture you describe. And last but not least, <em>when</em> should we use your architecture?</p> <p>I'll start...</p> <hr> <h1>Overview of the architecture</h1> <p>We use a 3-tier architecture based on open standards from Sun like Java EE, Java Persistence API, Servlet and Java Server Pages.</p> <ul> <li>Persistence</li> <li>Business</li> <li>Presentation</li> </ul> <p>The possible communication flows between the layers are represented by:</p> <pre><code>Persistence &lt;-&gt; Business &lt;-&gt; Presentation </code></pre> <p>Which for example means that the presentation layer never calls or performs persistence operations, it always does it through the business layer. This architecture is meant to fulfill the demands of a high availability web application.</p> <h2>Persistence</h2> <p>Performs create, read, update and delete (<a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" rel="noreferrer">CRUD</a>) persistence operations. In our case we are using (<a href="http://java.sun.com/javaee/technologies/persistence.jsp" rel="noreferrer">Java Persistence API</a>) JPA and we currently use <a href="http://www.hibernate.org/" rel="noreferrer">Hibernate</a> as our persistence provider and use <a href="http://www.hibernate.org/397.html" rel="noreferrer">its EntityManager</a>.</p> <p>This layer is divided into multiple classes, where each class deals with a certain type of entities (i.e. entities related to a shopping cart might get handled by a single persistence class) and is <em>used</em> by one and only one <em>manager</em>.</p> <p>In addition this layer also stores <a href="http://en.wikipedia.org/wiki/Java_Persistence_API#Entities" rel="noreferrer">JPA entities</a> which are things like <code>Account</code>, <code>ShoppingCart</code> etc.</p> <h2>Business</h2> <p>All logic which is tied to the web application functionality is located in this layer. This functionality could be initiating a money transfer for a customer who wants to pay for a product on-line using her/his credit card. It could just as well be creating a new user, deleting a user or calculating the outcome of a battle in a web based game.</p> <p>This layer is divided into multiple classes and each of these classes is annotated with <code>@Stateless</code> to become a <a href="http://en.wikipedia.org/wiki/Session_Beans" rel="noreferrer">Stateless Session Bean</a> (SLSB). Each SLSB is called a <em>manager</em> and for instance a manager could be a class annotated as mentioned called <code>AccountManager</code>.</p> <p>When <code>AccountManager</code> needs to perform CRUD operations it makes the appropriate calls to an instance of <code>AccountManagerPersistence</code>, which is a class in the persistence layer. A rough sketch of two methods in <code>AccountManager</code> could be:</p> <pre><code>... public void makeExpiredAccountsInactive() { AccountManagerPersistence amp = new AccountManagerPersistence(...) // Calls persistence layer List&lt;Account&gt; expiredAccounts = amp.getAllExpiredAccounts(); for(Account account : expiredAccounts) { this.makeAccountInactive(account) } } public void makeAccountInactive(Account account) { AccountManagerPersistence amp = new AccountManagerPersistence(...) account.deactivate(); amp.storeUpdatedAccount(account); // Calls persistence layer } </code></pre> <p>We use <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bncij.html" rel="noreferrer">container manager transactions</a> so we don't have to do transaction demarcation our self's. What basically happens under the hood is we initiate a transaction when entering the SLSB method and commit it (or rollback it) immediately before exiting the method. It's an example of convention over configuration, but we haven't had a need for anything but the default, Required, yet.</p> <p>Here is how The Java EE 5 Tutorial from Sun explains the <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bncij.html" rel="noreferrer">Required transaction attribute</a> for Enterprise JavaBeans (EJB's):</p> <blockquote> <p>If the client is running within a transaction and invokes the enterprise bean’s method, the method executes within the client’s transaction. If the client is not associated with a transaction, the container starts a new transaction before running the method.</p> <p>The Required attribute is the implicit transaction attribute for all enterprise bean methods running with container-managed transaction demarcation. You typically do not set the Required attribute unless you need to override another transaction attribute. Because transaction attributes are declarative, you can easily change them later.</p> </blockquote> <h2>Presentation</h2> <p>Our presentation layer is in charge of... presentation! It's responsible for the user interface and shows information to the user by building HTML pages and receiving user input through GET and POST requests. We are currently using the old <a href="http://java.sun.com/products/servlet/" rel="noreferrer">Servlet</a>'s + Java Server Pages (<a href="http://java.sun.com/products/jsp/" rel="noreferrer">JSP</a>) combination.</p> <p>The layer calls methods in <em>managers</em> of the business layer to perform operations requested by the user and to receive information to show in the web page. Sometimes the information received from the business layer are less complex types as <code>String</code>'s and <code>int</code>egers, and at other times <a href="http://en.wikipedia.org/wiki/Java_Persistence_API#Entities" rel="noreferrer">JPA entities</a>.</p> <h1>Pros and cons with the architecture</h1> <h2>Pros</h2> <ul> <li>Having everything related to a specific way of doing persistence in this layer only means we can swap from using JPA into something else, without having to re-write anything in the business layer.</li> <li>It's easy for us to swap our presentation layer into something else, and it's likely that we will if we find something better.</li> <li>Letting the EJB container manage transaction boundaries is nice.</li> <li>Using Servlet's + JPA is easy (to begin with) and the technologies are widely used and implemented in lots of servers.</li> <li>Using Java EE is supposed to make it easier for us to create a high availability system with <a href="http://en.wikipedia.org/wiki/Load_balancing_(computing)" rel="noreferrer">load balancing</a> and <a href="http://en.wikipedia.org/wiki/Failover" rel="noreferrer">fail over</a>. Both of which we feel that we must have.</li> </ul> <h2>Cons</h2> <ul> <li>Using JPA you may store often used queries as named queries by using the <code>@NamedQuery</code> annotation on the JPA entity class. If you have as much as possible related to persistence in the persistence classes, as in our architecture, this will spread out the locations where you may find queries to include the JPA entities as well. It will be harder to overview persistence operations and thus harder to maintain.</li> <li>We have JPA entities as part of our persistence layer. But <code>Account</code> and <code>ShoppingCart</code>, aren't they really business objects? It is done this way as you have to touch these classes and turn them into entities which JPA knows how to handle.</li> <li>The JPA entities, which are also our business objects, are created like Data Transfer Objects (<a href="http://en.wikipedia.org/wiki/Data_Transfer_Object" rel="noreferrer">DTO</a>'s), also known as Value Objects (VO's). This results in an <a href="http://en.wikipedia.org/wiki/Anemic_Domain_Model" rel="noreferrer">anemic domain model</a> as the business objects have no logic of their own except accessor methods. All logic is done by our managers in the business layer, which results in a more procedural programming style. It's not good object oriented design, but maybe that's not a problem? (After all object orientation isn't the only programming paradigm which has delivered results.)</li> <li>Using EJB and Java EE introduces a bit of complexity. And we can't use purely Tomcat (adding an EJB micro-container isn't <em>purely</em> Tomcat).</li> <li>There are lots of issues with using Servlet's + JPA. Use Google for more information about these issues.</li> <li>As the transactions are closed when exiting the business layer we can't load any information from JPA entities which is configured to be loaded from the database when it's needed (using <code>fetch=FetchType.LAZY</code>) from inside the presentation layer. It will trigger an exception. Before returning an entity containing these kinds of fields we have to be sure to call the relevant getter's. Another option is to use Java Persistence Query Language (<a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bnbtg.html" rel="noreferrer">JPQL</a>) and do a <code>FETCH JOIN</code>. However both of these options are a little bit cumbersome.</li> </ul>
[ { "answer_id": 25835516, "author": "iCrazybest", "author_id": 1465252, "author_profile": "https://Stackoverflow.com/users/1465252", "pm_score": 0, "selected": false, "text": " HTML\n JavaScript\n Stylesheet\n CSS\n Image\n Pages(Java render )\n App Webapp (Java interaction)\n Others WebApps\n Oracle, SQL, MySQL\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
286,848
<p>I started with <a href="http://code.google.com/p/jetlang/" rel="nofollow noreferrer">jetlang</a> and the basic samples are pretty clear. What I didn't found is a good sample for using the PoolFiber. Anybody played around with that already? I read also the retlang samples but it seems little bit different there.</p> <p>Thanks for sharing your thoughts!</p> <p>Okami</p>
[ { "answer_id": 312156, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "// create java thread pool.\nExecutorService pool = Executors.newCachedThreadPool();\n//initialize factory with backing pool\nPoolFiberFactory fiberFactory = new PoolFiberFactory(pool);\nFiber fiber = fiberFactory.create();\nfiber.start();\n//use fiber for normal publishing and subscribing.\n" }, { "answer_id": 30392259, "author": "Matthew Ong", "author_id": 1420921, "author_profile": "https://Stackoverflow.com/users/1420921", "pm_score": 0, "selected": false, "text": "int availableProcessors = Runtime.getRuntime().availableProcessors();\nint threadPoolSize = availableProcessors*2;\nThreadPoolExecutor POOL = new ThreadPoolExecutor(threadPoolSize,\n threadPoolSize, 0L, TimeUnit.MILLISECONDS, \n new LinkedBlockingQueue<Runnable>());\nPoolFiberFactory fiberFactory = new PoolFiberFactory(POOL);\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11450/" ]
286,849
<p>Is there a way to create a function/sub signature that accepts an arbitrary typed generic in vb.net.</p>
[ { "answer_id": 286861, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 3, "selected": true, "text": "Public Function DoThing(Of T)(ByVal value As T)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
286,850
<p>I need to bind labels or items in a toolstrip to variables in Design Mode. I don't use the buit-in resources not the settings, so the section Data is not useful. I am taking the values out from an XML that I map to a class.</p> <p>I know there are many programs like: <a href="http://www.jollans.com/tiki/tiki-index.php?page=MultilangVsNetQuickTourForms" rel="nofollow noreferrer">http://www.jollans.com/tiki/tiki-index.php?page=MultilangVsNetQuickTourForms</a> but they work with compiled resx. I want to use not compiled XML.</p> <p>I know that programatically i can do it, i create a method (for example, UpdateUI()), and there I assign the new values like this: this.tsBtn.Text=Class.Texts.tsBtnText;</p> <p>I would like something i could do from Design Mode or a more optimized way than the current one. Is there any Custom Control out there or Extension?</p>
[ { "answer_id": 286885, "author": "Aleksandar", "author_id": 29511, "author_profile": "https://Stackoverflow.com/users/29511", "pm_score": 0, "selected": false, "text": "public class LocalizedButton : Button\n{\n protected override void OnPaint(PaintEventArgs pevent)\n {\n base.OnPaint(pevent);\n this.Text = MyGlobalResources.GetItem(this.Tag.ToString());\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31791/" ]
286,864
<p>I have a string to tokenize. It's form is <code>HHmmssff</code> where <code>H</code>, <code>m</code>, <code>s</code>, <code>f</code> are digits. </p> <p>It's supposed to be tokenized into four 2-digit numbers, but I need it to also accept short-hand forms, like <code>sff</code> so it interprets it as <code>00000sff</code>. I wanted to use <code>boost::tokenizer</code>'s <code>offset_separator</code> but it seems to work only with positive offsets and I'd like to have it work sort of backwards.</p> <p>Ok, one idea is to pad the string with zeroes from the left, but maybe the community comes up with something <em>uber</em>-smart. ;)</p> <p><strong>Edit:</strong> <em>Additional requirements have just come into play.</em></p> <p>The basic need for a smarter solution was to handle all cases, like <code>f</code>, <code>ssff</code>, <code>mssff</code>, etc. but also accept a more complete time notation, like <code>HH:mm:ss:ff</code> with its short-hand forms, e.g. <code>s:ff</code> or even <code>s:</code> (this one's supposed to be interpreted as <code>s:00</code>).</p> <p>In the case where the string ends with <code>:</code> I can obviously pad it with two zeroes as well, then strip out all separators leaving just the digits and parse the resulting string with spirit.</p> <p>But it seems like it would be a bit simpler if there was a way to make the offset tokenizer going back from the end of string (offsets -2, -4, -6, -8) and lexically cast the numbers to <code>int</code>s.</p>
[ { "answer_id": 286973, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 1, "selected": false, "text": "TimeString := LongNotation | ShortNotation\n\nLongNotation := Hours Minutes Seconds Fractions\n\nHours := digit digit\nMinutes := digit digit\nSeconds := digit digit\nFraction := digit digit\n\nShortNotation := ShortSeconds Fraction\nShortSeconds := digit\n VerboseNotation = [ [ [ Hours ':' ] Minutes ':' ] Seconds ':' ] Fraction\n" }, { "answer_id": 286974, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 0, "selected": false, "text": "\"^0*?(\\\\d?\\\\d?)(\\\\d?\\\\d?)(\\\\d?\\\\d?)(\\\\d?\\\\d?)$\" boost::regex boost::regex" }, { "answer_id": 287039, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 0, "selected": false, "text": "void parse(const string &s) {\n string::const_iterator current = s.begin();\n int HH = 0;\n int mm = 0;\n int ss = 0;\n int ff = 0;\n switch(s.size()) {\n case 8:\n HH = (*(current++) - '0') * 10;\n case 7:\n HH += (*(current++) - '0');\n case 6:\n mm = (*(current++) - '0') * 10;\n // ... you get the idea.\n case 1:\n ff += (*current - '0');\n case 0: break;\n default: throw logic_error(\"invalid date\");\n // except that this code goes so badly wrong if the input isn't\n // valid that there's not much point objecting to the length...\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5049/" ]
286,870
<p>Is there any reasonable method to allow users of a webapp to download large files? I'm looking for something other than the browser's built-in download dialog - the requirements are that the user initiates the download from the browser and then some other application takes over, downloads the file in background and doesn't exit when the browser is closed. It might possibly work over http, ftp or even bittorrent. Platform independence would be a nice thing to have but I'm mostly concerned with Windows.</p>
[ { "answer_id": 287269, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": ".torrent" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6615/" ]
286,871
<p>I need to get authentication credentials from the users within a Windows script but the classic "first Google result" approach:</p> <pre><code>SET /P USR=Username: SET /P PWD=Password: </code></pre> <p>is less than satisfying, so I was wondering if there's let's say an "equivalent" to <strong>HTML's input type="password"</strong>?</p> <p>Any comment would be really appreciated, thanks much in advance!</p>
[ { "answer_id": 668455, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "@echo off & setlocal enableextensions\n :: Build a Visual Basic Script\n set vbs_=%temp%\\tmp$$$.vbs\n set skip=\n findstr \"'%skip%VBS\" \"%~f0\" > \"%vbs_%\"\n ::\n :: Prompting without linefeed as in Item #15\n echo.|set /p=\"Password: \"\n\n :: Run the script with Microsoft Windows Script Host Version 5.6\n for /f \"tokens=* delims=\" %%a in ('cscript //nologo \"%vbs_%\"') do set MyPass1=%%a\n\n ::\n ::echo.\n echo.|set /p=\"Retype : \"\n\n for /f \"tokens=* delims=\" %%a in ('cscript //nologo \"%vbs_%\"') do set MyPass2=%%a\n ::\n\n :: Clean up\n for %%f in (\"%vbs_%\") do if exist %%f del %%f\n ::\n :: Demonstrate the result\n echo.\n if \"%MyPass1%\"==\"%MyPass2%\" (\n echo The entered password was %MyPass1%\n ) else (\n echo No match)\n endlocal & goto :EOF\n '\n 'The Visual Basic Script\n Set WshPass = WScript.CreateObject(\"ScriptPW.Password\") 'VBS\n Password=WshPass.GetPassWord() 'VBS\n WScript.Echo PassWord 'VBS\n" }, { "answer_id": 694641, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 2, "selected": false, "text": "@echo off\n:: GetPwd.cmd - Get password with no echo.\n<nul: set /p passwd=Password: \nfor /f \"delims=\" %%i in ('cscript /nologo GetPwd.vbs') do set passwd=%%i\necho.\n:: This bit's just to prove we have the password.\necho %passwd%\n ' GetPwd.vbs - Get password with no echo then echo it. '\nSet oScriptPW = CreateObject(\"ScriptPW.Password\")\nstrPassword = oScriptPW.GetPassword()\nWscript.StdOut.WriteLine strPassword\n \"<nul: set /p passwd=Password: \" \"echo -n\" passwd \"for /f \"delims=\" %%i in ('cscript /nologo GetPwd.vbs') do set passwd=%%i\" /nologo \"Wscript.StdOut.WriteLine strPassword\" \"for ... do set ...\" passwd \"Password: \" C:\\Pax> GetPwd\nPassword:\nthis is my password\n\nC:\\Pax> \n scriptpw.dll Windows\\System32 Winnt\\System32 Windows\\System32 regsvr32 scriptpw.dll regsvr32 scriptpw.dll" }, { "answer_id": 16896331, "author": "Panos Rontogiannis", "author_id": 850119, "author_profile": "https://Stackoverflow.com/users/850119", "pm_score": 1, "selected": false, "text": "PowerShell Batch $password = Read-Host \"Enter password\" -AsSecureString;\n$decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password));\n& \"sc.exe\" config THE_SERVICE_NAME obj= THE_ACCOUNT password= $decodedPassword;\n call powershell -Command \"$password = Read-Host \"Enter password\" -AsSecureString; $decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)); & \"sc.exe\" config THE_SERVICE_NAME obj= THE_ACCOUNT password= $decodedPassword;\"\n PowerShell PowerShell" }, { "answer_id": 24792218, "author": "Aacini", "author_id": 778560, "author_profile": "https://Stackoverflow.com/users/778560", "pm_score": 1, "selected": false, "text": "call :ReadFormattedLine USR=\"********\" /M \"Username: \"\ncall :ReadFormattedLine PWD=\"********\" /M \"Password: \"\n call :ReadFormattedLine nameAndPass=\"******** / ********\" /M \"Enter Username / Password: \"\n" }, { "answer_id": 28250622, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 2, "selected": false, "text": "XCOPY /P /L :: Hidden.cmd\n::Tom Lavedas, 02/05/2013, 02/20/2013\n::Carlos, 02/22/2013\n::https://groups.google.com/forum/#!topic/alt.msdos.batch.nt/f7mb_f99lYI\n\n\n@Echo Off\n:HInput\nSetLocal EnableExtensions EnableDelayedExpansion\nSet \"FILE=%Temp%.\\T\"\nSet \"FILE=.\\T\"\nKeys List >\"%File%\"\nSet /P \"=Hidden text ending with Ctrl-C?: \" <Nul\nEcho.\nSet \"HInput=\"\n:HInput_\nFor /F \"tokens=1* delims=?\" %%A In (\n '\"Xcopy /P /L \"%FILE%\" \"%FILE%\" 2>Nul\"'\n) Do (\n Set \"Text=%%B\"\n If Defined Text (\n Set \"Char=!Text:~1,1!\"\n Set \"Intro=1\"\n For /F delims^=^ eol^= %%Z in (\"!Char!\") Do Set \"Intro=0\"\n Rem If press Intro\n If 1 Equ !Intro! Goto :HInput#\n Set \"HInput=!HInput!!Char!\"\n )\n)\nGoto :HInput_\n:HInput#\nEcho(!HInput!\nGoto :Eof \n <!-- :\n:: PasswordSubmitter.bat\n@echo off\nfor /f \"tokens=* delims=\" %%p in ('mshta.exe \"%~f0\"') do (\n set \"pass=%%p\"\n)\n\necho your password is %pass%\nexit /b\n-->\n\n<html>\n<head><title>Password submitter</title></head>\n<body>\n\n <script language='javascript' >\n function pipePass() {\n var pass=document.getElementById('pass').value;\n var fso= new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1);\n close(fso.Write(pass));\n\n }\n </script>\n\n <input type='password' name='pass' size='15'></input>\n <hr>\n <button onclick='pipePass()'>Submit</button>\n\n</body>\n</html>\n .bat @if (@X)==(@Y) @end /* JScript comment\n@echo off\nsetlocal\n\nfor /f \"tokens=* delims=\" %%v in ('dir /b /s /a:-d /o:-n \"%SystemRoot%\\Microsoft.NET\\Framework\\*jsc.exe\"') do (\n set \"jsc=%%v\"\n)\n\nif not exist \"%~n0.exe\" (\n \"%jsc%\" /nologo /out:\"%~n0.exe\" \"%~dpsfnx0\"\n)\n\nfor /f \"tokens=* delims=\" %%p in ('\"%~n0.exe\"') do (\n set \"pass=%%p\"\n)\n\necho your password is %pass%\n\nendlocal & exit /b %errorlevel%\n\n*/\n\n\n\nimport System;\n\n\n\nvar pwd = \"\";\nvar key;\n\nConsole.Error.Write(\"Enter password: \");\n\n do {\n key = Console.ReadKey(true);\n if ( (key.KeyChar.ToString().charCodeAt(0)) >= 20 && (key.KeyChar.ToString().charCodeAt(0) <= 126) ) {\n pwd=pwd+(key.KeyChar.ToString());\n Console.Error.Write(\"*\");\n } \n\n } while (key.Key != ConsoleKey.Enter);\n Console.Error.WriteLine();\n Console.WriteLine(pwd);\n" }, { "answer_id": 28252165, "author": "Mofi", "author_id": 3074564, "author_profile": "https://Stackoverflow.com/users/3074564", "pm_score": 0, "selected": false, "text": "ConSet.exe /PH \"PWD=Password: \"\n H" }, { "answer_id": 62939045, "author": "Bill_Stewart", "author_id": 2102693, "author_profile": "https://Stackoverflow.com/users/2102693", "pm_score": 0, "selected": false, "text": "editenv editv32 editv64 --maskinput -m editenv --maskinput --prompt=\"Password: \" PWD\n Password: PWD --maskinput -m" }, { "answer_id": 74472704, "author": "Roland", "author_id": 1845672, "author_profile": "https://Stackoverflow.com/users/1845672", "pm_score": 0, "selected": false, "text": "import getpass; password = getpass.getpass()" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6992/" ]
286,873
<p>I'm having a difficult time figuring out how to add a .jar/library to a Netbeans project in such a way that I can get it committed to the repository.</p> <p>The typical way to add a library (per the Netbeans documents I've already gone through) ends up with it just being local to me. Anyone who checks out my project ends up missing my required library.</p> <p>Inserting it manually and trying to work around Netbeans results in Netbeans hanging while trying to scan the project...</p> <p>So, how can I tell Netbeans to pick up a jar as a library and include it in my project in such a way that Subversion will be able to handle it?</p>
[ { "answer_id": 287767, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 2, "selected": false, "text": "libs.LIBRARY_NAME.classpath=... libs.Log4J.classpath=lib/log4j.jar" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15689/" ]
286,876
<p>what's the best practice for creating test persistence layers when doing an ASP.NET site (eg. ASP.NET MVC site)?</p> <p>Many examples I've seen use Moq (or another mocking framework) in the unit test project, but I want to, like .. moq out my persistence layer so that my website shows data and stuff, but it's not coming from a database. I want to do that last. All the mocking stuff I've seen only exists in unit tests.</p> <p>What practices do people do when they want to (stub?) fake out a persistence layer for quick and fast development? I use Dependency Injection to handle it and have some hard coded results for my persistence layer (which is really manual and boring).</p> <p>What are other people doing? Examples and links would be awesome :)</p> <h2>UPDATE</h2> <p>Just a little update: so far I'm getting a fair bit of mileage out of having a fake repository and a SQL repository - where each class implements an interface. Then, using DI (I'm using StructureMap), I can switch between my fake repository or the SQL repository. So far, it's working well :)</p> <p>(also scary to think that I asked this question nearly 11 months ago, from when I'm editing this, right now!)</p>
[ { "answer_id": 286942, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 2, "selected": false, "text": "public static ICatalogRepository GetCatalogRepository(bool useMock)\n{\n if(useMock)\n return new FakeCatalogRepository();\n else\n return new SqlCatalogRepository();\n}\n container.Resolve<ICatalogRepository>();\n public class Product\n{\n public int Identity { get; set; }\n public string Name { get; set; }\n public string Description { get; set; }\n //etc\n}\n\npublic class FakeCatalogRepository()\n{\n private List<Product> _fakes;\n\n public FakeCatalogCatalogRepository()\n {\n _fakes = new List<Product>();\n\n //Set up some initial fake data\n for(int i=0; i < 5; i++)\n {\n Product p = new Product\n {\n Identity = i,\n Name = \"product\"+i,\n Description = \"description of product\"+i\n };\n\n _fakes.Add(p);\n }\n }\n\n public void StoreProduct(Product p)\n {\n //Emulate insert/update functionality\n\n _fakes.Add(p);\n }\n\n public Product GetProductByIdentity(int id)\n {\n //emulate \"SELECT * FROM products WHERE id = 1234\n var aProduct = (from p in _fakes.AsQueryable()\n where p.Identity = id\n select p).SingleOrDefault();\n\n return aProduct;\n }\n}\n" }, { "answer_id": 287019, "author": "Greg Banister", "author_id": 23823, "author_profile": "https://Stackoverflow.com/users/23823", "pm_score": 0, "selected": false, "text": "public class SchemaBuilder\n{\n public static void ExportSchema()\n {\n Configuration configuration = new Configuration();\n configuration.Configure();\n new SchemaExport(configuration).Create(true, true);\n }\n}\n [SetUpFixture]\npublic class SetUpFixture\n{\n [SetUp]\n public void SetUp()\n {\n SchemaBuilder.ExportSchema();\n DataLoader.LoadData();\n }\n}\n" }, { "answer_id": 312682, "author": "Peter Evjan", "author_id": 3397, "author_profile": "https://Stackoverflow.com/users/3397", "pm_score": 0, "selected": false, "text": "ActiveRecord.Initalize(lots of parameters)\nActiveRecord.DropSchema();\nActiveRecord.CreateSchema();\n customerRepository.Save(customer);\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30674/" ]
286,894
<p>Like the title says, how can I remove GAC assembly file using vbscript?</p>
[ { "answer_id": 286898, "author": "Mikael Söderström", "author_id": 36944, "author_profile": "https://Stackoverflow.com/users/36944", "pm_score": 1, "selected": false, "text": "gacutil /u YourAssembly\n" }, { "answer_id": 286903, "author": "kenny", "author_id": 3225, "author_profile": "https://Stackoverflow.com/users/3225", "pm_score": 0, "selected": false, "text": "C:\\>gacutil\nMicrosoft (R) .NET Global Assembly Cache Utility. Version 3.5.21022.8\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nUsage: Gacutil <command> [ <options> ]\nCommands:\n /i <assembly_path> [ /r <...> ] [ /f ]\n Installs an assembly to the global assembly cache.\n\n /il <assembly_path_list_file> [ /r <...> ] [ /f ]\n Installs one or more assemblies to the global assembly cache.\n\n /u <assembly_display_name> [ /r <...> ]\n Uninstalls an assembly from the global assembly cache.\n\n /ul <assembly_display_name_list_file> [ /r <...> ]\n Uninstalls one or more assemblies from the global assembly cache.\n\n /l [ <assembly_name> ]\n List the global assembly cache filtered by <assembly_name>\n\n /lr [ <assembly_name> ]\n List the global assembly cache with all traced references.\n\n /cdl\n Deletes the contents of the download cache\n\n /ldl\n Lists the contents of the download cache\n\n /?\n Displays a detailed help screen\n\n Options:\n /r <reference_scheme> <reference_id> <description>\n Specifies a traced reference to install (/i, /il) or uninstall (/u, /ul).\n\n /f\n Forces reinstall of an assembly.\n\n /nologo\n Suppresses display of the logo banner\n\n /silent\n Suppresses display of all output\n" }, { "answer_id": 1136398, "author": "Helen", "author_id": 113116, "author_profile": "https://Stackoverflow.com/users/113116", "pm_score": 0, "selected": false, "text": "gacutil Const GACUTILPATH = \"C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Bin\\gacutil.exe\"\nstrAssembly = \"MyAssembly\" '' or \"MyAssembly,Version=1.1.0.0,Culture=en,PublicKeyToken=874e23ab874e23ab\"\n\nSet oShell = CreateObject(\"WScript.Shell\")\noShell.Run \"\"\"\" & GACUTILPATH & \"\"\" /nologo /u \" & strAssembly\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
286,904
<p>I am trying to adapt a simple WPF application to use the Model-View-ViewModel pattern. On my page I have a couple of animations:</p> <pre><code>&lt;Page.Resources&gt; &lt;Storyboard x:Name="storyboardRight" x:Key="storyboardRight"&gt; &lt;DoubleAnimation x:Name="da3" Storyboard.TargetName="labelRight" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.5" /&gt; &lt;DoubleAnimation x:Name="da4" Storyboard.TargetName="labelRight" Storyboard.TargetProperty="Opacity" From="1" To="0" BeginTime="0:0:1" Duration="0:0:0.5" /&gt; &lt;/Storyboard&gt; ... &lt;/Page.Resources&gt; </code></pre> <p>Currently I begin the animation in the code behind, and can listen to the Completed event to do something when it finishes with the following code:</p> <pre><code>storyboardRight = (Storyboard)TryFindResource("storyboardRight"); storyboardRight.Completed += new EventHandler(storyboardRight_Completed); storyboardRight.Begin(this); </code></pre> <p>Is there a way of data binding the storyboard to my ViewModel so that it starts on an event raised by the ViewModel and can call-back into that ViewModel when it is finished?</p>
[ { "answer_id": 286949, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 1, "selected": false, "text": "EventTrigger" }, { "answer_id": 402758, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 4, "selected": true, "text": "DataTrigger ContentPresenter ICommand" }, { "answer_id": 5980830, "author": "CowboyBebop", "author_id": 749626, "author_profile": "https://Stackoverflow.com/users/749626", "pm_score": 2, "selected": false, "text": "<Window\n xmlns:i=\"http://schemas.microsoft.com/expression/2010/interactivity\"\n xmlns:ei=\"http://schemas.microsoft.com/expression/2010/interactions\" \n x:Name=\"window\" >\n ...\n\n <i:Interaction.Triggers>\n <ei:DataTrigger Binding=\"{Binding FlashingBackground, Mode=OneWay}\" Value=\"ON\">\n <ei:ControlStoryboardAction Storyboard=\"{StaticResource MyAnimation}\" \n ControlStoryboardOption=\"Play\"/>\n </ei:DataTrigger>\n </i:Interaction.Triggers>\n\n ...\n</Window>\n private void TurnOnFlashingBackround()\n {\n this.FlashingBackground = \"ON\";\n }\n\n private string _FlashingBackround = \"OFF\";\n\n public string FlashingBackground\n {\n get { return this._FlashingBackround; }\n\n private set\n {\n if (this.FlashingBackground == value)\n {\n return;\n }\n\n this._FlashingBackround = value;\n this.OnPropertyChanged(\"FlashingBackground\");\n }\n }\n\n public new event PropertyChangedEventHandler PropertyChanged;\n\n private void OnPropertyChanged(string propertyName)\n {\n if (this.PropertyChanged != null)\n {\n this.PropertyChanged(\n this, \n new PropertyChangedEventArgs(propertyName));\n }\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7532/" ]
286,921
<p>For a poor man's implementation of <em>near</em>-collation-correct sorting on the client side I need a JavaScript function that does <em>efficient</em> single character replacement in a string.</p> <p>Here is what I mean (note that this applies to German text, other languages sort differently):</p> <pre> native sorting gets it wrong: a b c o u z ä ö ü collation-correct would be: a ä b c o ö u ü z </pre> <p>Basically, I need all occurrences of &quot;ä&quot; of a given string replaced with &quot;a&quot; (and so on). This way the result of native sorting would be very close to what a user would expect (or what a database would return).</p> <p>Other languages have facilities to do just that: <a href="http://docs.python.org/3.1/library/stdtypes.html#str.translate" rel="noreferrer">Python supplies <code>str.translate()</code></a>, in <a href="http://perldoc.perl.org/functions/tr.html" rel="noreferrer">Perl there is <code>tr/…/…/</code></a>, <a href="http://www.w3.org/TR/xpath/#function-translate" rel="noreferrer">XPath has a function <code>translate()</code></a>, <a href="http://livedocs.adobe.com/coldfusion/8/functions_m-r_33.html" rel="noreferrer">ColdFusion has <code>ReplaceList()</code></a>. But what about JavaScript?</p> <p>Here is what I have right now.</p> <pre><code>// s would be a rather short string (something like // 200 characters at max, most of the time much less) function makeSortString(s) { var translate = { &quot;ä&quot;: &quot;a&quot;, &quot;ö&quot;: &quot;o&quot;, &quot;ü&quot;: &quot;u&quot;, &quot;Ä&quot;: &quot;A&quot;, &quot;Ö&quot;: &quot;O&quot;, &quot;Ü&quot;: &quot;U&quot; // probably more to come }; var translate_re = /[öäüÖÄÜ]/g; return ( s.replace(translate_re, function(match) { return translate[match]; }) ); } </code></pre> <p>For starters, I don't like the fact that the regex is rebuilt every time I call the function. I guess a closure can help in this regard, but I don't seem to get the hang of it for some reason.</p> <p>Can someone think of something more efficient?</p> <hr /> <h2>Answers below fall in two categories:</h2> <ol> <li>String replacement functions of varying degrees of completeness and efficiency (what I was originally asking about)</li> <li>A <a href="https://stackoverflow.com/a/42163018/18771">late mention</a> of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare" rel="noreferrer"><code>String#localeCompare</code></a>, which is now <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare#Browser_compatibility" rel="noreferrer">widely supported</a> among JS engines (not so much at the time of the question) and could solve this category of problem much more elegantly.</li> </ol>
[ { "answer_id": 287173, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 6, "selected": true, "text": "function makeSortString(s) {\n if(!makeSortString.translate_re) makeSortString.translate_re = /[öäüÖÄÜ]/g;\n var translate = {\n \"ä\": \"a\", \"ö\": \"o\", \"ü\": \"u\",\n \"Ä\": \"A\", \"Ö\": \"O\", \"Ü\": \"U\" // probably more to come\n };\n return ( s.replace(makeSortString.translate_re, function(match) { \n return translate[match]; \n }) );\n}\n makeSortString.translate_re = /[a-z]/g;\n var makeSortString = (function() {\n var translate_re = /[öäüÖÄÜ]/g;\n return function(s) {\n var translate = {\n \"ä\": \"a\", \"ö\": \"o\", \"ü\": \"u\",\n \"Ä\": \"A\", \"Ö\": \"O\", \"Ü\": \"U\" // probably more to come\n };\n return ( s.replace(translate_re, function(match) { \n return translate[match]; \n }) );\n }\n})();\n translate var makeSortString = (function() {\n var translate_re = /[öäüÖÄÜ]/g;\n var translate = {\n \"ä\": \"a\", \"ö\": \"o\", \"ü\": \"u\",\n \"Ä\": \"A\", \"Ö\": \"O\", \"Ü\": \"U\" // probably more to come\n };\n return function(s) {\n return ( s.replace(translate_re, function(match) { \n return translate[match]; \n }) );\n }\n})();\n" }, { "answer_id": 614397, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": false, "text": "textExtraction 'dd.mm.yyyy' 'yyyy-mm-dd' // file encoding must be UTF-8!\nfunction getTextExtractor()\n{\n return (function() {\n var patternLetters = /[öäüÖÄÜáàâéèêúùûóòôÁÀÂÉÈÊÚÙÛÓÒÔß]/g;\n var patternDateDmy = /^(?:\\D+)?(\\d{1,2})\\.(\\d{1,2})\\.(\\d{2,4})$/;\n var lookupLetters = {\n \"ä\": \"a\", \"ö\": \"o\", \"ü\": \"u\",\n \"Ä\": \"A\", \"Ö\": \"O\", \"Ü\": \"U\",\n \"á\": \"a\", \"à\": \"a\", \"â\": \"a\",\n \"é\": \"e\", \"è\": \"e\", \"ê\": \"e\",\n \"ú\": \"u\", \"ù\": \"u\", \"û\": \"u\",\n \"ó\": \"o\", \"ò\": \"o\", \"ô\": \"o\",\n \"Á\": \"A\", \"À\": \"A\", \"Â\": \"A\",\n \"É\": \"E\", \"È\": \"E\", \"Ê\": \"E\",\n \"Ú\": \"U\", \"Ù\": \"U\", \"Û\": \"U\",\n \"Ó\": \"O\", \"Ò\": \"O\", \"Ô\": \"O\",\n \"ß\": \"s\"\n };\n var letterTranslator = function(match) { \n return lookupLetters[match] || match;\n }\n\n return function(node) {\n var text = $.trim($(node).text());\n var date = text.match(patternDateDmy);\n if (date)\n return [date[3], date[2], date[1]].join(\"-\");\n else\n return text.replace(patternLetters, letterTranslator);\n }\n })();\n}\n $(\"table.sortable\").tablesorter({ \n textExtraction: getTextExtractor()\n}); \n" }, { "answer_id": 6123591, "author": "Jan Hagge", "author_id": 769437, "author_profile": "https://Stackoverflow.com/users/769437", "pm_score": 3, "selected": false, "text": "String.prototype.strip = function() {\n var translate_re = /[öäüÖÄÜß ]/g;\n var translate = {\n \"ä\":\"a\", \"ö\":\"o\", \"ü\":\"u\",\n \"Ä\":\"A\", \"Ö\":\"O\", \"Ü\":\"U\",\n \" \":\"_\", \"ß\":\"ss\" // probably more to come\n };\n return (this.replace(translate_re, function(match){\n return translate[match];})\n );\n};\n var teststring = 'ä ö ü Ä Ö Ü ß';\nteststring.strip();\n" }, { "answer_id": 8490728, "author": "Martin_Lakes", "author_id": 1095915, "author_profile": "https://Stackoverflow.com/users/1095915", "pm_score": 4, "selected": false, "text": "String.prototype.stripAccents = function() {\n var translate_re = /[àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ]/g;\n var translate = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY';\n return (this.replace(translate_re, function(match){\n return translate.substr(translate_re.source.indexOf(match)-1, 1); })\n );\n};\n String.prototype.stripAccents = function() {\n var in_chrs = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',\n out_chrs = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY', \n transl = {};\n eval('var chars_rgx = /['+in_chrs+']/g');\n for(var i = 0; i < in_chrs.length; i++){ transl[in_chrs.charAt(i)] = out_chrs.charAt(i); }\n return this.replace(chars_rgx, function(match){\n return transl[match]; });\n};\n var stripAccents = (function () {\n var in_chrs = 'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',\n out_chrs = 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY', \n chars_rgx = new RegExp('[' + in_chrs + ']', 'g'),\n transl = {}, i,\n lookup = function (m) { return transl[m] || m; };\n\n for (i=0; i<in_chrs.length; i++) {\n transl[ in_chrs[i] ] = out_chrs[i];\n }\n\n return function (s) { return s.replace(chars_rgx, lookup); }\n})();\n" }, { "answer_id": 9667817, "author": "Ed.", "author_id": 171317, "author_profile": "https://Stackoverflow.com/users/171317", "pm_score": 7, "selected": false, "text": "var Latinise={};Latinise.latin_map={\"Á\":\"A\",\n\"Ă\":\"A\",\n\"Ắ\":\"A\",\n\"Ặ\":\"A\",\n\"Ằ\":\"A\",\n\"Ẳ\":\"A\",\n\"Ẵ\":\"A\",\n\"Ǎ\":\"A\",\n\"Â\":\"A\",\n\"Ấ\":\"A\",\n\"Ậ\":\"A\",\n\"Ầ\":\"A\",\n\"Ẩ\":\"A\",\n\"Ẫ\":\"A\",\n\"Ä\":\"A\",\n\"Ǟ\":\"A\",\n\"Ȧ\":\"A\",\n\"Ǡ\":\"A\",\n\"Ạ\":\"A\",\n\"Ȁ\":\"A\",\n\"À\":\"A\",\n\"Ả\":\"A\",\n\"Ȃ\":\"A\",\n\"Ā\":\"A\",\n\"Ą\":\"A\",\n\"Å\":\"A\",\n\"Ǻ\":\"A\",\n\"Ḁ\":\"A\",\n\"Ⱥ\":\"A\",\n\"Ã\":\"A\",\n\"Ꜳ\":\"AA\",\n\"Æ\":\"AE\",\n\"Ǽ\":\"AE\",\n\"Ǣ\":\"AE\",\n\"Ꜵ\":\"AO\",\n\"Ꜷ\":\"AU\",\n\"Ꜹ\":\"AV\",\n\"Ꜻ\":\"AV\",\n\"Ꜽ\":\"AY\",\n\"Ḃ\":\"B\",\n\"Ḅ\":\"B\",\n\"Ɓ\":\"B\",\n\"Ḇ\":\"B\",\n\"Ƀ\":\"B\",\n\"Ƃ\":\"B\",\n\"Ć\":\"C\",\n\"Č\":\"C\",\n\"Ç\":\"C\",\n\"Ḉ\":\"C\",\n\"Ĉ\":\"C\",\n\"Ċ\":\"C\",\n\"Ƈ\":\"C\",\n\"Ȼ\":\"C\",\n\"Ď\":\"D\",\n\"Ḑ\":\"D\",\n\"Ḓ\":\"D\",\n\"Ḋ\":\"D\",\n\"Ḍ\":\"D\",\n\"Ɗ\":\"D\",\n\"Ḏ\":\"D\",\n\"Dz\":\"D\",\n\"Dž\":\"D\",\n\"Đ\":\"D\",\n\"Ƌ\":\"D\",\n\"DZ\":\"DZ\",\n\"DŽ\":\"DZ\",\n\"É\":\"E\",\n\"Ĕ\":\"E\",\n\"Ě\":\"E\",\n\"Ȩ\":\"E\",\n\"Ḝ\":\"E\",\n\"Ê\":\"E\",\n\"Ế\":\"E\",\n\"Ệ\":\"E\",\n\"Ề\":\"E\",\n\"Ể\":\"E\",\n\"Ễ\":\"E\",\n\"Ḙ\":\"E\",\n\"Ë\":\"E\",\n\"Ė\":\"E\",\n\"Ẹ\":\"E\",\n\"Ȅ\":\"E\",\n\"È\":\"E\",\n\"Ẻ\":\"E\",\n\"Ȇ\":\"E\",\n\"Ē\":\"E\",\n\"Ḗ\":\"E\",\n\"Ḕ\":\"E\",\n\"Ę\":\"E\",\n\"Ɇ\":\"E\",\n\"Ẽ\":\"E\",\n\"Ḛ\":\"E\",\n\"Ꝫ\":\"ET\",\n\"Ḟ\":\"F\",\n\"Ƒ\":\"F\",\n\"Ǵ\":\"G\",\n\"Ğ\":\"G\",\n\"Ǧ\":\"G\",\n\"Ģ\":\"G\",\n\"Ĝ\":\"G\",\n\"Ġ\":\"G\",\n\"Ɠ\":\"G\",\n\"Ḡ\":\"G\",\n\"Ǥ\":\"G\",\n\"Ḫ\":\"H\",\n\"Ȟ\":\"H\",\n\"Ḩ\":\"H\",\n\"Ĥ\":\"H\",\n\"Ⱨ\":\"H\",\n\"Ḧ\":\"H\",\n\"Ḣ\":\"H\",\n\"Ḥ\":\"H\",\n\"Ħ\":\"H\",\n\"Í\":\"I\",\n\"Ĭ\":\"I\",\n\"Ǐ\":\"I\",\n\"Î\":\"I\",\n\"Ï\":\"I\",\n\"Ḯ\":\"I\",\n\"İ\":\"I\",\n\"Ị\":\"I\",\n\"Ȉ\":\"I\",\n\"Ì\":\"I\",\n\"Ỉ\":\"I\",\n\"Ȋ\":\"I\",\n\"Ī\":\"I\",\n\"Į\":\"I\",\n\"Ɨ\":\"I\",\n\"Ĩ\":\"I\",\n\"Ḭ\":\"I\",\n\"Ꝺ\":\"D\",\n\"Ꝼ\":\"F\",\n\"Ᵹ\":\"G\",\n\"Ꞃ\":\"R\",\n\"Ꞅ\":\"S\",\n\"Ꞇ\":\"T\",\n\"Ꝭ\":\"IS\",\n\"Ĵ\":\"J\",\n\"Ɉ\":\"J\",\n\"Ḱ\":\"K\",\n\"Ǩ\":\"K\",\n\"Ķ\":\"K\",\n\"Ⱪ\":\"K\",\n\"Ꝃ\":\"K\",\n\"Ḳ\":\"K\",\n\"Ƙ\":\"K\",\n\"Ḵ\":\"K\",\n\"Ꝁ\":\"K\",\n\"Ꝅ\":\"K\",\n\"Ĺ\":\"L\",\n\"Ƚ\":\"L\",\n\"Ľ\":\"L\",\n\"Ļ\":\"L\",\n\"Ḽ\":\"L\",\n\"Ḷ\":\"L\",\n\"Ḹ\":\"L\",\n\"Ⱡ\":\"L\",\n\"Ꝉ\":\"L\",\n\"Ḻ\":\"L\",\n\"Ŀ\":\"L\",\n\"Ɫ\":\"L\",\n\"Lj\":\"L\",\n\"Ł\":\"L\",\n\"LJ\":\"LJ\",\n\"Ḿ\":\"M\",\n\"Ṁ\":\"M\",\n\"Ṃ\":\"M\",\n\"Ɱ\":\"M\",\n\"Ń\":\"N\",\n\"Ň\":\"N\",\n\"Ņ\":\"N\",\n\"Ṋ\":\"N\",\n\"Ṅ\":\"N\",\n\"Ṇ\":\"N\",\n\"Ǹ\":\"N\",\n\"Ɲ\":\"N\",\n\"Ṉ\":\"N\",\n\"Ƞ\":\"N\",\n\"Nj\":\"N\",\n\"Ñ\":\"N\",\n\"NJ\":\"NJ\",\n\"Ó\":\"O\",\n\"Ŏ\":\"O\",\n\"Ǒ\":\"O\",\n\"Ô\":\"O\",\n\"Ố\":\"O\",\n\"Ộ\":\"O\",\n\"Ồ\":\"O\",\n\"Ổ\":\"O\",\n\"Ỗ\":\"O\",\n\"Ö\":\"O\",\n\"Ȫ\":\"O\",\n\"Ȯ\":\"O\",\n\"Ȱ\":\"O\",\n\"Ọ\":\"O\",\n\"Ő\":\"O\",\n\"Ȍ\":\"O\",\n\"Ò\":\"O\",\n\"Ỏ\":\"O\",\n\"Ơ\":\"O\",\n\"Ớ\":\"O\",\n\"Ợ\":\"O\",\n\"Ờ\":\"O\",\n\"Ở\":\"O\",\n\"Ỡ\":\"O\",\n\"Ȏ\":\"O\",\n\"Ꝋ\":\"O\",\n\"Ꝍ\":\"O\",\n\"Ō\":\"O\",\n\"Ṓ\":\"O\",\n\"Ṑ\":\"O\",\n\"Ɵ\":\"O\",\n\"Ǫ\":\"O\",\n\"Ǭ\":\"O\",\n\"Ø\":\"O\",\n\"Ǿ\":\"O\",\n\"Õ\":\"O\",\n\"Ṍ\":\"O\",\n\"Ṏ\":\"O\",\n\"Ȭ\":\"O\",\n\"Ƣ\":\"OI\",\n\"Ꝏ\":\"OO\",\n\"Ɛ\":\"E\",\n\"Ɔ\":\"O\",\n\"Ȣ\":\"OU\",\n\"Ṕ\":\"P\",\n\"Ṗ\":\"P\",\n\"Ꝓ\":\"P\",\n\"Ƥ\":\"P\",\n\"Ꝕ\":\"P\",\n\"Ᵽ\":\"P\",\n\"Ꝑ\":\"P\",\n\"Ꝙ\":\"Q\",\n\"Ꝗ\":\"Q\",\n\"Ŕ\":\"R\",\n\"Ř\":\"R\",\n\"Ŗ\":\"R\",\n\"Ṙ\":\"R\",\n\"Ṛ\":\"R\",\n\"Ṝ\":\"R\",\n\"Ȑ\":\"R\",\n\"Ȓ\":\"R\",\n\"Ṟ\":\"R\",\n\"Ɍ\":\"R\",\n\"Ɽ\":\"R\",\n\"Ꜿ\":\"C\",\n\"Ǝ\":\"E\",\n\"Ś\":\"S\",\n\"Ṥ\":\"S\",\n\"Š\":\"S\",\n\"Ṧ\":\"S\",\n\"Ş\":\"S\",\n\"Ŝ\":\"S\",\n\"Ș\":\"S\",\n\"Ṡ\":\"S\",\n\"Ṣ\":\"S\",\n\"Ṩ\":\"S\",\n\"Ť\":\"T\",\n\"Ţ\":\"T\",\n\"Ṱ\":\"T\",\n\"Ț\":\"T\",\n\"Ⱦ\":\"T\",\n\"Ṫ\":\"T\",\n\"Ṭ\":\"T\",\n\"Ƭ\":\"T\",\n\"Ṯ\":\"T\",\n\"Ʈ\":\"T\",\n\"Ŧ\":\"T\",\n\"Ɐ\":\"A\",\n\"Ꞁ\":\"L\",\n\"Ɯ\":\"M\",\n\"Ʌ\":\"V\",\n\"Ꜩ\":\"TZ\",\n\"Ú\":\"U\",\n\"Ŭ\":\"U\",\n\"Ǔ\":\"U\",\n\"Û\":\"U\",\n\"Ṷ\":\"U\",\n\"Ü\":\"U\",\n\"Ǘ\":\"U\",\n\"Ǚ\":\"U\",\n\"Ǜ\":\"U\",\n\"Ǖ\":\"U\",\n\"Ṳ\":\"U\",\n\"Ụ\":\"U\",\n\"Ű\":\"U\",\n\"Ȕ\":\"U\",\n\"Ù\":\"U\",\n\"Ủ\":\"U\",\n\"Ư\":\"U\",\n\"Ứ\":\"U\",\n\"Ự\":\"U\",\n\"Ừ\":\"U\",\n\"Ử\":\"U\",\n\"Ữ\":\"U\",\n\"Ȗ\":\"U\",\n\"Ū\":\"U\",\n\"Ṻ\":\"U\",\n\"Ų\":\"U\",\n\"Ů\":\"U\",\n\"Ũ\":\"U\",\n\"Ṹ\":\"U\",\n\"Ṵ\":\"U\",\n\"Ꝟ\":\"V\",\n\"Ṿ\":\"V\",\n\"Ʋ\":\"V\",\n\"Ṽ\":\"V\",\n\"Ꝡ\":\"VY\",\n\"Ẃ\":\"W\",\n\"Ŵ\":\"W\",\n\"Ẅ\":\"W\",\n\"Ẇ\":\"W\",\n\"Ẉ\":\"W\",\n\"Ẁ\":\"W\",\n\"Ⱳ\":\"W\",\n\"Ẍ\":\"X\",\n\"Ẋ\":\"X\",\n\"Ý\":\"Y\",\n\"Ŷ\":\"Y\",\n\"Ÿ\":\"Y\",\n\"Ẏ\":\"Y\",\n\"Ỵ\":\"Y\",\n\"Ỳ\":\"Y\",\n\"Ƴ\":\"Y\",\n\"Ỷ\":\"Y\",\n\"Ỿ\":\"Y\",\n\"Ȳ\":\"Y\",\n\"Ɏ\":\"Y\",\n\"Ỹ\":\"Y\",\n\"Ź\":\"Z\",\n\"Ž\":\"Z\",\n\"Ẑ\":\"Z\",\n\"Ⱬ\":\"Z\",\n\"Ż\":\"Z\",\n\"Ẓ\":\"Z\",\n\"Ȥ\":\"Z\",\n\"Ẕ\":\"Z\",\n\"Ƶ\":\"Z\",\n\"IJ\":\"IJ\",\n\"Œ\":\"OE\",\n\"ᴀ\":\"A\",\n\"ᴁ\":\"AE\",\n\"ʙ\":\"B\",\n\"ᴃ\":\"B\",\n\"ᴄ\":\"C\",\n\"ᴅ\":\"D\",\n\"ᴇ\":\"E\",\n\"ꜰ\":\"F\",\n\"ɢ\":\"G\",\n\"ʛ\":\"G\",\n\"ʜ\":\"H\",\n\"ɪ\":\"I\",\n\"ʁ\":\"R\",\n\"ᴊ\":\"J\",\n\"ᴋ\":\"K\",\n\"ʟ\":\"L\",\n\"ᴌ\":\"L\",\n\"ᴍ\":\"M\",\n\"ɴ\":\"N\",\n\"ᴏ\":\"O\",\n\"ɶ\":\"OE\",\n\"ᴐ\":\"O\",\n\"ᴕ\":\"OU\",\n\"ᴘ\":\"P\",\n\"ʀ\":\"R\",\n\"ᴎ\":\"N\",\n\"ᴙ\":\"R\",\n\"ꜱ\":\"S\",\n\"ᴛ\":\"T\",\n\"ⱻ\":\"E\",\n\"ᴚ\":\"R\",\n\"ᴜ\":\"U\",\n\"ᴠ\":\"V\",\n\"ᴡ\":\"W\",\n\"ʏ\":\"Y\",\n\"ᴢ\":\"Z\",\n\"á\":\"a\",\n\"ă\":\"a\",\n\"ắ\":\"a\",\n\"ặ\":\"a\",\n\"ằ\":\"a\",\n\"ẳ\":\"a\",\n\"ẵ\":\"a\",\n\"ǎ\":\"a\",\n\"â\":\"a\",\n\"ấ\":\"a\",\n\"ậ\":\"a\",\n\"ầ\":\"a\",\n\"ẩ\":\"a\",\n\"ẫ\":\"a\",\n\"ä\":\"a\",\n\"ǟ\":\"a\",\n\"ȧ\":\"a\",\n\"ǡ\":\"a\",\n\"ạ\":\"a\",\n\"ȁ\":\"a\",\n\"à\":\"a\",\n\"ả\":\"a\",\n\"ȃ\":\"a\",\n\"ā\":\"a\",\n\"ą\":\"a\",\n\"ᶏ\":\"a\",\n\"ẚ\":\"a\",\n\"å\":\"a\",\n\"ǻ\":\"a\",\n\"ḁ\":\"a\",\n\"ⱥ\":\"a\",\n\"ã\":\"a\",\n\"ꜳ\":\"aa\",\n\"æ\":\"ae\",\n\"ǽ\":\"ae\",\n\"ǣ\":\"ae\",\n\"ꜵ\":\"ao\",\n\"ꜷ\":\"au\",\n\"ꜹ\":\"av\",\n\"ꜻ\":\"av\",\n\"ꜽ\":\"ay\",\n\"ḃ\":\"b\",\n\"ḅ\":\"b\",\n\"ɓ\":\"b\",\n\"ḇ\":\"b\",\n\"ᵬ\":\"b\",\n\"ᶀ\":\"b\",\n\"ƀ\":\"b\",\n\"ƃ\":\"b\",\n\"ɵ\":\"o\",\n\"ć\":\"c\",\n\"č\":\"c\",\n\"ç\":\"c\",\n\"ḉ\":\"c\",\n\"ĉ\":\"c\",\n\"ɕ\":\"c\",\n\"ċ\":\"c\",\n\"ƈ\":\"c\",\n\"ȼ\":\"c\",\n\"ď\":\"d\",\n\"ḑ\":\"d\",\n\"ḓ\":\"d\",\n\"ȡ\":\"d\",\n\"ḋ\":\"d\",\n\"ḍ\":\"d\",\n\"ɗ\":\"d\",\n\"ᶑ\":\"d\",\n\"ḏ\":\"d\",\n\"ᵭ\":\"d\",\n\"ᶁ\":\"d\",\n\"đ\":\"d\",\n\"ɖ\":\"d\",\n\"ƌ\":\"d\",\n\"ı\":\"i\",\n\"ȷ\":\"j\",\n\"ɟ\":\"j\",\n\"ʄ\":\"j\",\n\"dz\":\"dz\",\n\"dž\":\"dz\",\n\"é\":\"e\",\n\"ĕ\":\"e\",\n\"ě\":\"e\",\n\"ȩ\":\"e\",\n\"ḝ\":\"e\",\n\"ê\":\"e\",\n\"ế\":\"e\",\n\"ệ\":\"e\",\n\"ề\":\"e\",\n\"ể\":\"e\",\n\"ễ\":\"e\",\n\"ḙ\":\"e\",\n\"ë\":\"e\",\n\"ė\":\"e\",\n\"ẹ\":\"e\",\n\"ȅ\":\"e\",\n\"è\":\"e\",\n\"ẻ\":\"e\",\n\"ȇ\":\"e\",\n\"ē\":\"e\",\n\"ḗ\":\"e\",\n\"ḕ\":\"e\",\n\"ⱸ\":\"e\",\n\"ę\":\"e\",\n\"ᶒ\":\"e\",\n\"ɇ\":\"e\",\n\"ẽ\":\"e\",\n\"ḛ\":\"e\",\n\"ꝫ\":\"et\",\n\"ḟ\":\"f\",\n\"ƒ\":\"f\",\n\"ᵮ\":\"f\",\n\"ᶂ\":\"f\",\n\"ǵ\":\"g\",\n\"ğ\":\"g\",\n\"ǧ\":\"g\",\n\"ģ\":\"g\",\n\"ĝ\":\"g\",\n\"ġ\":\"g\",\n\"ɠ\":\"g\",\n\"ḡ\":\"g\",\n\"ᶃ\":\"g\",\n\"ǥ\":\"g\",\n\"ḫ\":\"h\",\n\"ȟ\":\"h\",\n\"ḩ\":\"h\",\n\"ĥ\":\"h\",\n\"ⱨ\":\"h\",\n\"ḧ\":\"h\",\n\"ḣ\":\"h\",\n\"ḥ\":\"h\",\n\"ɦ\":\"h\",\n\"ẖ\":\"h\",\n\"ħ\":\"h\",\n\"ƕ\":\"hv\",\n\"í\":\"i\",\n\"ĭ\":\"i\",\n\"ǐ\":\"i\",\n\"î\":\"i\",\n\"ï\":\"i\",\n\"ḯ\":\"i\",\n\"ị\":\"i\",\n\"ȉ\":\"i\",\n\"ì\":\"i\",\n\"ỉ\":\"i\",\n\"ȋ\":\"i\",\n\"ī\":\"i\",\n\"į\":\"i\",\n\"ᶖ\":\"i\",\n\"ɨ\":\"i\",\n\"ĩ\":\"i\",\n\"ḭ\":\"i\",\n\"ꝺ\":\"d\",\n\"ꝼ\":\"f\",\n\"ᵹ\":\"g\",\n\"ꞃ\":\"r\",\n\"ꞅ\":\"s\",\n\"ꞇ\":\"t\",\n\"ꝭ\":\"is\",\n\"ǰ\":\"j\",\n\"ĵ\":\"j\",\n\"ʝ\":\"j\",\n\"ɉ\":\"j\",\n\"ḱ\":\"k\",\n\"ǩ\":\"k\",\n\"ķ\":\"k\",\n\"ⱪ\":\"k\",\n\"ꝃ\":\"k\",\n\"ḳ\":\"k\",\n\"ƙ\":\"k\",\n\"ḵ\":\"k\",\n\"ᶄ\":\"k\",\n\"ꝁ\":\"k\",\n\"ꝅ\":\"k\",\n\"ĺ\":\"l\",\n\"ƚ\":\"l\",\n\"ɬ\":\"l\",\n\"ľ\":\"l\",\n\"ļ\":\"l\",\n\"ḽ\":\"l\",\n\"ȴ\":\"l\",\n\"ḷ\":\"l\",\n\"ḹ\":\"l\",\n\"ⱡ\":\"l\",\n\"ꝉ\":\"l\",\n\"ḻ\":\"l\",\n\"ŀ\":\"l\",\n\"ɫ\":\"l\",\n\"ᶅ\":\"l\",\n\"ɭ\":\"l\",\n\"ł\":\"l\",\n\"lj\":\"lj\",\n\"ſ\":\"s\",\n\"ẜ\":\"s\",\n\"ẛ\":\"s\",\n\"ẝ\":\"s\",\n\"ḿ\":\"m\",\n\"ṁ\":\"m\",\n\"ṃ\":\"m\",\n\"ɱ\":\"m\",\n\"ᵯ\":\"m\",\n\"ᶆ\":\"m\",\n\"ń\":\"n\",\n\"ň\":\"n\",\n\"ņ\":\"n\",\n\"ṋ\":\"n\",\n\"ȵ\":\"n\",\n\"ṅ\":\"n\",\n\"ṇ\":\"n\",\n\"ǹ\":\"n\",\n\"ɲ\":\"n\",\n\"ṉ\":\"n\",\n\"ƞ\":\"n\",\n\"ᵰ\":\"n\",\n\"ᶇ\":\"n\",\n\"ɳ\":\"n\",\n\"ñ\":\"n\",\n\"nj\":\"nj\",\n\"ó\":\"o\",\n\"ŏ\":\"o\",\n\"ǒ\":\"o\",\n\"ô\":\"o\",\n\"ố\":\"o\",\n\"ộ\":\"o\",\n\"ồ\":\"o\",\n\"ổ\":\"o\",\n\"ỗ\":\"o\",\n\"ö\":\"o\",\n\"ȫ\":\"o\",\n\"ȯ\":\"o\",\n\"ȱ\":\"o\",\n\"ọ\":\"o\",\n\"ő\":\"o\",\n\"ȍ\":\"o\",\n\"ò\":\"o\",\n\"ỏ\":\"o\",\n\"ơ\":\"o\",\n\"ớ\":\"o\",\n\"ợ\":\"o\",\n\"ờ\":\"o\",\n\"ở\":\"o\",\n\"ỡ\":\"o\",\n\"ȏ\":\"o\",\n\"ꝋ\":\"o\",\n\"ꝍ\":\"o\",\n\"ⱺ\":\"o\",\n\"ō\":\"o\",\n\"ṓ\":\"o\",\n\"ṑ\":\"o\",\n\"ǫ\":\"o\",\n\"ǭ\":\"o\",\n\"ø\":\"o\",\n\"ǿ\":\"o\",\n\"õ\":\"o\",\n\"ṍ\":\"o\",\n\"ṏ\":\"o\",\n\"ȭ\":\"o\",\n\"ƣ\":\"oi\",\n\"ꝏ\":\"oo\",\n\"ɛ\":\"e\",\n\"ᶓ\":\"e\",\n\"ɔ\":\"o\",\n\"ᶗ\":\"o\",\n\"ȣ\":\"ou\",\n\"ṕ\":\"p\",\n\"ṗ\":\"p\",\n\"ꝓ\":\"p\",\n\"ƥ\":\"p\",\n\"ᵱ\":\"p\",\n\"ᶈ\":\"p\",\n\"ꝕ\":\"p\",\n\"ᵽ\":\"p\",\n\"ꝑ\":\"p\",\n\"ꝙ\":\"q\",\n\"ʠ\":\"q\",\n\"ɋ\":\"q\",\n\"ꝗ\":\"q\",\n\"ŕ\":\"r\",\n\"ř\":\"r\",\n\"ŗ\":\"r\",\n\"ṙ\":\"r\",\n\"ṛ\":\"r\",\n\"ṝ\":\"r\",\n\"ȑ\":\"r\",\n\"ɾ\":\"r\",\n\"ᵳ\":\"r\",\n\"ȓ\":\"r\",\n\"ṟ\":\"r\",\n\"ɼ\":\"r\",\n\"ᵲ\":\"r\",\n\"ᶉ\":\"r\",\n\"ɍ\":\"r\",\n\"ɽ\":\"r\",\n\"ↄ\":\"c\",\n\"ꜿ\":\"c\",\n\"ɘ\":\"e\",\n\"ɿ\":\"r\",\n\"ś\":\"s\",\n\"ṥ\":\"s\",\n\"š\":\"s\",\n\"ṧ\":\"s\",\n\"ş\":\"s\",\n\"ŝ\":\"s\",\n\"ș\":\"s\",\n\"ṡ\":\"s\",\n\"ṣ\":\"s\",\n\"ṩ\":\"s\",\n\"ʂ\":\"s\",\n\"ᵴ\":\"s\",\n\"ᶊ\":\"s\",\n\"ȿ\":\"s\",\n\"ɡ\":\"g\",\n\"ᴑ\":\"o\",\n\"ᴓ\":\"o\",\n\"ᴝ\":\"u\",\n\"ť\":\"t\",\n\"ţ\":\"t\",\n\"ṱ\":\"t\",\n\"ț\":\"t\",\n\"ȶ\":\"t\",\n\"ẗ\":\"t\",\n\"ⱦ\":\"t\",\n\"ṫ\":\"t\",\n\"ṭ\":\"t\",\n\"ƭ\":\"t\",\n\"ṯ\":\"t\",\n\"ᵵ\":\"t\",\n\"ƫ\":\"t\",\n\"ʈ\":\"t\",\n\"ŧ\":\"t\",\n\"ᵺ\":\"th\",\n\"ɐ\":\"a\",\n\"ᴂ\":\"ae\",\n\"ǝ\":\"e\",\n\"ᵷ\":\"g\",\n\"ɥ\":\"h\",\n\"ʮ\":\"h\",\n\"ʯ\":\"h\",\n\"ᴉ\":\"i\",\n\"ʞ\":\"k\",\n\"ꞁ\":\"l\",\n\"ɯ\":\"m\",\n\"ɰ\":\"m\",\n\"ᴔ\":\"oe\",\n\"ɹ\":\"r\",\n\"ɻ\":\"r\",\n\"ɺ\":\"r\",\n\"ⱹ\":\"r\",\n\"ʇ\":\"t\",\n\"ʌ\":\"v\",\n\"ʍ\":\"w\",\n\"ʎ\":\"y\",\n\"ꜩ\":\"tz\",\n\"ú\":\"u\",\n\"ŭ\":\"u\",\n\"ǔ\":\"u\",\n\"û\":\"u\",\n\"ṷ\":\"u\",\n\"ü\":\"u\",\n\"ǘ\":\"u\",\n\"ǚ\":\"u\",\n\"ǜ\":\"u\",\n\"ǖ\":\"u\",\n\"ṳ\":\"u\",\n\"ụ\":\"u\",\n\"ű\":\"u\",\n\"ȕ\":\"u\",\n\"ù\":\"u\",\n\"ủ\":\"u\",\n\"ư\":\"u\",\n\"ứ\":\"u\",\n\"ự\":\"u\",\n\"ừ\":\"u\",\n\"ử\":\"u\",\n\"ữ\":\"u\",\n\"ȗ\":\"u\",\n\"ū\":\"u\",\n\"ṻ\":\"u\",\n\"ų\":\"u\",\n\"ᶙ\":\"u\",\n\"ů\":\"u\",\n\"ũ\":\"u\",\n\"ṹ\":\"u\",\n\"ṵ\":\"u\",\n\"ᵫ\":\"ue\",\n\"ꝸ\":\"um\",\n\"ⱴ\":\"v\",\n\"ꝟ\":\"v\",\n\"ṿ\":\"v\",\n\"ʋ\":\"v\",\n\"ᶌ\":\"v\",\n\"ⱱ\":\"v\",\n\"ṽ\":\"v\",\n\"ꝡ\":\"vy\",\n\"ẃ\":\"w\",\n\"ŵ\":\"w\",\n\"ẅ\":\"w\",\n\"ẇ\":\"w\",\n\"ẉ\":\"w\",\n\"ẁ\":\"w\",\n\"ⱳ\":\"w\",\n\"ẘ\":\"w\",\n\"ẍ\":\"x\",\n\"ẋ\":\"x\",\n\"ᶍ\":\"x\",\n\"ý\":\"y\",\n\"ŷ\":\"y\",\n\"ÿ\":\"y\",\n\"ẏ\":\"y\",\n\"ỵ\":\"y\",\n\"ỳ\":\"y\",\n\"ƴ\":\"y\",\n\"ỷ\":\"y\",\n\"ỿ\":\"y\",\n\"ȳ\":\"y\",\n\"ẙ\":\"y\",\n\"ɏ\":\"y\",\n\"ỹ\":\"y\",\n\"ź\":\"z\",\n\"ž\":\"z\",\n\"ẑ\":\"z\",\n\"ʑ\":\"z\",\n\"ⱬ\":\"z\",\n\"ż\":\"z\",\n\"ẓ\":\"z\",\n\"ȥ\":\"z\",\n\"ẕ\":\"z\",\n\"ᵶ\":\"z\",\n\"ᶎ\":\"z\",\n\"ʐ\":\"z\",\n\"ƶ\":\"z\",\n\"ɀ\":\"z\",\n\"ff\":\"ff\",\n\"ffi\":\"ffi\",\n\"ffl\":\"ffl\",\n\"fi\":\"fi\",\n\"fl\":\"fl\",\n\"ij\":\"ij\",\n\"œ\":\"oe\",\n\"st\":\"st\",\n\"ₐ\":\"a\",\n\"ₑ\":\"e\",\n\"ᵢ\":\"i\",\n\"ⱼ\":\"j\",\n\"ₒ\":\"o\",\n\"ᵣ\":\"r\",\n\"ᵤ\":\"u\",\n\"ᵥ\":\"v\",\n\"ₓ\":\"x\"};\nString.prototype.latinise=function(){return this.replace(/[^A-Za-z0-9\\[\\] ]/g,function(a){return Latinise.latin_map[a]||a})};\nString.prototype.latinize=String.prototype.latinise;\nString.prototype.isLatin=function(){return this==this.latinise()}\n > \"Piqué\".latinize();\n\"Pique\"\n> \"Piqué\".isLatin();\nfalse\n> \"Pique\".isLatin();\ntrue\n> \"Piqué\".latinise().isLatin();\ntrue\n" }, { "answer_id": 11598969, "author": "jakov", "author_id": 1100709, "author_profile": "https://Stackoverflow.com/users/1100709", "pm_score": 2, "selected": false, "text": "a = a.replace(/ä/, 'a') .toLowerCase() function sortbyalphabet(a,b) {\n alphabet = \"0123456789AaÀàÁáÂâÃãÄäBbCcÇçDdÈèÉéÊêËëFfGgHhÌìÍíÎîÏïJjKkLlMmNnÑñOoÒòÓóÔôÕõÖöPpQqRrSsTtÙùÚúÛûÜüVvWwXxÝýŸÿZz\";\n a = a.toLowerCase();\n b = b.toLowerCase();\n shorterone = (a.length > b.length ? a : b);\n for (i=0; i<shorterone.length; i++){\n diff = alphabet.indexOf(a.charAt(i)) - alphabet.indexOf(b.charAt(i));\n if (diff!=0){\n return diff;\n }\n }\n // sort the shorter first\n return a.length - b.length;\n }\n var n = [\"ast\", \"Äste\", \"apfel\", \"äpfel\", \"à\"];\n console.log(n.sort(sortbyalphabet));\n // should return [\"apfel\", \"ast\", \"à\", \"äpfel\", \"äste\"]\n" }, { "answer_id": 16877175, "author": "yckart", "author_id": 1250044, "author_profile": "https://Stackoverflow.com/users/1250044", "pm_score": 2, "selected": false, "text": "/**\n * Normalise a string replacing foreign characters\n *\n * @param {String} str\n * @return {String} str\n */\n\nvar normalize = (function () {\n var a = ['À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ'];\n var b = ['A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o'];\n\n return function (str) {\n var i = a.length;\n while (i--) str = str.replace(a[i], b[i]);\n return str;\n };\n}());\n /**\n * Normalise a string replacing foreign characters\n *\n * @param {String} str\n * @return {String}\n */\nvar normalize = (function () {\n var map = {\n \"À\": \"A\",\n \"Á\": \"A\",\n \"Â\": \"A\",\n \"Ã\": \"A\",\n \"Ä\": \"A\",\n \"Å\": \"A\",\n \"Æ\": \"AE\",\n \"Ç\": \"C\",\n \"È\": \"E\",\n \"É\": \"E\",\n \"Ê\": \"E\",\n \"Ë\": \"E\",\n \"Ì\": \"I\",\n \"Í\": \"I\",\n \"Î\": \"I\",\n \"Ï\": \"I\",\n \"Ð\": \"D\",\n \"Ñ\": \"N\",\n \"Ò\": \"O\",\n \"Ó\": \"O\",\n \"Ô\": \"O\",\n \"Õ\": \"O\",\n \"Ö\": \"O\",\n \"Ø\": \"O\",\n \"Ù\": \"U\",\n \"Ú\": \"U\",\n \"Û\": \"U\",\n \"Ü\": \"U\",\n \"Ý\": \"Y\",\n \"ß\": \"s\",\n \"à\": \"a\",\n \"á\": \"a\",\n \"â\": \"a\",\n \"ã\": \"a\",\n \"ä\": \"a\",\n \"å\": \"a\",\n \"æ\": \"ae\",\n \"ç\": \"c\",\n \"è\": \"e\",\n \"é\": \"e\",\n \"ê\": \"e\",\n \"ë\": \"e\",\n \"ì\": \"i\",\n \"í\": \"i\",\n \"î\": \"i\",\n \"ï\": \"i\",\n \"ñ\": \"n\",\n \"ò\": \"o\",\n \"ó\": \"o\",\n \"ô\": \"o\",\n \"õ\": \"o\",\n \"ö\": \"o\",\n \"ø\": \"o\",\n \"ù\": \"u\",\n \"ú\": \"u\",\n \"û\": \"u\",\n \"ü\": \"u\",\n \"ý\": \"y\",\n \"ÿ\": \"y\",\n \"Ā\": \"A\",\n \"ā\": \"a\",\n \"Ă\": \"A\",\n \"ă\": \"a\",\n \"Ą\": \"A\",\n \"ą\": \"a\",\n \"Ć\": \"C\",\n \"ć\": \"c\",\n \"Ĉ\": \"C\",\n \"ĉ\": \"c\",\n \"Ċ\": \"C\",\n \"ċ\": \"c\",\n \"Č\": \"C\",\n \"č\": \"c\",\n \"Ď\": \"D\",\n \"ď\": \"d\",\n \"Đ\": \"D\",\n \"đ\": \"d\",\n \"Ē\": \"E\",\n \"ē\": \"e\",\n \"Ĕ\": \"E\",\n \"ĕ\": \"e\",\n \"Ė\": \"E\",\n \"ė\": \"e\",\n \"Ę\": \"E\",\n \"ę\": \"e\",\n \"Ě\": \"E\",\n \"ě\": \"e\",\n \"Ĝ\": \"G\",\n \"ĝ\": \"g\",\n \"Ğ\": \"G\",\n \"ğ\": \"g\",\n \"Ġ\": \"G\",\n \"ġ\": \"g\",\n \"Ģ\": \"G\",\n \"ģ\": \"g\",\n \"Ĥ\": \"H\",\n \"ĥ\": \"h\",\n \"Ħ\": \"H\",\n \"ħ\": \"h\",\n \"Ĩ\": \"I\",\n \"ĩ\": \"i\",\n \"Ī\": \"I\",\n \"ī\": \"i\",\n \"Ĭ\": \"I\",\n \"ĭ\": \"i\",\n \"Į\": \"I\",\n \"į\": \"i\",\n \"İ\": \"I\",\n \"ı\": \"i\",\n \"IJ\": \"IJ\",\n \"ij\": \"ij\",\n \"Ĵ\": \"J\",\n \"ĵ\": \"j\",\n \"Ķ\": \"K\",\n \"ķ\": \"k\",\n \"Ĺ\": \"L\",\n \"ĺ\": \"l\",\n \"Ļ\": \"L\",\n \"ļ\": \"l\",\n \"Ľ\": \"L\",\n \"ľ\": \"l\",\n \"Ŀ\": \"L\",\n \"ŀ\": \"l\",\n \"Ł\": \"l\",\n \"ł\": \"l\",\n \"Ń\": \"N\",\n \"ń\": \"n\",\n \"Ņ\": \"N\",\n \"ņ\": \"n\",\n \"Ň\": \"N\",\n \"ň\": \"n\",\n \"ʼn\": \"n\",\n \"Ō\": \"O\",\n \"ō\": \"o\",\n \"Ŏ\": \"O\",\n \"ŏ\": \"o\",\n \"Ő\": \"O\",\n \"ő\": \"o\",\n \"Œ\": \"OE\",\n \"œ\": \"oe\",\n \"Ŕ\": \"R\",\n \"ŕ\": \"r\",\n \"Ŗ\": \"R\",\n \"ŗ\": \"r\",\n \"Ř\": \"R\",\n \"ř\": \"r\",\n \"Ś\": \"S\",\n \"ś\": \"s\",\n \"Ŝ\": \"S\",\n \"ŝ\": \"s\",\n \"Ş\": \"S\",\n \"ş\": \"s\",\n \"Š\": \"S\",\n \"š\": \"s\",\n \"Ţ\": \"T\",\n \"ţ\": \"t\",\n \"Ť\": \"T\",\n \"ť\": \"t\",\n \"Ŧ\": \"T\",\n \"ŧ\": \"t\",\n \"Ũ\": \"U\",\n \"ũ\": \"u\",\n \"Ū\": \"U\",\n \"ū\": \"u\",\n \"Ŭ\": \"U\",\n \"ŭ\": \"u\",\n \"Ů\": \"U\",\n \"ů\": \"u\",\n \"Ű\": \"U\",\n \"ű\": \"u\",\n \"Ų\": \"U\",\n \"ų\": \"u\",\n \"Ŵ\": \"W\",\n \"ŵ\": \"w\",\n \"Ŷ\": \"Y\",\n \"ŷ\": \"y\",\n \"Ÿ\": \"Y\",\n \"Ź\": \"Z\",\n \"ź\": \"z\",\n \"Ż\": \"Z\",\n \"ż\": \"z\",\n \"Ž\": \"Z\",\n \"ž\": \"z\",\n \"ſ\": \"s\",\n \"ƒ\": \"f\",\n \"Ơ\": \"O\",\n \"ơ\": \"o\",\n \"Ư\": \"U\",\n \"ư\": \"u\",\n \"Ǎ\": \"A\",\n \"ǎ\": \"a\",\n \"Ǐ\": \"I\",\n \"ǐ\": \"i\",\n \"Ǒ\": \"O\",\n \"ǒ\": \"o\",\n \"Ǔ\": \"U\",\n \"ǔ\": \"u\",\n \"Ǖ\": \"U\",\n \"ǖ\": \"u\",\n \"Ǘ\": \"U\",\n \"ǘ\": \"u\",\n \"Ǚ\": \"U\",\n \"ǚ\": \"u\",\n \"Ǜ\": \"U\",\n \"ǜ\": \"u\",\n \"Ǻ\": \"A\",\n \"ǻ\": \"a\",\n \"Ǽ\": \"AE\",\n \"ǽ\": \"ae\",\n \"Ǿ\": \"O\",\n \"ǿ\": \"o\"\n },\n nonWord = /\\W/g,\n mapping = function (c) {\n return map[c] || c; \n };\n\n\n return function (str) {\n return str.replace(nonWord, mapping);\n };\n}());\n" }, { "answer_id": 17694737, "author": "Crisalin Petrovschi", "author_id": 1091277, "author_profile": "https://Stackoverflow.com/users/1091277", "pm_score": 4, "selected": false, "text": "function convert_accented_characters(str){\n var conversions = new Object();\n conversions['ae'] = 'ä|æ|ǽ';\n conversions['oe'] = 'ö|œ';\n conversions['ue'] = 'ü';\n conversions['Ae'] = 'Ä';\n conversions['Ue'] = 'Ü';\n conversions['Oe'] = 'Ö';\n conversions['A'] = 'À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ';\n conversions['a'] = 'à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª';\n conversions['C'] = 'Ç|Ć|Ĉ|Ċ|Č';\n conversions['c'] = 'ç|ć|ĉ|ċ|č';\n conversions['D'] = 'Ð|Ď|Đ';\n conversions['d'] = 'ð|ď|đ';\n conversions['E'] = 'È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě';\n conversions['e'] = 'è|é|ê|ë|ē|ĕ|ė|ę|ě';\n conversions['G'] = 'Ĝ|Ğ|Ġ|Ģ';\n conversions['g'] = 'ĝ|ğ|ġ|ģ';\n conversions['H'] = 'Ĥ|Ħ';\n conversions['h'] = 'ĥ|ħ';\n conversions['I'] = 'Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ';\n conversions['i'] = 'ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı';\n conversions['J'] = 'Ĵ';\n conversions['j'] = 'ĵ';\n conversions['K'] = 'Ķ';\n conversions['k'] = 'ķ';\n conversions['L'] = 'Ĺ|Ļ|Ľ|Ŀ|Ł';\n conversions['l'] = 'ĺ|ļ|ľ|ŀ|ł';\n conversions['N'] = 'Ñ|Ń|Ņ|Ň';\n conversions['n'] = 'ñ|ń|ņ|ň|ʼn';\n conversions['O'] = 'Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ';\n conversions['o'] = 'ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º';\n conversions['R'] = 'Ŕ|Ŗ|Ř';\n conversions['r'] = 'ŕ|ŗ|ř';\n conversions['S'] = 'Ś|Ŝ|Ş|Š';\n conversions['s'] = 'ś|ŝ|ş|š|ſ';\n conversions['T'] = 'Ţ|Ť|Ŧ';\n conversions['t'] = 'ţ|ť|ŧ';\n conversions['U'] = 'Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ';\n conversions['u'] = 'ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ';\n conversions['Y'] = 'Ý|Ÿ|Ŷ';\n conversions['y'] = 'ý|ÿ|ŷ';\n conversions['W'] = 'Ŵ';\n conversions['w'] = 'ŵ';\n conversions['Z'] = 'Ź|Ż|Ž';\n conversions['z'] = 'ź|ż|ž';\n conversions['AE'] = 'Æ|Ǽ';\n conversions['ss'] = 'ß';\n conversions['IJ'] = 'IJ';\n conversions['ij'] = 'ij';\n conversions['OE'] = 'Œ';\n conversions['f'] = 'ƒ';\n for(var i in conversions){\n var re = new RegExp(conversions[i],\"g\");\n str = str.replace(re,i);\n }\n return str;\n}\n" }, { "answer_id": 18160397, "author": "Jeroen Ooms", "author_id": 318752, "author_profile": "https://Stackoverflow.com/users/318752", "pm_score": 5, "selected": false, "text": "backbone.paginator function removeDiacritics (str) {\n\n var defaultDiacriticsRemovalMap = [\n {'base':'A', 'letters':/[\\u0041\\u24B6\\uFF21\\u00C0\\u00C1\\u00C2\\u1EA6\\u1EA4\\u1EAA\\u1EA8\\u00C3\\u0100\\u0102\\u1EB0\\u1EAE\\u1EB4\\u1EB2\\u0226\\u01E0\\u00C4\\u01DE\\u1EA2\\u00C5\\u01FA\\u01CD\\u0200\\u0202\\u1EA0\\u1EAC\\u1EB6\\u1E00\\u0104\\u023A\\u2C6F]/g},\n {'base':'AA','letters':/[\\uA732]/g},\n {'base':'AE','letters':/[\\u00C6\\u01FC\\u01E2]/g},\n {'base':'AO','letters':/[\\uA734]/g},\n {'base':'AU','letters':/[\\uA736]/g},\n {'base':'AV','letters':/[\\uA738\\uA73A]/g},\n {'base':'AY','letters':/[\\uA73C]/g},\n {'base':'B', 'letters':/[\\u0042\\u24B7\\uFF22\\u1E02\\u1E04\\u1E06\\u0243\\u0182\\u0181]/g},\n {'base':'C', 'letters':/[\\u0043\\u24B8\\uFF23\\u0106\\u0108\\u010A\\u010C\\u00C7\\u1E08\\u0187\\u023B\\uA73E]/g},\n {'base':'D', 'letters':/[\\u0044\\u24B9\\uFF24\\u1E0A\\u010E\\u1E0C\\u1E10\\u1E12\\u1E0E\\u0110\\u018B\\u018A\\u0189\\uA779]/g},\n {'base':'DZ','letters':/[\\u01F1\\u01C4]/g},\n {'base':'Dz','letters':/[\\u01F2\\u01C5]/g},\n {'base':'E', 'letters':/[\\u0045\\u24BA\\uFF25\\u00C8\\u00C9\\u00CA\\u1EC0\\u1EBE\\u1EC4\\u1EC2\\u1EBC\\u0112\\u1E14\\u1E16\\u0114\\u0116\\u00CB\\u1EBA\\u011A\\u0204\\u0206\\u1EB8\\u1EC6\\u0228\\u1E1C\\u0118\\u1E18\\u1E1A\\u0190\\u018E]/g},\n {'base':'F', 'letters':/[\\u0046\\u24BB\\uFF26\\u1E1E\\u0191\\uA77B]/g},\n {'base':'G', 'letters':/[\\u0047\\u24BC\\uFF27\\u01F4\\u011C\\u1E20\\u011E\\u0120\\u01E6\\u0122\\u01E4\\u0193\\uA7A0\\uA77D\\uA77E]/g},\n {'base':'H', 'letters':/[\\u0048\\u24BD\\uFF28\\u0124\\u1E22\\u1E26\\u021E\\u1E24\\u1E28\\u1E2A\\u0126\\u2C67\\u2C75\\uA78D]/g},\n {'base':'I', 'letters':/[\\u0049\\u24BE\\uFF29\\u00CC\\u00CD\\u00CE\\u0128\\u012A\\u012C\\u0130\\u00CF\\u1E2E\\u1EC8\\u01CF\\u0208\\u020A\\u1ECA\\u012E\\u1E2C\\u0197]/g},\n {'base':'J', 'letters':/[\\u004A\\u24BF\\uFF2A\\u0134\\u0248]/g},\n {'base':'K', 'letters':/[\\u004B\\u24C0\\uFF2B\\u1E30\\u01E8\\u1E32\\u0136\\u1E34\\u0198\\u2C69\\uA740\\uA742\\uA744\\uA7A2]/g},\n {'base':'L', 'letters':/[\\u004C\\u24C1\\uFF2C\\u013F\\u0139\\u013D\\u1E36\\u1E38\\u013B\\u1E3C\\u1E3A\\u0141\\u023D\\u2C62\\u2C60\\uA748\\uA746\\uA780]/g},\n {'base':'LJ','letters':/[\\u01C7]/g},\n {'base':'Lj','letters':/[\\u01C8]/g},\n {'base':'M', 'letters':/[\\u004D\\u24C2\\uFF2D\\u1E3E\\u1E40\\u1E42\\u2C6E\\u019C]/g},\n {'base':'N', 'letters':/[\\u004E\\u24C3\\uFF2E\\u01F8\\u0143\\u00D1\\u1E44\\u0147\\u1E46\\u0145\\u1E4A\\u1E48\\u0220\\u019D\\uA790\\uA7A4]/g},\n {'base':'NJ','letters':/[\\u01CA]/g},\n {'base':'Nj','letters':/[\\u01CB]/g},\n {'base':'O', 'letters':/[\\u004F\\u24C4\\uFF2F\\u00D2\\u00D3\\u00D4\\u1ED2\\u1ED0\\u1ED6\\u1ED4\\u00D5\\u1E4C\\u022C\\u1E4E\\u014C\\u1E50\\u1E52\\u014E\\u022E\\u0230\\u00D6\\u022A\\u1ECE\\u0150\\u01D1\\u020C\\u020E\\u01A0\\u1EDC\\u1EDA\\u1EE0\\u1EDE\\u1EE2\\u1ECC\\u1ED8\\u01EA\\u01EC\\u00D8\\u01FE\\u0186\\u019F\\uA74A\\uA74C]/g},\n {'base':'OI','letters':/[\\u01A2]/g},\n {'base':'OO','letters':/[\\uA74E]/g},\n {'base':'OU','letters':/[\\u0222]/g},\n {'base':'P', 'letters':/[\\u0050\\u24C5\\uFF30\\u1E54\\u1E56\\u01A4\\u2C63\\uA750\\uA752\\uA754]/g},\n {'base':'Q', 'letters':/[\\u0051\\u24C6\\uFF31\\uA756\\uA758\\u024A]/g},\n {'base':'R', 'letters':/[\\u0052\\u24C7\\uFF32\\u0154\\u1E58\\u0158\\u0210\\u0212\\u1E5A\\u1E5C\\u0156\\u1E5E\\u024C\\u2C64\\uA75A\\uA7A6\\uA782]/g},\n {'base':'S', 'letters':/[\\u0053\\u24C8\\uFF33\\u1E9E\\u015A\\u1E64\\u015C\\u1E60\\u0160\\u1E66\\u1E62\\u1E68\\u0218\\u015E\\u2C7E\\uA7A8\\uA784]/g},\n {'base':'T', 'letters':/[\\u0054\\u24C9\\uFF34\\u1E6A\\u0164\\u1E6C\\u021A\\u0162\\u1E70\\u1E6E\\u0166\\u01AC\\u01AE\\u023E\\uA786]/g},\n {'base':'TZ','letters':/[\\uA728]/g},\n {'base':'U', 'letters':/[\\u0055\\u24CA\\uFF35\\u00D9\\u00DA\\u00DB\\u0168\\u1E78\\u016A\\u1E7A\\u016C\\u00DC\\u01DB\\u01D7\\u01D5\\u01D9\\u1EE6\\u016E\\u0170\\u01D3\\u0214\\u0216\\u01AF\\u1EEA\\u1EE8\\u1EEE\\u1EEC\\u1EF0\\u1EE4\\u1E72\\u0172\\u1E76\\u1E74\\u0244]/g},\n {'base':'V', 'letters':/[\\u0056\\u24CB\\uFF36\\u1E7C\\u1E7E\\u01B2\\uA75E\\u0245]/g},\n {'base':'VY','letters':/[\\uA760]/g},\n {'base':'W', 'letters':/[\\u0057\\u24CC\\uFF37\\u1E80\\u1E82\\u0174\\u1E86\\u1E84\\u1E88\\u2C72]/g},\n {'base':'X', 'letters':/[\\u0058\\u24CD\\uFF38\\u1E8A\\u1E8C]/g},\n {'base':'Y', 'letters':/[\\u0059\\u24CE\\uFF39\\u1EF2\\u00DD\\u0176\\u1EF8\\u0232\\u1E8E\\u0178\\u1EF6\\u1EF4\\u01B3\\u024E\\u1EFE]/g},\n {'base':'Z', 'letters':/[\\u005A\\u24CF\\uFF3A\\u0179\\u1E90\\u017B\\u017D\\u1E92\\u1E94\\u01B5\\u0224\\u2C7F\\u2C6B\\uA762]/g},\n {'base':'a', 'letters':/[\\u0061\\u24D0\\uFF41\\u1E9A\\u00E0\\u00E1\\u00E2\\u1EA7\\u1EA5\\u1EAB\\u1EA9\\u00E3\\u0101\\u0103\\u1EB1\\u1EAF\\u1EB5\\u1EB3\\u0227\\u01E1\\u00E4\\u01DF\\u1EA3\\u00E5\\u01FB\\u01CE\\u0201\\u0203\\u1EA1\\u1EAD\\u1EB7\\u1E01\\u0105\\u2C65\\u0250]/g},\n {'base':'aa','letters':/[\\uA733]/g},\n {'base':'ae','letters':/[\\u00E6\\u01FD\\u01E3]/g},\n {'base':'ao','letters':/[\\uA735]/g},\n {'base':'au','letters':/[\\uA737]/g},\n {'base':'av','letters':/[\\uA739\\uA73B]/g},\n {'base':'ay','letters':/[\\uA73D]/g},\n {'base':'b', 'letters':/[\\u0062\\u24D1\\uFF42\\u1E03\\u1E05\\u1E07\\u0180\\u0183\\u0253]/g},\n {'base':'c', 'letters':/[\\u0063\\u24D2\\uFF43\\u0107\\u0109\\u010B\\u010D\\u00E7\\u1E09\\u0188\\u023C\\uA73F\\u2184]/g},\n {'base':'d', 'letters':/[\\u0064\\u24D3\\uFF44\\u1E0B\\u010F\\u1E0D\\u1E11\\u1E13\\u1E0F\\u0111\\u018C\\u0256\\u0257\\uA77A]/g},\n {'base':'dz','letters':/[\\u01F3\\u01C6]/g},\n {'base':'e', 'letters':/[\\u0065\\u24D4\\uFF45\\u00E8\\u00E9\\u00EA\\u1EC1\\u1EBF\\u1EC5\\u1EC3\\u1EBD\\u0113\\u1E15\\u1E17\\u0115\\u0117\\u00EB\\u1EBB\\u011B\\u0205\\u0207\\u1EB9\\u1EC7\\u0229\\u1E1D\\u0119\\u1E19\\u1E1B\\u0247\\u025B\\u01DD]/g},\n {'base':'f', 'letters':/[\\u0066\\u24D5\\uFF46\\u1E1F\\u0192\\uA77C]/g},\n {'base':'g', 'letters':/[\\u0067\\u24D6\\uFF47\\u01F5\\u011D\\u1E21\\u011F\\u0121\\u01E7\\u0123\\u01E5\\u0260\\uA7A1\\u1D79\\uA77F]/g},\n {'base':'h', 'letters':/[\\u0068\\u24D7\\uFF48\\u0125\\u1E23\\u1E27\\u021F\\u1E25\\u1E29\\u1E2B\\u1E96\\u0127\\u2C68\\u2C76\\u0265]/g},\n {'base':'hv','letters':/[\\u0195]/g},\n {'base':'i', 'letters':/[\\u0069\\u24D8\\uFF49\\u00EC\\u00ED\\u00EE\\u0129\\u012B\\u012D\\u00EF\\u1E2F\\u1EC9\\u01D0\\u0209\\u020B\\u1ECB\\u012F\\u1E2D\\u0268\\u0131]/g},\n {'base':'j', 'letters':/[\\u006A\\u24D9\\uFF4A\\u0135\\u01F0\\u0249]/g},\n {'base':'k', 'letters':/[\\u006B\\u24DA\\uFF4B\\u1E31\\u01E9\\u1E33\\u0137\\u1E35\\u0199\\u2C6A\\uA741\\uA743\\uA745\\uA7A3]/g},\n {'base':'l', 'letters':/[\\u006C\\u24DB\\uFF4C\\u0140\\u013A\\u013E\\u1E37\\u1E39\\u013C\\u1E3D\\u1E3B\\u017F\\u0142\\u019A\\u026B\\u2C61\\uA749\\uA781\\uA747]/g},\n {'base':'lj','letters':/[\\u01C9]/g},\n {'base':'m', 'letters':/[\\u006D\\u24DC\\uFF4D\\u1E3F\\u1E41\\u1E43\\u0271\\u026F]/g},\n {'base':'n', 'letters':/[\\u006E\\u24DD\\uFF4E\\u01F9\\u0144\\u00F1\\u1E45\\u0148\\u1E47\\u0146\\u1E4B\\u1E49\\u019E\\u0272\\u0149\\uA791\\uA7A5]/g},\n {'base':'nj','letters':/[\\u01CC]/g},\n {'base':'o', 'letters':/[\\u006F\\u24DE\\uFF4F\\u00F2\\u00F3\\u00F4\\u1ED3\\u1ED1\\u1ED7\\u1ED5\\u00F5\\u1E4D\\u022D\\u1E4F\\u014D\\u1E51\\u1E53\\u014F\\u022F\\u0231\\u00F6\\u022B\\u1ECF\\u0151\\u01D2\\u020D\\u020F\\u01A1\\u1EDD\\u1EDB\\u1EE1\\u1EDF\\u1EE3\\u1ECD\\u1ED9\\u01EB\\u01ED\\u00F8\\u01FF\\u0254\\uA74B\\uA74D\\u0275]/g},\n {'base':'oi','letters':/[\\u01A3]/g},\n {'base':'ou','letters':/[\\u0223]/g},\n {'base':'oo','letters':/[\\uA74F]/g},\n {'base':'p','letters':/[\\u0070\\u24DF\\uFF50\\u1E55\\u1E57\\u01A5\\u1D7D\\uA751\\uA753\\uA755]/g},\n {'base':'q','letters':/[\\u0071\\u24E0\\uFF51\\u024B\\uA757\\uA759]/g},\n {'base':'r','letters':/[\\u0072\\u24E1\\uFF52\\u0155\\u1E59\\u0159\\u0211\\u0213\\u1E5B\\u1E5D\\u0157\\u1E5F\\u024D\\u027D\\uA75B\\uA7A7\\uA783]/g},\n {'base':'s','letters':/[\\u0073\\u24E2\\uFF53\\u00DF\\u015B\\u1E65\\u015D\\u1E61\\u0161\\u1E67\\u1E63\\u1E69\\u0219\\u015F\\u023F\\uA7A9\\uA785\\u1E9B]/g},\n {'base':'t','letters':/[\\u0074\\u24E3\\uFF54\\u1E6B\\u1E97\\u0165\\u1E6D\\u021B\\u0163\\u1E71\\u1E6F\\u0167\\u01AD\\u0288\\u2C66\\uA787]/g},\n {'base':'tz','letters':/[\\uA729]/g},\n {'base':'u','letters':/[\\u0075\\u24E4\\uFF55\\u00F9\\u00FA\\u00FB\\u0169\\u1E79\\u016B\\u1E7B\\u016D\\u00FC\\u01DC\\u01D8\\u01D6\\u01DA\\u1EE7\\u016F\\u0171\\u01D4\\u0215\\u0217\\u01B0\\u1EEB\\u1EE9\\u1EEF\\u1EED\\u1EF1\\u1EE5\\u1E73\\u0173\\u1E77\\u1E75\\u0289]/g},\n {'base':'v','letters':/[\\u0076\\u24E5\\uFF56\\u1E7D\\u1E7F\\u028B\\uA75F\\u028C]/g},\n {'base':'vy','letters':/[\\uA761]/g},\n {'base':'w','letters':/[\\u0077\\u24E6\\uFF57\\u1E81\\u1E83\\u0175\\u1E87\\u1E85\\u1E98\\u1E89\\u2C73]/g},\n {'base':'x','letters':/[\\u0078\\u24E7\\uFF58\\u1E8B\\u1E8D]/g},\n {'base':'y','letters':/[\\u0079\\u24E8\\uFF59\\u1EF3\\u00FD\\u0177\\u1EF9\\u0233\\u1E8F\\u00FF\\u1EF7\\u1E99\\u1EF5\\u01B4\\u024F\\u1EFF]/g},\n {'base':'z','letters':/[\\u007A\\u24E9\\uFF5A\\u017A\\u1E91\\u017C\\u017E\\u1E93\\u1E95\\u01B6\\u0225\\u0240\\u2C6C\\uA763]/g}\n ];\n\n for(var i=0; i<defaultDiacriticsRemovalMap.length; i++) {\n str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base);\n }\n\n return str;\n\n}\n" }, { "answer_id": 23767389, "author": "atiruz", "author_id": 1491512, "author_profile": "https://Stackoverflow.com/users/1491512", "pm_score": 5, "selected": false, "text": "var str = \"Letras Á É Í Ó Ú Ñ - á é í ó ú ñ...\";\nconsole.log (str.normalize (\"NFKD\").replace (/[\\u0300-\\u036F]/g, \"\"));\n// Letras A E I O U N - a e i o u n...\n function noTilde (s) {\n if (s.normalize != undefined) {\n s = s.normalize (\"NFKD\");\n }\n return s.replace (/[\\u0300-\\u036F]/g, \"\");\n}\n" }, { "answer_id": 32050485, "author": "virgo47", "author_id": 658826, "author_profile": "https://Stackoverflow.com/users/658826", "pm_score": 2, "selected": false, "text": "TAB_00C0 = \"AAAAAAACEEEEIIII\" +\n \"DNOOOOO*OUUUUYIs\" +\n \"aaaaaaaceeeeiiii\" +\n \"?nooooo/ouuuuy?y\" +\n \"AaAaAaCcCcCcCcDd\" +\n \"DdEeEeEeEeEeGgGg\" +\n \"GgGgHhHhIiIiIiIi\" +\n \"IiJjJjKkkLlLlLlL\" +\n \"lLlNnNnNnnNnOoOo\" +\n \"OoOoRrRrRrSsSsSs\" +\n \"SsTtTtTtUuUuUuUu\" +\n \"UuUuWwYyYZzZzZzF\";\n\nfunction stripDiacritics(source) {\n var result = source.split('');\n for (var i = 0; i < result.length; i++) {\n var c = source.charCodeAt(i);\n if (c >= 0x00c0 && c <= 0x017f) {\n result[i] = String.fromCharCode(TAB_00C0.charCodeAt(c - 0x00c0));\n } else if (c > 127) {\n result[i] = '?';\n }\n }\n return result.join('');\n}\n\nstripDiacritics(\"Šupa, čo? ľšťčžýæøåℌð\")\n Supa, co? lstczyaoa??" }, { "answer_id": 36536366, "author": "Adam Pietrasiak", "author_id": 2446799, "author_profile": "https://Stackoverflow.com/users/2446799", "pm_score": 3, "selected": false, "text": "String.prototype.removeAccents = function() {\n\n var removalMap = {\n 'A' : /[AⒶAÀÁÂẦẤẪẨÃĀĂẰẮẴẲȦǠÄǞẢÅǺǍȀȂẠẬẶḀĄ]/g,\n 'AA' : /[Ꜳ]/g,\n 'AE' : /[ÆǼǢ]/g,\n 'AO' : /[Ꜵ]/g,\n 'AU' : /[Ꜷ]/g,\n 'AV' : /[ꜸꜺ]/g,\n 'AY' : /[Ꜽ]/g,\n 'B' : /[BⒷBḂḄḆɃƂƁ]/g,\n 'C' : /[CⒸCĆĈĊČÇḈƇȻꜾ]/g,\n 'D' : /[DⒹDḊĎḌḐḒḎĐƋƊƉꝹ]/g,\n 'DZ' : /[DZDŽ]/g,\n 'Dz' : /[DzDž]/g,\n 'E' : /[EⒺEÈÉÊỀẾỄỂẼĒḔḖĔĖËẺĚȄȆẸỆȨḜĘḘḚƐƎ]/g,\n 'F' : /[FⒻFḞƑꝻ]/g,\n 'G' : /[GⒼGǴĜḠĞĠǦĢǤƓꞠꝽꝾ]/g,\n 'H' : /[HⒽHĤḢḦȞḤḨḪĦⱧⱵꞍ]/g,\n 'I' : /[IⒾIÌÍÎĨĪĬİÏḮỈǏȈȊỊĮḬƗ]/g,\n 'J' : /[JⒿJĴɈ]/g,\n 'K' : /[KⓀKḰǨḲĶḴƘⱩꝀꝂꝄꞢ]/g,\n 'L' : /[LⓁLĿĹĽḶḸĻḼḺŁȽⱢⱠꝈꝆꞀ]/g,\n 'LJ' : /[LJ]/g,\n 'Lj' : /[Lj]/g,\n 'M' : /[MⓂMḾṀṂⱮƜ]/g,\n 'N' : /[NⓃNǸŃÑṄŇṆŅṊṈȠƝꞐꞤ]/g,\n 'NJ' : /[NJ]/g,\n 'Nj' : /[Nj]/g,\n 'O' : /[OⓄOÒÓÔỒỐỖỔÕṌȬṎŌṐṒŎȮȰÖȪỎŐǑȌȎƠỜỚỠỞỢỌỘǪǬØǾƆƟꝊꝌ]/g,\n 'OI' : /[Ƣ]/g,\n 'OO' : /[Ꝏ]/g,\n 'OU' : /[Ȣ]/g,\n 'P' : /[PⓅPṔṖƤⱣꝐꝒꝔ]/g,\n 'Q' : /[QⓆQꝖꝘɊ]/g,\n 'R' : /[RⓇRŔṘŘȐȒṚṜŖṞɌⱤꝚꞦꞂ]/g,\n 'S' : /[SⓈSẞŚṤŜṠŠṦṢṨȘŞⱾꞨꞄ]/g,\n 'T' : /[TⓉTṪŤṬȚŢṰṮŦƬƮȾꞆ]/g,\n 'TZ' : /[Ꜩ]/g,\n 'U' : /[UⓊUÙÚÛŨṸŪṺŬÜǛǗǕǙỦŮŰǓȔȖƯỪỨỮỬỰỤṲŲṶṴɄ]/g,\n 'V' : /[VⓋVṼṾƲꝞɅ]/g,\n 'VY' : /[Ꝡ]/g,\n 'W' : /[WⓌWẀẂŴẆẄẈⱲ]/g,\n 'X' : /[XⓍXẊẌ]/g,\n 'Y' : /[YⓎYỲÝŶỸȲẎŸỶỴƳɎỾ]/g,\n 'Z' : /[ZⓏZŹẐŻŽẒẔƵȤⱿⱫꝢ]/g,\n 'a' : /[aⓐaẚàáâầấẫẩãāăằắẵẳȧǡäǟảåǻǎȁȃạậặḁąⱥɐ]/g,\n 'aa' : /[ꜳ]/g,\n 'ae' : /[æǽǣ]/g,\n 'ao' : /[ꜵ]/g,\n 'au' : /[ꜷ]/g,\n 'av' : /[ꜹꜻ]/g,\n 'ay' : /[ꜽ]/g,\n 'b' : /[bⓑbḃḅḇƀƃɓ]/g,\n 'c' : /[cⓒcćĉċčçḉƈȼꜿↄ]/g,\n 'd' : /[dⓓdḋďḍḑḓḏđƌɖɗꝺ]/g,\n 'dz' : /[dzdž]/g,\n 'e' : /[eⓔeèéêềếễểẽēḕḗĕėëẻěȅȇẹệȩḝęḙḛɇɛǝ]/g,\n 'f' : /[fⓕfḟƒꝼ]/g,\n 'g' : /[gⓖgǵĝḡğġǧģǥɠꞡᵹꝿ]/g,\n 'h' : /[hⓗhĥḣḧȟḥḩḫẖħⱨⱶɥ]/g,\n 'hv' : /[ƕ]/g,\n 'i' : /[iⓘiìíîĩīĭïḯỉǐȉȋịįḭɨı]/g,\n 'j' : /[jⓙjĵǰɉ]/g,\n 'k' : /[kⓚkḱǩḳķḵƙⱪꝁꝃꝅꞣ]/g,\n 'l' : /[lⓛlŀĺľḷḹļḽḻſłƚɫⱡꝉꞁꝇ]/g,\n 'lj' : /[lj]/g,\n 'm' : /[mⓜmḿṁṃɱɯ]/g,\n 'n' : /[nⓝnǹńñṅňṇņṋṉƞɲʼnꞑꞥ]/g,\n 'nj' : /[nj]/g,\n 'o' : /[oⓞoòóôồốỗổõṍȭṏōṑṓŏȯȱöȫỏőǒȍȏơờớỡởợọộǫǭøǿɔꝋꝍɵ]/g,\n 'oi' : /[ƣ]/g,\n 'ou' : /[ȣ]/g,\n 'oo' : /[ꝏ]/g,\n 'p' : /[pⓟpṕṗƥᵽꝑꝓꝕ]/g,\n 'q' : /[qⓠqɋꝗꝙ]/g,\n 'r' : /[rⓡrŕṙřȑȓṛṝŗṟɍɽꝛꞧꞃ]/g,\n 's' : /[sⓢsßśṥŝṡšṧṣṩșşȿꞩꞅẛ]/g,\n 't' : /[tⓣtṫẗťṭțţṱṯŧƭʈⱦꞇ]/g,\n 'tz' : /[ꜩ]/g,\n 'u' : /[uⓤuùúûũṹūṻŭüǜǘǖǚủůűǔȕȗưừứữửựụṳųṷṵʉ]/g,\n 'v' : /[vⓥvṽṿʋꝟʌ]/g,\n 'vy' : /[ꝡ]/g,\n 'w' : /[wⓦwẁẃŵẇẅẘẉⱳ]/g,\n 'x' : /[xⓧxẋẍ]/g,\n 'y' : /[yⓨyỳýŷỹȳẏÿỷẙỵƴɏỿ]/g,\n 'z' : /[zⓩzźẑżžẓẕƶȥɀⱬꝣ]/g,\n };\n\n var str = this;\n\n for(var latin in removalMap) {\n var nonLatin = removalMap[latin];\n str = str.replace(nonLatin , latin);\n }\n\n return str;\n}\n \"ąąą\".removeAccents(); // returns \"aaa\"\n" }, { "answer_id": 41401106, "author": "Samiul", "author_id": 4537997, "author_profile": "https://Stackoverflow.com/users/4537997", "pm_score": 0, "selected": false, "text": "var text = \"your input string\";\nvar searchChars = ['Å','Ä','å','Ö','ö']; // add more charecter.\nvar replaceChars = ['A','A','a','O','o']; // exact same index to searchChars.\nvar index;\nfor (var i = 0; i < text.length; i++) {\n if( $.inArray(text[i], searchChars) >-1 ){ // $.inArray() is from jquery.\n index = searchChars.indexOf(text[i]);\n text = text.slice(0, i) + replaceChars[index] + text.slice(i+1,text.length);\n }\n}" }, { "answer_id": 42095260, "author": "Kelvin Marques", "author_id": 7529944, "author_profile": "https://Stackoverflow.com/users/7529944", "pm_score": 1, "selected": false, "text": "function remove-accents(p){\nc='áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';s='aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';n='';for(i=0;i<p.length;i++){if(c.search(p.substr(i,1))>=0){n+=s.substr(c.search(p.substr(i,1)),1);} else{n+=p.substr(i,1);}} return n;\n}\n remove-accents(\"Thís ís ân accêntéd phráse\");\n \"This is an accented phrase\"\n" }, { "answer_id": 42163018, "author": "Prinzhorn", "author_id": 1422124, "author_profile": "https://Stackoverflow.com/users/1422124", "pm_score": 2, "selected": false, "text": "String.localeCompare var list = ['a', 'b', 'c', 'o', 'u', 'z', 'ä', 'ö', 'ü'];\n\nlist.sort((a, b) => a.localeCompare(b));\n\nconsole.log(list);\n\n//Outputs ['a', 'ä', 'b', 'c', 'o', 'ö', 'u', 'ü', 'z']\n" }, { "answer_id": 42405872, "author": "undefined", "author_id": 610585, "author_profile": "https://Stackoverflow.com/users/610585", "pm_score": 4, "selected": false, "text": "var baseChars = [];\nfor (var i = 97; i < 97 + 26; i++) {\n baseChars.push(String.fromCharCode(i));\n}\n\n//if needed, handle fancy compound characters\nbaseChars = baseChars.concat('ss,aa,ae,ao,au,av,ay,dz,hv,lj,nj,oi,ou,oo,tz,vy'.split(','));\n\nfunction isUpperCase(c) { return c !== c.toLocaleLowerCase() }\n\nfunction toBaseChar(c, opts) {\n opts = opts || {};\n //if (!('nonAlphaChar' in opts)) opts.nonAlphaChar = '';\n //if (!('noMatchChar' in opts)) opts.noMatchChar = '';\n if (!('locale' in opts)) opts.locale = 'en';\n\n var cOpts = {sensitivity: 'base'};\n\n //exit early for any non-alphabetical character\n if (c.localeCompare('9', opts.locale, cOpts) <= 0) return opts.nonAlphaChar === undefined ? c : opts.nonAlphaChar;\n\n for (var i = 0; i < baseChars.length; i++) {\n var baseChar = baseChars[i];\n\n var comp = c.localeCompare(baseChar, opts.locale, cOpts);\n if (comp == 0) return (isUpperCase(c)) ? baseChar.toUpperCase() : baseChar;\n }\n\n return opts.noMatchChar === undefined ? c : opts.noMatchChar;\n}\n\nfunction latinify(str, opts) {\n return str.replace(/[^\\w\\s\\d]/g, function(c) {\n return toBaseChar(c, opts);\n })\n}\n\n// Example:\nconsole.log(latinify('Čeština Tsėhesenėstsestotse Tshivenḓa Emigliàn–Rumagnòl Slovenščina Português Tiếng Việt Straße'))\n\n// \"Cestina Tsehesenestsestotse Tshivenda Emiglian–Rumagnol Slovenscina Portugues Tieng Viet Strasse\" localeCompare" }, { "answer_id": 44162094, "author": "dinigo", "author_id": 621058, "author_profile": "https://Stackoverflow.com/users/621058", "pm_score": 2, "selected": false, "text": "const base_chars = [\n '1', '2', '3', '4', '5', '6', '7', '8', '9',\n '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',\n 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',\n 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n '-', '_', ' '\n];\nconst fix = str => str.normalize('NFKD').split('')\n .map(c => base_chars.find(bc => bc.localeCompare(c, 'en', { sensitivity: 'base' })==0))\n .join('');\n\nconst str = 'OÒ óëå-123';\nconsole.log(`fix(${str}) = ${fix(str)}`);" }, { "answer_id": 49901740, "author": "Revadike", "author_id": 4356020, "author_profile": "https://Stackoverflow.com/users/4356020", "pm_score": 5, "selected": false, "text": "const str = \"Crème Brulée\"\nstr.normalize('NFD').replace(/[\\u0300-\\u036f]/g, \"\")\n> 'Creme Brulee'\n normalize() NFD è Crème e ̀ g const c = new Intl.Collator();\n['creme brulee', 'crème brulée', 'crame brulai', 'crome brouillé',\n'creme brulay', 'creme brulfé', 'creme bruléa'].sort(c.compare)\n[ 'crame brulai','creme brulay','creme bruléa','creme brulee',\n'crème brulée','creme brulfé','crome brouillé' ]\n\n\n['creme brulee', 'crème brulée', 'crame brulai', 'crome brouillé'].sort((a,b) => a>b)\n[\"crame brulai\", \"creme brulee\", \"crome brouillé\", \"crème brulée\"]\n" }, { "answer_id": 50839049, "author": "rmpt", "author_id": 3763828, "author_profile": "https://Stackoverflow.com/users/3763828", "pm_score": 1, "selected": false, "text": "var normalizeConversions = [\n { regex: new RegExp('ä|æ|ǽ', 'g'), clean: 'ae' },\n { regex: new RegExp('ö|œ', 'g'), clean: 'oe' },\n { regex: new RegExp('ü', 'g'), clean: 'ue' },\n { regex: new RegExp('Ä', 'g'), clean: 'Ae' },\n { regex: new RegExp('Ü', 'g'), clean: 'Ue' },\n { regex: new RegExp('Ö', 'g'), clean: 'Oe' },\n { regex: new RegExp('À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ', 'g'), clean: 'A' },\n { regex: new RegExp('à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª', 'g'), clean: 'a' },\n { regex: new RegExp('Ç|Ć|Ĉ|Ċ|Č', 'g'), clean: 'C' },\n { regex: new RegExp('ç|ć|ĉ|ċ|č', 'g'), clean: 'c' },\n { regex: new RegExp('Ð|Ď|Đ', 'g'), clean: 'D' },\n { regex: new RegExp('ð|ď|đ', 'g'), clean: 'd' },\n { regex: new RegExp('È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě', 'g'), clean: 'E' },\n { regex: new RegExp('è|é|ê|ë|ē|ĕ|ė|ę|ě', 'g'), clean: 'e' },\n { regex: new RegExp('Ĝ|Ğ|Ġ|Ģ', 'g'), clean: 'G' },\n { regex: new RegExp('ĝ|ğ|ġ|ģ', 'g'), clean: 'g' },\n { regex: new RegExp('Ĥ|Ħ', 'g'), clean: 'H' },\n { regex: new RegExp('ĥ|ħ', 'g'), clean: 'h' },\n { regex: new RegExp('Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ', 'g'), clean: 'I' },\n { regex: new RegExp('ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı', 'g'), clean: 'i' },\n { regex: new RegExp('Ĵ', 'g'), clean: 'J' },\n { regex: new RegExp('ĵ', 'g'), clean: 'j' },\n { regex: new RegExp('Ķ', 'g'), clean: 'K' },\n { regex: new RegExp('ķ', 'g'), clean: 'k' },\n { regex: new RegExp('Ĺ|Ļ|Ľ|Ŀ|Ł', 'g'), clean: 'L' },\n { regex: new RegExp('ĺ|ļ|ľ|ŀ|ł', 'g'), clean: 'l' },\n { regex: new RegExp('Ñ|Ń|Ņ|Ň', 'g'), clean: 'N' },\n { regex: new RegExp('ñ|ń|ņ|ň|ʼn', 'g'), clean: 'n' },\n { regex: new RegExp('Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ', 'g'), clean: 'O' },\n { regex: new RegExp('ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º', 'g'), clean: 'o' },\n { regex: new RegExp('Ŕ|Ŗ|Ř', 'g'), clean: 'R' },\n { regex: new RegExp('ŕ|ŗ|ř', 'g'), clean: 'r' },\n { regex: new RegExp('Ś|Ŝ|Ş|Š', 'g'), clean: 'S' },\n { regex: new RegExp('ś|ŝ|ş|š|ſ', 'g'), clean: 's' },\n { regex: new RegExp('Ţ|Ť|Ŧ', 'g'), clean: 'T' },\n { regex: new RegExp('ţ|ť|ŧ', 'g'), clean: 't' },\n { regex: new RegExp('Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ', 'g'), clean: 'U' },\n { regex: new RegExp('ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ', 'g'), clean: 'u' },\n { regex: new RegExp('Ý|Ÿ|Ŷ', 'g'), clean: 'Y' },\n { regex: new RegExp('ý|ÿ|ŷ', 'g'), clean: 'y' },\n { regex: new RegExp('Ŵ', 'g'), clean: 'W' },\n { regex: new RegExp('ŵ', 'g'), clean: 'w' },\n { regex: new RegExp('Ź|Ż|Ž', 'g'), clean: 'Z' },\n { regex: new RegExp('ź|ż|ž', 'g'), clean: 'z' },\n { regex: new RegExp('Æ|Ǽ', 'g'), clean: 'AE' },\n { regex: new RegExp('ß', 'g'), clean: 'ss' },\n { regex: new RegExp('IJ', 'g'), clean: 'IJ' },\n { regex: new RegExp('ij', 'g'), clean: 'ij' },\n { regex: new RegExp('Œ', 'g'), clean: 'OE' },\n { regex: new RegExp('ƒ', 'g'), clean: 'f' }\n];\n function(str){\n normalizeConversions.forEach(function(normalizeEntry){\n str = str.replace(normalizeEntry.regex, normalizeEntry.clean);\n });\n return str;\n};\n" }, { "answer_id": 51874461, "author": "Takit Isy", "author_id": 5061000, "author_profile": "https://Stackoverflow.com/users/5061000", "pm_score": 4, "selected": false, "text": "var string = \"öäüÖÄÜ\";\nconsole.log(string);\n\nvar string_norm = string.normalize('NFD').replace(/\\p{Diacritic}/gu, \"\"); // Old method: .replace(/[\\u0300-\\u036f]/g, \"\");\nconsole.log(string_norm);" }, { "answer_id": 54075658, "author": "eddyP23", "author_id": 5018962, "author_profile": "https://Stackoverflow.com/users/5018962", "pm_score": 0, "selected": false, "text": " // Usage example:\n \"Some string\".replace(/[^a-zA-Z0-9-_]/g, char => ToLatinMap.get(char) || '')\n\n // Map:\n export let ToLatinMap: Map<string, string> = new Map<string, string>([\n [\"Á\", \"A\"],\n [\"Ă\", \"A\"],\n [\"Ắ\", \"A\"],\n [\"Ặ\", \"A\"],\n [\"Ằ\", \"A\"],\n [\"Ẳ\", \"A\"],\n [\"Ẵ\", \"A\"],\n [\"Ǎ\", \"A\"],\n [\"Â\", \"A\"],\n [\"Ấ\", \"A\"],\n [\"Ậ\", \"A\"],\n [\"Ầ\", \"A\"],\n [\"Ẩ\", \"A\"],\n [\"Ẫ\", \"A\"],\n [\"Ä\", \"A\"],\n [\"Ǟ\", \"A\"],\n [\"Ȧ\", \"A\"],\n [\"Ǡ\", \"A\"],\n [\"Ạ\", \"A\"],\n [\"Ȁ\", \"A\"],\n [\"À\", \"A\"],\n [\"Ả\", \"A\"],\n [\"Ȃ\", \"A\"],\n [\"Ā\", \"A\"],\n [\"Ą\", \"A\"],\n [\"Å\", \"A\"],\n [\"Ǻ\", \"A\"],\n [\"Ḁ\", \"A\"],\n [\"Ⱥ\", \"A\"],\n [\"Ã\", \"A\"],\n [\"Ꜳ\", \"AA\"],\n [\"Æ\", \"AE\"],\n [\"Ǽ\", \"AE\"],\n [\"Ǣ\", \"AE\"],\n [\"Ꜵ\", \"AO\"],\n [\"Ꜷ\", \"AU\"],\n [\"Ꜹ\", \"AV\"],\n [\"Ꜻ\", \"AV\"],\n [\"Ꜽ\", \"AY\"],\n [\"Ḃ\", \"B\"],\n [\"Ḅ\", \"B\"],\n [\"Ɓ\", \"B\"],\n [\"Ḇ\", \"B\"],\n [\"Ƀ\", \"B\"],\n [\"Ƃ\", \"B\"],\n [\"Ć\", \"C\"],\n [\"Č\", \"C\"],\n [\"Ç\", \"C\"],\n [\"Ḉ\", \"C\"],\n [\"Ĉ\", \"C\"],\n [\"Ċ\", \"C\"],\n [\"Ƈ\", \"C\"],\n [\"Ȼ\", \"C\"],\n [\"Ď\", \"D\"],\n [\"Ḑ\", \"D\"],\n [\"Ḓ\", \"D\"],\n [\"Ḋ\", \"D\"],\n [\"Ḍ\", \"D\"],\n [\"Ɗ\", \"D\"],\n [\"Ḏ\", \"D\"],\n [\"Dz\", \"D\"],\n [\"Dž\", \"D\"],\n [\"Đ\", \"D\"],\n [\"Ƌ\", \"D\"],\n [\"DZ\", \"DZ\"],\n [\"DŽ\", \"DZ\"],\n [\"É\", \"E\"],\n [\"Ĕ\", \"E\"],\n [\"Ě\", \"E\"],\n [\"Ȩ\", \"E\"],\n [\"Ḝ\", \"E\"],\n [\"Ê\", \"E\"],\n [\"Ế\", \"E\"],\n [\"Ệ\", \"E\"],\n [\"Ề\", \"E\"],\n [\"Ể\", \"E\"],\n [\"Ễ\", \"E\"],\n [\"Ḙ\", \"E\"],\n [\"Ë\", \"E\"],\n [\"Ė\", \"E\"],\n [\"Ẹ\", \"E\"],\n [\"Ȅ\", \"E\"],\n [\"È\", \"E\"],\n [\"Ẻ\", \"E\"],\n [\"Ȇ\", \"E\"],\n [\"Ē\", \"E\"],\n [\"Ḗ\", \"E\"],\n [\"Ḕ\", \"E\"],\n [\"Ę\", \"E\"],\n [\"Ɇ\", \"E\"],\n [\"Ẽ\", \"E\"],\n [\"Ḛ\", \"E\"],\n [\"Ꝫ\", \"ET\"],\n [\"Ḟ\", \"F\"],\n [\"Ƒ\", \"F\"],\n [\"Ǵ\", \"G\"],\n [\"Ğ\", \"G\"],\n [\"Ǧ\", \"G\"],\n [\"Ģ\", \"G\"],\n [\"Ĝ\", \"G\"],\n [\"Ġ\", \"G\"],\n [\"Ɠ\", \"G\"],\n [\"Ḡ\", \"G\"],\n [\"Ǥ\", \"G\"],\n [\"Ḫ\", \"H\"],\n [\"Ȟ\", \"H\"],\n [\"Ḩ\", \"H\"],\n [\"Ĥ\", \"H\"],\n [\"Ⱨ\", \"H\"],\n [\"Ḧ\", \"H\"],\n [\"Ḣ\", \"H\"],\n [\"Ḥ\", \"H\"],\n [\"Ħ\", \"H\"],\n [\"Í\", \"I\"],\n [\"Ĭ\", \"I\"],\n [\"Ǐ\", \"I\"],\n [\"Î\", \"I\"],\n [\"Ï\", \"I\"],\n [\"Ḯ\", \"I\"],\n [\"İ\", \"I\"],\n [\"Ị\", \"I\"],\n [\"Ȉ\", \"I\"],\n [\"Ì\", \"I\"],\n [\"Ỉ\", \"I\"],\n [\"Ȋ\", \"I\"],\n [\"Ī\", \"I\"],\n [\"Į\", \"I\"],\n [\"Ɨ\", \"I\"],\n [\"Ĩ\", \"I\"],\n [\"Ḭ\", \"I\"],\n [\"Ꝺ\", \"D\"],\n [\"Ꝼ\", \"F\"],\n [\"Ᵹ\", \"G\"],\n [\"Ꞃ\", \"R\"],\n [\"Ꞅ\", \"S\"],\n [\"Ꞇ\", \"T\"],\n [\"Ꝭ\", \"IS\"],\n [\"Ĵ\", \"J\"],\n [\"Ɉ\", \"J\"],\n [\"Ḱ\", \"K\"],\n [\"Ǩ\", \"K\"],\n [\"Ķ\", \"K\"],\n [\"Ⱪ\", \"K\"],\n [\"Ꝃ\", \"K\"],\n [\"Ḳ\", \"K\"],\n [\"Ƙ\", \"K\"],\n [\"Ḵ\", \"K\"],\n [\"Ꝁ\", \"K\"],\n [\"Ꝅ\", \"K\"],\n [\"Ĺ\", \"L\"],\n [\"Ƚ\", \"L\"],\n [\"Ľ\", \"L\"],\n [\"Ļ\", \"L\"],\n [\"Ḽ\", \"L\"],\n [\"Ḷ\", \"L\"],\n [\"Ḹ\", \"L\"],\n [\"Ⱡ\", \"L\"],\n [\"Ꝉ\", \"L\"],\n [\"Ḻ\", \"L\"],\n [\"Ŀ\", \"L\"],\n [\"Ɫ\", \"L\"],\n [\"Lj\", \"L\"],\n [\"Ł\", \"L\"],\n [\"LJ\", \"LJ\"],\n [\"Ḿ\", \"M\"],\n [\"Ṁ\", \"M\"],\n [\"Ṃ\", \"M\"],\n [\"Ɱ\", \"M\"],\n [\"Ń\", \"N\"],\n [\"Ň\", \"N\"],\n [\"Ņ\", \"N\"],\n [\"Ṋ\", \"N\"],\n [\"Ṅ\", \"N\"],\n [\"Ṇ\", \"N\"],\n [\"Ǹ\", \"N\"],\n [\"Ɲ\", \"N\"],\n [\"Ṉ\", \"N\"],\n [\"Ƞ\", \"N\"],\n [\"Nj\", \"N\"],\n [\"Ñ\", \"N\"],\n [\"NJ\", \"NJ\"],\n [\"Ó\", \"O\"],\n [\"Ŏ\", \"O\"],\n [\"Ǒ\", \"O\"],\n [\"Ô\", \"O\"],\n [\"Ố\", \"O\"],\n [\"Ộ\", \"O\"],\n [\"Ồ\", \"O\"],\n [\"Ổ\", \"O\"],\n [\"Ỗ\", \"O\"],\n [\"Ö\", \"O\"],\n [\"Ȫ\", \"O\"],\n [\"Ȯ\", \"O\"],\n [\"Ȱ\", \"O\"],\n [\"Ọ\", \"O\"],\n [\"Ő\", \"O\"],\n [\"Ȍ\", \"O\"],\n [\"Ò\", \"O\"],\n [\"Ỏ\", \"O\"],\n [\"Ơ\", \"O\"],\n [\"Ớ\", \"O\"],\n [\"Ợ\", \"O\"],\n [\"Ờ\", \"O\"],\n [\"Ở\", \"O\"],\n [\"Ỡ\", \"O\"],\n [\"Ȏ\", \"O\"],\n [\"Ꝋ\", \"O\"],\n [\"Ꝍ\", \"O\"],\n [\"Ō\", \"O\"],\n [\"Ṓ\", \"O\"],\n [\"Ṑ\", \"O\"],\n [\"Ɵ\", \"O\"],\n [\"Ǫ\", \"O\"],\n [\"Ǭ\", \"O\"],\n [\"Ø\", \"O\"],\n [\"Ǿ\", \"O\"],\n [\"Õ\", \"O\"],\n [\"Ṍ\", \"O\"],\n [\"Ṏ\", \"O\"],\n [\"Ȭ\", \"O\"],\n [\"Ƣ\", \"OI\"],\n [\"Ꝏ\", \"OO\"],\n [\"Ɛ\", \"E\"],\n [\"Ɔ\", \"O\"],\n [\"Ȣ\", \"OU\"],\n [\"Ṕ\", \"P\"],\n [\"Ṗ\", \"P\"],\n [\"Ꝓ\", \"P\"],\n [\"Ƥ\", \"P\"],\n [\"Ꝕ\", \"P\"],\n [\"Ᵽ\", \"P\"],\n [\"Ꝑ\", \"P\"],\n [\"Ꝙ\", \"Q\"],\n [\"Ꝗ\", \"Q\"],\n [\"Ŕ\", \"R\"],\n [\"Ř\", \"R\"],\n [\"Ŗ\", \"R\"],\n [\"Ṙ\", \"R\"],\n [\"Ṛ\", \"R\"],\n [\"Ṝ\", \"R\"],\n [\"Ȑ\", \"R\"],\n [\"Ȓ\", \"R\"],\n [\"Ṟ\", \"R\"],\n [\"Ɍ\", \"R\"],\n [\"Ɽ\", \"R\"],\n [\"Ꜿ\", \"C\"],\n [\"Ǝ\", \"E\"],\n [\"Ś\", \"S\"],\n [\"Ṥ\", \"S\"],\n [\"Š\", \"S\"],\n [\"Ṧ\", \"S\"],\n [\"Ş\", \"S\"],\n [\"Ŝ\", \"S\"],\n [\"Ș\", \"S\"],\n [\"Ṡ\", \"S\"],\n [\"Ṣ\", \"S\"],\n [\"Ṩ\", \"S\"],\n [\"Ť\", \"T\"],\n [\"Ţ\", \"T\"],\n [\"Ṱ\", \"T\"],\n [\"Ț\", \"T\"],\n [\"Ⱦ\", \"T\"],\n [\"Ṫ\", \"T\"],\n [\"Ṭ\", \"T\"],\n [\"Ƭ\", \"T\"],\n [\"Ṯ\", \"T\"],\n [\"Ʈ\", \"T\"],\n [\"Ŧ\", \"T\"],\n [\"Ɐ\", \"A\"],\n [\"Ꞁ\", \"L\"],\n [\"Ɯ\", \"M\"],\n [\"Ʌ\", \"V\"],\n [\"Ꜩ\", \"TZ\"],\n [\"Ú\", \"U\"],\n [\"Ŭ\", \"U\"],\n [\"Ǔ\", \"U\"],\n [\"Û\", \"U\"],\n [\"Ṷ\", \"U\"],\n [\"Ü\", \"U\"],\n [\"Ǘ\", \"U\"],\n [\"Ǚ\", \"U\"],\n [\"Ǜ\", \"U\"],\n [\"Ǖ\", \"U\"],\n [\"Ṳ\", \"U\"],\n [\"Ụ\", \"U\"],\n [\"Ű\", \"U\"],\n [\"Ȕ\", \"U\"],\n [\"Ù\", \"U\"],\n [\"Ủ\", \"U\"],\n [\"Ư\", \"U\"],\n [\"Ứ\", \"U\"],\n [\"Ự\", \"U\"],\n [\"Ừ\", \"U\"],\n [\"Ử\", \"U\"],\n [\"Ữ\", \"U\"],\n [\"Ȗ\", \"U\"],\n [\"Ū\", \"U\"],\n [\"Ṻ\", \"U\"],\n [\"Ų\", \"U\"],\n [\"Ů\", \"U\"],\n [\"Ũ\", \"U\"],\n [\"Ṹ\", \"U\"],\n [\"Ṵ\", \"U\"],\n [\"Ꝟ\", \"V\"],\n [\"Ṿ\", \"V\"],\n [\"Ʋ\", \"V\"],\n [\"Ṽ\", \"V\"],\n [\"Ꝡ\", \"VY\"],\n [\"Ẃ\", \"W\"],\n [\"Ŵ\", \"W\"],\n [\"Ẅ\", \"W\"],\n [\"Ẇ\", \"W\"],\n [\"Ẉ\", \"W\"],\n [\"Ẁ\", \"W\"],\n [\"Ⱳ\", \"W\"],\n [\"Ẍ\", \"X\"],\n [\"Ẋ\", \"X\"],\n [\"Ý\", \"Y\"],\n [\"Ŷ\", \"Y\"],\n [\"Ÿ\", \"Y\"],\n [\"Ẏ\", \"Y\"],\n [\"Ỵ\", \"Y\"],\n [\"Ỳ\", \"Y\"],\n [\"Ƴ\", \"Y\"],\n [\"Ỷ\", \"Y\"],\n [\"Ỿ\", \"Y\"],\n [\"Ȳ\", \"Y\"],\n [\"Ɏ\", \"Y\"],\n [\"Ỹ\", \"Y\"],\n [\"Ź\", \"Z\"],\n [\"Ž\", \"Z\"],\n [\"Ẑ\", \"Z\"],\n [\"Ⱬ\", \"Z\"],\n [\"Ż\", \"Z\"],\n [\"Ẓ\", \"Z\"],\n [\"Ȥ\", \"Z\"],\n [\"Ẕ\", \"Z\"],\n [\"Ƶ\", \"Z\"],\n [\"IJ\", \"IJ\"],\n [\"Œ\", \"OE\"],\n [\"ᴀ\", \"A\"],\n [\"ᴁ\", \"AE\"],\n [\"ʙ\", \"B\"],\n [\"ᴃ\", \"B\"],\n [\"ᴄ\", \"C\"],\n [\"ᴅ\", \"D\"],\n [\"ᴇ\", \"E\"],\n [\"ꜰ\", \"F\"],\n [\"ɢ\", \"G\"],\n [\"ʛ\", \"G\"],\n [\"ʜ\", \"H\"],\n [\"ɪ\", \"I\"],\n [\"ʁ\", \"R\"],\n [\"ᴊ\", \"J\"],\n [\"ᴋ\", \"K\"],\n [\"ʟ\", \"L\"],\n [\"ᴌ\", \"L\"],\n [\"ᴍ\", \"M\"],\n [\"ɴ\", \"N\"],\n [\"ᴏ\", \"O\"],\n [\"ɶ\", \"OE\"],\n [\"ᴐ\", \"O\"],\n [\"ᴕ\", \"OU\"],\n [\"ᴘ\", \"P\"],\n [\"ʀ\", \"R\"],\n [\"ᴎ\", \"N\"],\n [\"ᴙ\", \"R\"],\n [\"ꜱ\", \"S\"],\n [\"ᴛ\", \"T\"],\n [\"ⱻ\", \"E\"],\n [\"ᴚ\", \"R\"],\n [\"ᴜ\", \"U\"],\n [\"ᴠ\", \"V\"],\n [\"ᴡ\", \"W\"],\n [\"ʏ\", \"Y\"],\n [\"ᴢ\", \"Z\"],\n [\"á\", \"a\"],\n [\"ă\", \"a\"],\n [\"ắ\", \"a\"],\n [\"ặ\", \"a\"],\n [\"ằ\", \"a\"],\n [\"ẳ\", \"a\"],\n [\"ẵ\", \"a\"],\n [\"ǎ\", \"a\"],\n [\"â\", \"a\"],\n [\"ấ\", \"a\"],\n [\"ậ\", \"a\"],\n [\"ầ\", \"a\"],\n [\"ẩ\", \"a\"],\n [\"ẫ\", \"a\"],\n [\"ä\", \"a\"],\n [\"ǟ\", \"a\"],\n [\"ȧ\", \"a\"],\n [\"ǡ\", \"a\"],\n [\"ạ\", \"a\"],\n [\"ȁ\", \"a\"],\n [\"à\", \"a\"],\n [\"ả\", \"a\"],\n [\"ȃ\", \"a\"],\n [\"ā\", \"a\"],\n [\"ą\", \"a\"],\n [\"ᶏ\", \"a\"],\n [\"ẚ\", \"a\"],\n [\"å\", \"a\"],\n [\"ǻ\", \"a\"],\n [\"ḁ\", \"a\"],\n [\"ⱥ\", \"a\"],\n [\"ã\", \"a\"],\n [\"ꜳ\", \"aa\"],\n [\"æ\", \"ae\"],\n [\"ǽ\", \"ae\"],\n [\"ǣ\", \"ae\"],\n [\"ꜵ\", \"ao\"],\n [\"ꜷ\", \"au\"],\n [\"ꜹ\", \"av\"],\n [\"ꜻ\", \"av\"],\n [\"ꜽ\", \"ay\"],\n [\"ḃ\", \"b\"],\n [\"ḅ\", \"b\"],\n [\"ɓ\", \"b\"],\n [\"ḇ\", \"b\"],\n [\"ᵬ\", \"b\"],\n [\"ᶀ\", \"b\"],\n [\"ƀ\", \"b\"],\n [\"ƃ\", \"b\"],\n [\"ɵ\", \"o\"],\n [\"ć\", \"c\"],\n [\"č\", \"c\"],\n [\"ç\", \"c\"],\n [\"ḉ\", \"c\"],\n [\"ĉ\", \"c\"],\n [\"ɕ\", \"c\"],\n [\"ċ\", \"c\"],\n [\"ƈ\", \"c\"],\n [\"ȼ\", \"c\"],\n [\"ď\", \"d\"],\n [\"ḑ\", \"d\"],\n [\"ḓ\", \"d\"],\n [\"ȡ\", \"d\"],\n [\"ḋ\", \"d\"],\n [\"ḍ\", \"d\"],\n [\"ɗ\", \"d\"],\n [\"ᶑ\", \"d\"],\n [\"ḏ\", \"d\"],\n [\"ᵭ\", \"d\"],\n [\"ᶁ\", \"d\"],\n [\"đ\", \"d\"],\n [\"ɖ\", \"d\"],\n [\"ƌ\", \"d\"],\n [\"ı\", \"i\"],\n [\"ȷ\", \"j\"],\n [\"ɟ\", \"j\"],\n [\"ʄ\", \"j\"],\n [\"dz\", \"dz\"],\n [\"dž\", \"dz\"],\n [\"é\", \"e\"],\n [\"ĕ\", \"e\"],\n [\"ě\", \"e\"],\n [\"ȩ\", \"e\"],\n [\"ḝ\", \"e\"],\n [\"ê\", \"e\"],\n [\"ế\", \"e\"],\n [\"ệ\", \"e\"],\n [\"ề\", \"e\"],\n [\"ể\", \"e\"],\n [\"ễ\", \"e\"],\n [\"ḙ\", \"e\"],\n [\"ë\", \"e\"],\n [\"ė\", \"e\"],\n [\"ẹ\", \"e\"],\n [\"ȅ\", \"e\"],\n [\"è\", \"e\"],\n [\"ẻ\", \"e\"],\n [\"ȇ\", \"e\"],\n [\"ē\", \"e\"],\n [\"ḗ\", \"e\"],\n [\"ḕ\", \"e\"],\n [\"ⱸ\", \"e\"],\n [\"ę\", \"e\"],\n [\"ᶒ\", \"e\"],\n [\"ɇ\", \"e\"],\n [\"ẽ\", \"e\"],\n [\"ḛ\", \"e\"],\n [\"ꝫ\", \"et\"],\n [\"ḟ\", \"f\"],\n [\"ƒ\", \"f\"],\n [\"ᵮ\", \"f\"],\n [\"ᶂ\", \"f\"],\n [\"ǵ\", \"g\"],\n [\"ğ\", \"g\"],\n [\"ǧ\", \"g\"],\n [\"ģ\", \"g\"],\n [\"ĝ\", \"g\"],\n [\"ġ\", \"g\"],\n [\"ɠ\", \"g\"],\n [\"ḡ\", \"g\"],\n [\"ᶃ\", \"g\"],\n [\"ǥ\", \"g\"],\n [\"ḫ\", \"h\"],\n [\"ȟ\", \"h\"],\n [\"ḩ\", \"h\"],\n [\"ĥ\", \"h\"],\n [\"ⱨ\", \"h\"],\n [\"ḧ\", \"h\"],\n [\"ḣ\", \"h\"],\n [\"ḥ\", \"h\"],\n [\"ɦ\", \"h\"],\n [\"ẖ\", \"h\"],\n [\"ħ\", \"h\"],\n [\"ƕ\", \"hv\"],\n [\"í\", \"i\"],\n [\"ĭ\", \"i\"],\n [\"ǐ\", \"i\"],\n [\"î\", \"i\"],\n [\"ï\", \"i\"],\n [\"ḯ\", \"i\"],\n [\"ị\", \"i\"],\n [\"ȉ\", \"i\"],\n [\"ì\", \"i\"],\n [\"ỉ\", \"i\"],\n [\"ȋ\", \"i\"],\n [\"ī\", \"i\"],\n [\"į\", \"i\"],\n [\"ᶖ\", \"i\"],\n [\"ɨ\", \"i\"],\n [\"ĩ\", \"i\"],\n [\"ḭ\", \"i\"],\n [\"ꝺ\", \"d\"],\n [\"ꝼ\", \"f\"],\n [\"ᵹ\", \"g\"],\n [\"ꞃ\", \"r\"],\n [\"ꞅ\", \"s\"],\n [\"ꞇ\", \"t\"],\n [\"ꝭ\", \"is\"],\n [\"ǰ\", \"j\"],\n [\"ĵ\", \"j\"],\n [\"ʝ\", \"j\"],\n [\"ɉ\", \"j\"],\n [\"ḱ\", \"k\"],\n [\"ǩ\", \"k\"],\n [\"ķ\", \"k\"],\n [\"ⱪ\", \"k\"],\n [\"ꝃ\", \"k\"],\n [\"ḳ\", \"k\"],\n [\"ƙ\", \"k\"],\n [\"ḵ\", \"k\"],\n [\"ᶄ\", \"k\"],\n [\"ꝁ\", \"k\"],\n [\"ꝅ\", \"k\"],\n [\"ĺ\", \"l\"],\n [\"ƚ\", \"l\"],\n [\"ɬ\", \"l\"],\n [\"ľ\", \"l\"],\n [\"ļ\", \"l\"],\n [\"ḽ\", \"l\"],\n [\"ȴ\", \"l\"],\n [\"ḷ\", \"l\"],\n [\"ḹ\", \"l\"],\n [\"ⱡ\", \"l\"],\n [\"ꝉ\", \"l\"],\n [\"ḻ\", \"l\"],\n [\"ŀ\", \"l\"],\n [\"ɫ\", \"l\"],\n [\"ᶅ\", \"l\"],\n [\"ɭ\", \"l\"],\n [\"ł\", \"l\"],\n [\"lj\", \"lj\"],\n [\"ſ\", \"s\"],\n [\"ẜ\", \"s\"],\n [\"ẛ\", \"s\"],\n [\"ẝ\", \"s\"],\n [\"ḿ\", \"m\"],\n [\"ṁ\", \"m\"],\n [\"ṃ\", \"m\"],\n [\"ɱ\", \"m\"],\n [\"ᵯ\", \"m\"],\n [\"ᶆ\", \"m\"],\n [\"ń\", \"n\"],\n [\"ň\", \"n\"],\n [\"ņ\", \"n\"],\n [\"ṋ\", \"n\"],\n [\"ȵ\", \"n\"],\n [\"ṅ\", \"n\"],\n [\"ṇ\", \"n\"],\n [\"ǹ\", \"n\"],\n [\"ɲ\", \"n\"],\n [\"ṉ\", \"n\"],\n [\"ƞ\", \"n\"],\n [\"ᵰ\", \"n\"],\n [\"ᶇ\", \"n\"],\n [\"ɳ\", \"n\"],\n [\"ñ\", \"n\"],\n [\"nj\", \"nj\"],\n [\"ó\", \"o\"],\n [\"ŏ\", \"o\"],\n [\"ǒ\", \"o\"],\n [\"ô\", \"o\"],\n [\"ố\", \"o\"],\n [\"ộ\", \"o\"],\n [\"ồ\", \"o\"],\n [\"ổ\", \"o\"],\n [\"ỗ\", \"o\"],\n [\"ö\", \"o\"],\n [\"ȫ\", \"o\"],\n [\"ȯ\", \"o\"],\n [\"ȱ\", \"o\"],\n [\"ọ\", \"o\"],\n [\"ő\", \"o\"],\n [\"ȍ\", \"o\"],\n [\"ò\", \"o\"],\n [\"ỏ\", \"o\"],\n [\"ơ\", \"o\"],\n [\"ớ\", \"o\"],\n [\"ợ\", \"o\"],\n [\"ờ\", \"o\"],\n [\"ở\", \"o\"],\n [\"ỡ\", \"o\"],\n [\"ȏ\", \"o\"],\n [\"ꝋ\", \"o\"],\n [\"ꝍ\", \"o\"],\n [\"ⱺ\", \"o\"],\n [\"ō\", \"o\"],\n [\"ṓ\", \"o\"],\n [\"ṑ\", \"o\"],\n [\"ǫ\", \"o\"],\n [\"ǭ\", \"o\"],\n [\"ø\", \"o\"],\n [\"ǿ\", \"o\"],\n [\"õ\", \"o\"],\n [\"ṍ\", \"o\"],\n [\"ṏ\", \"o\"],\n [\"ȭ\", \"o\"],\n [\"ƣ\", \"oi\"],\n [\"ꝏ\", \"oo\"],\n [\"ɛ\", \"e\"],\n [\"ᶓ\", \"e\"],\n [\"ɔ\", \"o\"],\n [\"ᶗ\", \"o\"],\n [\"ȣ\", \"ou\"],\n [\"ṕ\", \"p\"],\n [\"ṗ\", \"p\"],\n [\"ꝓ\", \"p\"],\n [\"ƥ\", \"p\"],\n [\"ᵱ\", \"p\"],\n [\"ᶈ\", \"p\"],\n [\"ꝕ\", \"p\"],\n [\"ᵽ\", \"p\"],\n [\"ꝑ\", \"p\"],\n [\"ꝙ\", \"q\"],\n [\"ʠ\", \"q\"],\n [\"ɋ\", \"q\"],\n [\"ꝗ\", \"q\"],\n [\"ŕ\", \"r\"],\n [\"ř\", \"r\"],\n [\"ŗ\", \"r\"],\n [\"ṙ\", \"r\"],\n [\"ṛ\", \"r\"],\n [\"ṝ\", \"r\"],\n [\"ȑ\", \"r\"],\n [\"ɾ\", \"r\"],\n [\"ᵳ\", \"r\"],\n [\"ȓ\", \"r\"],\n [\"ṟ\", \"r\"],\n [\"ɼ\", \"r\"],\n [\"ᵲ\", \"r\"],\n [\"ᶉ\", \"r\"],\n [\"ɍ\", \"r\"],\n [\"ɽ\", \"r\"],\n [\"ↄ\", \"c\"],\n [\"ꜿ\", \"c\"],\n [\"ɘ\", \"e\"],\n [\"ɿ\", \"r\"],\n [\"ś\", \"s\"],\n [\"ṥ\", \"s\"],\n [\"š\", \"s\"],\n [\"ṧ\", \"s\"],\n [\"ş\", \"s\"],\n [\"ŝ\", \"s\"],\n [\"ș\", \"s\"],\n [\"ṡ\", \"s\"],\n [\"ṣ\", \"s\"],\n [\"ṩ\", \"s\"],\n [\"ʂ\", \"s\"],\n [\"ᵴ\", \"s\"],\n [\"ᶊ\", \"s\"],\n [\"ȿ\", \"s\"],\n [\"ɡ\", \"g\"],\n [\"ᴑ\", \"o\"],\n [\"ᴓ\", \"o\"],\n [\"ᴝ\", \"u\"],\n [\"ť\", \"t\"],\n [\"ţ\", \"t\"],\n [\"ṱ\", \"t\"],\n [\"ț\", \"t\"],\n [\"ȶ\", \"t\"],\n [\"ẗ\", \"t\"],\n [\"ⱦ\", \"t\"],\n [\"ṫ\", \"t\"],\n [\"ṭ\", \"t\"],\n [\"ƭ\", \"t\"],\n [\"ṯ\", \"t\"],\n [\"ᵵ\", \"t\"],\n [\"ƫ\", \"t\"],\n [\"ʈ\", \"t\"],\n [\"ŧ\", \"t\"],\n [\"ᵺ\", \"th\"],\n [\"ɐ\", \"a\"],\n [\"ᴂ\", \"ae\"],\n [\"ǝ\", \"e\"],\n [\"ᵷ\", \"g\"],\n [\"ɥ\", \"h\"],\n [\"ʮ\", \"h\"],\n [\"ʯ\", \"h\"],\n [\"ᴉ\", \"i\"],\n [\"ʞ\", \"k\"],\n [\"ꞁ\", \"l\"],\n [\"ɯ\", \"m\"],\n [\"ɰ\", \"m\"],\n [\"ᴔ\", \"oe\"],\n [\"ɹ\", \"r\"],\n [\"ɻ\", \"r\"],\n [\"ɺ\", \"r\"],\n [\"ⱹ\", \"r\"],\n [\"ʇ\", \"t\"],\n [\"ʌ\", \"v\"],\n [\"ʍ\", \"w\"],\n [\"ʎ\", \"y\"],\n [\"ꜩ\", \"tz\"],\n [\"ú\", \"u\"],\n [\"ŭ\", \"u\"],\n [\"ǔ\", \"u\"],\n [\"û\", \"u\"],\n [\"ṷ\", \"u\"],\n [\"ü\", \"u\"],\n [\"ǘ\", \"u\"],\n [\"ǚ\", \"u\"],\n [\"ǜ\", \"u\"],\n [\"ǖ\", \"u\"],\n [\"ṳ\", \"u\"],\n [\"ụ\", \"u\"],\n [\"ű\", \"u\"],\n [\"ȕ\", \"u\"],\n [\"ù\", \"u\"],\n [\"ủ\", \"u\"],\n [\"ư\", \"u\"],\n [\"ứ\", \"u\"],\n [\"ự\", \"u\"],\n [\"ừ\", \"u\"],\n [\"ử\", \"u\"],\n [\"ữ\", \"u\"],\n [\"ȗ\", \"u\"],\n [\"ū\", \"u\"],\n [\"ṻ\", \"u\"],\n [\"ų\", \"u\"],\n [\"ᶙ\", \"u\"],\n [\"ů\", \"u\"],\n [\"ũ\", \"u\"],\n [\"ṹ\", \"u\"],\n [\"ṵ\", \"u\"],\n [\"ᵫ\", \"ue\"],\n [\"ꝸ\", \"um\"],\n [\"ⱴ\", \"v\"],\n [\"ꝟ\", \"v\"],\n [\"ṿ\", \"v\"],\n [\"ʋ\", \"v\"],\n [\"ᶌ\", \"v\"],\n [\"ⱱ\", \"v\"],\n [\"ṽ\", \"v\"],\n [\"ꝡ\", \"vy\"],\n [\"ẃ\", \"w\"],\n [\"ŵ\", \"w\"],\n [\"ẅ\", \"w\"],\n [\"ẇ\", \"w\"],\n [\"ẉ\", \"w\"],\n [\"ẁ\", \"w\"],\n [\"ⱳ\", \"w\"],\n [\"ẘ\", \"w\"],\n [\"ẍ\", \"x\"],\n [\"ẋ\", \"x\"],\n [\"ᶍ\", \"x\"],\n [\"ý\", \"y\"],\n [\"ŷ\", \"y\"],\n [\"ÿ\", \"y\"],\n [\"ẏ\", \"y\"],\n [\"ỵ\", \"y\"],\n [\"ỳ\", \"y\"],\n [\"ƴ\", \"y\"],\n [\"ỷ\", \"y\"],\n [\"ỿ\", \"y\"],\n [\"ȳ\", \"y\"],\n [\"ẙ\", \"y\"],\n [\"ɏ\", \"y\"],\n [\"ỹ\", \"y\"],\n [\"ź\", \"z\"],\n [\"ž\", \"z\"],\n [\"ẑ\", \"z\"],\n [\"ʑ\", \"z\"],\n [\"ⱬ\", \"z\"],\n [\"ż\", \"z\"],\n [\"ẓ\", \"z\"],\n [\"ȥ\", \"z\"],\n [\"ẕ\", \"z\"],\n [\"ᵶ\", \"z\"],\n [\"ᶎ\", \"z\"],\n [\"ʐ\", \"z\"],\n [\"ƶ\", \"z\"],\n [\"ɀ\", \"z\"],\n [\"ff\", \"ff\"],\n [\"ffi\", \"ffi\"],\n [\"ffl\", \"ffl\"],\n [\"fi\", \"fi\"],\n [\"fl\", \"fl\"],\n [\"ij\", \"ij\"],\n [\"œ\", \"oe\"],\n [\"st\", \"st\"],\n [\"ₐ\", \"a\"],\n [\"ₑ\", \"e\"],\n [\"ᵢ\", \"i\"],\n [\"ⱼ\", \"j\"],\n [\"ₒ\", \"o\"],\n [\"ᵣ\", \"r\"],\n [\"ᵤ\", \"u\"],\n [\"ᵥ\", \"v\"],\n [\"ₓ\", \"x\"],\n ]);\n" }, { "answer_id": 74556988, "author": "Selim", "author_id": 14384258, "author_profile": "https://Stackoverflow.com/users/14384258", "pm_score": 0, "selected": false, "text": "latinize import latinize from 'latinize';\nlatinize('ỆᶍǍᶆṔƚÉ áéíóúýčďěňřšťžů'); // => 'ExAmPlE aeiouycdenrstzu'\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18771/" ]
286,932
<p>The following code is implemented in Page_Load event to show SaveFileDialog to the user</p> <pre><code>string targetFileName = Request.PhysicalApplicationPath + "Reports\\TempReports\\FolderMasters" + Utility.GetRandomNumber() + ".pdf"; FileInfo file = new FileInfo(targetFileName); // Clear the content of the response. Response.ClearContent(); Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/pdf"; Response.TransmitFile(file.FullName); Response.End(); </code></pre> <p>How can I get the user response to SaveFileDialog, as I need to know user response to this dialog?</p> <p>Also, is there something wrong with these lines of code, as I had the following exception</p> <p>"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."</p>
[ { "answer_id": 287006, "author": "Ahmed Atia", "author_id": 14118, "author_profile": "https://Stackoverflow.com/users/14118", "pm_score": 1, "selected": true, "text": "Response.End HttpContext.Current.ApplicationInstance.CompleteRequest" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14118/" ]
286,938
<p>What is the best way to password protect folder using php without a database or user name but using. Basically I have a page that will list contacts for organization and need to password protect that folder without having account for every user . Just one password that gets changes every so often and distributed to the group. I understand that it is not very secure but never the less I would like to know how to do this. In the best way.</p> <p>It would be nice if the password is remembered for a while once user entered it correctly.</p> <hr> <p>I am doing approximately what David Heggie suggested, except without cookies. It does seem insecure as hell, but it is probably better having a bad password protection then none at all. </p> <p>This is for internal site where people would have hell of a time remembering their login and password and would never go through <em>sign up</em> process... unless it is really easy they would not use the system at all. </p> <p>I wanted to see other solutions to this problem. </p> <p>With user base consisting of not very tech savvy people what are other ways to do this. </p>
[ { "answer_id": 287008, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 1, "selected": false, "text": "login.php\n...\nif(isset($_POST['password']) && $_POST['password'] == 'my_top_secret_word') {\n setcookie('loggedin', 'true', time() + 1200, '/url/');\n} else {\n setcookie('loggedin', 'false', time() - 1200, '/url/');\n // display a login form here\n}\netc\n if(isset($_COOKIE['loggedin'])) {\n if($_COOKIE['loggedin'] == 'true') {\n $showHidden = true;\n } else {\n $showHidden = false;\n }\n} else {\n $showHidden = false;\n}\n" }, { "answer_id": 287015, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 7, "selected": true, "text": "//access.php\n\n<?php\n//put sha1() encrypted password here - example is 'hello'\n$password = 'aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d';\n\nsession_start();\nif (!isset($_SESSION['loggedIn'])) {\n $_SESSION['loggedIn'] = false;\n}\n\nif (isset($_POST['password'])) {\n if (sha1($_POST['password']) == $password) {\n $_SESSION['loggedIn'] = true;\n } else {\n die ('Incorrect password');\n }\n} \n\nif (!$_SESSION['loggedIn']): ?>\n\n<html><head><title>Login</title></head>\n <body>\n <p>You need to login</p>\n <form method=\"post\">\n Password: <input type=\"password\" name=\"password\"> <br />\n <input type=\"submit\" name=\"submit\" value=\"Login\">\n </form>\n </body>\n</html>\n\n<?php\nexit();\nendif;\n?>\n <?php\nrequire('access.php');\n?>\nsecret text\n <?php\n session_start();\n $_SESSION['loggedIn'] = false;\n?>\nYou have logged out \n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35513/" ]
286,940
<p>I want to create a similar behavior to the data reader class but for a bespoke emailer program so that I can do the follow</p> <pre><code>Dim sender As New EmailSender(emailTemplate) While sender.Send() Response.Write(sender("HTMLContent")) End While </code></pre> <p>Is there an advised interface or mustInherit class to utilize the stepping functionality so that sender.Send() command prepares the next email for sending and returns true if it exists?</p>
[ { "answer_id": 287145, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": 0, "selected": false, "text": " Namespace Emailer\n\n Public Interface IBatchableEmailSender\n Function SendNextEmail() As Boolean\n Sub PrepareBatchEmail()\n Property EmailOutput() As EmailOutput\n End Interface\n\n Public MustInherit Class BaseBatchEmailSender\n Implements IBatchableEmailSender\n\n Private _emailOutput As EmailOutput\n Public Property EmailOutput() As EmailOutput Implements IBatchableEmailSender.EmailOutput\n Get\n Return _emailOutput\n End Get\n Set(ByVal value As EmailOutput)\n _emailOutput = value\n End Set\n End Property\n Public MustOverride Sub PrepareBatchEmail() Implements IBatchableEmailSender.PrepareBatchEmail\n Public MustOverride Function SendNextEmail() As Boolean Implements IBatchableEmailSender.SendNextEmail\n\n Public Sub New()\n PrepareBatchEmail()\n End Sub\n\n End Class\nPublic Class BatchCustomerEmail\n Inherits BaseBatchEmailSender\n\n Private EmailItems As New Generic.List(Of EmailItem)\n Private EmailItemNumber As Integer\n Private NextEmailItem As EmailItem\n\n Protected Class EmailItem\n Public MemberID As Integer\n Public Sub New(ByVal memberID As Integer)\n Me.MemberID = memberID\n End Sub\n End Class\n\n Public Overrides Function SendNextEmail() As Boolean\n Dim hasEmail As Boolean = EmailItemNumber < EmailItems.Count\n If hasEmail Then\n ' Run script to send email\n ' If necessary mark email as sent in the database \n EmailItemNumber = EmailItemNumber + 1\n End If\n Return hasEmail\n\n End Function\n\n Public Overrides Sub PrepareBatchEmail()\n '\n ' Creates a Generic.List(of EmailItems) to email.\n '\n EmailItemNumber = 0\n End Sub\n\n\n End Class\n\n\n Public Class EmailOutput\n Private _text As String\n\n Public Property Text() As String\n Get\n Return _text\n End Get\n Set(ByVal value As String)\n _text = value\n End Set\n End Property\n Private _html As String\n Public Property HTML() As String\n Get\n Return _html\n End Get\n Set(ByVal value As String)\n _html = value\n End Set\n End Property\n Private _error As String\n Public Property ErrorMessage() As String\n Get\n Return _error\n End Get\n Set(ByVal value As String)\n _error = value\n End Set\n End Property\n Public Sub New(ByVal errorMesage As String, ByVal html As String, ByVal text As String)\n Me.ErrorMessage = errorMesage\n Me.HTML = html\n Me.Text = text\n End Sub\n End Class\n\nEnd Namespace\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
286,945
<p>What is the JSON (JavaScript Object Notation) format?</p>
[ { "answer_id": 286978, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 7, "selected": true, "text": "{\n \"menu\": {\n \"id\": \"file\",\n \"value\": \"File\",\n \"popup\": {\n \"menuitem\": [{\n \"onclick\": \"CreateNewDoc()\"\n }, {\n \"value\": \"Open\",\n \"onclick\": \"OpenDoc()\"\n }, {\n \"value\": \"Close\",\n \"onclick\": \"CloseDoc()\"\n }]\n }\n }\n}\n <menu id=\"file\" value=\"File\">\n <popup>\n <menuitem value=\"New\" onclick=\"CreateNewDoc()\" />\n <menuitem value=\"Open\" onclick=\"OpenDoc()\" />\n <menuitem value=\"Close\" onclick=\"CloseDoc()\" />\n </popup>\n</menu>\n" }, { "answer_id": 32816007, "author": "Christeena Vincent", "author_id": 5319728, "author_profile": "https://Stackoverflow.com/users/5319728", "pm_score": 0, "selected": false, "text": " {\"employees\":[\n\n {\"firstName\":\"John\", \"lastName\":\"Doe\"},\n\n {\"firstName\":\"Anna\", \"lastName\":\"Smith\"},\n\n {\"firstName\":\"Peter\", \"lastName\":\"Jones\"}\n\n ]}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22076/" ]
286,946
<p>I've got a quick question about default values in PL/SQL functions in Oracle. Take this program as an example;</p> <pre><code>create or replace FUNCTION testFunction ( varNumber IN NUMBER DEFAULT 0 ) RETURN NUMBER AS BEGIN dbms_output.put_line(varNumber); RETURN varNumber; END; </code></pre> <p>The idea here being that if no value is specified for varNumber when this function is called, then it will take the value of 0.</p> <p>Now, my problem is that my functions are getting called from a web services layer that will always pass in NULL as the value for parameters which it doesn't have a value for. Oracle interprets NULL as a value, and so does not initialise varNumber to its default of 0.</p> <p>I can see why this approach makes sense, but I was wondering if there was a way to override this behaviour, and make it so that if a NULL value is passed, that it causes Oracle to assign the explicit DEFAULT value that is specified in the function header?</p> <p>I have considered the option of doing a manual check...</p> <pre><code>IF(varNumber IS NULL) THEN varNumber := 0; END IF; </code></pre> <p>However, there are hundreds of functions where this may be an issue, never mind the large number of parameters per function, and so I'd prefer it if I could find a more general solution to the problem.</p> <p>Cheers for any insight you can give.</p>
[ { "answer_id": 286963, "author": "Turnkey", "author_id": 13144, "author_profile": "https://Stackoverflow.com/users/13144", "pm_score": 2, "selected": false, "text": "NVL( value_in, replace_with )\n" }, { "answer_id": 286966, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 1, "selected": false, "text": "varNumber = NVL(varNumber,0);\n" }, { "answer_id": 287131, "author": "Jim Hudson", "author_id": 8051, "author_profile": "https://Stackoverflow.com/users/8051", "pm_score": 3, "selected": true, "text": "create or replace\nFUNCTION testFunction\n(\n varNumber IN NUMBER DEFAULT 0\n)\nRETURN NUMBER\nAS\n vFix number := nvl(varNumber,0);\nBEGIN\n dbms_output.put_line(vFix);\n RETURN vFix;\nEND;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5827/" ]
286,958
<p>I am trying to use some AOP in my Python programming, but I do not have any experience of the various libraries that exist. </p> <p>So my question are:</p> <blockquote> <p>What AOP support exists for Python? And what are the advantages of the differents libraries between them?</p> </blockquote> <hr> <h3>Edit</h3> <p>I've found some, but I don't know how they compare:</p> <ul> <li><a href="http://www.aspyct.org" rel="noreferrer">Aspyct</a></li> <li><a href="http://www.cs.tut.fi/~ask/aspects/aspects.html" rel="noreferrer">Lightweight AOP for Python</a></li> </ul> <h3>Edit 2</h3> <p>In which context will I use these? </p> <p>I have two applications, written in Python, which have typically methods which compute taxes and other money things. I'd like to be able to write a "skeleton" of a functionality, and customize it at runtime, for example changing the way local taxes are applied (by country, or state, or city, etc.) without having to overload the full stack.</p>
[ { "answer_id": 287640, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 5, "selected": false, "text": "import pickle, functools\ndef cache(f):\n _cache = {}\n def wrapper(*args, **kwargs):\n key = pickle.dumps((args, kwargs))\n if key not in _cache:\n _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache\n return _cache[key] # read value from cache\n functools.update_wrapper(wrapper, f) # update wrapper's metadata\n return wrapper\n\nimport time\n@cache\ndef foo(n):\n time.sleep(2)\n return n*2\n\nfoo(10) # first call with parameter 10, sleeps\nfoo(10) # returns immediately\n" }, { "answer_id": 2884843, "author": "Arx", "author_id": 347377, "author_profile": "https://Stackoverflow.com/users/347377", "pm_score": 2, "selected": false, "text": "Aspyct" }, { "answer_id": 5220447, "author": "Tim Diels", "author_id": 648243, "author_profile": "https://Stackoverflow.com/users/648243", "pm_score": 4, "selected": true, "text": "pytilities" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14262/" ]
286,964
<p>I need to cut out and save/use part of a string in C#. I figure the best way to do this is by using Regex. My string looks like this:</p> <p><code>"changed from 1 to 10"</code>. </p> <p>I need a way to cut out the two numbers and use them elsewhere. What's a good way to do this?</p>
[ { "answer_id": 286981, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 2, "selected": false, "text": "Match.Captures" }, { "answer_id": 286987, "author": "Rob Stevenson-Leggett", "author_id": 4950, "author_profile": "https://Stackoverflow.com/users/4950", "pm_score": 1, "selected": false, "text": "Regex r = new Regex(\"*(?<FirstNumber>[0-9]{1,2})*(?<SecondNumber>[0-9]{1,2})*\");\n string input = \"changed from 1 to 10\";\n string firstNumber = \"\";\n string secondNumber = \"\";\n\n MatchCollection joinMatches = regex.Matches(input);\n\n foreach (Match m in joinMatches)\n {\n firstNumber= m.Groups[\"FirstNumber\"].Value;\n secondNumber= m.Groups[\"SecondNumber\"].Value;\n }\n" }, { "answer_id": 286991, "author": "phihag", "author_id": 35070, "author_profile": "https://Stackoverflow.com/users/35070", "pm_score": 2, "selected": false, "text": "string pattern = @\"^changed from ([0-9]+) to ([0-9]+)$\";\nRegex r = new Regex(pattern);\nMatch m = r.match(text);\nif (m.Success) {\n Group g = m.Groups[0];\n CaptureCollection cc = g.Captures;\n\n int from = Convert.ToInt32(cc[0]);\n int to = Convert.ToInt32(cc[1]);\n\n // Do stuff\n} else {\n // Error, regex did not match\n}\n" }, { "answer_id": 286999, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": true, "text": " Regex regex = new Regex( @\"\\d+\" );\n MatchCollection matches = regex.Matches( \"changed from 1 to 10\" );\n int num1 = int.Parse( matches[0].Value );\n int num2 = int.Parse( matches[1].Value );\n" }, { "answer_id": 287344, "author": "Cros", "author_id": 1523, "author_profile": "https://Stackoverflow.com/users/1523", "pm_score": 0, "selected": false, "text": "using System.Text.RegularExpressions;\n\nstring text = \"changed from 1 to 10\";\nstring pattern = @\"\\b(?<digit>\\d+)\\b\";\nRegex r = new Regex(pattern);\nMatchCollection mc = r.Matches(text);\nforeach (Match m in mc) {\n CaptureCollection cc = m.Groups[\"digit\"].Captures;\n foreach (Capture c in cc){\n Console.WriteLine((Convert.ToInt32(c.Value)));\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1523/" ]
286,971
<p>How can I get the value between quotes with an RegEx</p> <p>for example I want to find all the parameters from the function test</p> <pre><code>&lt;html&gt; test("bla"); print("foo"); test("moo"); &lt;/html&gt; </code></pre> <p>The result must be { "bla", "moo" }</p>
[ { "answer_id": 287001, "author": "Jesper Palm", "author_id": 36455, "author_profile": "https://Stackoverflow.com/users/36455", "pm_score": 1, "selected": false, "text": " var array = (from Match m in Regex.Matches(inText, \"\\\"\\\\w+?\\\"\")\n select m.Groups[0].Value).ToArray();\n\n string json = string.Format(\"{{{0}}}\", string.Join(\",\", array));\n" }, { "answer_id": 287010, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "test StringBuilder sb = new StringBuilder(\"{\");\n bool first = true;\n foreach (Match match in Regex.Matches(html, @\"test\\((\"\"[^\\\"\"]*\\\"\")\\)\"))\n {\n if(first) {first = false;}\n else {sb.Append(',');}\n sb.Append(match.Groups[1].Value);\n }\n sb.Append('}');\n Console.WriteLine(sb);\n foreach (Match match in Regex.Matches(html, @\"test\\(\"\"([^\\\"\"]*)\\\"\"\\)\"))\n {\n Console.WriteLine(match.Groups[1].Value);\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37311/" ]
286,972
<p>In Java, is there a way to control the TTL of the IP header for packets sent on a socket? </p>
[ { "answer_id": 287017, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": true, "text": "MulticastSocket.setTimeToLive(int ttl);\n" }, { "answer_id": 1201687, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 1, "selected": false, "text": "MulticastSocket.setTimeToLive(int ttl);\n -Djava.net.preferIPv4Stack=true\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ]
286,982
<p>I want to get the headers only from a curl request</p> <p><code>curl -I www.google.com</code></p> <p>All grand. Now I want to do that but to pass in post data too:</p> <p><code>curl -I -d'test=test' www.google.com</code></p> <p>But all I get is:</p> <p><code>Warning: You can only select one HTTP request!</code></p> <p>Anyone have any idea how to do this or am I doing something stupid?</p>
[ { "answer_id": 287018, "author": "phihag", "author_id": 35070, "author_profile": "https://Stackoverflow.com/users/35070", "pm_score": 5, "selected": false, "text": "-d POST -I HEAD /dev/null -D headerfile headerfile -i" }, { "answer_id": 287299, "author": "J.D. Fitz.Gerald", "author_id": 11542, "author_profile": "https://Stackoverflow.com/users/11542", "pm_score": 8, "selected": true, "text": "-I -d'test=test' curl -s -d'test=test' -D- -o/dev/null www.google.com \n curl -s -d'test=test' -D- -onul: www.google.com \n -D- - -o/dev/null -s" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11542/" ]
286,988
<p>I cloned a Git master and made a lot of changes on the clone. I have since committed these changes on the clone and now want the master to be a carbon copy of what is on the clone.</p> <p>I've tried Git push on the clone to push the changes to the master - but nothing I do updates the master.</p> <p>How can I make the master an exact copy of what is on the clone? What is the command workflow of updating the clone and having the master sync with the clone?</p>
[ { "answer_id": 287817, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "git pull /path/to/clone\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/286988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36142/" ]
287,000
<p>I am trying to get intellisense in VS2008 in a js file, foo.js, from another js library/file I've written but cannot figure out the reference path ?syntax?/?string?</p> <p>The library is in a file called common.js which is in the same folder as foo.js I'm working on.</p> <p>Here's the paths I've tried...</p> <pre><code>/// &lt;reference path="../../scripts/common.js"/&gt; /// &lt;reference path="/../scripts/common.js"/&gt; /// &lt;reference path="../scripts/common.js"/&gt; /// &lt;reference path="/scripts/common.js"/&gt; /// &lt;reference path="scripts/common.js"/&gt; /// &lt;reference path="/common.js"/&gt; /// &lt;reference path="../common.js"/&gt; /// &lt;reference path="/common.js"/&gt; /// &lt;reference path="common.js"/&gt; </code></pre> <p>What's the secret path syntax/string that I'm missing?</p> <p>FWIW the top path is what is set in the master page of this MVC app...like so </p> <p><code>&lt;script type="text/javascript" src="../../scripts/common.js"&gt;&lt;/script&gt;</code></p> <p>Thanks Greg</p>
[ { "answer_id": 402967, "author": "w4ik", "author_id": 4232, "author_profile": "https://Stackoverflow.com/users/4232", "pm_score": 4, "selected": false, "text": "/// <reference path=\"common.js\" />\n/// <reference path=\"jquery-1.2.6.js\" />\n/// <reference path=\"jquery.formatCurrency.js\" />\n/*\n * Foo Scripts/foo Script: foo.js\n * Version 1.0\n * Copyright(c) 2008 FUBAR Management, LLC. All Rights Reserved. \n */\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4232/" ]
287,022
<p>I have an ASP.net page. When I am closing the webpage I need to clear the session variables.</p> <p>How to to handle this I need to maintain the timeout to 20 minutes. If he closes and login for any number of times in the 20 minutes timed out time</p> <p>Is there any possiblity for clearing the ASP.net session id</p>
[ { "answer_id": 287027, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "window.onbeforeunload function CloseSession( )\n{\n location.href = 'SignOut.aspx'; \n}\nwindow.onbeforeunload = CloseSession;\n" }, { "answer_id": 20046961, "author": "Nisarg Desai", "author_id": 3004564, "author_profile": "https://Stackoverflow.com/users/3004564", "pm_score": -1, "selected": false, "text": "function ConfirmClose() \n{ \nif (event.clientY < 0) \n{ \n /* Your asynchronouse request to the page and call that function*/ \n} \n}\n/*now call this method on event of javascript*/ \n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22162/" ]
287,041
<p><strong>Note:</strong> Question <a href="https://stackoverflow.com/questions/220465/using-256-x-256-vista-icon-in-application">Using 256 x 256 Vista icon in application</a> deals with using a "Vista" icon as the application's icon. This question deals with manually painting a Vista icon.</p> <p><strong>Note:</strong> Question <a href="https://stackoverflow.com/questions/281999/winforms-net-20-how-to-paint-with-the-proper-icon">WinForms .NET 2.0: How to paint the proper sized icon?</a> deals with painting a Vista icon loaded from a file. This question deals with painting a Vista icon that is loaded from a .resource.</p> <hr> <p>I've included an icon in my Visual Studio project that has various formats:</p> <ul> <li>16x16</li> <li>32x32</li> <li>48x48</li> <li>256x256 (PNG compressed)</li> </ul> <p>Now want to draw the 256x256 version. None of the following things I've tried work.</p> <p><strong>The following draws the 32x32 format stretched to 256x256:</strong></p> <pre><code>Icon ico = Properties.Resources.TestIconThatHasA256PNGFormat; e.Graphics.DrawIcon(ico, new Rectangle(0, 0, 256, 256)); </code></pre> <p><strong>The following draws the 32x32 format unstretched:</strong></p> <pre><code>Icon ico = Properties.Resources.TestIconThatHasA256PNGFormat; e.Graphics.DrawIconUnstretched(ico, new Rectangle(0, 0, 256, 256)); </code></pre> <p><strong>The following draws the 32x32 format stretched to 256x256:</strong></p> <pre><code>Icon ico = Properties.Resources.TestIconThatHasA256PNGFormat; e.Graphics.DrawImage(ico.ToBitmap(), new Rectangle(0, 0, 256, 256)); </code></pre> <p><strong>The following draws the 48x48 format stretched to 256x256:</strong></p> <pre><code>Icon ico = Properties.Resources.TestIconThatHasA256PNGFormat; e.Graphics.DrawIcon( new Icon(ico, new Size(256, 256)), new Rectangle(0, 0, 256, 256)); </code></pre> <p>How do I draw the 256x256 format icon?</p> <hr> <p>Notes:</p> <ol> <li><p>The icon is not coming from a file, so <a href="https://stackoverflow.com/questions/220465/using-256-x-256-vista-icon-in-application">PInvoking</a> LoadImage() will not help.</p></li> <li><p>The icon is not the icon associated with a file, so <a href="http://support.microsoft.com/kb/319350" rel="nofollow noreferrer">PInvoking</a> SHGetFileInfo() <a href="https://stackoverflow.com/questions/287041/winforms-net-20-how-to-draw-a-vista-icon#287076">will</a> not help. Nor will <a href="https://stackoverflow.com/questions/220465/using-256-x-256-vista-icon-in-application">using Icon.ExtractAssociatedIcon</a>.</p></li> <li><p>I'm also not trying to author icons with a 256x256 format at runtime, so <a href="http://www.codeproject.com/KB/cs/IconLib.aspx" rel="nofollow noreferrer">libraries designed to do that</a> will not help.</p> <p><a href="https://stackoverflow.com/questions/281999/winforms-net-20-how-to-paint-with-the-proper-icon">2</a>: Question <a href="https://stackoverflow.com/questions/281999/winforms-net-20-how-to-paint-with-the-proper-icon">WinForms .NET 2.0: How to paint the proper sized icon?</a></p></li> </ol>
[ { "answer_id": 1061822, "author": "Pierre Arnaud", "author_id": 4597, "author_profile": "https://Stackoverflow.com/users/4597", "pm_score": 2, "selected": false, "text": "ResourceManager System.Drawing.Icon LoadImage System.Resources.ResourceReader IconConverter.LoadIcon using System.Runtime.InteropServices;\n\nstatic class IconConverter\n{\n public static System.Drawing.Icon LoadIcon(string path, int width, int height)\n {\n System.IntPtr hIcon;\n hIcon = LoadImage (System.IntPtr.Zero, path, IMAGE_ICON, width, height,\n LR_LOADFROMFILE);\n if (hIcon == System.IntPtr.Zero)\n {\n return null;\n }\n return System.Drawing.Icon.FromHandle (hIcon);\n }\n\n const int IMAGE_ICON = 1;\n const int LR_LOADFROMFILE = 0x0010;\n\n [DllImport (\"user32.dll\", SetLastError=true, CharSet=CharSet.Auto)]\n static extern System.IntPtr LoadImage(System.IntPtr hInstance,\n string lpszName, uint uType,\n int cxDesired, int cyDesired,\n uint fuLoad);\n}\n System.Drawing.Icon graphics.DrawIconUnstretched" }, { "answer_id": 1945737, "author": "SLA80", "author_id": 228365, "author_profile": "https://Stackoverflow.com/users/228365", "pm_score": 0, "selected": false, "text": "Bitmap ExtractVistaIcon(Icon icoIcon)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
287,053
<p>How do I programmatically find out the width and height of the video in an mpeg-2 <strike>transport</strike> program stream file? </p> <p>Edit: I am using C++, but am happy for examples in any language. Edit: Corrected question - it was probably program streams I was asking about</p>
[ { "answer_id": 287435, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": true, "text": "mpeg2_header_sequence() header.c" }, { "answer_id": 287477, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "piwc->GetNativeVideoSize(&w, &h, NULL, NULL);\n pivb->GetVideoSize(&w, &h);\n" }, { "answer_id": 1743735, "author": "Andrew", "author_id": 67442, "author_profile": "https://Stackoverflow.com/users/67442", "pm_score": 1, "selected": false, "text": "#define VIDEO_SEQUENCE_HDR 0xB3\n#define HOR_SIZE_MASK 0xFFF00000\n#define HOR_SIZE_SHIFT 20\n#define VER_SIZE_MASK 0x000FFF00\n#define VER_SIZE_SHIFT 8\n\nunsigned char *pTmp = tsPacket;\nint len = 188;\nint horizontal, vertical;\n\n while(len>0 && !horizontal && !vertical)\n { \n if(*pTmp == 0 && *(pTmp+1) == 0\n && *(pTmp+2)== 0x01 && *(pTmp+3) == 0xB3 && (len-1) >0)\n {\n unsigned int *pHdr = (unsigned int *)pTmp; \n pHdr++ ; \n unsigned int secondByte = ntohl(*pHdr);\n horizontal = (secondByte & HOR_SIZE_MASK) >> HOR_SIZE_SHIFT;\n vertical = (secondByte & VER_SIZE_MASK) >> VER_SIZE_SHIFT; \n break;\n }\n pTmp++;\n len--;\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3590/" ]
287,060
<p>Is it possible to set up somehow Microsoft SQL Server to run a stored procedure on regular basis?</p>
[ { "answer_id": 287087, "author": "Ciaran Archer", "author_id": 446733, "author_profile": "https://Stackoverflow.com/users/446733", "pm_score": 4, "selected": false, "text": "exec MyStoredProcedure" }, { "answer_id": 1769443, "author": "Thomas Bratt", "author_id": 15985, "author_profile": "https://Stackoverflow.com/users/15985", "pm_score": 5, "selected": false, "text": "USE Master\nGO\n\nIF EXISTS( SELECT *\n FROM sys.objects\n WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')\n AND type in (N'P', N'PC'))\n DROP PROCEDURE [dbo].[MyBackgroundTask]\nGO\n\nCREATE PROCEDURE MyBackgroundTask\nAS\nBEGIN\n -- SET NOCOUNT ON added to prevent extra result sets from\n -- interfering with SELECT statements.\n SET NOCOUNT ON;\n\n -- The interval between cleanup attempts\n declare @timeToRun nvarchar(50)\n set @timeToRun = '03:33:33'\n\n while 1 = 1\n begin\n waitfor time @timeToRun\n begin\n execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];\n end\n end\nEND\nGO\n\n-- Run the procedure when the master database starts.\nsp_procoption @ProcName = 'MyBackgroundTask',\n @OptionName = 'startup',\n @OptionValue = 'on'\nGO\n" }, { "answer_id": 22259017, "author": "percebus", "author_id": 1361858, "author_profile": "https://Stackoverflow.com/users/1361858", "pm_score": 4, "selected": false, "text": "sqlcmd.exe -S \".\" -d YourDataBase -Q \"exec SP_YourJob\" .bat" }, { "answer_id": 41909818, "author": "Lukasz Szozda", "author_id": 5070879, "author_profile": "https://Stackoverflow.com/users/5070879", "pm_score": 3, "selected": false, "text": "DECLARE @dialog UNIQUEIDENTIFIER;\n\nBEGIN DIALOG CONVERSATION @dialog\n FROM SERVICE [name] \n TO SERVICE 'name' \n ...;\n DECLARE @time INT;\nBEGIN CONVERSATION TIMER (@dialog) TIMEOUT = @time;\n CREATE QUEUE queue_name WITH STATUS = ON, RETENTION = OFF\n , ACTIVATION (STATUS = ON, PROCEDURE_NAME = <procedure_name>\n , MAX_QUEUE_READERS = 20, EXECUTE AS N'dbo')\n , POISON_MESSAGE_HANDLING (STATUS = ON) \n [tsks].[tsksx_task_scheduler]" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
287,065
<p>I have an application that has to deal with getting "special" characters in its URL (like &amp;, +, %, etc). When I'm sending a request to the application using these characters (of course I'm sending them escaped) I'm getting "Bad Request" response code with the message "ASP.NET detected invalid characters in the URL". Tracing the request shown me that the error was thrown from the "Authentication Module".</p> <p>I've searched a bit and found that every page has a ValidateRequest and changing its value to false solves the problem. Unfortunately I'm using Httphandler. Does anyone know how to stop the request validation using http handler?</p>
[ { "answer_id": 287289, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 0, "selected": false, "text": "<httpModules>\n <clear />\n</httpModule>\n <httpModules>\n <add name=\"OutputCache\" type=\"System.Web.Caching.OutputCacheModule\" />\n <add name=\"Session\" type=\"System.Web.SessionState.SessionStateModule\" />\n <add name=\"WindowsAuthentication\" type=\"System.Web.Security.WindowsAuthenticationModule\" />\n <add name=\"FormsAuthentication\" type=\"System.Web.Security.FormsAuthenticationModule\" />\n <add name=\"PassportAuthentication\" type=\"System.Web.Security.PassportAuthenticationModule\" />\n <add name=\"RoleManager\" type=\"System.Web.Security.RoleManagerModule\" />\n <add name=\"UrlAuthorization\" type=\"System.Web.Security.UrlAuthorizationModule\" />\n <add name=\"FileAuthorization\" type=\"System.Web.Security.FileAuthorizationModule\" />\n <add name=\"AnonymousIdentification\" type=\"System.Web.Security.AnonymousIdentificationModule\" />\n <add name=\"Profile\" type=\"System.Web.Profile.ProfileModule\" />\n</httpModules>\n" }, { "answer_id": 300953, "author": "Bryan", "author_id": 22033, "author_profile": "https://Stackoverflow.com/users/22033", "pm_score": 0, "selected": false, "text": "<system.web>\n <pages validateRequest=\"false\">\n </pages>\n</system.web>\n" }, { "answer_id": 486127, "author": "jwanagel", "author_id": 15118, "author_profile": "https://Stackoverflow.com/users/15118", "pm_score": 3, "selected": true, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\ASP.NET\\VerificationCompatibility" }, { "answer_id": 2764683, "author": "Saurabh Maurya", "author_id": 332272, "author_profile": "https://Stackoverflow.com/users/332272", "pm_score": 1, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\ASP.NET\\VerificationCompatibility web.config allowDoubleEscaping requestFiltering true" }, { "answer_id": 3100487, "author": "David Thomas", "author_id": 374078, "author_profile": "https://Stackoverflow.com/users/374078", "pm_score": 2, "selected": false, "text": "<system.web>\n <httpRuntime requestValidationMode=\"2.0\" />\n ...\n <pages ... validateRequest=\"false\" />\n</system.web>\n" }, { "answer_id": 7756694, "author": "dossux", "author_id": 993788, "author_profile": "https://Stackoverflow.com/users/993788", "pm_score": 2, "selected": false, "text": "context.Request.RawUrl context.RewritePath(scrubbedUrl) context.Request.RawUrl context.RewritePath(srubbedUrl) context.Request.Params[]" }, { "answer_id": 48910542, "author": "Jesper", "author_id": 573976, "author_profile": "https://Stackoverflow.com/users/573976", "pm_score": 0, "selected": false, "text": "Unvalidated HttpRequest HttpRequestBase" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37343/" ]
287,077
<p>I need help in</p> <ul> <li>figuring out how to iterate through currently open Excel add-in files <em>(.xla)</em> that have not been registered in Excel using the <code>Tools &gt; Add-ins</code> menu path.</li> <li>more specifically, I am interested in any workbook that doesn't appear in the Add-In dialog, but has <code>ThisWorkbook.IsAddin = True</code>.</li> </ul> <p>Demonstrating the issue:</p> <p>Trying to loop through workbooks as follows doesn't get workbooks with <code>.AddIn = True</code>:</p> <pre><code>Dim book As Excel.Workbook For Each book In Application.Workbooks Debug.Print book.Name Next book </code></pre> <p>Looping through add-ins doesn't get add-ins that are not registered:</p> <pre><code>Dim addin As Excel.AddIn For Each addin In Application.AddIns Debug.Print addin.Name Next addin </code></pre> <p>Looping through the VBProjects collection works, but only if user has specifically trusted access to the Visual Basic Project in the Macro Security settings - which is rarely:</p> <pre><code>Dim vbproj As Object For Each vbproj In Application.VBE.VBProjects Debug.Print vbproj.Filename Next vbproj </code></pre> <p>However, if the name of the workbook is known, the workbook can be referenced directly regardless of whether it is an add-in or not:</p> <pre><code>Dim book As Excel.Workbook Set book = Application.Workbooks("add-in.xla") </code></pre> <p>But how the heck to get reference to this workbook if the name is not known, and user's macro security settings cannot be relied on?</p>
[ { "answer_id": 287383, "author": "jevakallio", "author_id": 4333, "author_profile": "https://Stackoverflow.com/users/4333", "pm_score": 0, "selected": false, "text": "Private Declare Function FindWindowEx Lib \"user32\" Alias \"FindWindowExA\" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long\nPrivate Declare Function GetClassName Lib \"user32\" Alias \"GetClassNameA\" (ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long\nPrivate Declare Function GetWindowText Lib \"user32\" Alias \"GetWindowTextA\" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long\n\nPublic Function GetAllOpenWorkbooks() As Collection\n\n'Retrieves a collection of all open workbooks and add-ins.\n\nConst EXCEL_APPLICATION_WINDOW As String = \"XLDESK\"\nConst EXCEL_WORKBOOK_WINDOW As String = \"EXCEL7\"\n\nDim hWnd As Long\nDim hWndExcel As Long\nDim contentLength As Long\nDim buffer As String\nDim bookName As String\nDim books As Collection\n\nSet books = New Collection\n\n'Find the main Excel window\nhWndExcel = FindWindowEx(Application.hWnd, 0&, EXCEL_APPLICATION_WINDOW, vbNullString)\n\nDo\n\n 'Find next window\n hWnd = FindWindowEx(hWndExcel, hWnd, vbNullString, vbNullString)\n\n If hWnd Then\n\n 'Create a string buffer for 100 chars\n buffer = String$(100, Chr$(0))\n\n 'Get the window class name\n contentLength = GetClassName(hWnd, buffer, 100)\n\n 'If the window found is a workbook window\n If Left$(buffer, contentLength) = EXCEL_WORKBOOK_WINDOW Then\n\n 'Recreate the buffer\n buffer = String$(100, Chr$(0))\n\n 'Get the window text\n contentLength = GetWindowText(hWnd, buffer, 100)\n\n 'If the window text was returned, get the workbook and add it to the collection\n If contentLength Then\n bookName = Left$(buffer, contentLength)\n books.Add Excel.Application.Workbooks(bookName), bookName\n End If\n\n End If\n\n End If\n\nLoop While hWnd\n\n'Return the collection\nSet GetAllOpenWorkbooks = books\n\nEnd Function\n" }, { "answer_id": 320473, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 0, "selected": false, "text": "Public Sub ListAddins()\n\nDim ai As AddIn\n\n For Each ai In Application.AddIns\n If Not ai.Installed Then\n Debug.Print ai.Application, ai.Parent, ai.Name, ai.FullName\n End If\n Next\n\nEnd Sub\n" }, { "answer_id": 325793, "author": "Hobbo", "author_id": 6387, "author_profile": "https://Stackoverflow.com/users/6387", "pm_score": 0, "selected": false, "text": "Dim Docs As Variant\nDocs = Application.Evaluate(\"documents(2)\")\n Type_num Returns\n1 or omitted Names of all open workbooks except add-in workbooks\n2 Names of add-in workbooks only\n3 Names of all open workbooks\n" }, { "answer_id": 362875, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 0, "selected": false, "text": "'Active add-ins are in values called OPEN*\nHKEY_CURRENT_USER\\Software\\Microsoft\\Office\\12.0\\Excel\\Options\n\n'Inactive add-ins are in values of their full path\nHKEY_CURRENT_USER\\Software\\Microsoft\\Office\\12.0\\Excel\\Add-in Manager\n" }, { "answer_id": 14387580, "author": "Chris C.", "author_id": 393423, "author_profile": "https://Stackoverflow.com/users/393423", "pm_score": 5, "selected": true, "text": "Dim a As AddIn\nDim w As Workbook\n\nOn Error Resume Next\nWith Application\n For Each a In .AddIns2\n If LCase(Right(a.name, 4)) = \".xla\" Then\n Set w = Nothing\n Set w = .Workbooks(a.name)\n If w Is Nothing Then\n Set w = .Workbooks.Open(a.FullName)\n End If\n End If\n Next\nEnd With\n" }, { "answer_id": 39607656, "author": "brettdj", "author_id": 641067, "author_profile": "https://Stackoverflow.com/users/641067", "pm_score": 1, "selected": false, "text": "Addin Dim a As AddIn\nDim wb As Workbook\n\nOn Error Resume Next\nWith Application\n .DisplayAlerts = False\n For Each a In .AddIns2\n Debug.Print a.Name, a.Installed\n If LCase(Right$(a.Name, 4)) = \".xla\" Or LCase(Right$(a.Name, 5)) Like \".xla*\" Then\n Set wb = Nothing\n Set wb = .Workbooks(a.Name)\n wb.Close False\n Set wb = .Workbooks.Open(a.FullName)\n End If\n Next\n .DisplayAlerts = True\nEnd With\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4333/" ]
287,085
<p>What exactly do <code>*args</code> and <code>**kwargs</code> mean?</p> <p>According to the Python documentation, from what it seems, it passes in a tuple of arguments.</p> <pre><code>def foo(hello, *args): print(hello) for each in args: print(each) if __name__ == '__main__': foo(&quot;LOVE&quot;, [&quot;lol&quot;, &quot;lololol&quot;]) </code></pre> <p>This prints out:</p> <pre><code>LOVE ['lol', 'lololol'] </code></pre> <p>How do you effectively use them?</p>
[ { "answer_id": 287101, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 9, "selected": true, "text": "*args **kwargs def my_sum(*args):\n return sum(args)\n args kwargs * **" }, { "answer_id": 287293, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 7, "selected": false, "text": "class Super( object ):\n def __init__( self, this, that ):\n self.this = this\n self.that = that\n\nclass Sub( Super ):\n def __init__( self, myStuff, *args, **kw ):\n super( Sub, self ).__init__( *args, **kw )\n self.myStuff= myStuff\n\nx= Super( 2.7, 3.1 )\ny= Sub( \"green\", 7, 6 )\n" }, { "answer_id": 287582, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 6, "selected": false, "text": "*mylist **mydict def foo(a, b, c, d):\n print a, b, c, d\n\nl = [0, 1]\nd = {\"d\":3, \"c\":2}\n\nfoo(*l, **d)\n 0 1 2 3" }, { "answer_id": 287616, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 5, "selected": false, "text": "*args **kwargs import pickle, functools\ndef cache(f):\n _cache = {}\n def wrapper(*args, **kwargs):\n key = pickle.dumps((args, kwargs))\n if key not in _cache:\n _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache\n return _cache[key] # read value from cache\n functools.update_wrapper(wrapper, f) # update wrapper's metadata\n return wrapper\n\nimport time\n@cache\ndef foo(n):\n time.sleep(2)\n return n*2\n\nfoo(10) # first call with parameter 10, sleeps\nfoo(10) # returns immediately\n" }, { "answer_id": 17261859, "author": "Kaushik Ghose", "author_id": 2512851, "author_profile": "https://Stackoverflow.com/users/2512851", "pm_score": 4, "selected": false, "text": "def func(**keyword_args):\n #-->keyword_args is a dictionary\n print 'func:'\n print keyword_args\n if keyword_args.has_key('b'): print keyword_args['b']\n if keyword_args.has_key('c'): print keyword_args['c']\n\ndef func2(*positional_args):\n #-->positional_args is a tuple\n print 'func2:'\n print positional_args\n if len(positional_args) > 1:\n print positional_args[1]\n\ndef func3(*positional_args, **keyword_args):\n #It is an error to switch the order ie. def func3(**keyword_args, *positional_args):\n print 'func3:'\n print positional_args\n print keyword_args\n\nfunc(a='apple',b='banana')\nfunc(c='candle')\nfunc2('apple','banana')#It is an error to do func2(a='apple',b='banana')\nfunc3('apple','banana',a='apple',b='banana')\nfunc3('apple',b='banana')#It is an error to do func3(b='banana','apple')\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34395/" ]
287,089
<p>What number would you give someone who wants a concrete target number for API code coverage?</p> <p>UPDATE: To clarify, statement/line code coverage. I realize concrete numbers don't make much sense, but this is for the situation where you tell people that concrete numbers don't make much sense and they still insist on getting a number from you no matter what. I specifically wrote API/SDK because some people might find lower code coverages more acceptable for application/GUI level software, as opposed to libraries, where more interfaces are exposed.</p>
[ { "answer_id": 287101, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 9, "selected": true, "text": "*args **kwargs def my_sum(*args):\n return sum(args)\n args kwargs * **" }, { "answer_id": 287293, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 7, "selected": false, "text": "class Super( object ):\n def __init__( self, this, that ):\n self.this = this\n self.that = that\n\nclass Sub( Super ):\n def __init__( self, myStuff, *args, **kw ):\n super( Sub, self ).__init__( *args, **kw )\n self.myStuff= myStuff\n\nx= Super( 2.7, 3.1 )\ny= Sub( \"green\", 7, 6 )\n" }, { "answer_id": 287582, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 6, "selected": false, "text": "*mylist **mydict def foo(a, b, c, d):\n print a, b, c, d\n\nl = [0, 1]\nd = {\"d\":3, \"c\":2}\n\nfoo(*l, **d)\n 0 1 2 3" }, { "answer_id": 287616, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 5, "selected": false, "text": "*args **kwargs import pickle, functools\ndef cache(f):\n _cache = {}\n def wrapper(*args, **kwargs):\n key = pickle.dumps((args, kwargs))\n if key not in _cache:\n _cache[key] = f(*args, **kwargs) # call the wrapped function, save in cache\n return _cache[key] # read value from cache\n functools.update_wrapper(wrapper, f) # update wrapper's metadata\n return wrapper\n\nimport time\n@cache\ndef foo(n):\n time.sleep(2)\n return n*2\n\nfoo(10) # first call with parameter 10, sleeps\nfoo(10) # returns immediately\n" }, { "answer_id": 17261859, "author": "Kaushik Ghose", "author_id": 2512851, "author_profile": "https://Stackoverflow.com/users/2512851", "pm_score": 4, "selected": false, "text": "def func(**keyword_args):\n #-->keyword_args is a dictionary\n print 'func:'\n print keyword_args\n if keyword_args.has_key('b'): print keyword_args['b']\n if keyword_args.has_key('c'): print keyword_args['c']\n\ndef func2(*positional_args):\n #-->positional_args is a tuple\n print 'func2:'\n print positional_args\n if len(positional_args) > 1:\n print positional_args[1]\n\ndef func3(*positional_args, **keyword_args):\n #It is an error to switch the order ie. def func3(**keyword_args, *positional_args):\n print 'func3:'\n print positional_args\n print keyword_args\n\nfunc(a='apple',b='banana')\nfunc(c='candle')\nfunc2('apple','banana')#It is an error to do func2(a='apple',b='banana')\nfunc3('apple','banana',a='apple',b='banana')\nfunc3('apple',b='banana')#It is an error to do func3(b='banana','apple')\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36727/" ]
287,093
<p>I am building an application that is very similar to a shopping cart. The user selects a product from a list, and then based on that product, a few properties need to be set and saved.</p> <p>Example.</p> <p>If the user selects a type of paint that allows custom color matches, then I must allow them to enter in a formula number that they received through a color match process. So I have an Order Detail item for a Product that is a type of Paint, and that sku has the attribute of "AllowsCustomColorMatch", but I need to store the Formula Number somewhere also.</p> <p>I'm not sure how to handle this elegantly throughout my code. Should I be creating subclasses or products? Right now I'm saving the data the user enters in an OrderDetails object that has a reference to the Product it is associated with.</p>
[ { "answer_id": 287120, "author": "Bruno Shine", "author_id": 28294, "author_profile": "https://Stackoverflow.com/users/28294", "pm_score": 4, "selected": true, "text": " public class Product\n {\n private Dictionary<string, string> properties;\n\n /// <summary>\n /// Gets or sets the name.\n /// </summary>\n /// <value>The name.</value>\n public string Name\n {\n get;\n set;\n }\n\n /// <summary>\n /// Gets or sets the price.\n /// </summary>\n /// <value>The price.</value>\n public double Price\n {\n get;\n set;\n }\n\n public Dictionary<string, string> Properties\n {\n get;\n }\n\n public Product()\n {\n properties = new Dictionary<string, string>();\n }\n\n }\n" }, { "answer_id": 327094, "author": "Matt R", "author_id": 4298, "author_profile": "https://Stackoverflow.com/users/4298", "pm_score": 0, "selected": false, "text": "public class Paint {\nprivate decimal _price;\nprivate bool _allowFormula;\n\npublic Paint() { ... }\npublic Paint(int price) {\n _price = price;\n}\npublic ChangePrice(decimal p) {\n _price = p;\n }\n}\n public class PaintSpecialize : Paint {\nstring _formula;\n[...]\npublic PaintSpecialize(int price, string formula) : base(price) {\n _formula=formula;\n}\n PaintSpecialize ps = new PaintSpecialize(15.00, \"FormulaXXYY\");\nps.ChangePrice(12.00);\nList<Paint> plist = new List<Paint>();\nplist.Add((Paint)ps);\nforeach(Paint p in plist) {\nif(p.AllowFormula) {\n PaintSpecialize tmp = (PaintSpecialize)p;\n MessageBox.Show(tmp._formula);\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37347/" ]
287,097
<p>This is a question not really about "programming" (is not specific to any language or database), but more of design and architecture. It's also a question of the type "What the best way to do X". I hope does no cause to much "religious" controversy.</p> <p>In the past I have developed systems that in one way or another, keep some form of inventory of items (not relevant what items). Some using languages/DB's that do not support transactions. In those cases I opted not to save item <em>quantity on hand</em> in a field in the item record. Instead the <em>quantity on hand</em> is calculated totaling inventory received - total of inventory sold. This has resulted in almost no discrepancies in inventory because of software. The tables are properly indexed and the performance is good. There is a archiving process in case the amount of record start to affect performance.</p> <p>Now, few years ago I started working in this company, and I inherited a system that tracks inventory. But the quantity is saved in a field. When an entry is registered, the quantity received is added to the quantity field for the item. When an item is sold, the quantity is subtracted. This has resulted in discrepancies. In my opinion this is not the right approach, but the previous programmers here swear by it.</p> <p>I would like to know if there is a consensus on what's the right way is to design such system. Also what resources are available, printed or online, to seek guidance on this.</p> <p>Thanks</p>
[ { "answer_id": 287276, "author": "nmarmol", "author_id": 20448, "author_profile": "https://Stackoverflow.com/users/20448", "pm_score": 0, "selected": false, "text": "Select sum(quantity) as inventory_received from Inventory_entry\nSelect sum(quantity) as inventory_sold from Sales_items\n Qunatity_on_hand = inventory_received - inventory_sold\n" }, { "answer_id": 287321, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "inventory_received\ninventory_sold\nestimated_on_hand\n SELECT * \nFROM Inventory\nWHERE estimated_on_hand != inventory_received - inventory_sold\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20448/" ]
287,105
<p>I'm looking to find records in a table that match a specific number that the user enters. So, the user may enter 12345, but this could be 123zz4-5 in the database.</p> <p>I imagine something like this would work, if PHP functions worked in MySQL.</p> <pre><code>SELECT * FROM foo WHERE preg_replace(&quot;/[^0-9]/&quot;,&quot;&quot;,bar) = '12345' </code></pre> <p>What's the equivalent function or way to do this with just MySQL?</p> <p><em>Speed is not important.</em></p>
[ { "answer_id": 287153, "author": "Gareth", "author_id": 31582, "author_profile": "https://Stackoverflow.com/users/31582", "pm_score": 2, "selected": false, "text": "WHERE foo LIKE '1\\D*2\\D*3\\D*4\\D*5'\n preg_replace" }, { "answer_id": 287225, "author": "Chris Bartow", "author_id": 497, "author_profile": "https://Stackoverflow.com/users/497", "pm_score": 4, "selected": true, "text": "SELECT * FROM foo WHERE bar LIKE = '%1%2%3%4%5%'\n" }, { "answer_id": 287251, "author": "Nelson Miranda", "author_id": 1130097, "author_profile": "https://Stackoverflow.com/users/1130097", "pm_score": 2, "selected": false, "text": "--Create a table with numbers\nDROP TABLE IF EXISTS ints;\nCREATE TABLE ints (i INT UNSIGNED NOT NULL PRIMARY KEY);\n\nINSERT INTO ints (i) VALUES\n( 1), ( 2), ( 3), ( 4), ( 5), ( 6), ( 7), ( 8), ( 9), (10),\n(11), (12), (13), (14), (15), (16), (17), (18), (19), (20);\n\n--Then extract the numbers from the specified column\nSELECT\n bar,\n GROUP_CONCAT(SUBSTRING(bar, i, 1) ORDER BY i SEPARATOR '')\nFROM foo\nJOIN ints ON i BETWEEN 1 AND LENGTH(bar)\nWHERE\n SUBSTRING(bar, i, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')\nGROUP BY bar;\n" }, { "answer_id": 287325, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "SELECT * FROM foo WHERE bar REGEXP '[^0-9]*1[^0-9]*2[^0-9]*3[^0-9]*4[^0-9]*5[^0-9]*';\n" }, { "answer_id": 9508722, "author": "Jeremy Warne", "author_id": 299589, "author_profile": "https://Stackoverflow.com/users/299589", "pm_score": 2, "selected": false, "text": "SELECT NumericOnly(\"asdf11asf\"); 11" }, { "answer_id": 12057337, "author": "user1467716", "author_id": 1467716, "author_profile": "https://Stackoverflow.com/users/1467716", "pm_score": 6, "selected": false, "text": "DROP FUNCTION IF EXISTS STRIP_NON_DIGIT;\nDELIMITER $$\nCREATE FUNCTION STRIP_NON_DIGIT(input VARCHAR(255))\n RETURNS VARCHAR(255)\nBEGIN\n DECLARE output VARCHAR(255) DEFAULT '';\n DECLARE iterator INT DEFAULT 1;\n WHILE iterator < (LENGTH(input) + 1) DO\n IF SUBSTRING(input, iterator, 1) IN ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ) THEN\n SET output = CONCAT(output, SUBSTRING(input, iterator, 1));\n END IF;\n SET iterator = iterator + 1;\n END WHILE;\n RETURN output;\nEND\n$$\n" }, { "answer_id": 27307636, "author": "modle13", "author_id": 1028844, "author_profile": "https://Stackoverflow.com/users/1028844", "pm_score": 1, "selected": false, "text": "DECLARE count INT DEFAULT 0; AND count < 5 WHILE SET COUNT=COUNT+1; IF DROP FUNCTION IF EXISTS STRIP_NON_DIGIT;\nDELIMITER $$\nCREATE FUNCTION STRIP_NON_DIGIT(input VARCHAR(255))\n RETURNS VARCHAR(255)\nBEGIN\n DECLARE output VARCHAR(255) DEFAULT '';\n DECLARE iterator INT DEFAULT 1;\n DECLARE count INT DEFAULT 0;\n WHILE iterator < (LENGTH(input) + 1) AND count < 5 DO --limits to 5 chars\n IF SUBSTRING(input, iterator, 1) IN ( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ) THEN\n SET output = CONCAT(output, SUBSTRING(input, iterator, 1));\n SET COUNT=COUNT+1;\n END IF;\n SET iterator = iterator + 1;\n END WHILE;\n RETURN output;\nEND\n$$\nDELIMITER $$ --added this\n" }, { "answer_id": 35924262, "author": "wally", "author_id": 817132, "author_profile": "https://Stackoverflow.com/users/817132", "pm_score": 5, "selected": false, "text": "REGEX_REPLACE DELIMITER ;;\nDROP FUNCTION IF EXISTS `STRIP_NON_DIGIT`;;\n\nCREATE DEFINER=`root`@`localhost` FUNCTION `STRIP_NON_DIGIT`(input VARCHAR(255)) RETURNS VARCHAR(255) CHARSET utf8\nREADS SQL DATA\nBEGIN\n DECLARE output VARCHAR(255) DEFAULT '';\n DECLARE iterator INT DEFAULT 1;\n DECLARE lastDigit INT DEFAULT 1;\n DECLARE len INT;\n \n SET len = LENGTH(input) + 1;\n WHILE iterator < len DO\n -- skip past all digits\n SET lastDigit = iterator;\n WHILE ORD(SUBSTRING(input, iterator, 1)) BETWEEN 48 AND 57 AND iterator < len DO\n SET iterator = iterator + 1;\n END WHILE;\n\n IF iterator != lastDigit THEN\n SET output = CONCAT(output, SUBSTRING(input, lastDigit, iterator - lastDigit));\n END IF;\n\n WHILE ORD(SUBSTRING(input, iterator, 1)) NOT BETWEEN 48 AND 57 AND iterator < len DO\n SET iterator = iterator + 1;\n END WHILE;\n END WHILE;\n \n RETURN output;\nEND;;\n -- original\nExecution Time : 7.389 sec\nExecution Time : 7.257 sec\nExecution Time : 7.506 sec\n\n-- ORD between not string IN\nExecution Time : 4.031 sec\n\n-- With less substrings\nExecution Time : 3.243 sec\nExecution Time : 3.415 sec\nExecution Time : 2.848 sec\n" }, { "answer_id": 45475521, "author": "Hugo R", "author_id": 7771019, "author_profile": "https://Stackoverflow.com/users/7771019", "pm_score": 0, "selected": false, "text": " -- function removes non numberic characters from input\n-- returne only the numbers in the string\n\nCREATE DEFINER =`root`@`localhost` FUNCTION `remove_alpha`(inputPhoneNumber VARCHAR(50))\n RETURNS VARCHAR(50)\n CHARSET latin1\nDETERMINISTIC\n BEGIN\n\n\n DECLARE inputLenght INT DEFAULT 0;\n -- var for our iteration \n DECLARE counter INT DEFAULT 1;\n -- if null is passed, we still return an tempty string\n DECLARE sanitizedText VARCHAR(50) DEFAULT '';\n -- holder of each character during the iteration\n DECLARE oneChar VARCHAR(1) DEFAULT '';\n\n\n -- we'll process only if it is not null.\n IF NOT ISNULL(inputPhoneNumber)\n THEN\n SET inputLenght = LENGTH(inputPhoneNumber);\n WHILE counter <= inputLenght DO\n SET oneChar = SUBSTRING(inputPhoneNumber, counter, 1);\n IF (oneChar REGEXP ('^[0-9]+$'))\n THEN\n SET sanitizedText = Concat(sanitizedText, oneChar);\n END IF;\n\n SET counter = counter + 1;\n END WHILE;\n END IF;\n\n RETURN sanitizedText;\n END\n col1\n(513)983-3983\n1-838-338-9898\nphone983-889-8383\n select remove_alpha(col1) from mytable\n 5139833983\n18383389898\n9838898383\n" }, { "answer_id": 50176912, "author": "Marlom", "author_id": 6877699, "author_profile": "https://Stackoverflow.com/users/6877699", "pm_score": 5, "selected": false, "text": "REGEXP_REPLACE REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]]) SELECT REGEXP_REPLACE('123asd12333', '[a-zA-Z]+', '');\n 12312333\n" }, { "answer_id": 54896511, "author": "user11122383", "author_id": 11122383, "author_profile": "https://Stackoverflow.com/users/11122383", "pm_score": 0, "selected": false, "text": "drop procedure if exists strip_non_numeric_characters;\nDELIMITER ;;\n\nCREATE PROCEDURE `strip_non_numeric_characters`(\n tablename varchar(100)\n ,columnname varchar(100)\n )\nBEGIN\n\n-- =============================================\n-- Author: <Author,,David Melton>\n-- Create date: <Create Date,,2/26/2019>\n-- Description: <Description,,loops through data and strips out the bad characters in whatever table and column you pass it>\n-- =============================================\n\n#this idea was generated from the idea STRIP_NON_DIGIT function\n#https://stackoverflow.com/questions/287105/mysql-strip-non-numeric-characters-to-compare\n\ndeclare input,output varchar(255);\ndeclare iterator,lastDigit,len,counter int;\ndeclare date_updated varchar(100);\n\nselect column_name \n into date_updated\n from information_schema.columns \n where table_schema = database() \n and extra rlike 'on update CURRENT_TIMESTAMP'\n and table_name = tablename\n limit 1;\n\n#only goes up to 255 so people don't run this for a longtext field\n#just to be careful, i've excluded columns that are part of keys, that could potentially mess something else up\nset @find_column_length = \nconcat(\"select character_maximum_length\n into @len\n from information_schema.columns\n where table_schema = '\",database(),\"'\n and column_name = '\",columnname,\"'\n and table_name = '\",tablename,\"'\n and length(ifnull(character_maximum_length,100)) < 255\n and data_type in ('char','varchar')\n and column_key = '';\");\n\nprepare stmt from @find_column_length;\nexecute stmt;\ndeallocate prepare stmt;\n\nset counter = 1; \nset len = @len;\n\nwhile counter <= ifnull(len,1) DO\n\n #this just removes it by putting all the characters before and after the character i'm looking at\n #you have to start at the end of the field otherwise the lengths don't stay in order and you have to run it multiple times\n set @update_query = \n concat(\"update `\",tablename,\"`\n set `\",columnname,\"` = concat(substring(`\",columnname,\"`,1,\",len - counter,\"),SUBSTRING(`\",columnname,\"`,\",len - counter,\",\",counter - 1,\"))\n \",if(date_updated is not null,concat(\",`\",date_updated,\"` = `\",date_updated,\"`\n \"),''),\n \"where SUBSTRING(`\",columnname,\"`,\",len - counter,\", 1) not REGEXP '^[0-9]+$';\");\n\n prepare stmt from @update_query;\n execute stmt;\n deallocate prepare stmt;\n\n set counter = counter + 1;\n\nend while;\n\nEND ;;\nDELIMITER ;\n" }, { "answer_id": 56978493, "author": "Icaro Mota", "author_id": 8500958, "author_profile": "https://Stackoverflow.com/users/8500958", "pm_score": 3, "selected": false, "text": "SELECT * FROM foo WHERE REGEXP_REPLACE(bar,'[^0-9]+',\"\") = '12345'\n" }, { "answer_id": 59852090, "author": "Dr. Tom Kahigu", "author_id": 12758522, "author_profile": "https://Stackoverflow.com/users/12758522", "pm_score": 0, "selected": false, "text": "SELECT * \nFROM foo \nWHERE Convert(Regexp_replace(bar, '[a-zA-Z]+', ''), signed) = 12345 \n" }, { "answer_id": 73303363, "author": "winwin", "author_id": 13438431, "author_profile": "https://Stackoverflow.com/users/13438431", "pm_score": 0, "selected": false, "text": "REGEXP_REPLACE mysql [:alnum:] [:alpha:] REGEXP_REPLACE REGEXP_REPLACE('My number is: +59 (29) 889-23-56', '[[:alpha:][:blank:][:punct:][:cntrl:]]', '')\n 59298892356" }, { "answer_id": 74308401, "author": "Parley Hammon", "author_id": 7460995, "author_profile": "https://Stackoverflow.com/users/7460995", "pm_score": 0, "selected": false, "text": "DROP TABLE IF EXISTS ints;\nCREATE TABLE ints (i INT UNSIGNED NOT NULL PRIMARY KEY);\n \nINSERT INTO ints (i) VALUES\n( 1), ( 2), ( 3), ( 4), ( 5), ( 6), ( 7), ( 8), ( 9), (10),\n(11), (12), (13), (14), (15), (16), (17), (18), (19), (20);\n \nSELECT * FROM foo f \nWHERE (SELECT GROUP_CONCAT(SUBSTRING(f.bar, i, 1) ORDER BY i SEPARATOR '') \n FROM ints \n WHERE i BETWEEN 1 AND LENGTH(f.bar) \n AND SUBSTRING(f.bar, i, 1) IN ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')) = '12345'\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497/" ]
287,106
<p>I am using LINQ-to-SQL for an application that queries a legacy database. I need to call a stored procedure, that selects a single integer value. Changing the stored procedure is not an option.</p> <p>The designer creates a method with this signature:</p> <pre><code>private ISingleResult&lt;sp_xal_seqnoResult&gt; NextRowNumber([Parameter(DbType="Int")] System.Nullable&lt;int&gt; increment, [Parameter(DbType="Char(3)")] string dataset) </code></pre> <p>I would like the return type to be int. How do I do this using LINQ-to-SQL ? </p>
[ { "answer_id": 287129, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "<Function Name=\"dbo.foo\" Method=\"foo\">\n <Parameter Name=\"inc\" Type=\"System.Int32\" DbType=\"Int\" />\n <Parameter Name=\"dataset\" Type=\"System.String\" DbType=\"VarChar(20)\" />\n <Return Type=\"System.Int32\" />\n</Function>\n [Function(Name=\"dbo.foo\")]\npublic int foo([Parameter(DbType=\"Int\")] System.Nullable<int> inc, [Parameter(DbType=\"VarChar(20)\")] string dataset)\n{\n IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset);\n return ((int)(result.ReturnValue));\n}\n <Function Name=\"dbo.foo\" Method=\"FooPrivate\" AccessModifier=\"Private\">\n <Parameter Name=\"inc\" Type=\"System.Int32\" DbType=\"Int\" />\n <Parameter Name=\"dataset\" Type=\"System.String\" DbType=\"VarChar(20)\" />\n <ElementType Name=\"fooResult\" AccessModifier=\"Internal\">\n <Column Name=\"value\" Type=\"System.Int32\" DbType=\"Int NOT NULL\" CanBeNull=\"false\" />\n </ElementType>\n</Function>\n [Function(Name=\"dbo.foo\")]\nprivate ISingleResult<fooResult> FooPrivate(\n [Parameter(DbType=\"Int\")] System.Nullable<int> inc,\n [Parameter(DbType=\"VarChar(20)\")] string dataset)\n{\n IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), inc, dataset);\n return ((ISingleResult<fooResult>)(result.ReturnValue));\n}\n namespace MyNamespace {\n partial class MyDataContext\n {\n public int Foo(int? inc, string dataSet)\n {\n return FooPrivate(inc, dataSet).Single().value;\n }\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13627/" ]
287,126
<p>I have the SOAP request in an XML file. I want to post the request to the web service in .net How to implement?</p>
[ { "answer_id": 287189, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "var uri = new Uri(\"http://localhost/SOAP/SOAPSMS.asmx/add\");\n\nvar req = (HttpWebRequest) WebRequest.CreateDefault(uri); \nreq.ContentType = \"text/xml; charset=utf-8\"; \nreq.Method = \"POST\"; \nreq.Accept = \"text/xml\"; \nreq.Headers.Add(\"SOAPAction\", \"http://localhost/SOAP/SOAPSMS.asmx/add\"); \n\nvar strSoapMessage = @\"<?xml version='1.0' encoding='utf-8'?>\n<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' \n xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \n xmlns:xsd='http://www.w3.org/2001/XMLSchema'>\n <soap:Body><add xmlns='http://tempuri.org/'><a>23</a><b>5</b></soap:Body>\n</soap:Envelope>\"; \n\nusing (var stream = new StreamWriter(req.GetRequestStream(), Encoding.UTF8)) \n stream.Write(strSoapMessage); \n" }, { "answer_id": 287207, "author": "marcus.greasly", "author_id": 28200, "author_profile": "https://Stackoverflow.com/users/28200", "pm_score": 3, "selected": false, "text": "string data = \"the xml document to submit\";\nstring url = \"the webservice url\";\nstring response = \"the response from the server\";\n\n// build request objects to pass the data/xml to the server\nbyte[] buffer = Encoding.ASCII.GetBytes(data);\nHttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;\nrequest.Method = \"POST\";\nrequest.ContentType = \"application/x-www-form-urlencoded\";\nrequest.ContentLength = buffer.Length;\nStream post = request.GetRequestStream();\n\n// post data and close connection\npost.Write(buffer, 0, buffer.Length);\npost.Close();\n\n// build response object\nHttpWebResponse response = request.GetResponse() as HttpWebResponse;\nStream responsedata = response.GetResponseStream();\nStreamReader responsereader = new StreamReader(responsedata);\nresponse = responsereader.ReadToEnd();\n" }, { "answer_id": 441916, "author": "jeffspost", "author_id": 362693, "author_profile": "https://Stackoverflow.com/users/362693", "pm_score": 2, "selected": false, "text": " Dim manualWebClient As New System.Net.WebClient()\n\n manualWebClient.Headers.Add(\"Content-Type\", \"application/soap+xml; charset=utf-8\")\n\n ' Note: don't put the <?xml... tag in--otherwise it will blow up with a 500 internal error message!\n Dim bytArguments As Byte() = System.Text.Encoding.ASCII.GetBytes( _\n \"<soap12:Envelope xmlns:xsi=\"\"http://www.w3.org/2001/XMLSchema-instance\"\" xmlns:xsd=\"\"http://www.w3.org/2001/XMLSchema\"\" xmlns:soap12=\"\"http://www.w3.org/2003/05/soap-envelope\"\">\" & System.Environment.NewLine & _\n \" <soap12:Body>\" & System.Environment.NewLine & _\n \" <Multiply xmlns=\"\"http://cptr446.class/\"\">\" & System.Environment.NewLine & _\n \" <x>5</x>\" & System.Environment.NewLine & _\n \" <y>4</y>\" & System.Environment.NewLine & _\n \" </Multiply>\" & System.Environment.NewLine & _\n \" </soap12:Body>\" & System.Environment.NewLine & _\n \"</soap12:Envelope>\")\n Dim bytRetData As Byte() = manualWebClient.UploadData(\"http://localhost/CPTR446.asmx\", \"POST\", bytArguments)\n\n MessageBox.Show(System.Text.Encoding.ASCII.GetString(bytRetData))\n" }, { "answer_id": 5115716, "author": "bgs264", "author_id": 270392, "author_profile": "https://Stackoverflow.com/users/270392", "pm_score": 1, "selected": false, "text": "''' <summary>\n''' Sends SOAP to a web service and sends back the XML it got back.\n''' </summary>\nPublic Class SoapDispenser\n Public Shared Function CallWebService(ByVal WebserviceURL As String, ByVal SOAP As String) As XmlDocument\n Using wc As New WebClient()\n Dim retXMLDoc As New XmlDocument()\n\n wc.Headers.Add(\"Content-Type\", \"application/soap+xml; charset=utf-8\")\n retXMLDoc.LoadXml(wc.UploadString(WebserviceURL, SOAP))\n\n Return retXMLDoc\n End Using\n End Function\nEnd Class\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
287,133
<p>Using Lucene, one can retrieve the terms contained within in an index, i.e. the unique, stemmed words, excluding stop-words, that documents in the index contain. This is useful for generating autocomplete suggestions amongst other things. Is something similar possible with MS SQL Server full text indices?</p>
[ { "answer_id": 337013, "author": "Coolcoder", "author_id": 42434, "author_profile": "https://Stackoverflow.com/users/42434", "pm_score": 5, "selected": true, "text": "sys.dm_fts_index_keywords_by_document\n( \n DB_ID('database_name'), \n OBJECT_ID('table_name') \n)\n db_id object_id" }, { "answer_id": 1773521, "author": "Newfave", "author_id": 193908, "author_profile": "https://Stackoverflow.com/users/193908", "pm_score": 3, "selected": false, "text": "SELECT * FROM sys.dm_fts_parser (' \"The Microsoft business analysis\" ', 1033, 0, 0)\n" }, { "answer_id": 17575433, "author": "toto", "author_id": 2569320, "author_profile": "https://Stackoverflow.com/users/2569320", "pm_score": 0, "selected": false, "text": "sys.dm_fts_index_keywords sys.fulltext_stopwords" }, { "answer_id": 25898699, "author": "tic", "author_id": 1898688, "author_profile": "https://Stackoverflow.com/users/1898688", "pm_score": 1, "selected": false, "text": "DECLARE @TableName NVARCHAR(200) = 'MyTable'\nDECLARE @ColumnName NVARCHAR(200) = 'MyColumn'\n\nSELECT DISTINCT(display_term), occurrence_count FROM sys.dm_fts_index_keywords_by_document\n( \n DB_ID(), \n OBJECT_ID(@TableName) \n)\nWHERE column_id =\n(\n SELECT TOP 1 col.column_id FROM sys.objects obj\n INNER JOIN sys.columns col ON col.object_id = obj.object_id\n WHERE obj.name = @TableName\n AND col.name = @ColumnName\n)\nAND keyword != 0xFF\nORDER BY occurrence_count DESC\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2942/" ]
287,142
<p>From time to time my applications GUI stops redrawing. There a lot of threads that are firing all kinds of events (like timers or network data ready etc.). Also there are a lot of controls that are subscribing these events. Because of that, all the event handlers play the InvokeRequired/Invoke game. Now I figured out that when the GUI freezes a lot of threads are waiting for Invoke() to return. Looks like the message pump stopped pumping. The handlers look like this:</p> <pre><code>private void MyEventHandler( object sender, EventArgs e ) { if ( InvokeRequired ) { Invoke( new EventHandler( MyEventHandler ), sender, e ); return; } SetSomeStateVariable(); Invalidate(); } </code></pre> <p>Any ideas?</p> <p>Solution: BeginInvoke(). Looks like you should always use BeginInvoke() if you have lots of CrossThread-Events...</p> <p>Thanks.</p> <p>Thanks everybody.</p> <p><strong>EDIT:</strong> Looks like <code>BeginInvoke()</code> really solved it. No freezing until now.</p>
[ { "answer_id": 287149, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "Invoke((EventHandler) MyEventHandler, sender, e);\n" }, { "answer_id": 287258, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "ThreadPool.SetMaxThreads(...)" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8976/" ]
287,144
<p>I have a load of user-submitted content. It is HTML, and may contain URLs. Some of them will be <code>&lt;a&gt;</code>'s already (if the user is good) but sometimes users are lazy and just type www.something.com or at best <a href="http://www.something.com" rel="noreferrer">http://www.something.com</a>.</p> <p>I can't find a decent regex to capture URLs but ignore ones that are immediately to the right of either a double quote or '>'. Anyone got one?</p>
[ { "answer_id": 287186, "author": "Tim Pietzcker", "author_id": 20670, "author_profile": "https://Stackoverflow.com/users/20670", "pm_score": 4, "selected": false, "text": "\\b(?:(?:https?|ftp|file)://|www\\.|ftp\\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]\n (?<![\">]) (?<![\">])\\b(?:(?:https?|ftp|file)://|www\\.|ftp\\.)[-A-Z0-9+&@#/%=~_|$?!:,.]*[A-Z0-9+&@#/%=~_|$]\n" }, { "answer_id": 287473, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "\"http://\" \"ftp://\" \"mailto:\" (href\\s*=\\s*['\"]?)?((?:http://|ftp://|mailto:)?[^.,<>\"'\\s\\r\\n\\t]+(?:\\.(?![.<>\"'\\s\\r\\n])[^.,!<>\"'\\s\\r\\n\\t]+)+)\n 'href=\"' <a> <a>" }, { "answer_id": 2328010, "author": "Nicole", "author_id": 143295, "author_profile": "https://Stackoverflow.com/users/143295", "pm_score": 1, "selected": false, "text": "(?<!href=\") /(?<!href=\")http://\\S*/\n" }, { "answer_id": 2951276, "author": "Hodge", "author_id": 355594, "author_profile": "https://Stackoverflow.com/users/355594", "pm_score": 4, "selected": false, "text": "(?<![.*\">])\\b(?:(?:https?|ftp|file)://|[a-z]\\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]\n $convertedText = preg_replace( '@(?<![.*\">])\\b(?:(?:https?|ftp|file)://|[a-z]\\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]@i', '<a href=\"\\0\" target=\"_blank\">\\0</a>', $originalText );\n" }, { "answer_id": 10500178, "author": "Matt", "author_id": 443862, "author_profile": "https://Stackoverflow.com/users/443862", "pm_score": 4, "selected": false, "text": "(?!(?!.*?<a)[^<]*<\\/a>)(?:(?:https?|ftp|file)://|www\\.|ftp\\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]\n http://www.google.com\nhttp://google.com\nwww.google.com\n\n<p>http://www.google.com<p>\n\nthis is a normal sentence. let's hope it's ok.\n\n<a href=\"http://www.google.com\">www.google.com</a>\n <a href=\"http://www.google.com\" rel=\"nofollow\">http://www.google.com</a>\n<a href=\"http://google.com\" rel=\"nofollow\">http://google.com</a>\n<a href=\"www.google.com\" rel=\"nofollow\">www.google.com</a>\n\n<p><a href=\"http://www.google.com\" rel=\"nofollow\">http://www.google.com</a><p>\n\nthis is a normal sentence. let's hope it's ok.\n\n<a href=\"http://www.google.com\">www.google.com</a>\n" }, { "answer_id": 11147156, "author": "RUX", "author_id": 1473407, "author_profile": "https://Stackoverflow.com/users/1473407", "pm_score": 1, "selected": false, "text": "if (preg_match('/\\b(?<!=\")(https?|ftp|file):\\/\\/[-A-Z0-9+&@#\\/%?=~_|!:,.;]*[A-Z0-9+&@#\\/%=~_|](?!.*\".*>)(?!.*<\\/a>)/i', $subject)) {\n # Successful match\n} else {\n # Match attempt failed\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37313/" ]
287,178
<p>Say a class </p> <pre><code>Person +Name: string +Contacts: List&lt;Person&gt; </code></pre> <p>I want to be able to check if a person has a contact with a certain name without having to create a dummy Person instance.</p> <pre><code>person.Contacts.Contains&lt;string&gt;("aPersonName"); </code></pre> <p>This should check all persons in the Contacts list if their Name.Equals("aPersonName"); I see that there is a Contains already available, but I don't know where I should implement it's logic.</p>
[ { "answer_id": 287190, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": " return person.Contacts.Any(person => person.Name==\"aPersonName\");\n return person.Select(person => person.Name).Contains(\"aPersonName\");\n" }, { "answer_id": 287197, "author": "configurator", "author_id": 9536, "author_profile": "https://Stackoverflow.com/users/9536", "pm_score": 0, "selected": false, "text": "public static bool Contains(this IList<Person> list, string name) {\n return list.Any(c => c.Name == name);\n}\n" }, { "answer_id": 287200, "author": "Sekhat", "author_id": 1610, "author_profile": "https://Stackoverflow.com/users/1610", "pm_score": 2, "selected": false, "text": "bool hasContact = person.Contacts.Exists(p => p.Name == \"aPersonName\");\n bool hasContact = person.Contacts.Exists(delegate(Person p){ return p.Name == \"aPersonName\"; });\n" }, { "answer_id": 287209, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "Any List<T>.Find List<T>.Exists Find Exists // C# 2.0\nbool knowsFred = person.Contacts.Find(delegate(Person x) { return x.Name == \"Fred\"; }) != null;\n// C# 3.0\nbool knowsFred = person.Contacts.Find(x => x.Name == \"Fred\") != null;\n" }, { "answer_id": 287228, "author": "Ricardo Villamil", "author_id": 19314, "author_profile": "https://Stackoverflow.com/users/19314", "pm_score": 0, "selected": false, "text": "public static class ContactListExtensions\n{\n public static bool Contains<T>(this List<Person> contacts, string aPersonName)\n {\n //Then use any of the already suggested solutions like:\n return contacts.Contains(c => c.Name == aPersonName);\n }\n} \n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
287,187
<p>I want to extend a CFC in a different directory and I have a couple of options, but can't figure out how to do this:</p> <p>A) Use a dynamic mapping (this will have to be dynamic based on the site, e.g. for the live site it would be cfc.myPackage.MyCFC but on a dev site it would be myCfcRoot.myPackage.MyCFC) - I've tried putting expressions into the extends bit but obviously CF doesn't like that, e.g. :</p> <pre><code>&lt;cfcomponent name="MyComponent" extends="#config.cfcRoot#.BaseComponent"&gt; </code></pre> <p>or</p> <pre><code>&lt;cfcomponent name="MyComponent" extends="#GetRealPath(../BaseComponent.cfc)#"&gt; </code></pre> <p>B) Provide a relative path (somehow) to the CFC to extend.</p> <p>I fear that I can't do this, but I'm hoping that there is something I've missed.</p>
[ { "answer_id": 287357, "author": "Nathan Strutz", "author_id": 5918, "author_profile": "https://Stackoverflow.com/users/5918", "pm_score": 5, "selected": true, "text": "<cfcomponent name=\"MyComponent\" extends=\"Example\">\n <cfcomponent name=\"MyComponent\" extends=\"subdirectory.Example\"> \n <cfset this.mappings[\"/MyApp\"] = expandPath(\".\") />\n wwwroot\\MyApp\\com\\MyApp\\example.cfc\n MyApp.com.MyApp.Example\n <cfcomponent name=\"MyComponent\" extends=\"MyApp.com.MyApp.Example\">\n" }, { "answer_id": 300292, "author": "rip747", "author_id": 31278, "author_profile": "https://Stackoverflow.com/users/31278", "pm_score": 2, "selected": false, "text": "<cfcomponent output=\"false\" extends=\"/.application\">\n <!--- whatever code you have --->\n</cfcomponent>\n [webroot]/1/1a\n[webroot]/2\n <cfcomponent output=\"false\" extends=\"/./1/1a/application\">\n <!--- whatever code you have --->\n</cfcomponent>\n" }, { "answer_id": 11344269, "author": "nosilleg", "author_id": 238592, "author_profile": "https://Stackoverflow.com/users/238592", "pm_score": 0, "selected": false, "text": "cffunction extends=\"basecomponent_extend\" cfinclude <cfinclude template=\"/somepathtobasecomponent/basecomponent.cfc\">\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6432/" ]
287,188
<p>I have a table style page with rows. Each row has a checkbox. I can select all/many checkboxes and click "submit" and what is does is a Jquery ajax call for each row. </p> <p>Basically I have a form for each row and I iterate over all the checked rows and submit that form which does the jquery ajax call.</p> <p>So I have a button that does:</p> <pre><code> $("input:checked").parent("form").submit(); </code></pre> <p>Then each row has:</p> <pre><code> &lt;form name="MyForm&lt;%=i%&gt;" action="javascript:processRow(&lt;%=i%&gt;)" method="post" style="margin:0px;"&gt; &lt;input type="checkbox" name="X" value="XChecked"/&gt; &lt;input type="hidden" id="XNumber&lt;%=i%&gt;" name="X&lt;%=i%&gt;" value="&lt;%=XNumber%&gt;"/&gt; &lt;input type="hidden" id="XId&lt;%=i%&gt;" name="XId&lt;%=i%&gt;" value="&lt;%=XNumber%&gt;"/&gt; &lt;input type="hidden" id="XAmt&lt;%=i%&gt;" name="XAmt&lt;%=i%&gt;" value="&lt;%=XAmount%&gt;"/&gt; &lt;input type="hidden" name="X" value="rXChecked"/&gt; &lt;/form&gt; </code></pre> <p>This form submits to processRow:</p> <pre><code> function processRow(rowNum) { var Amount = $('#XAmt'+rowNum).val(); var XId = $('#XId'+rowNum).val(); var XNum = $('#OrderNumber'+rowNum).val(); var queryString = "xAmt=" + "1.00" + "&amp;xNumber=" + OrdNum + "&amp;xId=" + xId; $('#coda_'+rowNum).removeClass("loader"); $('#coda_'+rowNum).addClass("loading"); $.ajax({ url: "x.asp", cache: false, type: "POST", data: queryString, success: function(html){ $('#result_'+rowNum).empty().append(html); $('#coda_'+rowNum).removeClass("loading"); $('#coda_'+rowNum).addClass("loader"); } }); } </code></pre> <p>What I wanted to know is, from this is there a way I can tell if all my Ajax calls are complete. Reason being that want to enable/disable the submit button while all these calls are taking place.</p> <p>Thanks and please note that I had to mangle my variable names due to the sensitivity of the application, so many of them may be duplicated.</p>
[ { "answer_id": 287212, "author": "Tomasz Tybulewicz", "author_id": 17405, "author_profile": "https://Stackoverflow.com/users/17405", "pm_score": 8, "selected": true, "text": ".ajaxStop() $(document).ajaxStop(function() {\n // place code to be executed on completion of last outstanding ajax call here\n});\n var activeAjaxConnections = 0;\n $.ajax({\n beforeSend: function(xhr) {\n activeAjaxConnections++;\n },\n url (...)\n success success: function(html){\n activeAjaxConnections--;\n $('#result_'+rowNum).empty().append(html);\n $('#coda_'+rowNum).removeClass(\"loading\");\n $('#coda_'+rowNum).addClass(\"loader\");\n if (0 == activeAjaxConnections) {\n // this was the last Ajax connection, do the thing\n }\n},\nerror: function(xhr, errDesc, exception) {\n activeAjaxConnections--;\n if (0 == activeAjaxConnections) {\n // this was the last Ajax connection, do the thing\n }\n}\n" }, { "answer_id": 7610798, "author": "Orson", "author_id": 207756, "author_profile": "https://Stackoverflow.com/users/207756", "pm_score": 5, "selected": false, "text": "$(\"body\").ajaxStop(function() {\n //Your code\n});\n" }, { "answer_id": 15226923, "author": "nothing-special-here", "author_id": 418518, "author_profile": "https://Stackoverflow.com/users/418518", "pm_score": 4, "selected": false, "text": "jQuery.active == 0\n" }, { "answer_id": 36843059, "author": "Jaroslav", "author_id": 2734568, "author_profile": "https://Stackoverflow.com/users/2734568", "pm_score": -1, "selected": false, "text": "success: function(html){\n if(html.success == true ){\n $('#result_'+rowNum).empty().append(html);\n $('#coda_'+rowNum).removeClass(\"loading\");\n $('#coda_'+rowNum).addClass(\"loader\");\n\n }\n }\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
287,193
<p>Are there any wizard type controls in WPF? I need functionality where I can go forward and back and use tabs to select a particular item which will show the details of the nested items. I can use the TabControl control but the tab items are dynamic so I cannot nest the region inside the tab item.</p>
[ { "answer_id": 5041459, "author": "MattP", "author_id": 623117, "author_profile": "https://Stackoverflow.com/users/623117", "pm_score": 4, "selected": false, "text": " <Grid Name=\"Page1\">\n <TextBlock>Page 1</TextBlock>\n </Grid>\n\n <Grid Name=\"Page2\" Visibility=\"Hidden\">\n <TextBlock>Page 2</TextBlock>\n </Grid>\n" }, { "answer_id": 51804137, "author": "lezhkin11", "author_id": 3601887, "author_profile": "https://Stackoverflow.com/users/3601887", "pm_score": 2, "selected": false, "text": "<controls:Wizard>\n <controls:WizardStep ViewType=\"{x:Type test:View1}\" />\n <controls:WizardStep ViewType=\"{x:Type test:View2}\" />\n <controls:WizardStep ViewType=\"{x:Type test:View3}\" />\n</controls:Wizard>\n <controls:Wizard>\n\n <controls:WizardStep>\n <test:View1 />\n </controls:WizardStep>\n\n <controls:WizardStep>\n <test:View2 />\n </controls:WizardStep>\n\n <controls:WizardStep>\n <test:View3 />\n </controls:WizardStep>\n\n</controls:Wizard>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
287,195
<p>The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code. </p> <pre><code>var urls = new List&lt;string&gt;(); urls.Add("http://www.google.com"); foreach (string url in urls) { // Get all links from the url List&lt;string&gt; newUrls = GetLinks(url); urls.AddRange(newUrls); // &lt;-- This is really the problematic row, adding values to the collection I'm looping } </code></pre> <p>How can I rewrite this in a better way? I'm guessing a recursive solution?</p>
[ { "answer_id": 287205, "author": "Martin Brown", "author_id": 20553, "author_profile": "https://Stackoverflow.com/users/20553", "pm_score": 1, "selected": false, "text": "var urls = new List<string>();\nvar destUrls = new List<string>(urls);\nurls.Add(\"http://www.google.com\");\nforeach (string url in urls)\n{ \n // Get all links from the url \n List<string> newUrls = GetLinks(url); \n destUrls.AddRange(newUrls);\n}\nurls = destUrls;\n" }, { "answer_id": 287211, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "IList<string> urls = new List<string>();\nurls.Add(\"http://www.google.com\");\nwhile (urls.Count > 0)\n{\n string url = urls[0];\n urls.RemoveAt(0);\n // Get all links from the url\n List<string> newUrls = GetLinks(url);\n urls.AddRange(newUrls);\n}\n" }, { "answer_id": 287217, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "var urls = new Queue<string>();\nurls.Enqueue(\"http://www.google.com\");\n\nwhile(urls.Count != 0)\n{\n String url = url.Dequeue();\n // Get all links from the url\n List<string> newUrls = GetLinks(url);\n foreach (string newUrl in newUrls)\n {\n queue.Enqueue(newUrl);\n }\n}\n AddRange Queue<T>" }, { "answer_id": 287223, "author": "Tim Merrifield", "author_id": 36706, "author_profile": "https://Stackoverflow.com/users/36706", "pm_score": 2, "selected": false, "text": "var urls = new List<string>();\nvar destUrls = new List<string>();\nurls.Add(\"http://www.google.com\");\nurls.ForEach(i => destUrls.Add(GetLinks(i)));\nurls.AddRange(destUrls);\n" }, { "answer_id": 287229, "author": "FallenAvatar", "author_id": 36965, "author_profile": "https://Stackoverflow.com/users/36965", "pm_score": 0, "selected": false, "text": "var urls = new List<string>();\nvar turls = new List<string();\nturls.Add(\"http://www.google.com\")\n\niterate(turls);\n\nfunction iterate(List<string> u)\n{\n foreach(string url in u)\n {\n List<string> newUrls = GetLinks(url);\n\n urls.AddRange(newUrls);\n\n iterate(newUrls);\n }\n}\n" }, { "answer_id": 287231, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "var urls = new List<string>();\nurls.Add(\"http://www.google.com\");\nint count = urls.Count;\n\nfor (int index = 0; index < count; index++)\n{\n // Get all links from the url\n List<string> newUrls = GetLinks(urls[index]);\n\n urls.AddRange(newUrls);\n}\n" }, { "answer_id": 287245, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "IEnumerable<string> GetUrl(string url)\n{\n foreach(string u in GetUrl(url))\n yield return u;\n foreach(string ret_url in WHERE_I_GET_MY_URLS)\n yield return ret_url;\n}\n\nList<string> MyEnumerateFunction()\n{\n return new List<string>(GetUrl(\"http://www.google.com\"));\n}\n" }, { "answer_id": 288489, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 0, "selected": false, "text": "string System.Web.Uri" }, { "answer_id": 288590, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 0, "selected": false, "text": "public List<string> ExpandLinksOrSomething(List<string> urls)\n{\n List<string> result = new List<string>();\n Queue<string> queue = new Queue<string>(urls);\n\n while (queue.Any())\n {\n string url = queue.Dequeue();\n result.Add(url);\n\n foreach( string newResult in GetLinks(url) )\n {\n queue.Enqueue(newResult);\n }\n\n }\n\n return result;\n}\n GetLinks() List<string> newItems = GetLinks(url).Except(result).ToList();\n foreach( string newResult in newItems )\n {\n queue.Enqueue(newResult);\n }\n public static List<string> StraightProcess(List<string> urls)\n{\n List<string> result = new List<string>();\n\n foreach (string url in urls)\n {\n result.Add(url);\n result.AddRange(GetLinks(url));\n }\n\n return result;\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17436/" ]
287,201
<p>What is the smartest way to get an entity with a field of type List persisted?</p> <h2>Command.java</h2> <pre><code>package persistlistofstring; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Persistence; @Entity public class Command implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) Long id; @Basic List&lt;String&gt; arguments = new ArrayList&lt;String&gt;(); public static void main(String[] args) { Command command = new Command(); EntityManager em = Persistence .createEntityManagerFactory("pu") .createEntityManager(); em.getTransaction().begin(); em.persist(command); em.getTransaction().commit(); em.close(); System.out.println("Persisted with id=" + command.id); } } </code></pre> <hr> <p>This code produces:</p> <pre><code>&gt; Exception in thread "main" javax.persistence.PersistenceException: No Persistence provider for EntityManager named pu: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory: &gt; oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException &gt; Local Exception Stack: &gt; Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException &gt; Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7 &gt; Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException &gt; Exception Description: predeploy for PersistenceUnit [pu] failed. &gt; Internal Exception: Exception [TOPLINK-7155] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException &gt; Exception Description: The type [interface java.util.List] for the attribute [arguments] on the entity class [class persistlistofstring.Command] is not a valid type for a serialized mapping. The attribute type must implement the Serializable interface. &gt; at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143) &gt; at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169) &gt; at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110) &gt; at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) &gt; at persistlistofstring.Command.main(Command.java:30) &gt; Caused by: &gt; ... </code></pre>
[ { "answer_id": 287238, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": false, "text": "@CollectionOfElements(targetElement = String.class)\n@JoinTable(name = \"foo\", joinColumns = @JoinColumn(name = \"foo_id\"))\n@IndexColumn(name = \"POSITION\", base = 1)\n@Column(name = \"baz\", nullable = false)\nprivate List<String> arguments = new ArrayList<String>();\n" }, { "answer_id": 391297, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "@Entity\npublic class Command implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n Long id;\n\n ArrayList<String> arguments = new ArrayList<String>();\n\n\n}\n" }, { "answer_id": 1428480, "author": "Thiago H. de Paula Figueiredo", "author_id": 167264, "author_profile": "https://Stackoverflow.com/users/167264", "pm_score": 9, "selected": true, "text": "javax.persistence.ElementCollection\n\n@ElementCollection\nMap<Key, Value> collection;\n" }, { "answer_id": 1940978, "author": "Anthony", "author_id": 236152, "author_profile": "https://Stackoverflow.com/users/236152", "pm_score": 3, "selected": false, "text": "// a ; separated list of arguments\nString arguments;\n\npublic List<String> getArguments() {\n return Arrays.asList(arguments.split(\";\"));\n}\n" }, { "answer_id": 40709802, "author": "Inverce", "author_id": 3175019, "author_profile": "https://Stackoverflow.com/users/3175019", "pm_score": 3, "selected": false, "text": "@Basic\nArrayList<Color> lovedColors;\n\n@Basic\nArrayList<String> catNames;\n" }, { "answer_id": 44236970, "author": "Zia", "author_id": 2750224, "author_profile": "https://Stackoverflow.com/users/2750224", "pm_score": 3, "selected": false, "text": "@ElementCollection\nprivate Collection<String> options = new ArrayList<String>();\n @Embedded\n@ElementCollection\nprivate Collection<Car> carList = new ArrayList<Car>();\n @Embeddable\npublic class Car {\n}\n" }, { "answer_id": 45574061, "author": "Jaimin Patel", "author_id": 7758868, "author_profile": "https://Stackoverflow.com/users/7758868", "pm_score": 4, "selected": false, "text": "@Column(name=\"arguments\")\n@ElementCollection(targetClass=String.class)\nprivate List<String> arguments;\n" }, { "answer_id": 50448142, "author": "Jonck van der Kogel", "author_id": 718849, "author_profile": "https://Stackoverflow.com/users/718849", "pm_score": 7, "selected": false, "text": "import java.util.Arrays;\nimport java.util.List;\n\nimport javax.persistence.AttributeConverter;\nimport javax.persistence.Converter;\n\nimport static java.util.Collections.*;\n\n@Converter\npublic class StringListConverter implements AttributeConverter<List<String>, String> {\n private static final String SPLIT_CHAR = \";\";\n \n @Override\n public String convertToDatabaseColumn(List<String> stringList) {\n return stringList != null ? String.join(SPLIT_CHAR, stringList) : \"\";\n }\n\n @Override\n public List<String> convertToEntityAttribute(String string) {\n return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();\n }\n}\n @Convert(converter = StringListConverter.class)\nprivate List<String> yourList;\n foo;bar;foobar" }, { "answer_id": 57241586, "author": "diogo", "author_id": 1269558, "author_profile": "https://Stackoverflow.com/users/1269558", "pm_score": 6, "selected": false, "text": "@ElementCollection @Entity\n@Table(name = \"sample\")\npublic class MySample {\n\n @Id\n @GeneratedValue\n private Long id;\n\n @ElementCollection // 1\n @CollectionTable(name = \"my_list\", joinColumns = @JoinColumn(name = \"id\")) // 2\n @Column(name = \"list\") // 3\n private List<String> list;\n \n}\n @ElementCollection fetch targetClass @CollectionTable joinColumns foreignKey indexes uniqueConstraints @Column varchar -- table sample\nCREATE TABLE sample (\n id bigint(20) NOT NULL AUTO_INCREMENT,\n PRIMARY KEY (id)\n);\n\n-- table my_list\nCREATE TABLE IF NOT EXISTS my_list (\n id bigint(20) NOT NULL,\n list varchar(255) DEFAULT NULL,\n FOREIGN KEY (id) REFERENCES sample (id)\n);\n" }, { "answer_id": 61269717, "author": "gosuer1921", "author_id": 1770873, "author_profile": "https://Stackoverflow.com/users/1770873", "pm_score": 3, "selected": false, "text": "@Convert(converter = StringSetConverter.class)\n@Column\nprivate Set<String> washSaleTickers;\n package com.model.domain.converters;\n\nimport javax.persistence.AttributeConverter;\nimport javax.persistence.Converter;\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.StringTokenizer;\n\n@Converter\npublic class StringSetConverter implements AttributeConverter<Set<String>, String> {\n private final String GROUP_DELIMITER = \"=IWILLNEVERHAPPEN=\";\n\n @Override\n public String convertToDatabaseColumn(Set<String> stringList) {\n if (stringList == null) {\n return new String();\n }\n return String.join(GROUP_DELIMITER, stringList);\n }\n\n @Override\n public Set<String> convertToEntityAttribute(String string) {\n Set<String> resultingSet = new HashSet<>();\n StringTokenizer st = new StringTokenizer(string, GROUP_DELIMITER);\n while (st.hasMoreTokens())\n resultingSet.add(st.nextToken());\n return resultingSet;\n }\n}\n" }, { "answer_id": 67617077, "author": "razvang", "author_id": 1864614, "author_profile": "https://Stackoverflow.com/users/1864614", "pm_score": 1, "selected": false, "text": " @Column(name = \"eligible_approvers\", columnDefinition = \"json\")\n @Convert(converter = ArrayJsonConverter.class)\n private Set<String> eligibleApprovers;\n @Converter(autoApply = true)\npublic class ArrayJsonConverter implements AttributeConverter<Set, String> {\n\n static final ObjectMapper mapper = new ObjectMapper();\n\n @Override\n public String convertToDatabaseColumn(Set list) {\n if (list == null)\n return null;\n try {\n return mapper.writeValueAsString(list);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n\n @Override\n public Set convertToEntityAttribute(String dbJson) {\n if (dbJson == null)\n return null;\n try {\n return mapper.readValue(dbJson, new TypeReference<Set<String>>() {\n });\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}\n" }, { "answer_id": 70304277, "author": "Julian Eckhardt", "author_id": 7399497, "author_profile": "https://Stackoverflow.com/users/7399497", "pm_score": 1, "selected": false, "text": "auto_apply = true @Convert(converter = <CONVERTER_CLASS_NAME>.class) RuntimeException" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36131/" ]
287,204
<p>Should I start a Python program with:</p> <pre><code>if__name__ == '__main__': some code... </code></pre> <p>And if so, why? I saw it many times but don't have a clue about it.</p>
[ { "answer_id": 287215, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 6, "selected": true, "text": "__name__ 'foo' __name__ '__main__' if __name__ == '__main__':\n main program here\n" }, { "answer_id": 287237, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 5, "selected": false, "text": "def main():\n ...\n\nif __name__ == '__main__':\n main()\n" }, { "answer_id": 287548, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 5, "selected": false, "text": "def main(argv=None):\n if argv is None:\n argv = sys.argv\n ...\n\nif __name__ == \"__main__\":\n sys.exit(main())\n main() return 1 main()" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25705/" ]
287,242
<p>Modern browsers have multi-tab interface, but JavaScript function <code>window.showModalDialog()</code> creates a modal dialog that blocks <em>all</em> of the tabs. </p> <p>I'd like to know if there is a way to create a modal dialog that blocks only the tab it's been created in?</p>
[ { "answer_id": 287252, "author": "Michiel Overeem", "author_id": 5043, "author_profile": "https://Stackoverflow.com/users/5043", "pm_score": 4, "selected": true, "text": "showModalDialog()" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
287,259
<p>I've looking to find a simple recommended "minimal" c++ makefile for linux which will use g++ to compile and link a single file and h file. Ideally the make file will not even have the physical file names in it and only have a .cpp to .o transform. What is the best way to generate such a makefile without diving into the horrors of autoconf?</p> <p>The current dir contains, for example</p> <p>t.cpp t.h</p> <p>and I want a makefile for that to be created. I tried autoconf but its assuming .h is gcc instead of g++. Yes, while not a beginner, I am relearning from years ago best approaches to project manipulation and hence am looking for automated ways to create and maintain makefiles for small projects.</p>
[ { "answer_id": 287265, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 6, "selected": true, "text": "make t\n g++ t.cpp -o t\n SOURCES := t.cpp\n# Objs are all the sources, with .cpp replaced by .o\nOBJS := $(SOURCES:.cpp=.o)\n\nall: t\n\n# Compile the binary 't' by calling the compiler with cflags, lflags, and any libs (if defined) and the list of objects.\nt: $(OBJS)\n $(CC) $(CFLAGS) -o t $(OBJS) $(LFLAGS) $(LIBS)\n\n# Get a .o from a .cpp by calling compiler with cflags and includes (if defined)\n.cpp.o:\n $(CC) $(CFLAGS) $(INCLUDES) -c $<\n" }, { "answer_id": 287288, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 3, "selected": false, "text": "Program(\"t.cpp\")\n scons\n" }, { "answer_id": 287291, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 3, "selected": false, "text": "make CXX = g++\nCPPFLAGS = # put pre-processor settings (-I, -D, etc) here\nCXXFLAGS = -Wall # put compiler settings here\nLDFLAGS = # put linker settings here\n\ntest: test.o\n $(CXX) -o $@ $(CXXFLAGS) $(LDFLAGS) test.o\n\n.cpp.o:\n $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $<\n\ntest.cpp: test.h\n" }, { "answer_id": 287313, "author": "florin", "author_id": 18308, "author_profile": "https://Stackoverflow.com/users/18308", "pm_score": 4, "selected": false, "text": "SOURCES=$(wildcard *.cpp)\nOBJECTS=$(SOURCES:.cpp=.o)\nDEPS=$(SOURCES:.cpp=.d)\nBINS=$(SOURCES:.cpp=)\n\nCFLAGS+=-MMD\nCXXFLAGS+=-MMD\n\nall: $(BINS)\n\n.PHONY: clean\n\nclean:\n $(RM) $(OBJECTS) $(DEPS) $(BINS)\n\n-include $(DEPS)\n clean: make" }, { "answer_id": 288920, "author": "RichieHH", "author_id": 37370, "author_profile": "https://Stackoverflow.com/users/37370", "pm_score": 0, "selected": false, "text": "env = Environment()\n\nif ARGUMENTS.get('debug', 0):\n env.Append(CCFLAGS = ' -g')\n\nenv.Program( source = \"template.cpp\" )\n" }, { "answer_id": 289563, "author": "bltxd", "author_id": 11892, "author_profile": "https://Stackoverflow.com/users/11892", "pm_score": 1, "selected": false, "text": "open build/C\nDefineCommandVars()\n.SUBDIRS: .\n .DEFAULT: $(CXXProgram test, test)\n omake\n" }, { "answer_id": 28251908, "author": "Sam Watkins", "author_id": 218294, "author_profile": "https://Stackoverflow.com/users/218294", "pm_score": 2, "selected": false, "text": "CC=c++\nCXXFLAGS=-g -Wall -Wextra -MMD\nLDLIBS=-lm\nprogram: program.o sub.o\nclean:\n $(RM) *.o *.d program\n-include $(wildcard *.d)\n" }, { "answer_id": 48481570, "author": "Bob Smith", "author_id": 2421191, "author_profile": "https://Stackoverflow.com/users/2421191", "pm_score": 0, "selected": false, "text": "some_stuff:\n @echo \"Hello World\"\n NAME = my_project\n\nFILES = $(shell basename -a $$(ls *.cpp) | sed 's/\\.cpp//g')\nSRC = $(patsubst %, %.cpp, $(FILES))\nOBJ = $(patsubst %, %.o, $(FILES))\nHDR = $(patsubst %, -include %.h, $(FILES))\nCXX = g++ -Wall\n\n%.o : %.cpp\n $(CXX) $(HDR) -c -o $@ $<\n\nbuild: $(OBJ)\n $(CXX) -o $(NAME) $(OBJ)\n\nclean:\n rm -vf $(NAME) $(OBJ)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37370/" ]
287,271
<p>What are the steps to get Team Foundation Server running unit tests when a given build runs? </p> <p>What are the caveats / pitfalls / workarounds a dev or sysadmin should be aware of when setting up a TFS server to do this for the first time? </p> <p>What are common troubleshooting steps for unit test problems during builds?</p>
[ { "answer_id": 289501, "author": "Mr. Kraus", "author_id": 5132, "author_profile": "https://Stackoverflow.com/users/5132", "pm_score": 5, "selected": true, "text": "<RunConfigFile>$(SolutionRoot)\\TestRunConfig.testrunconfig</RunConfigFile>\n" }, { "answer_id": 292648, "author": "vfilby", "author_id": 24279, "author_profile": "https://Stackoverflow.com/users/24279", "pm_score": 2, "selected": false, "text": "<ItemGroup>\n <TestContainerInOutput Include=\"MyProject.UnitTests.dll\" />\n</ItemGroup>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19020/" ]
287,298
<p>Vista has introduced a new API to display a text in the list view control when it doesn't have any items. As the MSDN library states, I should process the <code>LVN_GETEMPTYMARKUP</code> notification.</p> <p>In the inherited <code>ListView</code> control the <code>WndProc</code> method is overriden:</p> <pre><code>protected override void WndProc(ref Message m) { try { if(m.Msg == 78 /* WM_NOTIFY */) { var nmhdr = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR)); if(nmhdr.code == -187 /* LVN_GETEMPTYMARKUP */) { var nmlvemptymarkup = (NMLVEMPTYMARKUP)Marshal.PtrToStructure(m.LParam, typeof(NMLVEMPTYMARKUP)); nmlvemptymarkup.szMarkup = "The ListView is empty."; m.Result = (IntPtr)1; } } } finally { base.WndProc(ref m); } } </code></pre> <p>However, it doesn't work (although it doesn't throw any exception). Actually I never get <code>nmhdr.code</code> equals to -187. Any ideas?</p>
[ { "answer_id": 287319, "author": "Sunlight", "author_id": 33650, "author_profile": "https://Stackoverflow.com/users/33650", "pm_score": 0, "selected": false, "text": "SetWindowTheme" }, { "answer_id": 287330, "author": "Pondidum", "author_id": 1500, "author_profile": "https://Stackoverflow.com/users/1500", "pm_score": 0, "selected": false, "text": "listview_onPaint(object sender, eventargs e)\n{\n if ( listview.items.count <= 0 )\n {\n e.graphics.drawstring(\"The Listview is empty\"); //put all the proper args in here!\n }\n}\n" }, { "answer_id": 397172, "author": "Miral", "author_id": 43534, "author_profile": "https://Stackoverflow.com/users/43534", "pm_score": 2, "selected": false, "text": "WM_NOTIFY WM_NOTIFY WM_REFLECT WM_NOTIFY" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
287,320
<p>Problem, there's no method:</p> <pre><code>bool ChangePassword(string newPassword); </code></pre> <p>You have to know the current password (which is probably hashed and forgotten).</p>
[ { "answer_id": 287322, "author": "mcqwerty", "author_id": 2115, "author_profile": "https://Stackoverflow.com/users/2115", "pm_score": 8, "selected": true, "text": "MembershipUser u = Membership.GetUser();\nu.ChangePassword(u.ResetPassword(), \"myAwesomePassword\");\n" }, { "answer_id": 4900483, "author": "Mangesh Shelar", "author_id": 603470, "author_profile": "https://Stackoverflow.com/users/603470", "pm_score": 2, "selected": false, "text": " MembershipUser currentUser = Membership.Providers[\"AspNetSqlMembershipProviderReset\"].GetUser(psUserName,false);\n\n //Reset the user password.\n String vsResetPassword = currentUser.ResetPassword(); \n\n //Change the User password with the required password \n currentUser.ChangePassword(vsResetPassword, psNewPassword);\n //Changed the comments to to force the user to change the password on next login attempt\n currentUser.Comment = \"CHANGEPASS\";\n //Check if the user is locked out and if yes unlock the user\n if (currentUser.IsLockedOut == true)\n {\n currentUser.UnlockUser();\n }\n Membership.Providers[\"AspNetSqlMembershipProviderReset\"].UpdateUser(currentUser); return true;\n }\n catch (Exception ex)\n {\n throw ex;\n return false;\n }\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2115/" ]
287,333
<p>I'm looking for a way to select until a sum is reached.</p> <p>My &quot;documents&quot; table has &quot;<code>tag_id</code>&quot; and &quot;<code>size</code>&quot; fields.</p> <p>I want to select all of the documents with <code>tag_id = 26</code> but I know I can only handle 600 units of size. So, there's no point in selecting 100 documents and discarding 90 of them when I could have known that the first 10 already added up to &gt; 600 units.</p> <p>So, the goal is: don't bring back a ton of data to parse through when I'm going to discard most of it.</p> <p>...but I'd also really like to avoid introducing working with cursors to this app.</p> <p>I'm using MySQL.</p>
[ { "answer_id": 287374, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "SELECT d.id, d.size, d.date_created\nFROM documents d\nINNER JOIN documents d2 ON d2.tag_id=d.tag_id AND d2.date_created >= d.date_created\nWHERE d.tag_id=26\nGROUP BY d.id, d.size, d.date_created\nHAVING sum(d2.size) <= 600\nORDER BY d.date_created DESC\n" }, { "answer_id": 287386, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 0, "selected": false, "text": "select a.id, (select sum(b.size) from documents b where b.id <= a.id and b.tag_id = 26)\nfrom documents a\nwhere a.tag_id = 26\norder by a.id\n" }, { "answer_id": 287391, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 0, "selected": false, "text": " declare @documents_temp table (\n tag_id int,\n size int,\n cumulative_size int null)\n\ninsert into @documents_temp\nselect tag_id, size, size from documents order by tag_id\n\nupdate @documents_temp d set d.cumulative_size = d.size + \n (select top 1 cumulative_size from @documents_temp \n where tag_id < d.tag_id order by tag_id desc)\n\nselect tag_id, size from @documents_temp where cumulative_size <= 600\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37378/" ]
287,335
<p>I am trying to setup Weblogic Server 10.3 (and Portal etc.) to use <a href="http://maven.apache.org/" rel="noreferrer">maven</a> as a build tool. I am trying to find a decent tutorial or documentation how to do this. There are some tutorials for older versions like 9.0, but there is little info for version 10.</p> <p>I am looking a way to build weblogic's ear file with maven. Are people actually doing this? Is using maven worth the trouble? </p> <p>I would like to use maven in order to have easier integration with continuous integration tools like <a href="http://hudson-ci.org/" rel="noreferrer">Hudson</a>.</p> <p>edit: There seems to be a way to export maven files directly <a href="http://edocs.bea.com/wlw/docs102/guide/ideuserguide/build/conMavenScript.html" rel="noreferrer">http://edocs.bea.com/wlw/docs102/guide/ideuserguide/build/conMavenScript.html</a>. But those files are simple wrappers for ant.</p>
[ { "answer_id": 629807, "author": "Jan Kronquist", "author_id": 43935, "author_profile": "https://Stackoverflow.com/users/43935", "pm_score": 5, "selected": true, "text": "pom.xml\nsrc/\n main/\n app/\n META-INF/\n weblogic-application.xml\n <build>\n <plugins>\n <plugin>\n <artifactId>maven-ear-plugin</artifactId>\n <configuration>\n <displayName>My Project</displayName>\n <earSourceDirectory>src/main/app</earSourceDirectory>\n <modules>\n <webModule>\n <groupId>com.somecompany</groupId>\n <artifactId>webapp</artifactId>\n </webModule>\n </modules>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>weblogic-maven-plugin</artifactId>\n <version>2.9.1</version>\n <executions>\n <execution>\n <phase>deploy</phase>\n <goals>\n <goal>deploy</goal>\n <goal>start</goal>\n </goals>\n </execution>\n </executions>\n <configuration>\n <name>my-project</name>\n <adminServerHostName>${wls.adminServerHostName}</adminServerHostName>\n <adminServerPort>${wls.adminServerPort}</adminServerPort>\n <adminServerProtocol>t3</adminServerProtocol>\n <userId>${wls.userId}</userId>\n <password>${wls.password}</password>\n <upload>true</upload>\n <remote>true</remote>\n <verbose>false</verbose>\n <debug>false</debug>\n <targetNames>AdminServer</targetNames>\n <noExit>true</noExit>\n </configuration>\n <dependencies>\n <dependency>\n <groupId>com.sun</groupId>\n <artifactId>tools</artifactId>\n <version>1.5</version>\n <scope>system</scope>\n <systemPath>${java.home}/../lib/tools.jar</systemPath>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>weblogic</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>webservices</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.utils.full</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.i18n</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.rmi.client</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>javax.enterprise.deploy</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>webserviceclient</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.security.wls</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.security.identity</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.security</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>wlclient</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.transaction</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.utils.classloaders</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>wljmsclient</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.management.core</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>wls-api</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.descriptor</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.logging</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.socket.api</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.security.digest</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.workmanager</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.weblogic.lifecycle</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.utils.wrapper</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>wlsafclient</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.management.jmx</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n <dependency>\n <groupId>weblogic</groupId>\n <artifactId>com.bea.core.descriptor.wl</artifactId>\n <version>${weblogic.version}</version>\n <scope>provided</scope>\n </dependency>\n </dependencies>\n </plugin>\n </plugins>\n</build>\n" }, { "answer_id": 743362, "author": "michal.slocinski", "author_id": 90159, "author_profile": "https://Stackoverflow.com/users/90159", "pm_score": 3, "selected": false, "text": "pom.xml <plugin>\n <groupId>org.codehaus.cargo</groupId>\n <artifactId>cargo-maven2-plugin</artifactId>\n <version>1.0-SNAPSHOT</version>\n <configuration>\n <container>\n <containerId>weblogic103x</containerId>\n <home>/path/to/your/wlserver_10.3</home>\n </container>\n </configuration>\n </plugin>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431/" ]
287,358
<p>I'm using a repeater control and I'm trying to pass a parameter as such:</p> <pre><code>&lt;%# SomeFunction( DataBinder.Eval(Container.DataItem, "Id") ) %&gt; </code></pre> <p>It's basically calling:</p> <pre><code>public string SomeFunction(long id) { return "Hello"; } </code></pre> <p>I'm not able to achieve this as I get an error:</p> <p>error CS1502: The best overloaded method match ... SomeFunction(long id) ... has some invalid arguments.</p> <p>Any ideas?</p>
[ { "answer_id": 287368, "author": "Kieron", "author_id": 5791, "author_profile": "https://Stackoverflow.com/users/5791", "pm_score": 5, "selected": true, "text": "<%# SomeFunction( (long)DataBinder.Eval(Container.DataItem, \"Id\") ) %>\n <%# SomeFunction(Container.DataItem) %>\n public string SomeFunction(object dataItem) {\n var typedDataItem = (TYPED_DATA_ITEM_TYPE)dataItem;\n\n // DO STUFF HERE WITH THE TYPED DATA ITEM\n\n return \"Hello\"; \n\n}\n" }, { "answer_id": 22508594, "author": "Michael", "author_id": 2965268, "author_profile": "https://Stackoverflow.com/users/2965268", "pm_score": 1, "selected": false, "text": "OnClientClick='<%# \"return myFunction(\\\"\"+ Container.DataItem + \"\\\");\" %>'\n function myFunction(imgPath)\n{\n alert(imgPath);\n}\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5853/" ]
287,369
<p>I was wondering if there was a simple way to use WMI to get you the current windows user name with domain. The Windows API call just gets you the short username, so you end up doing another call for the domain name. I have some code, but I get an automation error. Any ideas? I think I'm on the right path, but I am a little new to WMI.</p> <pre> Function GetFullName() As String Dim computer As String computer = "." Dim objWMIService, colProcessList As Object Set objWMIService = GetObject("winmgmts:\\" & computer & "\root\cimv2") Set colProcessList = objWMIService.ExecQuery _ ("SELECT TOP 1 * FROM Win32_Process WHERE Name = 'EXCEL.EXE'") Dim uname, udomain As String Dim objProcess As Object For Each objProcess In colProcessList objProcess.GetOwner uname, udomain Next GetFullName = UCase(udomain) & "\" & UCase(uname) End Function </pre> <p>UPDATE: see comments on accepted answer</p>
[ { "answer_id": 287658, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "\"SELECT * FROM Win32_Process WHERE Name = 'EXCEL.EXE'\"\n" }, { "answer_id": 288751, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 2, "selected": false, "text": "UserName = Environ(\"Username\")\nDomain = Environ(\"UserDomain\")\nCombined= Environ(\"UserDomain\") & \"\\\" & Environ(\"Username\")\n" }, { "answer_id": 16103794, "author": "Russ", "author_id": 2218206, "author_profile": "https://Stackoverflow.com/users/2218206", "pm_score": 2, "selected": false, "text": "Declare Function GetCurrentProcessId Lib \"kernel32\" () As Long\n...\nProcessID = GetCurrentProcessId\n\nSet ColProcessIDList = objWMIService.ExecQuery( _\n \"SELECT * FROM Win32_Process WHERE ProcessID = '\" & ProcessID & \"'\")\n...\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
287,370
<p>I'm supporting/enhancing a web application written in Classic ASP/VBScript. It has been about 10 years since I have used either in a day to day capacity. I just ran across an issue that I would consider a "gotcha" and was wondering if others had similar things that I should learn to be aware of.</p> <p>My issue:<br> I had to convert a Column in a SQL Table from float to decimal. It turns out that decimal isn't a type that is really supported (or supported well) in vbscript. So the following code:</p> <pre><code>Dim var1, var2 var1 = rs("DecimalField1").Value var2 = rs("DecimalField2").Value If (var1 &lt;&gt; var2) Then 'Do Something' End If </code></pre> <p>Would blow up with a Type Mismatch error on the line:</p> <pre><code>If (var1 &lt;&gt; var2) Then </code></pre> <p>After much searching I found out that:</p> <pre><code>var1 = CDBL(rs("DecimalField1").Value) var2 = CDBL(rs("DecimalField2").Value) </code></pre> <p>resolves the issue. But that didn't seem like an obvious thing and it took me a while to figure out why the heck I was getting a Type Mismatch on that line.</p> <p>So my question to everyone is, what other little quirks like this have you run across? What are some things within ASP/vbscript that you would think of as "gotchas" that I should be on the lookout for?</p>
[ { "answer_id": 287429, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "Set Dim rs : Set rs = CreateObject(\"ADODB.Recordset\");\n Dim field : Set field = rs(0)\n Dim fieldValue : fieldValue = rs(0) 'Same as field.Value\n" }, { "answer_id": 287436, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": " DoSomething withThisArgument\n Dim result : result = DoSomething(withThisArgument)\n result = DoSomething withThisArgument 'SYNTAX ERROR\n" }, { "answer_id": 287440, "author": "chakrit", "author_id": 3055, "author_profile": "https://Stackoverflow.com/users/3055", "pm_score": 0, "selected": false, "text": "Dim varA, varB\n\nvarA = varA + varV\n varV" }, { "answer_id": 310460, "author": "AnonJr", "author_id": 25163, "author_profile": "https://Stackoverflow.com/users/25163", "pm_score": 3, "selected": false, "text": "Option Explicit" }, { "answer_id": 312108, "author": "Mike Henry", "author_id": 14934, "author_profile": "https://Stackoverflow.com/users/14934", "pm_score": 2, "selected": false, "text": "Null True Null False Null IsNull valueIsTrue = True\nvalueIsNull = Null\nIf valueIsTrue <> valueIsNull Then ...\n False myObject Nothing If Not IsNothing(myObject) And myObject.IsValid() Then ...\n If If Not IsNothing(myObject) Then\n If myObject.IsValid() Then\n ...\n" }, { "answer_id": 312151, "author": "JB King", "author_id": 8745, "author_profile": "https://Stackoverflow.com/users/8745", "pm_score": 3, "selected": false, "text": "On Error Resume Next\n" }, { "answer_id": 481172, "author": "feihtthief", "author_id": 320070, "author_profile": "https://Stackoverflow.com/users/320070", "pm_score": 2, "selected": false, "text": "<% OPTION EXPLICIT %>\n<%\n\nsub MakeLonger(byref something)\n something = \"hello \" & something \nend sub\n\ndim msg\nmsg = \"World\"\n\nMakeLonger(msg)\nresponse.write msg\nresponse.write \"<br />\"\n\nMakeLonger msg\nresponse.write msg\n\n%>\n World \nhello World\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32528/" ]
287,373
<p>How can you find the number of occurrences of a particular character in a string using sql?</p> <p>Example: I want to find the number of times the letter ‘d’ appears in this string.</p> <pre><code>declare @string varchar(100) select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa' </code></pre>
[ { "answer_id": 287388, "author": "Mladen Prajdic", "author_id": 31345, "author_profile": "https://Stackoverflow.com/users/31345", "pm_score": 7, "selected": true, "text": "declare @string varchar(100)\nselect @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'\nSELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count\n" }, { "answer_id": 2421948, "author": "Rob Farley", "author_id": 144351, "author_profile": "https://Stackoverflow.com/users/144351", "pm_score": 4, "selected": false, "text": "declare @searchstring varchar(10);\nset @searchstring = 'Rob';\n\nselect original_string, \n(len(orginal_string) - len(replace(original_string, @searchstring, '')) \n / len(@searchstring)\nfrom someTable;\n" }, { "answer_id": 60285343, "author": "Tiggyboo", "author_id": 3266589, "author_profile": "https://Stackoverflow.com/users/3266589", "pm_score": 2, "selected": false, "text": "SELECT LEN(@string) - LEN(REPLACE(@string, 'd', null)) AS D_Count\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
287,378
<p>I'm trying to switch on and off the Rotate 180 degree setting for an HP Laserjet printer (4200/ 4350) using a duplexer unit.</p> <p>The Business has a requirement to "print on both sides", for maximum control I'd like to be able to manipulate at print time (through print macros) whether or not duplex printing is enabled for each of the different types of a document the business works with.</p> <p>I can control the tray assignments, print order and switch duplexing on and off. However, cannot figure out how to control the rotation option (switch this on and off).</p> <p>Any solutions available other than a blanket - enable this option on the print server for all documents/ users?</p>
[ { "answer_id": 287388, "author": "Mladen Prajdic", "author_id": 31345, "author_profile": "https://Stackoverflow.com/users/31345", "pm_score": 7, "selected": true, "text": "declare @string varchar(100)\nselect @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'\nSELECT LEN(@string) - LEN(REPLACE(@string, 'd', '')) AS D_Count\n" }, { "answer_id": 2421948, "author": "Rob Farley", "author_id": 144351, "author_profile": "https://Stackoverflow.com/users/144351", "pm_score": 4, "selected": false, "text": "declare @searchstring varchar(10);\nset @searchstring = 'Rob';\n\nselect original_string, \n(len(orginal_string) - len(replace(original_string, @searchstring, '')) \n / len(@searchstring)\nfrom someTable;\n" }, { "answer_id": 60285343, "author": "Tiggyboo", "author_id": 3266589, "author_profile": "https://Stackoverflow.com/users/3266589", "pm_score": 2, "selected": false, "text": "SELECT LEN(@string) - LEN(REPLACE(@string, 'd', null)) AS D_Count\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32337/" ]
287,379
<p>I have a C/C++ source file with conditional compilation. Before I ship it to customers I want to remove most of the #if statements, so that my customers do not need to worry about passing the right -D options to the compiler.</p> <p>I have this implemented and working in Python, but it only handles #ifdef and #ifndef statements properly. I need to add support for #if statements, but the syntax of #if is much more complex. (E.g. you can use &amp;&amp;, ||, !, brackets, relational operators, arithmetic, etc).</p> <p>Is there any existing open-source code to parse and evaluate #if statements? (Preferably in Python).</p> <p>The only implementation I know of is GCC, and that's much too complex for this task.</p>
[ { "answer_id": 287393, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 0, "selected": false, "text": "cpp" }, { "answer_id": 287521, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": true, "text": "#define -D" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37386/" ]
287,385
<p>I'm trying to write an algorithm that will find the set of all vertices in a graph with degree smaller than their neighbors. My initial approach is to find the degree of each vertex, then work through the list, comparing the degree of each vertex with the degree(s) of its neighbors. Unfortunately, this looks like it could be very time consuming. Is there a more efficient way to find this set?</p>
[ { "answer_id": 287546, "author": "Scott Wegner", "author_id": 33791, "author_profile": "https://Stackoverflow.com/users/33791", "pm_score": 1, "selected": false, "text": "let Q = all nodes which haven't been checked (initialize all V)\nlet Q* = all nodes which satisfy the required condition (initialize to empty)\nstart with an arbitrary node, v in Q\nwhile Q is not empty\n let minDeg be the minimum degree of all v's neighbors\n if degree(v) < minDeg\n add v to Q*\n remove all neighbors of v from Q\n remove v from Q\n set v = new arbitrary node, v in Q\n else\n remove v from Q\n set v = v's neighbor in Q of minimum degree\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27884/" ]
287,398
<p>When writing a custom itemRenderer, how do you reference the height and width of the grid cell that it will be rendered in? In such a way that it will resize correctly when the grid is resized.</p> <p>I am writing a dataGrid itemRenderer that draws a bar graph in the final column of a table.</p> <p>I have tried referencing 'this', 'this.parent', and a few other things with no success. My interim hack solution is to add this data to the datacollection, but this wont work when the grid changes size, so I will have to edit it every time.</p>
[ { "answer_id": 289217, "author": "seanalltogether", "author_id": 26986, "author_profile": "https://Stackoverflow.com/users/26986", "pm_score": 3, "selected": false, "text": "ResizeEvent.RESIZE protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32392/" ]
287,399
<p>I have an msbuild project which builds a SLN file from visual studio which holds all the projects in (about 70+ project), and a lot of the projects are dependent on each other meaning they need to be build in order - sometimes a developer forgets to set the build order manually in visual studio in the solution file causing the msbuild on a clean solution to fail as something gets built out of order/cant find a dll.</p> <p>Is there a way for msbuild to take all projects and work out the dependencies and build the projects in order, if there is how do i do this? using an MSBuild task? With current tries it seems to just build in the order it reads the projects in - if i pass in a list of project files+paths.</p> <p>Currently the only way i can think to solve this is a external app which scans the proj files and references and then manually creates a solution each time.. but this seems overkill for such a simple thing.</p> <p>Anyone solved / seen this before? </p>
[ { "answer_id": 5656948, "author": "Ruben Bartelink", "author_id": 11635, "author_profile": "https://Stackoverflow.com/users/11635", "pm_score": 2, "selected": false, "text": "ResolveReferences Microsoft.Common.targets Task DependsOnTargets Microsoft.Common.targets ResolveReferences ProjectReferences" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28197/" ]
287,401
<p>The following code does not compile:</p> <pre><code>public class GenericsTest { public static void main(String[] args) { MyList&lt;?&gt; list = new MyList&lt;Object&gt;(); Class&lt;?&gt; clazz = list.get(0); // Does not compile with reason // "Type mismatch: cannot convert from Object to Class" MyList list2 = new MyList(); Class clazz2 = list2.get(0); } static class MyList&lt;T&gt; extends ArrayList&lt;Class&lt;T&gt;&gt; { } } </code></pre> <p>I wanted to do this to introduce generics to old code without breaking the build.</p> <p>Is this a bug in both the compiler (both eclipse and javac) or am I missing something here? What other possibility exists to introduce generics to MyList?</p> <p><strong>EDIT</strong></p> <p>For clarification:</p> <p>I have the generic class</p> <pre><code>public class MyList extends ArrayList&lt;MyObject&gt; {} </code></pre> <p>with </p> <pre><code>public class MyObject {} </code></pre> <p>and code using MyList</p> <pre><code>MyList list = new MyList(); ... MyObject o = list.get(0); </code></pre> <p>Now during development I see I want to introduce generics to MyObject</p> <pre><code>public class MyObject&lt;T&gt; {} </code></pre> <p>and now I want to have this new generic thingy in MyList as well</p> <pre><code>public class MyList&lt;T&gt; extends ArrayList&lt;MyObject&lt;T&gt;&gt; {} </code></pre> <p>But that does break my build. Interestingly</p> <pre><code>public class MyList&lt;T&gt; extends ArrayList&lt;MyObject&lt;T&gt;&gt; { public MyObject&lt;T&gt; get(int i) { return super.get(i); } } </code></pre> <p>will allow old code </p> <pre><code>MyList list = new MyList(); ... MyObject o = list.get(0); </code></pre> <p>to compile. </p> <p>OK, seems that when I introduce this generic, I will have to live with having to change all calls to MyList to the generic form. I wanted the old code to just introduce a warning instead of an error.</p>
[ { "answer_id": 287426, "author": "Bogdan", "author_id": 24022, "author_profile": "https://Stackoverflow.com/users/24022", "pm_score": -1, "selected": false, "text": "Class clazz2 = list2.get(0).getClass();\n" }, { "answer_id": 287430, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 5, "selected": true, "text": "MyList<?> list = new MyList<Object>();\nClass<String> clazz= list.get(0);\n list Class<Object> Class<String> list Class<String> MyList<String> list = new MyList<String>();\nClass<String> clazz = list.get(0);\n MyList<?> list = new MyList<Object>();\n//generates a warning about an unchecked cast\nClass<String> clazz = (Class<String>) list.get(0);\n Object get() MyList list2 = new MyList();\nClass clazz2 = (Class) list2.get(0);\n" }, { "answer_id": 287433, "author": "Itay Maman", "author_id": 27198, "author_profile": "https://Stackoverflow.com/users/27198", "pm_score": 1, "selected": false, "text": "public class GenericsTest { \n public static void main(String[] args) {\n MyList<Object> list = new MyList<Object>();\n Class<?> clazz= list.get(0);\n\n }\n\n\n static class MyList<T> extends ArrayList<Class<? extends T>> {\n }\n}\n" }, { "answer_id": 288053, "author": "laz", "author_id": 8753, "author_profile": "https://Stackoverflow.com/users/8753", "pm_score": 1, "selected": false, "text": "Object o = new Object();\nClass c = o;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969/" ]
287,404
<p>So I've got a big text file which looks like the following:</p> <pre><code>&lt;option value value='1' &gt;A &lt;option value value='2' &gt;B &lt;option value value='3' &gt;C &lt;option value value='4' &gt;D </code></pre> <p>It's several hundred lines long and I really don't want to do it manually. The expression that I'm trying to use is:</p> <pre><code>&lt;option value='.{1,}' &gt; </code></pre> <p>Which is working as intended when i run it through several online regular expression testers. I basically want to remove everything before A, B, C, etc. The issue is when I try to use that expression in Vim and Notepad++, it can't seem to find anything.</p>
[ { "answer_id": 287415, "author": "xsl", "author_id": 11387, "author_profile": "https://Stackoverflow.com/users/11387", "pm_score": 3, "selected": false, "text": "option :%s/<option.*>//g\n" }, { "answer_id": 287416, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 2, "selected": false, "text": "%s/^<[^>]+>//\n" }, { "answer_id": 287420, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "1,$s/^<option value value=['].['] >/\n" }, { "answer_id": 287459, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": false, "text": "<option value value='1' >A\n :%s/<option value value='.\\{1,}' >//g\n" }, { "answer_id": 287519, "author": "andHapp", "author_id": 20301, "author_profile": "https://Stackoverflow.com/users/20301", "pm_score": 3, "selected": false, "text": "(.*)(>)(.*)\n (.*)(>)(.*) \\3 (.*)" }, { "answer_id": 287520, "author": "rampion", "author_id": 9859, "author_profile": "https://Stackoverflow.com/users/9859", "pm_score": 2, "selected": false, "text": ":%s/<option value='.\\{1,}' >//\n :%s/<option value='.\\+' >//\n :help /magic" }, { "answer_id": 287586, "author": "Whaledawg", "author_id": 23829, "author_profile": "https://Stackoverflow.com/users/23829", "pm_score": 5, "selected": true, "text": ":%s/<.*>//\n" }, { "answer_id": 421869, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<option value value='1' >A\n<option value value='2' >B\n<option value value='3' >C\n<option value value='4' >D\n\n\nFind what: (.*)(>)(.)\nReplace with: \\3\n\nReplace All\n\n\nA\nB\nC\nD\n" }, { "answer_id": 4525056, "author": "bcmoney", "author_id": 335867, "author_profile": "https://Stackoverflow.com/users/335867", "pm_score": 1, "selected": false, "text": "<select>\n <option value=\"AC\">saint_helena\">Ascension Island</option>\n <option value=\"AD\">andorra\">Andorra</option>\n <option value=\"AE\">united_arab_emirates\">United Arab Emirates</option>\n <option value=\"AF\">afghanistan\">Afghanistan</option>:\n ...\n</select>\n <select>\n <option value=\"AC\">Ascension Island</option>\n <option value=\"AD\">Andorra</option>\n <option value=\"AE\">United Arab Emirates</option>\n <option value=\"AF\">Afghanistan</option>\n ...\n</select>\n (\">)([a-z]+([_]*[a-z]*)*)(\">)\n (\">)([a-z]+[_]*[a-z]*[_]*[a-z]*[_]*[a-z]*[_]*[a-z]*)[_]*[a-z]*[_]*[a-z]*[_]*[a-z]*[_]*[a-z]*(\">)\n" }, { "answer_id": 5470650, "author": "helpful anonymous", "author_id": 681804, "author_profile": "https://Stackoverflow.com/users/681804", "pm_score": 2, "selected": false, "text": "(<option value=\"\\w\\w\">)\\w+\">(.+)\n \\1\\2\n" }, { "answer_id": 37109074, "author": "Ibrahim Akbar", "author_id": 4012478, "author_profile": "https://Stackoverflow.com/users/4012478", "pm_score": 0, "selected": false, "text": "<option value value=.*?>\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25371/" ]
287,407
<p>I've got a popup div showing on rightclick (I know this breaks expected functionality but Google Docs does it so why not?) However the element I'm showing my popup on has a "title" attribute set which appears over the top of my div. I still want the tooltip to work but not when the popup is there.</p> <p>What's the best way to stop the tooltip showing while the popup is open/openning?</p> <p>Edit: I am using jQuery</p>
[ { "answer_id": 287469, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 3, "selected": true, "text": "$(\"element#id\").hover(\n function() {\n $(this).attr(\"title\",\"\");\n $(\"div#popout\").show();\n },\n function() {\n $(\"div#popout\").hide();\n $(this).attr(\"title\",originalTitle);\n }\n);\n" }, { "answer_id": 13124084, "author": "Nazariy", "author_id": 118222, "author_profile": "https://Stackoverflow.com/users/118222", "pm_score": 2, "selected": false, "text": "data prop $('[title]').on({\n mouseenter : function()\n {\n $(this).data('title', this.title).prop('title', '');\n },\n mouseleave: function()\n {\n $(this).prop('title', $(this).data('title'));\n }\n});\n" }, { "answer_id": 30212391, "author": "Jack", "author_id": 1255427, "author_profile": "https://Stackoverflow.com/users/1255427", "pm_score": 1, "selected": false, "text": "$('a').hover(function() {\n\n $(this).attr('title', '');\n\n});\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950/" ]
287,408
<p>So I've setup an Ubuntu server running the 8.04 release. I set it up to authenticate with our Active Directory using the likewise-open package using <a href="http://devarthur.blogspot.com/2008/05/integrating-ubuntu-hardy-heron-804-with.html" rel="nofollow noreferrer">these instructions</a>. Part of that setup was giving Domain Admin users who login to the machine sudo access.</p> <p>Now I'd like to deny login rights for all domain logins except for those users that are in the "Domain Admins" group. Local users should still be able to login. Anyone have any idea how to accomplish this?</p>
[ { "answer_id": 287777, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 0, "selected": false, "text": "+@AdminGroup::::::/bin/bash\n+@Everyone::::::/sbin/nologin\n" }, { "answer_id": 288503, "author": "Lance McNearney", "author_id": 25549, "author_profile": "https://Stackoverflow.com/users/25549", "pm_score": 2, "selected": true, "text": "# make successful authentication dependent on membership of one of\n# the following SIDs/groups/users (comma-separated)\nrequire_membership_of = MYDOMAIN\\domain^admins\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25549/" ]
287,409
<p>Lucky me, I have to work with Oracle. And packages. </p> <p>I have a package that a lot of different developers are touching and it's scaring me. Is it possible to put a package inside of Version Control? Is there some kind of software out there that already does this? If not, is there some kind of export procedure? Can I just grab a file off of a file system?</p>
[ { "answer_id": 287455, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 3, "selected": true, "text": "CREATE OR REPLACE PACKAGE MYPACKAGE AS END; SELECT TEXT FROM ALL_SOURCE\nWHERE TYPE='PACKAGE BODY'\n AND NAME='MYPACKAGE' \n AND OWNER='MYPACKAGEOWNER'\nORDER BY LINE\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/543/" ]
287,414
<p>I have some static images in a folder on my IIS 6-based website that I want to be downloaded as little as possible (to preserve bandwidth). I've set the Content Expiration to expire after 30 days. Is there anything else I can do in IIS to try to maximize the caching by browsers, proxy, and gateway caches?</p> <p>Such as adding a Cache-Control header? Anything else?</p>
[ { "answer_id": 287455, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 3, "selected": true, "text": "CREATE OR REPLACE PACKAGE MYPACKAGE AS END; SELECT TEXT FROM ALL_SOURCE\nWHERE TYPE='PACKAGE BODY'\n AND NAME='MYPACKAGE' \n AND OWNER='MYPACKAGEOWNER'\nORDER BY LINE\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36400/" ]
287,441
<p>Let's assume I have a model called "product." Let's assume that product has three fields. These fields are 'name' (type string), 'cost' (type integer), and 'is_visible' (type bool).</p> <p>1) How can I do a search query using the Rails "find" method (if there is another method, that's fine) so that I can search for all products with a cost greater than 100 AND is_visible is true?</p> <p>2) What if we wanted to change this to search to where name != '' OR cost == 0?</p> <p>This isn't a problem to do an SQL, but I would like to think that Rails has a way to do AND/OR queries to the database without using SQL.</p> <p>Thanks!</p>
[ { "answer_id": 287547, "author": "scottd", "author_id": 5935, "author_profile": "https://Stackoverflow.com/users/5935", "pm_score": 5, "selected": true, "text": "Product.find(:all, :conditions => ['cost > ? and is_visible is true', 100])\n Product.find(:all, :conditions => [\"name != '' or cost =0])\n" }, { "answer_id": 287677, "author": "Adam Byrtek", "author_id": 36656, "author_profile": "https://Stackoverflow.com/users/36656", "pm_score": 2, "selected": false, "text": "items.filter((:cost > 100) & (:is_visible = 1))\n Model.all(:cost.gt => 100, :is_visible.eq => 1)\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
287,443
<p>Consider an SQL Server table containing:</p> <pre><code>ID ParentID Text === ========= ============= 1 (null) Product 2 (null) Applications 3 1 Background 4 1 Details 5 2 Mobile </code></pre> <p>i fill a SqlDataSet with the table, and now i want to add the Parent-Child relation to the DataSet:</p> <pre><code>public DataRelation( string relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints ) </code></pre> <p>Now <a href="http://aspalliance.com/822" rel="nofollow noreferrer">this guy</a> uses:</p> <pre><code>DataRelation relation = newDataRelation("ParentChild", ds.Tables[0].Columns["ID"], //parentColumn ds.Tables[0].Columns["ParentID"] //childColumn, true //createConstraints ); </code></pre> <p>But when i do that i get the exception:</p> <pre><code>This constraint cannot be enabled as not all values have corresponding parent values. </code></pre> <p>People have suggested passing false for <code>createConstraints</code>; but then why does it work for him? </p> <p>And what is a child and what is a parent anyway? i would have thought the <strong>child column</strong> is the column that needs pointing to a parent, and <strong>parent column</strong> is the thing that does the pointing, which would reverse the relation:</p> <pre><code>DataRelation relation = newDataRelation("ParentChild", ds.Tables[0].Columns["ParentID"], //parentColumn ds.Tables[0].Columns["ID"], //childColumn true //createConstraints ); </code></pre> <p>So which is it? Why does his work? What's with the exception? Why can he create the constraint when he has nulls?</p> <p><em>God it's hot in here.</em></p>
[ { "answer_id": 5697912, "author": "goamn", "author_id": 712700, "author_profile": "https://Stackoverflow.com/users/712700", "pm_score": 3, "selected": true, "text": "relation.Nested = true;\nds.Relations.Add(relation);\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
287,445
<p>I can understand wanting to avoid having to use a cursor due to the overhead and inconvenience, but it looks like there's some serious cursor-phobia-mania going on where people are going to great lengths to avoid having to use one.</p> <p>For example, one question asked how to do something obviously trivial with a cursor and the accepted answer proposed using a common table expression (CTE) recursive query with a recursive custom function, even though this limits the number of rows that could be processed to 32 (due to recursive function call limit in sql server). This strikes me as a terrible solution for system longevity, not to mention a tremendous effort just to avoid using a simple cursor.</p> <p>What is the reason for this level of insane hatred? Has some 'noted authority' issued a fatwa against cursors? Does some unspeakable evil lurk in the heart of cursors that corrupts the morals of children or something?</p> <p>Wiki question, more interested in the answer than the rep.</p> <p>Related Info:</p> <p><a href="https://stackoverflow.com/questions/37029/sql-server-fast-forward-cursors">SQL Server Fast Forward Cursors</a></p> <p>EDIT: let me be more precise: I understand that <strong>cursors should not be used instead of normal relational operations</strong>; that is a no-brainer. What I don't understand is people going waaaaay out of their way to avoid cursors like they have cooties or something, even when a cursor is a simpler and/or more efficient solution. It's the irrational hatred that baffles me, not the obvious technical efficiencies.</p>
[ { "answer_id": 287492, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 7, "selected": true, "text": "CREATE TABLE INSERT SELECT" }, { "answer_id": 287508, "author": "Mladen Prajdic", "author_id": 31345, "author_profile": "https://Stackoverflow.com/users/31345", "pm_score": 0, "selected": false, "text": "SELECT * INTO #temp FROM master..spt_values\nDECLARE @startTime DATETIME\n\nBEGIN TRAN \n\nSELECT @startTime = GETDATE()\nUPDATE #temp\nSET number = 0\nselect DATEDIFF(ms, @startTime, GETDATE())\n\nROLLBACK \n\nBEGIN TRAN \nDECLARE @name VARCHAR\n\nDECLARE tempCursor CURSOR\n FOR SELECT name FROM #temp\n\nOPEN tempCursor\n\nFETCH NEXT FROM tempCursor \nINTO @name\n\nSELECT @startTime = GETDATE()\nWHILE @@FETCH_STATUS = 0\nBEGIN\n\n UPDATE #temp SET number = 0 WHERE NAME = @name\n FETCH NEXT FROM tempCursor \n INTO @name\n\nEND \nselect DATEDIFF(ms, @startTime, GETDATE())\nCLOSE tempCursor\nDEALLOCATE tempCursor\n\nROLLBACK \nDROP TABLE #temp\n" }, { "answer_id": 430935, "author": "tuinstoel", "author_id": 43901, "author_profile": "https://Stackoverflow.com/users/43901", "pm_score": 3, "selected": false, "text": " for x in (select ....) loop\n --do something \n end loop;\n" } ]
2008/11/13
[ "https://Stackoverflow.com/questions/287445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]